commonobject.class.php 329 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640
  1. <?php
  2. /* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
  5. * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
  6. * Copyright (C) 2011-2019 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-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
  11. * Copyright (C) 2016 Bahfir abbes <dolipar@dolipar.org>
  12. * Copyright (C) 2017 ATM Consulting <support@atm-consulting.fr>
  13. * Copyright (C) 2017-2019 Nicolas ZABOURI <info@inovea-conseil.com>
  14. * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
  15. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  16. * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
  17. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  18. *
  19. * This program is free software; you can redistribute it and/or modify
  20. * it under the terms of the GNU General Public License as published by
  21. * the Free Software Foundation; either version 3 of the License, or
  22. * (at your option) any later version.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU General Public License
  30. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  31. */
  32. /**
  33. * \file htdocs/core/class/commonobject.class.php
  34. * \ingroup core
  35. * \brief File of parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  36. */
  37. /**
  38. * Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  39. */
  40. abstract class CommonObject
  41. {
  42. /**
  43. * @var DoliDb Database handler (result of a new DoliDB)
  44. */
  45. public $db;
  46. /**
  47. * @var int The object identifier
  48. */
  49. public $id;
  50. /**
  51. * @var int The environment ID when using a multicompany module
  52. */
  53. public $entity;
  54. /**
  55. * @var string Error string
  56. * @see $errors
  57. */
  58. public $error;
  59. /**
  60. * @var string Error string that is hidden but can be used to store complementatry technical code.
  61. */
  62. public $errorhidden;
  63. /**
  64. * @var string[] Array of error strings
  65. */
  66. public $errors = array();
  67. /**
  68. * @var array To store error results of ->validateField()
  69. */
  70. public $validateFieldsErrors = array();
  71. /**
  72. * @var string ID to identify managed object
  73. */
  74. public $element;
  75. /**
  76. * @var string Name of table without prefix where object is stored
  77. */
  78. public $table_element;
  79. /**
  80. * @var string Name of subtable line
  81. */
  82. public $table_element_line = '';
  83. /**
  84. * @var string Key value used to track if data is coming from import wizard
  85. */
  86. public $import_key;
  87. /**
  88. * @var mixed Contains data to manage extrafields
  89. */
  90. public $array_options = array();
  91. /**
  92. * @var mixed Array to store alternative languages values of object
  93. */
  94. public $array_languages = null; // Value is array() when load already tried
  95. /**
  96. * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked
  97. */
  98. public $linkedObjectsIds;
  99. /**
  100. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  101. */
  102. public $linkedObjects;
  103. /**
  104. * @var Object To store a cloned copy of object before to edit it and keep track of old properties
  105. */
  106. public $oldcopy;
  107. /**
  108. * @var string Column name of the ref field.
  109. */
  110. protected $table_ref_field = '';
  111. /**
  112. * @var integer 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user
  113. */
  114. public $restrictiononfksoc = 0;
  115. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  116. /**
  117. * @var array<string,mixed> Can be used to pass information when only object is provided to method
  118. */
  119. public $context = array();
  120. /**
  121. * @var string Contains canvas name if record is an alternative canvas record
  122. */
  123. public $canvas;
  124. /**
  125. * @var Project The related project
  126. * @see fetch_projet()
  127. */
  128. public $project;
  129. /**
  130. * @var int The related project ID
  131. * @see setProject(), project
  132. */
  133. public $fk_project;
  134. /**
  135. * @deprecated
  136. * @see project
  137. */
  138. public $projet;
  139. /**
  140. * @var Contact a related contact
  141. * @see fetch_contact()
  142. */
  143. public $contact;
  144. /**
  145. * @var int The related contact ID
  146. * @see fetch_contact()
  147. */
  148. public $contact_id;
  149. /**
  150. * @var Societe A related thirdparty
  151. * @see fetch_thirdparty()
  152. */
  153. public $thirdparty;
  154. /**
  155. * @var User A related user
  156. * @see fetch_user()
  157. */
  158. public $user;
  159. /**
  160. * @var string The type of originating object ('commande', 'facture', ...)
  161. * @see fetch_origin()
  162. */
  163. public $origin;
  164. /**
  165. * @var int The id of originating object
  166. * @see fetch_origin()
  167. */
  168. public $origin_id;
  169. /**
  170. * @var string The object's reference
  171. */
  172. public $ref;
  173. /**
  174. * @var string An external reference for the object
  175. */
  176. public $ref_ext;
  177. /**
  178. * @var string The object's previous reference
  179. */
  180. public $ref_previous;
  181. /**
  182. * @var string The object's next reference
  183. */
  184. public $ref_next;
  185. /**
  186. * @var string Ref to store on object to save the new ref to use for example when making a validate() of an object
  187. */
  188. public $newref;
  189. /**
  190. * @var int The object's status
  191. * @see setStatut()
  192. */
  193. public $statut;
  194. /**
  195. * @var int The object's status
  196. * @see setStatut()
  197. */
  198. public $status;
  199. /**
  200. * @var string
  201. * @see getFullAddress()
  202. */
  203. public $country;
  204. /**
  205. * @var int
  206. * @see getFullAddress(), country
  207. */
  208. public $country_id;
  209. /**
  210. * @var string
  211. * @see getFullAddress(), isInEEC(), country
  212. */
  213. public $country_code;
  214. /**
  215. * @var string
  216. * @see getFullAddress()
  217. */
  218. public $state;
  219. /**
  220. * @var int
  221. * @see getFullAddress(), state
  222. */
  223. public $state_id;
  224. /**
  225. * @var string
  226. * @see getFullAddress(), $state
  227. */
  228. public $state_code;
  229. /**
  230. * @var int
  231. * @see getFullAddress(), $region_code, $region
  232. */
  233. public $region_id;
  234. /**
  235. * @var string
  236. * @see getFullAddress(), $region_id, $region
  237. */
  238. public $region_code;
  239. /**
  240. * @var string
  241. * @see getFullAddress(), $region_id, $region_code
  242. */
  243. public $region;
  244. /**
  245. * @var int
  246. * @see fetch_barcode()
  247. */
  248. public $barcode_type;
  249. /**
  250. * @var string
  251. * @see fetch_barcode(), barcode_type
  252. */
  253. public $barcode_type_code;
  254. /**
  255. * @var string
  256. * @see fetch_barcode(), barcode_type
  257. */
  258. public $barcode_type_label;
  259. /**
  260. * @var string
  261. * @see fetch_barcode(), barcode_type
  262. */
  263. public $barcode_type_coder;
  264. /**
  265. * @var int Payment method ID (cheque, cash, ...)
  266. * @see setPaymentMethods()
  267. */
  268. public $mode_reglement_id;
  269. /**
  270. * @var int Payment terms ID
  271. * @see setPaymentTerms()
  272. */
  273. public $cond_reglement_id;
  274. /**
  275. * @var int Demand reason ID
  276. */
  277. public $demand_reason_id;
  278. /**
  279. * @var int Transport mode ID (For module intracomm report)
  280. * @see setTransportMode()
  281. */
  282. public $transport_mode_id;
  283. /**
  284. * @var int Payment terms ID
  285. * @deprecated Kept for compatibility
  286. * @see cond_reglement_id;
  287. */
  288. public $cond_reglement;
  289. /**
  290. * @var int Delivery address ID
  291. * @see setDeliveryAddress()
  292. * @deprecated
  293. */
  294. public $fk_delivery_address;
  295. /**
  296. * @var int Shipping method ID
  297. * @see setShippingMethod()
  298. */
  299. public $shipping_method_id;
  300. /**
  301. * @var string
  302. * @see SetDocModel()
  303. */
  304. public $model_pdf;
  305. /**
  306. * @var string
  307. * @deprecated
  308. * @see $model_pdf
  309. */
  310. public $modelpdf;
  311. /**
  312. * @var string
  313. * Contains relative path of last generated main file
  314. */
  315. public $last_main_doc;
  316. /**
  317. * @var int Bank account ID sometimes, ID of record into llx_bank sometimes
  318. * @deprecated
  319. * @see $fk_account
  320. */
  321. public $fk_bank;
  322. /**
  323. * @var int Bank account ID
  324. * @see SetBankAccount()
  325. */
  326. public $fk_account;
  327. /**
  328. * @var string Open ID
  329. */
  330. public $openid;
  331. /**
  332. * @var string Public note
  333. * @see update_note()
  334. */
  335. public $note_public;
  336. /**
  337. * @var string Private note
  338. * @see update_note()
  339. */
  340. public $note_private;
  341. /**
  342. * @deprecated
  343. * @see $note_private
  344. */
  345. public $note;
  346. /**
  347. * @var float Total amount before taxes
  348. * @see update_price()
  349. */
  350. public $total_ht;
  351. /**
  352. * @var float Total VAT amount
  353. * @see update_price()
  354. */
  355. public $total_tva;
  356. /**
  357. * @var float Total local tax 1 amount
  358. * @see update_price()
  359. */
  360. public $total_localtax1;
  361. /**
  362. * @var float Total local tax 2 amount
  363. * @see update_price()
  364. */
  365. public $total_localtax2;
  366. /**
  367. * @var float Total amount with taxes
  368. * @see update_price()
  369. */
  370. public $total_ttc;
  371. /**
  372. * @var CommonObjectLine[]
  373. */
  374. public $lines;
  375. /**
  376. * @var mixed Contains comments
  377. * @see fetchComments()
  378. */
  379. public $comments = array();
  380. /**
  381. * @var string The name
  382. */
  383. public $name;
  384. /**
  385. * @var string The lastname
  386. */
  387. public $lastname;
  388. /**
  389. * @var string The firstname
  390. */
  391. public $firstname;
  392. /**
  393. * @var string The civility code, not an integer
  394. */
  395. public $civility_id;
  396. // Dates
  397. /**
  398. * @var integer|string date_creation
  399. */
  400. public $date_creation;
  401. /**
  402. * @var integer|string $date_validation;
  403. */
  404. public $date_validation; // Date validation
  405. /**
  406. * @var integer|string $date_modification;
  407. */
  408. public $date_modification; // Date last change (tms field)
  409. public $next_prev_filter;
  410. /**
  411. * @var int 1 if object is specimen
  412. */
  413. public $specimen = 0;
  414. /**
  415. * @var int Id of contact to send object (used by the trigger of module Agenda)
  416. */
  417. public $sendtoid;
  418. /**
  419. * @var float Amount already paid (used to show correct status)
  420. */
  421. public $alreadypaid;
  422. /**
  423. * @var array List of child tables. To test if we can delete object.
  424. */
  425. protected $childtables = array();
  426. /**
  427. * @var array List of child tables. To know object to delete on cascade.
  428. * If name is like '@ClassName:FilePathClass:ParentFkFieldName', it will
  429. * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object.
  430. */
  431. protected $childtablesoncascade = array();
  432. // No constructor as it is an abstract class
  433. /**
  434. * Check an object id/ref exists
  435. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  436. *
  437. * @param string $element String of element ('product', 'facture', ...)
  438. * @param int $id Id of object
  439. * @param string $ref Ref of object to check
  440. * @param string $ref_ext Ref ext of object to check
  441. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  442. */
  443. public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
  444. {
  445. global $db, $conf;
  446. $sql = "SELECT rowid, ref, ref_ext";
  447. $sql .= " FROM ".MAIN_DB_PREFIX.$element;
  448. $sql .= " WHERE entity IN (".getEntity($element).")";
  449. if ($id > 0) {
  450. $sql .= " AND rowid = ".((int) $id);
  451. } elseif ($ref) {
  452. $sql .= " AND ref = '".$db->escape($ref)."'";
  453. } elseif ($ref_ext) {
  454. $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
  455. } else {
  456. $error = 'ErrorWrongParameters';
  457. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  458. return -1;
  459. }
  460. if ($ref || $ref_ext) {
  461. $sql .= " AND entity = ".((int) $conf->entity);
  462. }
  463. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  464. $resql = $db->query($sql);
  465. if ($resql) {
  466. $num = $db->num_rows($resql);
  467. if ($num > 0) {
  468. return 1;
  469. } else {
  470. return 0;
  471. }
  472. }
  473. return -1;
  474. }
  475. /**
  476. * Method to output saved errors
  477. *
  478. * @return string String with errors
  479. */
  480. public function errorsToString()
  481. {
  482. return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
  483. }
  484. /**
  485. * Return customer ref for screen output.
  486. *
  487. * @param string $objref Customer ref
  488. * @return string Customer ref formated
  489. */
  490. public function getFormatedCustomerRef($objref)
  491. {
  492. global $hookmanager;
  493. $parameters = array('objref'=>$objref);
  494. $action = '';
  495. $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  496. if ($reshook > 0) {
  497. return $hookmanager->resArray['objref'];
  498. }
  499. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  500. }
  501. /**
  502. * Return supplier ref for screen output.
  503. *
  504. * @param string $objref Supplier ref
  505. * @return string Supplier ref formated
  506. */
  507. public function getFormatedSupplierRef($objref)
  508. {
  509. global $hookmanager;
  510. $parameters = array('objref'=>$objref);
  511. $action = '';
  512. $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  513. if ($reshook > 0) {
  514. return $hookmanager->resArray['objref'];
  515. }
  516. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  517. }
  518. /**
  519. * Return full name (civility+' '+name+' '+lastname)
  520. *
  521. * @param Translate $langs Language object for translation of civility (used only if option is 1)
  522. * @param int $option 0=No option, 1=Add civility
  523. * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname, 3=Firstname if defined else lastname, 4=Lastname, 5=Lastname if defined else firstname
  524. * @param int $maxlen Maximum length
  525. * @return string String with full name
  526. */
  527. public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
  528. {
  529. //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
  530. $lastname = $this->lastname;
  531. $firstname = $this->firstname;
  532. if (empty($lastname)) {
  533. $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 : '')))));
  534. }
  535. $ret = '';
  536. if (!empty($option) && !empty($this->civility_code)) {
  537. if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) {
  538. $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
  539. } else {
  540. $ret .= $this->civility_code.' ';
  541. }
  542. }
  543. $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
  544. return dol_trunc($ret, $maxlen);
  545. }
  546. /**
  547. * Set to upper or ucwords/lower if needed
  548. *
  549. * @return void;
  550. */
  551. public function setUpperOrLowerCase()
  552. {
  553. global $conf;
  554. if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
  555. $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
  556. $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
  557. $this->name = dol_ucwords(dol_strtolower($this->name));
  558. $this->name_alias = dol_ucwords(dol_strtolower($this->name_alias));
  559. }
  560. if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
  561. $this->lastname = dol_strtoupper($this->lastname);
  562. $this->name = dol_strtoupper($this->name);
  563. $this->name_alias = dol_strtoupper($this->name_alias);
  564. }
  565. if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
  566. $this->address = dol_strtoupper($this->address);
  567. $this->town = dol_strtoupper($this->town);
  568. }
  569. }
  570. /**
  571. * Return clicable link of object (with eventually picto)
  572. *
  573. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  574. * @return string HTML Code for Kanban thumb.
  575. */
  576. public function getKanbanView($option = '')
  577. {
  578. $return = '<div class="box-flex-item">';
  579. $return .= '<div class="info-box info-box-sm">';
  580. $return .= '<span class="info-box-icon bg-infobox-action">';
  581. $return .= '<i class="fa fa-dol-action"></i>'; // Can be image
  582. $return .= '</span>';
  583. $return .= '<div class="info-box-content">';
  584. $return .= '<span class="info-box-title">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  585. $return .= '</div>';
  586. $return .= '</div>';
  587. $return .= '</div>';
  588. return $return;
  589. }
  590. /**
  591. * Return full address of contact
  592. *
  593. * @param int $withcountry 1=Add country into address string
  594. * @param string $sep Separator to use to build string
  595. * @param int $withregion 1=Add region into address string
  596. * @param string $extralangcode User extralanguages as value
  597. * @return string Full address string
  598. */
  599. public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
  600. {
  601. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
  602. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  603. $tmparray = getCountry($this->country_id, 'all');
  604. $this->country_code = $tmparray['code'];
  605. $this->country = $tmparray['label'];
  606. }
  607. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
  608. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  609. $tmparray = getState($this->state_id, 'all', 0, 1);
  610. $this->state_code = $tmparray['code'];
  611. $this->state = $tmparray['label'];
  612. $this->region_code = $tmparray['region_code'];
  613. $this->region = $tmparray['region'];
  614. }
  615. return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
  616. }
  617. /**
  618. * Return full address for banner
  619. *
  620. * @param string $htmlkey HTML id to make banner content unique
  621. * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member)
  622. * @return string Full address string
  623. */
  624. public function getBannerAddress($htmlkey, $object)
  625. {
  626. global $conf, $langs, $form, $extralanguages;
  627. $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
  628. $contactid = 0;
  629. $thirdpartyid = 0;
  630. $elementforaltlanguage = $this->element;
  631. if ($this->element == 'societe') {
  632. $thirdpartyid = $this->id;
  633. }
  634. if ($this->element == 'contact') {
  635. $contactid = $this->id;
  636. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  637. }
  638. if ($this->element == 'user') {
  639. $contactid = $this->contact_id;
  640. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  641. }
  642. $out = '';
  643. $outdone = 0;
  644. $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
  645. if ($coords) {
  646. if (!empty($conf->use_javascript_ajax)) {
  647. // Add picto with tooltip on map
  648. $namecoords = '';
  649. if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
  650. $namecoords .= $object->name.'<br>';
  651. }
  652. $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
  653. // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
  654. $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
  655. $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
  656. $out .= '</a> ';
  657. }
  658. $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  659. $outdone++;
  660. $outdone++;
  661. // List of extra languages
  662. $arrayoflangcode = array();
  663. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  664. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  665. }
  666. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  667. if (!is_object($extralanguages)) {
  668. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  669. $extralanguages = new ExtraLanguages($this->db);
  670. }
  671. $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
  672. if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
  673. $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
  674. $this->fetchValuesForExtraLanguages();
  675. if (!is_object($form)) {
  676. $form = new Form($this->db);
  677. }
  678. $htmltext = '';
  679. // If there is extra languages
  680. foreach ($arrayoflangcode as $extralangcode) {
  681. $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  682. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
  683. $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  684. }
  685. $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  686. }
  687. }
  688. }
  689. 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
  690. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
  691. if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
  692. $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
  693. } else {
  694. $out .= ($outdone ? ' - ' : '').$this->state;
  695. }
  696. $outdone++;
  697. }
  698. 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)) {
  699. $out .= ($outdone ? '<br>' : '');
  700. }
  701. if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  702. $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  703. $outdone++;
  704. }
  705. if (!empty($this->phone_pro)) {
  706. $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  707. $outdone++;
  708. }
  709. if (!empty($this->phone_mobile)) {
  710. $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  711. $outdone++;
  712. }
  713. if (!empty($this->phone_perso)) {
  714. $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
  715. $outdone++;
  716. }
  717. if (!empty($this->office_phone)) {
  718. $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  719. $outdone++;
  720. }
  721. if (!empty($this->user_mobile)) {
  722. $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  723. $outdone++;
  724. }
  725. if (!empty($this->fax)) {
  726. $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  727. $outdone++;
  728. }
  729. if (!empty($this->office_fax)) {
  730. $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  731. $outdone++;
  732. }
  733. if ($out) {
  734. $out .= '<div style="clear: both;"></div>';
  735. }
  736. $outdone = 0;
  737. if (!empty($this->email)) {
  738. $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
  739. $outdone++;
  740. }
  741. if (!empty($this->url)) {
  742. //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
  743. $out .= dol_print_url($this->url, '_blank', 0, 1);
  744. $outdone++;
  745. }
  746. if (!empty($conf->socialnetworks->enabled)) {
  747. $outsocialnetwork = '';
  748. if (!empty($this->socialnetworks) && is_countable($this->socialnetworks) && count($this->socialnetworks) > 0) {
  749. $socialnetworksdict = getArrayOfSocialNetworks();
  750. foreach ($this->socialnetworks as $key => $value) {
  751. if ($value) {
  752. $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
  753. }
  754. $outdone++;
  755. }
  756. } else { // Old code to remove
  757. if (!empty($this->skype)) {
  758. $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
  759. }
  760. $outdone++;
  761. if (!empty($this->jabberid)) {
  762. $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
  763. }
  764. $outdone++;
  765. if (!empty($this->twitter)) {
  766. $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
  767. }
  768. $outdone++;
  769. if (!empty($this->facebook)) {
  770. $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
  771. }
  772. $outdone++;
  773. if (!empty($this->linkedin)) {
  774. $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
  775. }
  776. $outdone++;
  777. }
  778. if ($outsocialnetwork) {
  779. $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
  780. }
  781. }
  782. if ($out) {
  783. return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
  784. } else {
  785. return '';
  786. }
  787. }
  788. /**
  789. * Return the link of last main doc file for direct public download.
  790. *
  791. * @param string $modulepart Module related to document
  792. * @param int $initsharekey Init the share key if it was not yet defined
  793. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  794. * @return string Link or empty string if there is no download link
  795. */
  796. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  797. {
  798. global $user, $dolibarr_main_url_root;
  799. if (empty($this->last_main_doc)) {
  800. return ''; // No way to known which document name to use
  801. }
  802. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  803. $ecmfile = new EcmFiles($this->db);
  804. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  805. if ($result < 0) {
  806. $this->error = $ecmfile->error;
  807. $this->errors = $ecmfile->errors;
  808. return -1;
  809. }
  810. if (empty($ecmfile->id)) {
  811. // Add entry into index
  812. if ($initsharekey) {
  813. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  814. // TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first
  815. /*
  816. $ecmfile->filepath = $rel_dir;
  817. $ecmfile->filename = $filename;
  818. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  819. $ecmfile->fullpath_orig = '';
  820. $ecmfile->gen_or_uploaded = 'generated';
  821. $ecmfile->description = ''; // indexed content
  822. $ecmfile->keywords = ''; // keyword content
  823. $ecmfile->share = getRandomPassword(true);
  824. $result = $ecmfile->create($user);
  825. if ($result < 0)
  826. {
  827. $this->error = $ecmfile->error;
  828. $this->errors = $ecmfile->errors;
  829. }
  830. */
  831. } else {
  832. return '';
  833. }
  834. } elseif (empty($ecmfile->share)) {
  835. // Add entry into index
  836. if ($initsharekey) {
  837. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  838. $ecmfile->share = getRandomPassword(true);
  839. $ecmfile->update($user);
  840. } else {
  841. return '';
  842. }
  843. }
  844. // Define $urlwithroot
  845. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  846. // This is to use external domain name found into config file
  847. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  848. //else
  849. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  850. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  851. $forcedownload = 0;
  852. $paramlink = '';
  853. //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  854. //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  855. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  856. if (!empty($ecmfile->share)) {
  857. $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
  858. }
  859. if ($forcedownload) {
  860. $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  861. }
  862. if ($relativelink) {
  863. $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
  864. } else {
  865. $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  866. }
  867. // Here $ecmfile->share is defined
  868. return $linktoreturn;
  869. }
  870. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  871. /**
  872. * Add a link between element $this->element and a contact
  873. *
  874. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  875. * @param int|string $type_contact Type of contact (code or id). Must be id or code found into table llx_c_type_contact. For example: SALESREPFOLL
  876. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  877. * @param int $notrigger Disable all triggers
  878. * @return int <0 if KO, 0 if already added, >0 if OK
  879. */
  880. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  881. {
  882. // phpcs:enable
  883. global $user, $langs;
  884. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  885. // Check parameters
  886. if ($fk_socpeople <= 0) {
  887. $langs->load("errors");
  888. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  889. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  890. return -1;
  891. }
  892. if (!$type_contact) {
  893. $langs->load("errors");
  894. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  895. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  896. return -2;
  897. }
  898. $id_type_contact = 0;
  899. if (is_numeric($type_contact)) {
  900. $id_type_contact = $type_contact;
  901. } else {
  902. // We look for id type_contact
  903. $sql = "SELECT tc.rowid";
  904. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  905. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  906. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  907. $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  908. //print $sql;
  909. $resql = $this->db->query($sql);
  910. if ($resql) {
  911. $obj = $this->db->fetch_object($resql);
  912. if ($obj) {
  913. $id_type_contact = $obj->rowid;
  914. }
  915. }
  916. }
  917. if ($id_type_contact == 0) {
  918. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  919. 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");
  920. return -3;
  921. }
  922. $datecreate = dol_now();
  923. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  924. $TListeContacts = $this->liste_contact(-1, $source);
  925. $already_added = false;
  926. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  927. foreach ($TListeContacts as $array_contact) {
  928. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  929. $already_added = true;
  930. break;
  931. }
  932. }
  933. }
  934. if (!$already_added) {
  935. $this->db->begin();
  936. // Insert into database
  937. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact";
  938. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  939. $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
  940. $sql .= "'".$this->db->idate($datecreate)."'";
  941. $sql .= ", 4, ".((int) $id_type_contact);
  942. $sql .= ")";
  943. $resql = $this->db->query($sql);
  944. if ($resql) {
  945. if (!$notrigger) {
  946. $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  947. if ($result < 0) {
  948. $this->db->rollback();
  949. return -1;
  950. }
  951. }
  952. $this->db->commit();
  953. return 1;
  954. } else {
  955. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  956. $this->error = $this->db->errno();
  957. $this->db->rollback();
  958. return -2;
  959. } else {
  960. $this->error = $this->db->lasterror();
  961. $this->db->rollback();
  962. return -1;
  963. }
  964. }
  965. } else {
  966. return 0;
  967. }
  968. }
  969. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  970. /**
  971. * Copy contact from one element to current
  972. *
  973. * @param CommonObject $objFrom Source element
  974. * @param string $source Nature of contact ('internal' or 'external')
  975. * @return int >0 if OK, <0 if KO
  976. */
  977. public function copy_linked_contact($objFrom, $source = 'internal')
  978. {
  979. // phpcs:enable
  980. $contacts = $objFrom->liste_contact(-1, $source);
  981. foreach ($contacts as $contact) {
  982. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
  983. return -1;
  984. }
  985. }
  986. return 1;
  987. }
  988. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  989. /**
  990. * Update a link to contact line
  991. *
  992. * @param int $rowid Id of line contact-element
  993. * @param int $statut New status of link
  994. * @param int $type_contact_id Id of contact type (not modified if 0)
  995. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  996. * @return int <0 if KO, >= 0 if OK
  997. */
  998. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  999. {
  1000. // phpcs:enable
  1001. // Insert into database
  1002. $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set";
  1003. $sql .= " statut = ".$statut;
  1004. if ($type_contact_id) {
  1005. $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
  1006. }
  1007. if ($fk_socpeople) {
  1008. $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
  1009. }
  1010. $sql .= " where rowid = ".((int) $rowid);
  1011. $resql = $this->db->query($sql);
  1012. if ($resql) {
  1013. return 0;
  1014. } else {
  1015. $this->error = $this->db->lasterror();
  1016. return -1;
  1017. }
  1018. }
  1019. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1020. /**
  1021. * Delete a link to contact line
  1022. *
  1023. * @param int $rowid Id of contact link line to delete
  1024. * @param int $notrigger Disable all triggers
  1025. * @return int >0 if OK, <0 if KO
  1026. */
  1027. public function delete_contact($rowid, $notrigger = 0)
  1028. {
  1029. // phpcs:enable
  1030. global $user;
  1031. $this->db->begin();
  1032. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  1033. $sql .= " WHERE rowid = ".((int) $rowid);
  1034. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  1035. if ($this->db->query($sql)) {
  1036. if (!$notrigger) {
  1037. $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  1038. if ($result < 0) {
  1039. $this->db->rollback();
  1040. return -1;
  1041. }
  1042. }
  1043. $this->db->commit();
  1044. return 1;
  1045. } else {
  1046. $this->error = $this->db->lasterror();
  1047. $this->db->rollback();
  1048. return -1;
  1049. }
  1050. }
  1051. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1052. /**
  1053. * Delete all links between an object $this and all its contacts
  1054. *
  1055. * @param string $source '' or 'internal' or 'external'
  1056. * @param string $code Type of contact (code or id)
  1057. * @return int >0 if OK, <0 if KO
  1058. */
  1059. public function delete_linked_contact($source = '', $code = '')
  1060. {
  1061. // phpcs:enable
  1062. $temp = array();
  1063. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  1064. foreach ($typeContact as $key => $value) {
  1065. array_push($temp, $key);
  1066. }
  1067. $listId = implode(",", $temp);
  1068. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  1069. $sql .= " WHERE element_id = ".((int) $this->id);
  1070. if ($listId) {
  1071. $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
  1072. }
  1073. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  1074. if ($this->db->query($sql)) {
  1075. return 1;
  1076. } else {
  1077. $this->error = $this->db->lasterror();
  1078. return -1;
  1079. }
  1080. }
  1081. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1082. /**
  1083. * Get array of all contacts for an object
  1084. *
  1085. * @param int $status Status of links to get (-1=all)
  1086. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  1087. * @param int $list 0:Return array contains all properties, 1:Return array contains just id
  1088. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1089. * @return array|int Array of contacts, -1 if error
  1090. */
  1091. public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
  1092. {
  1093. // phpcs:enable
  1094. global $langs;
  1095. $tab = array();
  1096. $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
  1097. if ($source == 'internal') {
  1098. $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  1099. }
  1100. if ($source == 'external' || $source == 'thirdparty') {
  1101. $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1102. }
  1103. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  1104. $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
  1105. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
  1106. $sql .= ", ".MAIN_DB_PREFIX."element_contact ec";
  1107. if ($source == 'internal') {
  1108. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
  1109. }
  1110. if ($source == 'external' || $source == 'thirdparty') {
  1111. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
  1112. }
  1113. $sql .= " WHERE ec.element_id = ".((int) $this->id);
  1114. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1115. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1116. if ($code) {
  1117. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1118. }
  1119. if ($source == 'internal') {
  1120. $sql .= " AND tc.source = 'internal'";
  1121. }
  1122. if ($source == 'external' || $source == 'thirdparty') {
  1123. $sql .= " AND tc.source = 'external'";
  1124. }
  1125. $sql .= " AND tc.active=1";
  1126. if ($status >= 0) {
  1127. $sql .= " AND ec.statut = ".((int) $status);
  1128. }
  1129. $sql .= " ORDER BY t.lastname ASC";
  1130. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  1131. $resql = $this->db->query($sql);
  1132. if ($resql) {
  1133. $num = $this->db->num_rows($resql);
  1134. $i = 0;
  1135. while ($i < $num) {
  1136. $obj = $this->db->fetch_object($resql);
  1137. if (!$list) {
  1138. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1139. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1140. $tab[$i] = array(
  1141. 'source' => $obj->source,
  1142. 'socid' => $obj->socid,
  1143. 'id' => $obj->id,
  1144. 'nom' => $obj->lastname, // For backward compatibility
  1145. 'civility' => $obj->civility,
  1146. 'lastname' => $obj->lastname,
  1147. 'firstname' => $obj->firstname,
  1148. 'email'=>$obj->email,
  1149. 'login'=> (empty($obj->login) ? '' : $obj->login),
  1150. 'photo' => (empty($obj->photo) ? '' : $obj->photo),
  1151. 'statuscontact' => $obj->statuscontact,
  1152. 'rowid' => $obj->rowid,
  1153. 'code' => $obj->code,
  1154. 'libelle' => $libelle_type,
  1155. 'status' => $obj->statuslink,
  1156. 'fk_c_type_contact' => $obj->fk_c_type_contact
  1157. );
  1158. } else {
  1159. $tab[$i] = $obj->id;
  1160. }
  1161. $i++;
  1162. }
  1163. return $tab;
  1164. } else {
  1165. $this->error = $this->db->lasterror();
  1166. dol_print_error($this->db);
  1167. return -1;
  1168. }
  1169. }
  1170. /**
  1171. * Update status of a contact linked to object
  1172. *
  1173. * @param int $rowid Id of link between object and contact
  1174. * @return int <0 if KO, >=0 if OK
  1175. */
  1176. public function swapContactStatus($rowid)
  1177. {
  1178. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1179. $sql .= " tc.code, tc.libelle";
  1180. $sql .= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)";
  1181. $sql .= " WHERE ec.rowid =".((int) $rowid);
  1182. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1183. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1184. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  1185. $resql = $this->db->query($sql);
  1186. if ($resql) {
  1187. $obj = $this->db->fetch_object($resql);
  1188. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1189. $result = $this->update_contact($rowid, $newstatut);
  1190. $this->db->free($resql);
  1191. return $result;
  1192. } else {
  1193. $this->error = $this->db->error();
  1194. dol_print_error($this->db);
  1195. return -1;
  1196. }
  1197. }
  1198. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1199. /**
  1200. * Return array with list of possible values for type of contacts
  1201. *
  1202. * @param string $source 'internal', 'external' or 'all'
  1203. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  1204. * @param int $option 0=Return array id->label, 1=Return array code->label
  1205. * @param int $activeonly 0=all status of contact, 1=only the active
  1206. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1207. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1208. */
  1209. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1210. {
  1211. // phpcs:enable
  1212. global $langs;
  1213. if (empty($order)) {
  1214. $order = 'position';
  1215. }
  1216. if ($order == 'position') {
  1217. $order .= ',code';
  1218. }
  1219. $tab = array();
  1220. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  1221. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  1222. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1223. if ($activeonly == 1) {
  1224. $sql .= " AND tc.active=1"; // only the active types
  1225. }
  1226. if (!empty($source) && $source != 'all') {
  1227. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1228. }
  1229. if (!empty($code)) {
  1230. $sql .= " AND tc.code='".$this->db->escape($code)."'";
  1231. }
  1232. $sql .= $this->db->order($order, 'ASC');
  1233. //print "sql=".$sql;
  1234. $resql = $this->db->query($sql);
  1235. if ($resql) {
  1236. $num = $this->db->num_rows($resql);
  1237. $i = 0;
  1238. while ($i < $num) {
  1239. $obj = $this->db->fetch_object($resql);
  1240. $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
  1241. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1242. if (empty($option)) {
  1243. $tab[$obj->rowid] = $libelle_type;
  1244. } else {
  1245. $tab[$obj->code] = $libelle_type;
  1246. }
  1247. $i++;
  1248. }
  1249. return $tab;
  1250. } else {
  1251. $this->error = $this->db->lasterror();
  1252. //dol_print_error($this->db);
  1253. return null;
  1254. }
  1255. }
  1256. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1257. /**
  1258. * Return array with list of possible values for type of contacts
  1259. *
  1260. * @param string $source 'internal', 'external' or 'all'
  1261. * @param int $option 0=Return array id->label, 1=Return array code->label
  1262. * @param int $activeonly 0=all status of contact, 1=only the active
  1263. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1264. * @param string $element Filter on 1 element type
  1265. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1266. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1267. */
  1268. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1269. {
  1270. // phpcs:enable
  1271. global $langs, $conf;
  1272. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1273. $tab = array();
  1274. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
  1275. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  1276. $sqlWhere = array();
  1277. if (!empty($element)) {
  1278. $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
  1279. }
  1280. if (!empty($excludeelement)) {
  1281. $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
  1282. }
  1283. if ($activeonly == 1) {
  1284. $sqlWhere[] = " tc.active=1"; // only the active types
  1285. }
  1286. if (!empty($source) && $source != 'all') {
  1287. $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
  1288. }
  1289. if (!empty($code)) {
  1290. $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
  1291. }
  1292. if (count($sqlWhere) > 0) {
  1293. $sql .= " WHERE ".implode(' AND ', $sqlWhere);
  1294. }
  1295. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1296. dol_syslog(__METHOD__, LOG_DEBUG);
  1297. $resql = $this->db->query($sql);
  1298. if ($resql) {
  1299. $num = $this->db->num_rows($resql);
  1300. if ($num > 0) {
  1301. $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
  1302. while ($obj = $this->db->fetch_object($resql)) {
  1303. $modulename = $obj->element;
  1304. if (strpos($obj->element, 'project') !== false) {
  1305. $modulename = 'projet';
  1306. } elseif ($obj->element == 'contrat') {
  1307. $element = 'contract';
  1308. } elseif ($obj->element == 'action') {
  1309. $modulename = 'agenda';
  1310. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1311. $modulename = 'fournisseur';
  1312. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1313. $modulename = 'fournisseur';
  1314. }
  1315. if (!empty($conf->{$modulename}->enabled)) {
  1316. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1317. $tmpelement = $obj->element;
  1318. $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
  1319. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1320. if (empty($option)) {
  1321. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1322. } else {
  1323. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1324. }
  1325. }
  1326. }
  1327. }
  1328. return $tab;
  1329. } else {
  1330. $this->error = $this->db->lasterror();
  1331. return null;
  1332. }
  1333. }
  1334. /**
  1335. * Return id of contacts for a source and a contact code.
  1336. * Example: contact client de facturation ('external', 'BILLING')
  1337. * Example: contact client de livraison ('external', 'SHIPPING')
  1338. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1339. *
  1340. * @param string $source 'external' or 'internal'
  1341. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1342. * @param int $status limited to a certain status
  1343. * @return array List of id for such contacts
  1344. */
  1345. public function getIdContact($source, $code, $status = 0)
  1346. {
  1347. global $conf;
  1348. $result = array();
  1349. $i = 0;
  1350. //cas particulier pour les expeditions
  1351. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1352. $id = $this->origin_id;
  1353. $element = 'commande';
  1354. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1355. $id = $this->origin_id;
  1356. $element = 'order_supplier';
  1357. } else {
  1358. $id = $this->id;
  1359. $element = $this->element;
  1360. }
  1361. $sql = "SELECT ec.fk_socpeople";
  1362. $sql .= " FROM ".MAIN_DB_PREFIX."element_contact as ec,";
  1363. if ($source == 'internal') {
  1364. $sql .= " ".MAIN_DB_PREFIX."user as c,";
  1365. }
  1366. if ($source == 'external') {
  1367. $sql .= " ".MAIN_DB_PREFIX."socpeople as c,";
  1368. }
  1369. $sql .= " ".MAIN_DB_PREFIX."c_type_contact as tc";
  1370. $sql .= " WHERE ec.element_id = ".((int) $id);
  1371. $sql .= " AND ec.fk_socpeople = c.rowid";
  1372. if ($source == 'internal') {
  1373. $sql .= " AND c.entity IN (".getEntity('user').")";
  1374. }
  1375. if ($source == 'external') {
  1376. $sql .= " AND c.entity IN (".getEntity('societe').")";
  1377. }
  1378. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1379. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1380. $sql .= " AND tc.source = '".$this->db->escape($source)."'";
  1381. if ($code) {
  1382. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1383. }
  1384. $sql .= " AND tc.active = 1";
  1385. if ($status) {
  1386. $sql .= " AND ec.statut = ".((int) $status);
  1387. }
  1388. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1389. $resql = $this->db->query($sql);
  1390. if ($resql) {
  1391. while ($obj = $this->db->fetch_object($resql)) {
  1392. $result[$i] = $obj->fk_socpeople;
  1393. $i++;
  1394. }
  1395. } else {
  1396. $this->error = $this->db->error();
  1397. return null;
  1398. }
  1399. return $result;
  1400. }
  1401. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1402. /**
  1403. * Load object contact with id=$this->contact_id into $this->contact
  1404. *
  1405. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1406. * @return int <0 if KO, >0 if OK
  1407. */
  1408. public function fetch_contact($contactid = null)
  1409. {
  1410. // phpcs:enable
  1411. if (empty($contactid)) {
  1412. $contactid = $this->contact_id;
  1413. }
  1414. if (empty($contactid)) {
  1415. return 0;
  1416. }
  1417. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1418. $contact = new Contact($this->db);
  1419. $result = $contact->fetch($contactid);
  1420. $this->contact = $contact;
  1421. return $result;
  1422. }
  1423. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1424. /**
  1425. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1426. *
  1427. * @param int $force_thirdparty_id Force thirdparty id
  1428. * @return int <0 if KO, >0 if OK
  1429. */
  1430. public function fetch_thirdparty($force_thirdparty_id = 0)
  1431. {
  1432. // phpcs:enable
  1433. global $conf;
  1434. if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) {
  1435. return 0;
  1436. }
  1437. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1438. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
  1439. if ($force_thirdparty_id) {
  1440. $idtofetch = $force_thirdparty_id;
  1441. }
  1442. if ($idtofetch) {
  1443. $thirdparty = new Societe($this->db);
  1444. $result = $thirdparty->fetch($idtofetch);
  1445. if ($result<0) {
  1446. $this->errors=array_merge($this->errors, $thirdparty->errors);
  1447. }
  1448. $this->thirdparty = $thirdparty;
  1449. // Use first price level if level not defined for third party
  1450. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1451. $this->thirdparty->price_level = 1;
  1452. }
  1453. return $result;
  1454. } else {
  1455. return -1;
  1456. }
  1457. }
  1458. /**
  1459. * Looks for an object with ref matching the wildcard provided
  1460. * It does only work when $this->table_ref_field is set
  1461. *
  1462. * @param string $ref Wildcard
  1463. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1464. */
  1465. public function fetchOneLike($ref)
  1466. {
  1467. if (!$this->table_ref_field) {
  1468. return 0;
  1469. }
  1470. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."' LIMIT 1";
  1471. $query = $this->db->query($sql);
  1472. if (!$this->db->num_rows($query)) {
  1473. return 0;
  1474. }
  1475. $result = $this->db->fetch_object($query);
  1476. return $this->fetch($result->rowid);
  1477. }
  1478. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1479. /**
  1480. * Load data for barcode into properties ->barcode_type*
  1481. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1482. * if it is not defined, ->element must be defined to know default barcode type.
  1483. *
  1484. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1485. */
  1486. public function fetch_barcode()
  1487. {
  1488. // phpcs:enable
  1489. global $conf;
  1490. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1491. $idtype = $this->barcode_type;
  1492. 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
  1493. if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
  1494. $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1495. } elseif ($this->element == 'societe') {
  1496. $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1497. } else {
  1498. dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1499. }
  1500. }
  1501. if ($idtype > 0) {
  1502. 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
  1503. $sql = "SELECT rowid, code, libelle as label, coder";
  1504. $sql .= " FROM ".MAIN_DB_PREFIX."c_barcode_type";
  1505. $sql .= " WHERE rowid = ".((int) $idtype);
  1506. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1507. $resql = $this->db->query($sql);
  1508. if ($resql) {
  1509. $obj = $this->db->fetch_object($resql);
  1510. $this->barcode_type = $obj->rowid;
  1511. $this->barcode_type_code = $obj->code;
  1512. $this->barcode_type_label = $obj->label;
  1513. $this->barcode_type_coder = $obj->coder;
  1514. return 1;
  1515. } else {
  1516. dol_print_error($this->db);
  1517. return -1;
  1518. }
  1519. }
  1520. }
  1521. return 0;
  1522. }
  1523. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1524. /**
  1525. * Load the project with id $this->fk_project into this->project
  1526. *
  1527. * @return int <0 if KO, >=0 if OK
  1528. */
  1529. public function fetch_project()
  1530. {
  1531. // phpcs:enable
  1532. return $this->fetch_projet();
  1533. }
  1534. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1535. /**
  1536. * Load the project with id $this->fk_project into this->project
  1537. *
  1538. * @return int <0 if KO, >=0 if OK
  1539. */
  1540. public function fetch_projet()
  1541. {
  1542. // phpcs:enable
  1543. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1544. if (empty($this->fk_project) && !empty($this->fk_projet)) {
  1545. $this->fk_project = $this->fk_projet; // For backward compatibility
  1546. }
  1547. if (empty($this->fk_project)) {
  1548. return 0;
  1549. }
  1550. $project = new Project($this->db);
  1551. $result = $project->fetch($this->fk_project);
  1552. $this->projet = $project; // deprecated
  1553. $this->project = $project;
  1554. return $result;
  1555. }
  1556. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1557. /**
  1558. * Load the product with id $this->fk_product into this->product
  1559. *
  1560. * @return int <0 if KO, >=0 if OK
  1561. */
  1562. public function fetch_product()
  1563. {
  1564. // phpcs:enable
  1565. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1566. if (empty($this->fk_product)) {
  1567. return 0;
  1568. }
  1569. $product = new Product($this->db);
  1570. $result = $product->fetch($this->fk_product);
  1571. $this->product = $product;
  1572. return $result;
  1573. }
  1574. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1575. /**
  1576. * Load the user with id $userid into this->user
  1577. *
  1578. * @param int $userid Id du contact
  1579. * @return int <0 if KO, >0 if OK
  1580. */
  1581. public function fetch_user($userid)
  1582. {
  1583. // phpcs:enable
  1584. $user = new User($this->db);
  1585. $result = $user->fetch($userid);
  1586. $this->user = $user;
  1587. return $result;
  1588. }
  1589. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1590. /**
  1591. * Read linked origin object
  1592. *
  1593. * @return void
  1594. */
  1595. public function fetch_origin()
  1596. {
  1597. // phpcs:enable
  1598. if ($this->origin == 'shipping') {
  1599. $this->origin = 'expedition';
  1600. }
  1601. if ($this->origin == 'delivery') {
  1602. $this->origin = 'livraison';
  1603. }
  1604. if ($this->origin == 'order_supplier') {
  1605. $this->origin = 'commandeFournisseur';
  1606. }
  1607. $origin = $this->origin;
  1608. $classname = ucfirst($origin);
  1609. $this->$origin = new $classname($this->db);
  1610. $this->$origin->fetch($this->origin_id);
  1611. }
  1612. /**
  1613. * Load object from specific field
  1614. *
  1615. * @param string $table Table element or element line
  1616. * @param string $field Field selected
  1617. * @param string $key Import key
  1618. * @param string $element Element name
  1619. * @return int <0 if KO, >0 if OK
  1620. */
  1621. public function fetchObjectFrom($table, $field, $key, $element = null)
  1622. {
  1623. global $conf;
  1624. $result = false;
  1625. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$table;
  1626. $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
  1627. if (!empty($element)) {
  1628. $sql .= " AND entity IN (".getEntity($element).")";
  1629. } else {
  1630. $sql .= " AND entity = ".((int) $conf->entity);
  1631. }
  1632. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1633. $resql = $this->db->query($sql);
  1634. if ($resql) {
  1635. $row = $this->db->fetch_row($resql);
  1636. // Test for avoid error -1
  1637. if ($row[0] > 0) {
  1638. $result = $this->fetch($row[0]);
  1639. }
  1640. }
  1641. return $result;
  1642. }
  1643. /**
  1644. * Getter generic. Load value from a specific field
  1645. *
  1646. * @param string $table Table of element or element line
  1647. * @param int $id Element id
  1648. * @param string $field Field selected
  1649. * @return int <0 if KO, >0 if OK
  1650. */
  1651. public function getValueFrom($table, $id, $field)
  1652. {
  1653. $result = false;
  1654. if (!empty($id) && !empty($field) && !empty($table)) {
  1655. $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table;
  1656. $sql .= " WHERE rowid = ".((int) $id);
  1657. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1658. $resql = $this->db->query($sql);
  1659. if ($resql) {
  1660. $row = $this->db->fetch_row($resql);
  1661. $result = $row[0];
  1662. }
  1663. }
  1664. return $result;
  1665. }
  1666. /**
  1667. * Setter generic. Update a specific field into database.
  1668. * Warning: Trigger is run only if param trigkey is provided.
  1669. *
  1670. * @param string $field Field to update
  1671. * @param mixed $value New value
  1672. * @param string $table To force other table element or element line (should not be used)
  1673. * @param int $id To force other object id (should not be used)
  1674. * @param string $format Data format ('text', 'date'). 'text' is used if not defined
  1675. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1676. * @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'
  1677. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1678. * @param string $fk_user_field Name of field to save user id making change
  1679. * @return int <0 if KO, >0 if OK
  1680. * @see updateExtraField()
  1681. */
  1682. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1683. {
  1684. global $user, $langs, $conf;
  1685. if (empty($table)) {
  1686. $table = $this->table_element;
  1687. }
  1688. if (empty($id)) {
  1689. $id = $this->id;
  1690. }
  1691. if (empty($format)) {
  1692. $format = 'text';
  1693. }
  1694. if (empty($id_field)) {
  1695. $id_field = 'rowid';
  1696. }
  1697. $error = 0;
  1698. $this->db->begin();
  1699. // Special case
  1700. if ($table == 'product' && $field == 'note_private') {
  1701. $field = 'note';
  1702. }
  1703. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  1704. $fk_user_field = 'fk_user_mod';
  1705. }
  1706. $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
  1707. if ($format == 'text') {
  1708. $sql .= $field." = '".$this->db->escape($value)."'";
  1709. } elseif ($format == 'int') {
  1710. $sql .= $field." = ".((int) $value);
  1711. } elseif ($format == 'date') {
  1712. $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1713. }
  1714. if ($fk_user_field) {
  1715. if (!empty($fuser) && is_object($fuser)) {
  1716. $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
  1717. } elseif (empty($fuser) || $fuser != 'none') {
  1718. $sql .= ", ".$fk_user_field." = ".((int) $user->id);
  1719. }
  1720. }
  1721. $sql .= " WHERE ".$id_field." = ".((int) $id);
  1722. dol_syslog(__METHOD__."", LOG_DEBUG);
  1723. $resql = $this->db->query($sql);
  1724. if ($resql) {
  1725. if ($trigkey) {
  1726. // call trigger with updated object values
  1727. if (empty($this->fields) && method_exists($this, 'fetch')) {
  1728. $result = $this->fetch($id);
  1729. } else {
  1730. $result = $this->fetchCommon($id);
  1731. }
  1732. if ($result >= 0) {
  1733. $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1734. }
  1735. if ($result < 0) {
  1736. $error++;
  1737. }
  1738. }
  1739. if (!$error) {
  1740. if (property_exists($this, $field)) {
  1741. $this->$field = $value;
  1742. }
  1743. $this->db->commit();
  1744. return 1;
  1745. } else {
  1746. $this->db->rollback();
  1747. return -2;
  1748. }
  1749. } else {
  1750. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1751. $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
  1752. } else {
  1753. $this->error = $this->db->lasterror();
  1754. }
  1755. $this->db->rollback();
  1756. return -1;
  1757. }
  1758. }
  1759. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1760. /**
  1761. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1762. *
  1763. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')". Do not allow user input data here.
  1764. * @param string $fieldid Name of field to use for the select MAX and MIN
  1765. * @param int $nodbprefix Do not include DB prefix to forge table name
  1766. * @return int <0 if KO, >0 if OK
  1767. */
  1768. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1769. {
  1770. // phpcs:enable
  1771. global $conf, $user;
  1772. if (!$this->table_element) {
  1773. dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1774. return -1;
  1775. }
  1776. if ($fieldid == 'none') {
  1777. return 1;
  1778. }
  1779. // For backward compatibility
  1780. if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
  1781. $fieldid = 'titre';
  1782. }
  1783. // Security on socid
  1784. $socid = 0;
  1785. if ($user->socid > 0) {
  1786. $socid = $user->socid;
  1787. }
  1788. // this->ismultientitymanaged contains
  1789. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1790. $aliastablesociete = 's';
  1791. if ($this->element == 'societe') {
  1792. $aliastablesociete = 'te'; // te as table_element
  1793. }
  1794. $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
  1795. $sql = "SELECT MAX(te.".$fieldid.")";
  1796. $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1797. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1798. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  1799. }
  1800. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1801. $tmparray = explode('@', $this->ismultientitymanaged);
  1802. $sql .= ", ".MAIN_DB_PREFIX.$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1803. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1804. $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid
  1805. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1806. $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
  1807. }
  1808. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1809. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1810. }
  1811. $sql .= " WHERE te.".$fieldid." < '".$this->db->escape($fieldid == 'rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
  1812. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1813. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1814. }
  1815. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1816. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1817. }
  1818. if (!empty($filter)) {
  1819. if (!preg_match('/^\s*AND/i', $filter)) {
  1820. $sql .= " AND "; // For backward compatibility
  1821. }
  1822. $sql .= $filter;
  1823. }
  1824. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1825. $tmparray = explode('@', $this->ismultientitymanaged);
  1826. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1827. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1828. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1829. }
  1830. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1831. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1832. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1833. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1834. } else {
  1835. $sql .= " AND ug.fk_user = te.rowid";
  1836. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1837. }
  1838. } else {
  1839. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1840. }
  1841. }
  1842. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1843. $tmparray = explode('@', $this->ismultientitymanaged);
  1844. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1845. }
  1846. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1847. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1848. }
  1849. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1850. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1851. }
  1852. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1853. $sql .= ' AND te.rowid = '.((int) $socid);
  1854. }
  1855. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1856. $result = $this->db->query($sql);
  1857. if (!$result) {
  1858. $this->error = $this->db->lasterror();
  1859. return -1;
  1860. }
  1861. $row = $this->db->fetch_row($result);
  1862. $this->ref_previous = $row[0];
  1863. $sql = "SELECT MIN(te.".$fieldid.")";
  1864. $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1865. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1866. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  1867. }
  1868. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1869. $tmparray = explode('@', $this->ismultientitymanaged);
  1870. $sql .= ", ".MAIN_DB_PREFIX.$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1871. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1872. $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid
  1873. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1874. $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
  1875. }
  1876. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1877. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1878. }
  1879. $sql .= " WHERE te.".$fieldid." > '".$this->db->escape($fieldid == 'rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
  1880. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1881. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1882. }
  1883. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1884. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1885. }
  1886. if (!empty($filter)) {
  1887. if (!preg_match('/^\s*AND/i', $filter)) {
  1888. $sql .= " AND "; // For backward compatibility
  1889. }
  1890. $sql .= $filter;
  1891. }
  1892. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1893. $tmparray = explode('@', $this->ismultientitymanaged);
  1894. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1895. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1896. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1897. }
  1898. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1899. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1900. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1901. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1902. } else {
  1903. $sql .= " AND ug.fk_user = te.rowid";
  1904. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1905. }
  1906. } else {
  1907. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1908. }
  1909. }
  1910. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1911. $tmparray = explode('@', $this->ismultientitymanaged);
  1912. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1913. }
  1914. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1915. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1916. }
  1917. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1918. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1919. }
  1920. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1921. $sql .= ' AND te.rowid = '.((int) $socid);
  1922. }
  1923. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1924. // 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
  1925. $result = $this->db->query($sql);
  1926. if (!$result) {
  1927. $this->error = $this->db->lasterror();
  1928. return -2;
  1929. }
  1930. $row = $this->db->fetch_row($result);
  1931. $this->ref_next = $row[0];
  1932. return 1;
  1933. }
  1934. /**
  1935. * Return list of id of contacts of object
  1936. *
  1937. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  1938. * @return array Array of id of contacts (if source=external or internal)
  1939. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  1940. */
  1941. public function getListContactId($source = 'external')
  1942. {
  1943. $contactAlreadySelected = array();
  1944. $tab = $this->liste_contact(-1, $source);
  1945. $num = count($tab);
  1946. $i = 0;
  1947. while ($i < $num) {
  1948. if ($source == 'thirdparty') {
  1949. $contactAlreadySelected[$i] = $tab[$i]['socid'];
  1950. } else {
  1951. $contactAlreadySelected[$i] = $tab[$i]['id'];
  1952. }
  1953. $i++;
  1954. }
  1955. return $contactAlreadySelected;
  1956. }
  1957. /**
  1958. * Link element with a project
  1959. *
  1960. * @param int $projectid Project id to link element to
  1961. * @return int <0 if KO, >0 if OK
  1962. */
  1963. public function setProject($projectid)
  1964. {
  1965. if (!$this->table_element) {
  1966. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  1967. return -1;
  1968. }
  1969. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  1970. if (!empty($this->fields['fk_project'])) { // Common case
  1971. if ($projectid) {
  1972. $sql .= " SET fk_project = ".((int) $projectid);
  1973. } else {
  1974. $sql .= " SET fk_project = NULL";
  1975. }
  1976. $sql .= ' WHERE rowid = '.((int) $this->id);
  1977. } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
  1978. if ($projectid) {
  1979. $sql .= " SET fk_project = ".((int) $projectid);
  1980. } else {
  1981. $sql .= " SET fk_project = NULL";
  1982. }
  1983. $sql .= ' WHERE id = '.((int) $this->id);
  1984. } else // Special case for old architecture objects
  1985. {
  1986. if ($projectid) {
  1987. $sql .= ' SET fk_projet = '.((int) $projectid);
  1988. } else {
  1989. $sql .= ' SET fk_projet = NULL';
  1990. }
  1991. $sql .= " WHERE rowid = ".((int) $this->id);
  1992. }
  1993. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  1994. if ($this->db->query($sql)) {
  1995. $this->fk_project = ((int) $projectid);
  1996. return 1;
  1997. } else {
  1998. dol_print_error($this->db);
  1999. return -1;
  2000. }
  2001. }
  2002. /**
  2003. * Change the payments methods
  2004. *
  2005. * @param int $id Id of new payment method
  2006. * @return int >0 if OK, <0 if KO
  2007. */
  2008. public function setPaymentMethods($id)
  2009. {
  2010. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  2011. if ($this->statut >= 0 || $this->element == 'societe') {
  2012. // TODO uniformize field name
  2013. $fieldname = 'fk_mode_reglement';
  2014. if ($this->element == 'societe') {
  2015. $fieldname = 'mode_reglement';
  2016. }
  2017. if (get_class($this) == 'Fournisseur') {
  2018. $fieldname = 'mode_reglement_supplier';
  2019. }
  2020. if (get_class($this) == 'Tva') {
  2021. $fieldname = 'fk_typepayment';
  2022. }
  2023. if (get_class($this) == 'Salary') {
  2024. $fieldname = 'fk_typepayment';
  2025. }
  2026. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2027. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2028. $sql .= ' WHERE rowid='.((int) $this->id);
  2029. if ($this->db->query($sql)) {
  2030. $this->mode_reglement_id = $id;
  2031. // for supplier
  2032. if (get_class($this) == 'Fournisseur') {
  2033. $this->mode_reglement_supplier_id = $id;
  2034. }
  2035. return 1;
  2036. } else {
  2037. dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
  2038. $this->error = $this->db->error();
  2039. return -1;
  2040. }
  2041. } else {
  2042. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  2043. $this->error = 'Status of the object is incompatible '.$this->statut;
  2044. return -2;
  2045. }
  2046. }
  2047. /**
  2048. * Change the multicurrency code
  2049. *
  2050. * @param string $code multicurrency code
  2051. * @return int >0 if OK, <0 if KO
  2052. */
  2053. public function setMulticurrencyCode($code)
  2054. {
  2055. dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
  2056. if ($this->statut >= 0 || $this->element == 'societe') {
  2057. $fieldname = 'multicurrency_code';
  2058. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2059. $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
  2060. $sql .= ' WHERE rowid='.((int) $this->id);
  2061. if ($this->db->query($sql)) {
  2062. $this->multicurrency_code = $code;
  2063. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  2064. if ($rate) {
  2065. $this->setMulticurrencyRate($rate, 2);
  2066. }
  2067. return 1;
  2068. } else {
  2069. dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
  2070. $this->error = $this->db->error();
  2071. return -1;
  2072. }
  2073. } else {
  2074. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  2075. $this->error = 'Status of the object is incompatible '.$this->statut;
  2076. return -2;
  2077. }
  2078. }
  2079. /**
  2080. * Change the multicurrency rate
  2081. *
  2082. * @param double $rate multicurrency rate
  2083. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  2084. * @return int >0 if OK, <0 if KO
  2085. */
  2086. public function setMulticurrencyRate($rate, $mode = 1)
  2087. {
  2088. dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
  2089. if ($this->statut >= 0 || $this->element == 'societe') {
  2090. $fieldname = 'multicurrency_tx';
  2091. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2092. $sql .= " SET ".$fieldname." = ".((float) $rate);
  2093. $sql .= ' WHERE rowid='.((int) $this->id);
  2094. if ($this->db->query($sql)) {
  2095. $this->multicurrency_tx = $rate;
  2096. // Update line price
  2097. if (!empty($this->lines)) {
  2098. foreach ($this->lines as &$line) {
  2099. // Amounts in company currency will be recalculated
  2100. if ($mode == 1) {
  2101. $line->subprice = 0;
  2102. }
  2103. // Amounts in foreign currency will be recalculated
  2104. if ($mode == 2) {
  2105. $line->multicurrency_subprice = 0;
  2106. }
  2107. switch ($this->element) {
  2108. case 'propal':
  2109. $this->updateline(
  2110. $line->id,
  2111. $line->subprice,
  2112. $line->qty,
  2113. $line->remise_percent,
  2114. $line->tva_tx,
  2115. $line->localtax1_tx,
  2116. $line->localtax2_tx,
  2117. ($line->description ? $line->description : $line->desc),
  2118. 'HT',
  2119. $line->info_bits,
  2120. $line->special_code,
  2121. $line->fk_parent_line,
  2122. $line->skip_update_total,
  2123. $line->fk_fournprice,
  2124. $line->pa_ht,
  2125. $line->label,
  2126. $line->product_type,
  2127. $line->date_start,
  2128. $line->date_end,
  2129. $line->array_options,
  2130. $line->fk_unit,
  2131. $line->multicurrency_subprice
  2132. );
  2133. break;
  2134. case 'commande':
  2135. $this->updateline(
  2136. $line->id,
  2137. ($line->description ? $line->description : $line->desc),
  2138. $line->subprice,
  2139. $line->qty,
  2140. $line->remise_percent,
  2141. $line->tva_tx,
  2142. $line->localtax1_tx,
  2143. $line->localtax2_tx,
  2144. 'HT',
  2145. $line->info_bits,
  2146. $line->date_start,
  2147. $line->date_end,
  2148. $line->product_type,
  2149. $line->fk_parent_line,
  2150. $line->skip_update_total,
  2151. $line->fk_fournprice,
  2152. $line->pa_ht,
  2153. $line->label,
  2154. $line->special_code,
  2155. $line->array_options,
  2156. $line->fk_unit,
  2157. $line->multicurrency_subprice
  2158. );
  2159. break;
  2160. case 'facture':
  2161. $this->updateline(
  2162. $line->id,
  2163. ($line->description ? $line->description : $line->desc),
  2164. $line->subprice,
  2165. $line->qty,
  2166. $line->remise_percent,
  2167. $line->date_start,
  2168. $line->date_end,
  2169. $line->tva_tx,
  2170. $line->localtax1_tx,
  2171. $line->localtax2_tx,
  2172. 'HT',
  2173. $line->info_bits,
  2174. $line->product_type,
  2175. $line->fk_parent_line,
  2176. $line->skip_update_total,
  2177. $line->fk_fournprice,
  2178. $line->pa_ht,
  2179. $line->label,
  2180. $line->special_code,
  2181. $line->array_options,
  2182. $line->situation_percent,
  2183. $line->fk_unit,
  2184. $line->multicurrency_subprice
  2185. );
  2186. break;
  2187. case 'supplier_proposal':
  2188. $this->updateline(
  2189. $line->id,
  2190. $line->subprice,
  2191. $line->qty,
  2192. $line->remise_percent,
  2193. $line->tva_tx,
  2194. $line->localtax1_tx,
  2195. $line->localtax2_tx,
  2196. ($line->description ? $line->description : $line->desc),
  2197. 'HT',
  2198. $line->info_bits,
  2199. $line->special_code,
  2200. $line->fk_parent_line,
  2201. $line->skip_update_total,
  2202. $line->fk_fournprice,
  2203. $line->pa_ht,
  2204. $line->label,
  2205. $line->product_type,
  2206. $line->array_options,
  2207. $line->ref_fourn,
  2208. $line->multicurrency_subprice
  2209. );
  2210. break;
  2211. case 'order_supplier':
  2212. $this->updateline(
  2213. $line->id,
  2214. ($line->description ? $line->description : $line->desc),
  2215. $line->subprice,
  2216. $line->qty,
  2217. $line->remise_percent,
  2218. $line->tva_tx,
  2219. $line->localtax1_tx,
  2220. $line->localtax2_tx,
  2221. 'HT',
  2222. $line->info_bits,
  2223. $line->product_type,
  2224. false,
  2225. $line->date_start,
  2226. $line->date_end,
  2227. $line->array_options,
  2228. $line->fk_unit,
  2229. $line->multicurrency_subprice,
  2230. $line->ref_supplier
  2231. );
  2232. break;
  2233. case 'invoice_supplier':
  2234. $this->updateline(
  2235. $line->id,
  2236. ($line->description ? $line->description : $line->desc),
  2237. $line->subprice,
  2238. $line->tva_tx,
  2239. $line->localtax1_tx,
  2240. $line->localtax2_tx,
  2241. $line->qty,
  2242. 0,
  2243. 'HT',
  2244. $line->info_bits,
  2245. $line->product_type,
  2246. $line->remise_percent,
  2247. false,
  2248. $line->date_start,
  2249. $line->date_end,
  2250. $line->array_options,
  2251. $line->fk_unit,
  2252. $line->multicurrency_subprice,
  2253. $line->ref_supplier
  2254. );
  2255. break;
  2256. default:
  2257. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  2258. break;
  2259. }
  2260. }
  2261. }
  2262. return 1;
  2263. } else {
  2264. dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
  2265. $this->error = $this->db->error();
  2266. return -1;
  2267. }
  2268. } else {
  2269. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  2270. $this->error = 'Status of the object is incompatible '.$this->statut;
  2271. return -2;
  2272. }
  2273. }
  2274. /**
  2275. * Change the payments terms
  2276. *
  2277. * @param int $id Id of new payment terms
  2278. * @return int >0 if OK, <0 if KO
  2279. */
  2280. public function setPaymentTerms($id)
  2281. {
  2282. dol_syslog(get_class($this).'::setPaymentTerms('.$id.')');
  2283. if ($this->statut >= 0 || $this->element == 'societe') {
  2284. // TODO uniformize field name
  2285. $fieldname = 'fk_cond_reglement';
  2286. if ($this->element == 'societe') {
  2287. $fieldname = 'cond_reglement';
  2288. }
  2289. if (get_class($this) == 'Fournisseur') {
  2290. $fieldname = 'cond_reglement_supplier';
  2291. }
  2292. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2293. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2294. $sql .= ' WHERE rowid='.((int) $this->id);
  2295. if ($this->db->query($sql)) {
  2296. $this->cond_reglement_id = $id;
  2297. // for supplier
  2298. if (get_class($this) == 'Fournisseur') {
  2299. $this->cond_reglement_supplier_id = $id;
  2300. }
  2301. $this->cond_reglement = $id; // for compatibility
  2302. return 1;
  2303. } else {
  2304. dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
  2305. $this->error = $this->db->error();
  2306. return -1;
  2307. }
  2308. } else {
  2309. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  2310. $this->error = 'Status of the object is incompatible '.$this->statut;
  2311. return -2;
  2312. }
  2313. }
  2314. /**
  2315. * Change the transport mode methods
  2316. *
  2317. * @param int $id Id of transport mode
  2318. * @return int >0 if OK, <0 if KO
  2319. */
  2320. public function setTransportMode($id)
  2321. {
  2322. dol_syslog(get_class($this).'::setTransportMode('.$id.')');
  2323. if ($this->statut >= 0 || $this->element == 'societe') {
  2324. $fieldname = 'fk_transport_mode';
  2325. if ($this->element == 'societe') {
  2326. $fieldname = 'transport_mode';
  2327. }
  2328. if (get_class($this) == 'Fournisseur') {
  2329. $fieldname = 'transport_mode_supplier';
  2330. }
  2331. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2332. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2333. $sql .= ' WHERE rowid='.((int) $this->id);
  2334. if ($this->db->query($sql)) {
  2335. $this->transport_mode_id = $id;
  2336. // for supplier
  2337. if (get_class($this) == 'Fournisseur') {
  2338. $this->transport_mode_supplier_id = $id;
  2339. }
  2340. return 1;
  2341. } else {
  2342. dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
  2343. $this->error = $this->db->error();
  2344. return -1;
  2345. }
  2346. } else {
  2347. dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
  2348. $this->error = 'Status of the object is incompatible '.$this->statut;
  2349. return -2;
  2350. }
  2351. }
  2352. /**
  2353. * Change the retained warranty payments terms
  2354. *
  2355. * @param int $id Id of new payment terms
  2356. * @return int >0 if OK, <0 if KO
  2357. */
  2358. public function setRetainedWarrantyPaymentTerms($id)
  2359. {
  2360. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
  2361. if ($this->statut >= 0 || $this->element == 'societe') {
  2362. $fieldname = 'retained_warranty_fk_cond_reglement';
  2363. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2364. $sql .= " SET ".$fieldname." = ".((int) $id);
  2365. $sql .= ' WHERE rowid='.((int) $this->id);
  2366. if ($this->db->query($sql)) {
  2367. $this->retained_warranty_fk_cond_reglement = $id;
  2368. return 1;
  2369. } else {
  2370. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
  2371. $this->error = $this->db->error();
  2372. return -1;
  2373. }
  2374. } else {
  2375. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  2376. $this->error = 'Status of the object is incompatible '.$this->statut;
  2377. return -2;
  2378. }
  2379. }
  2380. /**
  2381. * Define delivery address
  2382. * @deprecated
  2383. *
  2384. * @param int $id Address id
  2385. * @return int <0 si ko, >0 si ok
  2386. */
  2387. public function setDeliveryAddress($id)
  2388. {
  2389. $fieldname = 'fk_delivery_address';
  2390. if ($this->element == 'delivery' || $this->element == 'shipping') {
  2391. $fieldname = 'fk_address';
  2392. }
  2393. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".((int) $id);
  2394. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
  2395. if ($this->db->query($sql)) {
  2396. $this->fk_delivery_address = $id;
  2397. return 1;
  2398. } else {
  2399. $this->error = $this->db->error();
  2400. dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
  2401. return -1;
  2402. }
  2403. }
  2404. /**
  2405. * Change the shipping method
  2406. *
  2407. * @param int $shipping_method_id Id of shipping method
  2408. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2409. * @param User $userused Object user
  2410. *
  2411. * @return int 1 if OK, 0 if KO
  2412. */
  2413. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  2414. {
  2415. global $user;
  2416. if (empty($userused)) {
  2417. $userused = $user;
  2418. }
  2419. $error = 0;
  2420. if (!$this->table_element) {
  2421. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2422. return -1;
  2423. }
  2424. $this->db->begin();
  2425. if ($shipping_method_id < 0) {
  2426. $shipping_method_id = 'NULL';
  2427. }
  2428. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  2429. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2430. $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
  2431. $sql .= " WHERE rowid=".((int) $this->id);
  2432. $resql = $this->db->query($sql);
  2433. if (!$resql) {
  2434. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  2435. $this->error = $this->db->lasterror();
  2436. $error++;
  2437. } else {
  2438. if (!$notrigger) {
  2439. // Call trigger
  2440. $this->context = array('shippingmethodupdate'=>1);
  2441. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2442. if ($result < 0) {
  2443. $error++;
  2444. }
  2445. // End call trigger
  2446. }
  2447. }
  2448. if ($error) {
  2449. $this->db->rollback();
  2450. return -1;
  2451. } else {
  2452. $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
  2453. $this->db->commit();
  2454. return 1;
  2455. }
  2456. }
  2457. /**
  2458. * Change the warehouse
  2459. *
  2460. * @param int $warehouse_id Id of warehouse
  2461. * @return int 1 if OK, 0 if KO
  2462. */
  2463. public function setWarehouse($warehouse_id)
  2464. {
  2465. if (!$this->table_element) {
  2466. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2467. return -1;
  2468. }
  2469. if ($warehouse_id < 0) {
  2470. $warehouse_id = 'NULL';
  2471. }
  2472. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  2473. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2474. $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
  2475. $sql .= " WHERE rowid=".((int) $this->id);
  2476. if ($this->db->query($sql)) {
  2477. $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
  2478. return 1;
  2479. } else {
  2480. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  2481. $this->error = $this->db->error();
  2482. return 0;
  2483. }
  2484. }
  2485. /**
  2486. * Set last model used by doc generator
  2487. *
  2488. * @param User $user User object that make change
  2489. * @param string $modelpdf Modele name
  2490. * @return int <0 if KO, >0 if OK
  2491. */
  2492. public function setDocModel($user, $modelpdf)
  2493. {
  2494. if (!$this->table_element) {
  2495. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2496. return -1;
  2497. }
  2498. $newmodelpdf = dol_trunc($modelpdf, 255);
  2499. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2500. $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  2501. $sql .= " WHERE rowid = ".((int) $this->id);
  2502. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  2503. $resql = $this->db->query($sql);
  2504. if ($resql) {
  2505. $this->model_pdf = $modelpdf;
  2506. $this->modelpdf = $modelpdf; // For bakward compatibility
  2507. return 1;
  2508. } else {
  2509. dol_print_error($this->db);
  2510. return 0;
  2511. }
  2512. }
  2513. /**
  2514. * Change the bank account
  2515. *
  2516. * @param int $fk_account Id of bank account
  2517. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2518. * @param User $userused Object user
  2519. * @return int 1 if OK, 0 if KO
  2520. */
  2521. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2522. {
  2523. global $user;
  2524. if (empty($userused)) {
  2525. $userused = $user;
  2526. }
  2527. $error = 0;
  2528. if (!$this->table_element) {
  2529. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2530. return -1;
  2531. }
  2532. $this->db->begin();
  2533. if ($fk_account < 0) {
  2534. $fk_account = 'NULL';
  2535. }
  2536. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  2537. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2538. $sql .= " SET fk_account = ".((int) $fk_account);
  2539. $sql .= " WHERE rowid=".((int) $this->id);
  2540. $resql = $this->db->query($sql);
  2541. if (!$resql) {
  2542. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  2543. $this->error = $this->db->lasterror();
  2544. $error++;
  2545. } else {
  2546. if (!$notrigger) {
  2547. // Call trigger
  2548. $this->context = array('bankaccountupdate'=>1);
  2549. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2550. if ($result < 0) {
  2551. $error++;
  2552. }
  2553. // End call trigger
  2554. }
  2555. }
  2556. if ($error) {
  2557. $this->db->rollback();
  2558. return -1;
  2559. } else {
  2560. $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
  2561. $this->db->commit();
  2562. return 1;
  2563. }
  2564. }
  2565. // TODO: Move line related operations to CommonObjectLine?
  2566. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2567. /**
  2568. * Save a new position (field rang) for details lines.
  2569. * You can choose to set position for lines with already a position or lines without any position defined.
  2570. *
  2571. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2572. * @param string $rowidorder ASC or DESC
  2573. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2574. * @return int <0 if KO, >0 if OK
  2575. */
  2576. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2577. {
  2578. // phpcs:enable
  2579. if (!$this->table_element_line) {
  2580. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2581. return -1;
  2582. }
  2583. if (!$this->fk_element) {
  2584. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2585. return -1;
  2586. }
  2587. // Count number of lines to reorder (according to choice $renum)
  2588. $nl = 0;
  2589. $sql = "SELECT count(rowid) FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  2590. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2591. if (!$renum) {
  2592. $sql .= ' AND rang = 0';
  2593. }
  2594. if ($renum) {
  2595. $sql .= ' AND rang <> 0';
  2596. }
  2597. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  2598. $resql = $this->db->query($sql);
  2599. if ($resql) {
  2600. $row = $this->db->fetch_row($resql);
  2601. $nl = $row[0];
  2602. } else {
  2603. dol_print_error($this->db);
  2604. }
  2605. if ($nl > 0) {
  2606. // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
  2607. $rows = array();
  2608. // We first search all lines that are parent lines (for multilevel details lines)
  2609. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  2610. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2611. if ($fk_parent_line) {
  2612. $sql .= ' AND fk_parent_line IS NULL';
  2613. }
  2614. $sql .= " ORDER BY rang ASC, rowid ".$rowidorder;
  2615. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  2616. $resql = $this->db->query($sql);
  2617. if ($resql) {
  2618. $i = 0;
  2619. $num = $this->db->num_rows($resql);
  2620. while ($i < $num) {
  2621. $row = $this->db->fetch_row($resql);
  2622. $rows[] = $row[0]; // Add parent line into array rows
  2623. $childrens = $this->getChildrenOfLine($row[0]);
  2624. if (!empty($childrens)) {
  2625. foreach ($childrens as $child) {
  2626. array_push($rows, $child);
  2627. }
  2628. }
  2629. $i++;
  2630. }
  2631. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2632. if (!empty($rows)) {
  2633. foreach ($rows as $key => $row) {
  2634. $this->updateRangOfLine($row, ($key + 1));
  2635. }
  2636. }
  2637. } else {
  2638. dol_print_error($this->db);
  2639. }
  2640. }
  2641. return 1;
  2642. }
  2643. /**
  2644. * Get children of line
  2645. *
  2646. * @param int $id Id of parent line
  2647. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2648. * @return array Array with list of children lines id
  2649. */
  2650. public function getChildrenOfLine($id, $includealltree = 0)
  2651. {
  2652. $rows = array();
  2653. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  2654. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2655. $sql .= ' AND fk_parent_line = '.((int) $id);
  2656. $sql .= ' ORDER BY rang ASC';
  2657. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
  2658. $resql = $this->db->query($sql);
  2659. if ($resql) {
  2660. if ($this->db->num_rows($resql) > 0) {
  2661. while ($row = $this->db->fetch_row($resql)) {
  2662. $rows[] = $row[0];
  2663. if (!empty($includealltree)) {
  2664. $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2665. }
  2666. }
  2667. }
  2668. }
  2669. return $rows;
  2670. }
  2671. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2672. /**
  2673. * Update a line to have a lower rank
  2674. *
  2675. * @param int $rowid Id of line
  2676. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2677. * @return void
  2678. */
  2679. public function line_up($rowid, $fk_parent_line = true)
  2680. {
  2681. // phpcs:enable
  2682. $this->line_order(false, 'ASC', $fk_parent_line);
  2683. // Get rang of line
  2684. $rang = $this->getRangOfLine($rowid);
  2685. // Update position of line
  2686. $this->updateLineUp($rowid, $rang);
  2687. }
  2688. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2689. /**
  2690. * Update a line to have a higher rank
  2691. *
  2692. * @param int $rowid Id of line
  2693. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2694. * @return void
  2695. */
  2696. public function line_down($rowid, $fk_parent_line = true)
  2697. {
  2698. // phpcs:enable
  2699. $this->line_order(false, 'ASC', $fk_parent_line);
  2700. // Get rang of line
  2701. $rang = $this->getRangOfLine($rowid);
  2702. // Get max value for rang
  2703. $max = $this->line_max();
  2704. // Update position of line
  2705. $this->updateLineDown($rowid, $rang, $max);
  2706. }
  2707. /**
  2708. * Update position of line (rang)
  2709. *
  2710. * @param int $rowid Id of line
  2711. * @param int $rang Position
  2712. * @return int <0 if KO, >0 if OK
  2713. */
  2714. public function updateRangOfLine($rowid, $rang)
  2715. {
  2716. global $hookmanager;
  2717. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2718. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction'))) {
  2719. $fieldposition = 'position';
  2720. }
  2721. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2722. $sql .= ' WHERE rowid = '.((int) $rowid);
  2723. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2724. if (!$this->db->query($sql)) {
  2725. dol_print_error($this->db);
  2726. return -1;
  2727. } else {
  2728. $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
  2729. $action='';
  2730. $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
  2731. return 1;
  2732. }
  2733. }
  2734. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2735. /**
  2736. * Update position of line with ajax (rang)
  2737. *
  2738. * @param array $rows Array of rows
  2739. * @return void
  2740. */
  2741. public function line_ajaxorder($rows)
  2742. {
  2743. // phpcs:enable
  2744. $num = count($rows);
  2745. for ($i = 0; $i < $num; $i++) {
  2746. $this->updateRangOfLine($rows[$i], ($i + 1));
  2747. }
  2748. }
  2749. /**
  2750. * Update position of line up (rang)
  2751. *
  2752. * @param int $rowid Id of line
  2753. * @param int $rang Position
  2754. * @return void
  2755. */
  2756. public function updateLineUp($rowid, $rang)
  2757. {
  2758. if ($rang > 1) {
  2759. $fieldposition = 'rang';
  2760. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
  2761. $fieldposition = 'position';
  2762. }
  2763. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2764. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2765. $sql .= ' AND rang = '.((int) ($rang - 1));
  2766. if ($this->db->query($sql)) {
  2767. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
  2768. $sql .= ' WHERE rowid = '.((int) $rowid);
  2769. if (!$this->db->query($sql)) {
  2770. dol_print_error($this->db);
  2771. }
  2772. } else {
  2773. dol_print_error($this->db);
  2774. }
  2775. }
  2776. }
  2777. /**
  2778. * Update position of line down (rang)
  2779. *
  2780. * @param int $rowid Id of line
  2781. * @param int $rang Position
  2782. * @param int $max Max
  2783. * @return void
  2784. */
  2785. public function updateLineDown($rowid, $rang, $max)
  2786. {
  2787. if ($rang < $max) {
  2788. $fieldposition = 'rang';
  2789. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
  2790. $fieldposition = 'position';
  2791. }
  2792. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2793. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2794. $sql .= ' AND rang = '.((int) ($rang + 1));
  2795. if ($this->db->query($sql)) {
  2796. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
  2797. $sql .= ' WHERE rowid = '.((int) $rowid);
  2798. if (!$this->db->query($sql)) {
  2799. dol_print_error($this->db);
  2800. }
  2801. } else {
  2802. dol_print_error($this->db);
  2803. }
  2804. }
  2805. }
  2806. /**
  2807. * Get position of line (rang)
  2808. *
  2809. * @param int $rowid Id of line
  2810. * @return int Value of rang in table of lines
  2811. */
  2812. public function getRangOfLine($rowid)
  2813. {
  2814. $sql = "SELECT rang FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  2815. $sql .= " WHERE rowid = ".((int) $rowid);
  2816. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  2817. $resql = $this->db->query($sql);
  2818. if ($resql) {
  2819. $row = $this->db->fetch_row($resql);
  2820. return $row[0];
  2821. }
  2822. }
  2823. /**
  2824. * Get rowid of the line relative to its position
  2825. *
  2826. * @param int $rang Rang value
  2827. * @return int Rowid of the line
  2828. */
  2829. public function getIdOfLine($rang)
  2830. {
  2831. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  2832. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2833. $sql .= " AND rang = ".((int) $rang);
  2834. $resql = $this->db->query($sql);
  2835. if ($resql) {
  2836. $row = $this->db->fetch_row($resql);
  2837. return $row[0];
  2838. }
  2839. }
  2840. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2841. /**
  2842. * Get max value used for position of line (rang)
  2843. *
  2844. * @param int $fk_parent_line Parent line id
  2845. * @return int Max value of rang in table of lines
  2846. */
  2847. public function line_max($fk_parent_line = 0)
  2848. {
  2849. // phpcs:enable
  2850. $positionfield = 'rang';
  2851. if ($this->table_element == 'bom_bom') {
  2852. $positionfield = 'position';
  2853. }
  2854. // Search the last rang with fk_parent_line
  2855. if ($fk_parent_line) {
  2856. $sql = "SELECT max(".$positionfield.") FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  2857. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2858. $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
  2859. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2860. $resql = $this->db->query($sql);
  2861. if ($resql) {
  2862. $row = $this->db->fetch_row($resql);
  2863. if (!empty($row[0])) {
  2864. return $row[0];
  2865. } else {
  2866. return $this->getRangOfLine($fk_parent_line);
  2867. }
  2868. }
  2869. } else {
  2870. // If not, search the last rang of element
  2871. $sql = "SELECT max(".$positionfield.") FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  2872. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2873. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2874. $resql = $this->db->query($sql);
  2875. if ($resql) {
  2876. $row = $this->db->fetch_row($resql);
  2877. return $row[0];
  2878. }
  2879. }
  2880. }
  2881. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2882. /**
  2883. * Update external ref of element
  2884. *
  2885. * @param string $ref_ext Update field ref_ext
  2886. * @return int <0 if KO, >0 if OK
  2887. */
  2888. public function update_ref_ext($ref_ext)
  2889. {
  2890. // phpcs:enable
  2891. if (!$this->table_element) {
  2892. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  2893. return -1;
  2894. }
  2895. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2896. $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  2897. $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
  2898. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  2899. if ($this->db->query($sql)) {
  2900. $this->ref_ext = $ref_ext;
  2901. return 1;
  2902. } else {
  2903. $this->error = $this->db->error();
  2904. return -1;
  2905. }
  2906. }
  2907. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2908. /**
  2909. * Update note of element
  2910. *
  2911. * @param string $note New value for note
  2912. * @param string $suffix '', '_public' or '_private'
  2913. * @return int <0 if KO, >0 if OK
  2914. */
  2915. public function update_note($note, $suffix = '')
  2916. {
  2917. // phpcs:enable
  2918. global $user;
  2919. if (!$this->table_element) {
  2920. $this->error = 'update_note was called on objet with property table_element not defined';
  2921. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  2922. return -1;
  2923. }
  2924. if (!in_array($suffix, array('', '_public', '_private'))) {
  2925. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  2926. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  2927. return -2;
  2928. }
  2929. $newsuffix = $suffix;
  2930. // Special cas
  2931. if ($this->table_element == 'product' && $newsuffix == '_private') {
  2932. $newsuffix = '';
  2933. }
  2934. if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  2935. $fieldusermod = "fk_user_mod";
  2936. } elseif ($this->table_element == 'ecm_files') {
  2937. $fieldusermod = "fk_user_m";
  2938. } else {
  2939. $fieldusermod = "fk_user_modif";
  2940. }
  2941. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2942. $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
  2943. $sql .= ", ".$fieldusermod." = ".((int) $user->id);
  2944. $sql .= " WHERE rowid = ".((int) $this->id);
  2945. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  2946. if ($this->db->query($sql)) {
  2947. if ($suffix == '_public') {
  2948. $this->note_public = $note;
  2949. } elseif ($suffix == '_private') {
  2950. $this->note_private = $note;
  2951. } else {
  2952. $this->note = $note; // deprecated
  2953. $this->note_private = $note;
  2954. }
  2955. return 1;
  2956. } else {
  2957. $this->error = $this->db->lasterror();
  2958. return -1;
  2959. }
  2960. }
  2961. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2962. /**
  2963. * Update public note (kept for backward compatibility)
  2964. *
  2965. * @param string $note New value for note
  2966. * @return int <0 if KO, >0 if OK
  2967. * @deprecated
  2968. * @see update_note()
  2969. */
  2970. public function update_note_public($note)
  2971. {
  2972. // phpcs:enable
  2973. return $this->update_note($note, '_public');
  2974. }
  2975. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2976. /**
  2977. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  2978. * Must be called at end of methods addline or updateline.
  2979. *
  2980. * @param int $exclspec >0 = Exclude special product (product_type=9)
  2981. * @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
  2982. * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object.
  2983. * @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.
  2984. * @return int <0 if KO, >0 if OK
  2985. */
  2986. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  2987. {
  2988. // phpcs:enable
  2989. global $conf, $hookmanager, $action;
  2990. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  2991. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  2992. if ($reshook > 0) {
  2993. return 1; // replacement code
  2994. } elseif ($reshook < 0) {
  2995. return -1; // failure
  2996. } // reshook = 0 => execute normal code
  2997. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  2998. $MODULE = "";
  2999. if ($this->element == 'propal') {
  3000. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  3001. } elseif ($this->element == 'commande' || $this->element == 'order') {
  3002. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  3003. } elseif ($this->element == 'facture' || $this->element == 'invoice') {
  3004. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  3005. } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier') {
  3006. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  3007. } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
  3008. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  3009. } elseif ($this->element == 'supplier_proposal') {
  3010. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  3011. }
  3012. if (!empty($MODULE)) {
  3013. if (!empty($conf->global->$MODULE)) {
  3014. $modsactivated = explode(',', $conf->global->$MODULE);
  3015. foreach ($modsactivated as $mod) {
  3016. if ($conf->$mod->enabled) {
  3017. return 1; // update was disabled by specific setup
  3018. }
  3019. }
  3020. }
  3021. }
  3022. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  3023. if ($roundingadjust == '-1') {
  3024. $roundingadjust = 'auto'; // For backward compatibility
  3025. }
  3026. $forcedroundingmode = $roundingadjust;
  3027. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
  3028. $forcedroundingmode = $conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
  3029. } elseif ($forcedroundingmode == 'auto') {
  3030. $forcedroundingmode = '0';
  3031. }
  3032. $error = 0;
  3033. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  3034. // Define constants to find lines to sum
  3035. $fieldtva = 'total_tva';
  3036. $fieldlocaltax1 = 'total_localtax1';
  3037. $fieldlocaltax2 = 'total_localtax2';
  3038. $fieldup = 'subprice';
  3039. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3040. $fieldtva = 'tva';
  3041. $fieldup = 'pu_ht';
  3042. }
  3043. if ($this->element == 'expensereport') {
  3044. $fieldup = 'value_unit';
  3045. }
  3046. $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,";
  3047. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  3048. if ($this->table_element_line == 'facturedet') {
  3049. $sql .= ', situation_percent';
  3050. }
  3051. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3052. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  3053. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3054. if ($exclspec) {
  3055. $product_field = 'product_type';
  3056. if ($this->table_element_line == 'contratdet') {
  3057. $product_field = ''; // contratdet table has no product_type field
  3058. }
  3059. if ($product_field) {
  3060. $sql .= " AND ".$product_field." <> 9";
  3061. }
  3062. }
  3063. $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
  3064. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3065. $resql = $this->db->query($sql);
  3066. if ($resql) {
  3067. $this->total_ht = 0;
  3068. $this->total_tva = 0;
  3069. $this->total_localtax1 = 0;
  3070. $this->total_localtax2 = 0;
  3071. $this->total_ttc = 0;
  3072. $total_ht_by_vats = array();
  3073. $total_tva_by_vats = array();
  3074. $total_ttc_by_vats = array();
  3075. $this->multicurrency_total_ht = 0;
  3076. $this->multicurrency_total_tva = 0;
  3077. $this->multicurrency_total_ttc = 0;
  3078. $num = $this->db->num_rows($resql);
  3079. $i = 0;
  3080. while ($i < $num) {
  3081. $obj = $this->db->fetch_object($resql);
  3082. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  3083. $parameters = array('fk_element' => $obj->rowid);
  3084. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3085. 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'
  3086. // This part of code is to fix data. We should not call it too often.
  3087. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  3088. $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);
  3089. $diff_when_using_price_ht = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); // If price was set with tax price adn unit price HT has a low number of digits, then we may have a diff on recalculation from unit price HT.
  3090. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  3091. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
  3092. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  3093. if ($diff_when_using_price_ht && $diff_on_current_total) {
  3094. $sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2])." WHERE rowid = ".((int) $obj->rowid);
  3095. dol_syslog('We found unconsistent data into detailed line (diff_when_using_price_ht = '.$diff_when_using_price_ht.' and diff_on_current_total = '.$diff_on_current_total.') 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, LOG_WARNING);
  3096. $resqlfix = $this->db->query($sqlfix);
  3097. if (!$resqlfix) {
  3098. dol_print_error($this->db, 'Failed to update line');
  3099. }
  3100. $obj->total_tva = $tmpcal[1];
  3101. $obj->total_ttc = $tmpcal[2];
  3102. }
  3103. }
  3104. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  3105. $this->total_tva += $obj->total_tva;
  3106. $this->total_localtax1 += $obj->total_localtax1;
  3107. $this->total_localtax2 += $obj->total_localtax2;
  3108. $this->total_ttc += $obj->total_ttc;
  3109. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  3110. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  3111. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  3112. if (!isset($total_ht_by_vats[$obj->vatrate])) {
  3113. $total_ht_by_vats[$obj->vatrate] = 0;
  3114. }
  3115. if (!isset($total_tva_by_vats[$obj->vatrate])) {
  3116. $total_tva_by_vats[$obj->vatrate] = 0;
  3117. }
  3118. if (!isset($total_ttc_by_vats[$obj->vatrate])) {
  3119. $total_ttc_by_vats[$obj->vatrate] = 0;
  3120. }
  3121. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  3122. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  3123. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  3124. if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  3125. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  3126. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  3127. //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";
  3128. if ($diff) {
  3129. if (abs($diff) > 0.1) {
  3130. $errmsg = 'A rounding difference was detected into TOTAL but is too high to be corrected. Some data in your line may be corrupted. Try to edit each line manually.';
  3131. dol_syslog($errmsg, LOG_WARNING);
  3132. dol_print_error('', $errmsg);
  3133. exit;
  3134. }
  3135. $sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".price2num($obj->total_tva - $diff).", total_ttc = ".price2num($obj->total_ttc - $diff)." WHERE rowid = ".((int) $obj->rowid);
  3136. 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);
  3137. $resqlfix = $this->db->query($sqlfix);
  3138. if (!$resqlfix) {
  3139. dol_print_error($this->db, 'Failed to update line');
  3140. }
  3141. $this->total_tva -= $diff;
  3142. $this->total_ttc -= $diff;
  3143. $total_tva_by_vats[$obj->vatrate] -= $diff;
  3144. $total_ttc_by_vats[$obj->vatrate] -= $diff;
  3145. }
  3146. }
  3147. $i++;
  3148. }
  3149. // Add revenue stamp to total
  3150. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  3151. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  3152. // Situations totals
  3153. if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
  3154. $prev_sits = $this->get_prev_sits();
  3155. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  3156. $this->total_ht -= $sit->total_ht;
  3157. $this->total_tva -= $sit->total_tva;
  3158. $this->total_localtax1 -= $sit->total_localtax1;
  3159. $this->total_localtax2 -= $sit->total_localtax2;
  3160. $this->total_ttc -= $sit->total_ttc;
  3161. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  3162. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  3163. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  3164. }
  3165. }
  3166. $this->db->free($resql);
  3167. // Now update global field total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_*
  3168. $fieldht = 'total_ht';
  3169. $fieldtva = 'tva';
  3170. $fieldlocaltax1 = 'localtax1';
  3171. $fieldlocaltax2 = 'localtax2';
  3172. $fieldttc = 'total_ttc';
  3173. // Specific code for backward compatibility with old field names
  3174. if ($this->element == 'facture' || $this->element == 'facturerec') {
  3175. $fieldtva = 'total_tva';
  3176. }
  3177. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3178. $fieldtva = 'total_tva';
  3179. }
  3180. if ($this->element == 'propal') {
  3181. $fieldtva = 'total_tva';
  3182. }
  3183. if ($this->element == 'expensereport') {
  3184. $fieldtva = 'total_tva';
  3185. }
  3186. if ($this->element == 'supplier_proposal') {
  3187. $fieldtva = 'total_tva';
  3188. }
  3189. if ($this->element == 'commande') {
  3190. $fieldtva = 'total_tva';
  3191. }
  3192. if ($this->element == 'order_supplier') {
  3193. $fieldtva = 'total_tva';
  3194. }
  3195. if (empty($nodatabaseupdate)) {
  3196. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element.' SET';
  3197. $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht)).",";
  3198. $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva)).",";
  3199. $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1)).",";
  3200. $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2)).",";
  3201. $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc));
  3202. $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
  3203. $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
  3204. $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
  3205. $sql .= " WHERE rowid = ".((int) $this->id);
  3206. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3207. $resql = $this->db->query($sql);
  3208. if (!$resql) {
  3209. $error++;
  3210. $this->error = $this->db->lasterror();
  3211. $this->errors[] = $this->db->lasterror();
  3212. }
  3213. }
  3214. if (!$error) {
  3215. return 1;
  3216. } else {
  3217. return -1;
  3218. }
  3219. } else {
  3220. dol_print_error($this->db, 'Bad request in update_price');
  3221. return -1;
  3222. }
  3223. }
  3224. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3225. /**
  3226. * Add objects linked in llx_element_element.
  3227. *
  3228. * @param string $origin Linked element type
  3229. * @param int $origin_id Linked element id
  3230. * @param User $f_user User that create
  3231. * @param int $notrigger 1=Does not execute triggers, 0=execute triggers
  3232. * @return int <=0 if KO, >0 if OK
  3233. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  3234. */
  3235. public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
  3236. {
  3237. // phpcs:enable
  3238. global $user, $hookmanager, $action;
  3239. $origin = (!empty($origin) ? $origin : $this->origin);
  3240. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  3241. $f_user = isset($f_user) ? $f_user : $user;
  3242. // Special case
  3243. if ($origin == 'order') {
  3244. $origin = 'commande';
  3245. }
  3246. if ($origin == 'invoice') {
  3247. $origin = 'facture';
  3248. }
  3249. if ($origin == 'invoice_template') {
  3250. $origin = 'facturerec';
  3251. }
  3252. if ($origin == 'supplierorder') {
  3253. $origin = 'order_supplier';
  3254. }
  3255. // Elements of the core modules which have `$module` property but may to which we don't want to prefix module part to the element name for finding the linked object in llx_element_element.
  3256. // It's because an entry for this element may be exist in llx_element_element before this modification (version <=14.2) and ave named only with their element name in fk_source or fk_target.
  3257. $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization');
  3258. // Add module part to target type if object has $module property and isn't in core modules.
  3259. $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
  3260. $parameters = array('targettype'=>$targettype);
  3261. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3262. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3263. if ($reshook > 0) {
  3264. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3265. }
  3266. $this->db->begin();
  3267. $error = 0;
  3268. $sql = "INSERT INTO " . MAIN_DB_PREFIX . "element_element (";
  3269. $sql .= "fk_source";
  3270. $sql .= ", sourcetype";
  3271. $sql .= ", fk_target";
  3272. $sql .= ", targettype";
  3273. $sql .= ") VALUES (";
  3274. $sql .= ((int) $origin_id);
  3275. $sql .= ", '" . $this->db->escape($origin) . "'";
  3276. $sql .= ", " . ((int) $this->id);
  3277. $sql .= ", '" . $this->db->escape($targettype) . "'";
  3278. $sql .= ")";
  3279. dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
  3280. if ($this->db->query($sql)) {
  3281. if (!$notrigger) {
  3282. // Call trigger
  3283. $this->context['link_origin'] = $origin;
  3284. $this->context['link_origin_id'] = $origin_id;
  3285. $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
  3286. if ($result < 0) {
  3287. $error++;
  3288. }
  3289. // End call triggers
  3290. }
  3291. } else {
  3292. $this->error = $this->db->lasterror();
  3293. $error++;
  3294. }
  3295. if (!$error) {
  3296. $this->db->commit();
  3297. return 1;
  3298. } else {
  3299. $this->db->rollback();
  3300. return 0;
  3301. }
  3302. }
  3303. /**
  3304. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  3305. * this->linkedObjectsIds array +
  3306. * this->linkedObjects array if $loadalsoobjects = 1
  3307. * Possible usage for parameters:
  3308. * - all parameters empty -> we look all link to current object (current object can be source or target)
  3309. * - source id+type -> will get target list linked to source
  3310. * - target id+type -> will get source list linked to target
  3311. * - source id+type + target type -> will get target list of the type
  3312. * - target id+type + target source -> will get source list of the type
  3313. *
  3314. * @param int $sourceid Object source id (if not defined, id of object)
  3315. * @param string $sourcetype Object source type (if not defined, element name of object)
  3316. * @param int $targetid Object target id (if not defined, id of object)
  3317. * @param string $targettype Object target type (if not defined, elemennt name of object)
  3318. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  3319. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  3320. * @param string $orderby SQL 'ORDER BY' clause
  3321. * @param int $loadalsoobjects Load also array this->linkedObjects (Use 0 to increase performances)
  3322. * @return int <0 if KO, >0 if OK
  3323. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  3324. */
  3325. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  3326. {
  3327. global $conf, $hookmanager, $action;
  3328. $this->linkedObjectsIds = array();
  3329. $this->linkedObjects = array();
  3330. $justsource = false;
  3331. $justtarget = false;
  3332. $withtargettype = false;
  3333. $withsourcetype = false;
  3334. $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
  3335. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3336. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3337. if ($reshook > 0) {
  3338. if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
  3339. if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
  3340. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3341. if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
  3342. }
  3343. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
  3344. $justsource = true; // the source (id and type) is a search criteria
  3345. if (!empty($targettype)) {
  3346. $withtargettype = true;
  3347. }
  3348. }
  3349. if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
  3350. $justtarget = true; // the target (id and type) is a search criteria
  3351. if (!empty($sourcetype)) {
  3352. $withsourcetype = true;
  3353. }
  3354. }
  3355. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3356. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3357. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3358. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3359. /*if (empty($sourceid) && empty($targetid))
  3360. {
  3361. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  3362. return -1;
  3363. }*/
  3364. // Links between objects are stored in table element_element
  3365. $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype';
  3366. $sql .= ' FROM '.MAIN_DB_PREFIX.'element_element';
  3367. $sql .= " WHERE ";
  3368. if ($justsource || $justtarget) {
  3369. if ($justsource) {
  3370. $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3371. if ($withtargettype) {
  3372. $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
  3373. }
  3374. } elseif ($justtarget) {
  3375. $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
  3376. if ($withsourcetype) {
  3377. $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3378. }
  3379. }
  3380. } else {
  3381. $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
  3382. $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
  3383. }
  3384. $sql .= ' ORDER BY '.$orderby;
  3385. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  3386. $resql = $this->db->query($sql);
  3387. if ($resql) {
  3388. $num = $this->db->num_rows($resql);
  3389. $i = 0;
  3390. while ($i < $num) {
  3391. $obj = $this->db->fetch_object($resql);
  3392. if ($justsource || $justtarget) {
  3393. if ($justsource) {
  3394. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3395. } elseif ($justtarget) {
  3396. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3397. }
  3398. } else {
  3399. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
  3400. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3401. }
  3402. if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
  3403. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3404. }
  3405. }
  3406. $i++;
  3407. }
  3408. if (!empty($this->linkedObjectsIds)) {
  3409. $tmparray = $this->linkedObjectsIds;
  3410. foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  3411. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  3412. $module = $element = $subelement = $objecttype;
  3413. $regs = array();
  3414. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  3415. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  3416. $module = $element = $regs[1];
  3417. $subelement = $regs[2];
  3418. }
  3419. $classpath = $element.'/class';
  3420. // To work with non standard classpath or module name
  3421. if ($objecttype == 'facture') {
  3422. $classpath = 'compta/facture/class';
  3423. } elseif ($objecttype == 'facturerec') {
  3424. $classpath = 'compta/facture/class';
  3425. $module = 'facture';
  3426. } elseif ($objecttype == 'propal') {
  3427. $classpath = 'comm/propal/class';
  3428. } elseif ($objecttype == 'supplier_proposal') {
  3429. $classpath = 'supplier_proposal/class';
  3430. } elseif ($objecttype == 'shipping') {
  3431. $classpath = 'expedition/class';
  3432. $subelement = 'expedition';
  3433. $module = 'expedition_bon';
  3434. } elseif ($objecttype == 'delivery') {
  3435. $classpath = 'delivery/class';
  3436. $subelement = 'delivery';
  3437. $module = 'delivery_note';
  3438. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  3439. $classpath = 'fourn/class';
  3440. $module = 'fournisseur';
  3441. } elseif ($objecttype == 'fichinter') {
  3442. $classpath = 'fichinter/class';
  3443. $subelement = 'fichinter';
  3444. $module = 'ficheinter';
  3445. } elseif ($objecttype == 'subscription') {
  3446. $classpath = 'adherents/class';
  3447. $module = 'adherent';
  3448. } elseif ($objecttype == 'contact') {
  3449. $module = 'societe';
  3450. }
  3451. // Set classfile
  3452. $classfile = strtolower($subelement);
  3453. $classname = ucfirst($subelement);
  3454. if ($objecttype == 'order') {
  3455. $classfile = 'commande';
  3456. $classname = 'Commande';
  3457. } elseif ($objecttype == 'invoice_supplier') {
  3458. $classfile = 'fournisseur.facture';
  3459. $classname = 'FactureFournisseur';
  3460. } elseif ($objecttype == 'order_supplier') {
  3461. $classfile = 'fournisseur.commande';
  3462. $classname = 'CommandeFournisseur';
  3463. } elseif ($objecttype == 'supplier_proposal') {
  3464. $classfile = 'supplier_proposal';
  3465. $classname = 'SupplierProposal';
  3466. } elseif ($objecttype == 'facturerec') {
  3467. $classfile = 'facture-rec';
  3468. $classname = 'FactureRec';
  3469. } elseif ($objecttype == 'subscription') {
  3470. $classfile = 'subscription';
  3471. $classname = 'Subscription';
  3472. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  3473. $classpath = 'projet/class';
  3474. $classfile = 'project';
  3475. $classname = 'Project';
  3476. } elseif ($objecttype == 'conferenceorboothattendee') {
  3477. $classpath = 'eventorganization/class';
  3478. $classfile = 'conferenceorboothattendee';
  3479. $classname = 'ConferenceOrBoothAttendee';
  3480. $module = 'eventorganization';
  3481. } elseif ($objecttype == 'conferenceorbooth') {
  3482. $classpath = 'eventorganization/class';
  3483. $classfile = 'conferenceorbooth';
  3484. $classname = 'ConferenceOrBooth';
  3485. $module = 'eventorganization';
  3486. } elseif ($objecttype == 'mo') {
  3487. $classpath = 'mrp/class';
  3488. $classfile = 'mo';
  3489. $classname = 'Mo';
  3490. $module = 'mrp';
  3491. }
  3492. // Here $module, $classfile and $classname are set
  3493. if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
  3494. if ($loadalsoobjects) {
  3495. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  3496. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  3497. if (class_exists($classname)) {
  3498. foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
  3499. $object = new $classname($this->db);
  3500. $ret = $object->fetch($objectid);
  3501. if ($ret >= 0) {
  3502. $this->linkedObjects[$objecttype][$i] = $object;
  3503. }
  3504. }
  3505. }
  3506. }
  3507. } else {
  3508. unset($this->linkedObjectsIds[$objecttype]);
  3509. }
  3510. }
  3511. }
  3512. return 1;
  3513. } else {
  3514. dol_print_error($this->db);
  3515. return -1;
  3516. }
  3517. }
  3518. /**
  3519. * Update object linked of a current object
  3520. *
  3521. * @param int $sourceid Object source id
  3522. * @param string $sourcetype Object source type
  3523. * @param int $targetid Object target id
  3524. * @param string $targettype Object target type
  3525. * @param User $f_user User that create
  3526. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3527. * @return int >0 if OK, <0 if KO
  3528. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3529. */
  3530. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
  3531. {
  3532. global $user;
  3533. $updatesource = false;
  3534. $updatetarget = false;
  3535. $f_user = isset($f_user) ? $f_user : $user;
  3536. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3537. $updatesource = true;
  3538. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3539. $updatetarget = true;
  3540. }
  3541. $this->db->begin();
  3542. $error = 0;
  3543. $sql = "UPDATE " . MAIN_DB_PREFIX . "element_element SET ";
  3544. if ($updatesource) {
  3545. $sql .= "fk_source = " . ((int) $sourceid);
  3546. $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3547. $sql .= " WHERE fk_target = " . ((int) $this->id);
  3548. $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
  3549. } elseif ($updatetarget) {
  3550. $sql .= "fk_target = " . ((int) $targetid);
  3551. $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
  3552. $sql .= " WHERE fk_source = " . ((int) $this->id);
  3553. $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3554. }
  3555. dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
  3556. if ($this->db->query($sql)) {
  3557. if (!$notrigger) {
  3558. // Call trigger
  3559. $this->context['link_source_id'] = $sourceid;
  3560. $this->context['link_source_type'] = $sourcetype;
  3561. $this->context['link_target_id'] = $targetid;
  3562. $this->context['link_target_type'] = $targettype;
  3563. $result = $this->call_trigger('OBJECT_LINK_UPDATE', $f_user);
  3564. if ($result < 0) {
  3565. $error++;
  3566. }
  3567. // End call triggers
  3568. }
  3569. } else {
  3570. $this->error = $this->db->lasterror();
  3571. $error++;
  3572. }
  3573. if (!$error) {
  3574. $this->db->commit();
  3575. return 1;
  3576. } else {
  3577. $this->db->rollback();
  3578. return -1;
  3579. }
  3580. }
  3581. /**
  3582. * Delete all links between an object $this
  3583. *
  3584. * @param int $sourceid Object source id
  3585. * @param string $sourcetype Object source type
  3586. * @param int $targetid Object target id
  3587. * @param string $targettype Object target type
  3588. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3589. * @param User $f_user User that create
  3590. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3591. * @return int >0 if OK, <0 if KO
  3592. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3593. */
  3594. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
  3595. {
  3596. global $user;
  3597. $deletesource = false;
  3598. $deletetarget = false;
  3599. $f_user = isset($f_user) ? $f_user : $user;
  3600. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3601. $deletesource = true;
  3602. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3603. $deletetarget = true;
  3604. }
  3605. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3606. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3607. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3608. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3609. $this->db->begin();
  3610. $error = 0;
  3611. if (!$notrigger) {
  3612. // Call trigger
  3613. $this->context['link_id'] = $rowid;
  3614. $this->context['link_source_id'] = $sourceid;
  3615. $this->context['link_source_type'] = $sourcetype;
  3616. $this->context['link_target_id'] = $targetid;
  3617. $this->context['link_target_type'] = $targettype;
  3618. $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
  3619. if ($result < 0) {
  3620. $error++;
  3621. }
  3622. // End call triggers
  3623. }
  3624. if (!$error) {
  3625. $sql = "DELETE FROM " . MAIN_DB_PREFIX . "element_element";
  3626. $sql .= " WHERE";
  3627. if ($rowid > 0) {
  3628. $sql .= " rowid = " . ((int) $rowid);
  3629. } else {
  3630. if ($deletesource) {
  3631. $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3632. $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
  3633. } elseif ($deletetarget) {
  3634. $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
  3635. $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3636. } else {
  3637. $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
  3638. $sql .= " OR";
  3639. $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
  3640. }
  3641. }
  3642. dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
  3643. if (!$this->db->query($sql)) {
  3644. $this->error = $this->db->lasterror();
  3645. $this->errors[] = $this->error;
  3646. $error++;
  3647. }
  3648. }
  3649. if (!$error) {
  3650. $this->db->commit();
  3651. return 1;
  3652. } else {
  3653. $this->db->rollback();
  3654. return 0;
  3655. }
  3656. }
  3657. /**
  3658. * Function used to get an array with all items linked to an object id in association table
  3659. *
  3660. * @param int $fk_object_where id of object we need to get linked items
  3661. * @param string $field_select name of field we need to get a list
  3662. * @param string $field_where name of field of object we need to get linked items
  3663. * @param string $table_element name of association table
  3664. * @return array Array of record
  3665. */
  3666. public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
  3667. {
  3668. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3669. return -1;
  3670. }
  3671. global $db;
  3672. $sql = "SELECT ".$field_select." FROM ".MAIN_DB_PREFIX.$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3673. $resql = $db->query($sql);
  3674. $TRes = array();
  3675. if (!empty($resql)) {
  3676. while ($res = $db->fetch_object($resql)) {
  3677. $TRes[] = $res->{$field_select};
  3678. }
  3679. }
  3680. return $TRes;
  3681. }
  3682. /**
  3683. * Function used to remove all items linked to an object id in association table
  3684. *
  3685. * @param int $fk_object_where id of object we need to remove linked items
  3686. * @param string $field_where name of field of object we need to delete linked items
  3687. * @param string $table_element name of association table
  3688. * @return int <0 if KO, 0 if nothing done, >0 if OK and something done
  3689. */
  3690. public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
  3691. {
  3692. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3693. return -1;
  3694. }
  3695. global $db;
  3696. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3697. $resql = $db->query($sql);
  3698. if (empty($resql)) {
  3699. return 0;
  3700. }
  3701. return 1;
  3702. }
  3703. /**
  3704. * Set status of an object
  3705. *
  3706. * @param int $status Status to set
  3707. * @param int $elementId Id of element to force (use this->id by default)
  3708. * @param string $elementType Type of element to force (use this->table_element by default)
  3709. * @param string $trigkey Trigger key to use for trigger
  3710. * @return int <0 if KO, >0 if OK
  3711. */
  3712. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '')
  3713. {
  3714. global $user, $langs, $conf;
  3715. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3716. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3717. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3718. $this->db->begin();
  3719. $fieldstatus = "fk_statut";
  3720. if ($elementTable == 'facture_rec') {
  3721. $fieldstatus = "suspended";
  3722. }
  3723. if ($elementTable == 'mailing') {
  3724. $fieldstatus = "statut";
  3725. }
  3726. if ($elementTable == 'cronjob') {
  3727. $fieldstatus = "status";
  3728. }
  3729. if ($elementTable == 'user') {
  3730. $fieldstatus = "statut";
  3731. }
  3732. if ($elementTable == 'expensereport') {
  3733. $fieldstatus = "fk_statut";
  3734. }
  3735. if ($elementTable == 'commande_fournisseur_dispatch') {
  3736. $fieldstatus = "status";
  3737. }
  3738. if (is_array($this->fields) && array_key_exists('status', $this->fields)) {
  3739. $fieldstatus = 'status';
  3740. }
  3741. $sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable;
  3742. $sql .= " SET ".$fieldstatus." = ".((int) $status);
  3743. // If status = 1 = validated, update also fk_user_valid
  3744. if ($status == 1 && $elementTable == 'expensereport') {
  3745. $sql .= ", fk_user_valid = ".((int) $user->id);
  3746. }
  3747. $sql .= " WHERE rowid=".((int) $elementId);
  3748. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  3749. if ($this->db->query($sql)) {
  3750. $error = 0;
  3751. // Try autoset of trigkey
  3752. if (empty($trigkey)) {
  3753. if ($this->element == 'supplier_proposal' && $status == 2) {
  3754. $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3755. }
  3756. if ($this->element == 'supplier_proposal' && $status == 3) {
  3757. $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3758. }
  3759. if ($this->element == 'supplier_proposal' && $status == 4) {
  3760. $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3761. }
  3762. if ($this->element == 'fichinter' && $status == 3) {
  3763. $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3764. }
  3765. if ($this->element == 'fichinter' && $status == 2) {
  3766. $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3767. }
  3768. if ($this->element == 'fichinter' && $status == 1) {
  3769. $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3770. }
  3771. }
  3772. if ($trigkey) {
  3773. // Call trigger
  3774. $result = $this->call_trigger($trigkey, $user);
  3775. if ($result < 0) {
  3776. $error++;
  3777. }
  3778. // End call triggers
  3779. }
  3780. if (!$error) {
  3781. $this->db->commit();
  3782. if (empty($savElementId)) { // If the element we update was $this (so $elementId is null)
  3783. $this->statut = $status;
  3784. $this->status = $status;
  3785. }
  3786. return 1;
  3787. } else {
  3788. $this->db->rollback();
  3789. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  3790. return -1;
  3791. }
  3792. } else {
  3793. $this->error = $this->db->lasterror();
  3794. $this->db->rollback();
  3795. return -1;
  3796. }
  3797. }
  3798. /**
  3799. * Load type of canvas of an object if it exists
  3800. *
  3801. * @param int $id Record id
  3802. * @param string $ref Record ref
  3803. * @return int <0 if KO, 0 if nothing done, >0 if OK
  3804. */
  3805. public function getCanvas($id = 0, $ref = '')
  3806. {
  3807. global $conf;
  3808. if (empty($id) && empty($ref)) {
  3809. return 0;
  3810. }
  3811. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
  3812. return 0; // To increase speed. Not enabled by default.
  3813. }
  3814. // Clean parameters
  3815. $ref = trim($ref);
  3816. $sql = "SELECT rowid, canvas";
  3817. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
  3818. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  3819. if (!empty($id)) {
  3820. $sql .= " AND rowid = ".((int) $id);
  3821. }
  3822. if (!empty($ref)) {
  3823. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  3824. }
  3825. $resql = $this->db->query($sql);
  3826. if ($resql) {
  3827. $obj = $this->db->fetch_object($resql);
  3828. if ($obj) {
  3829. $this->canvas = $obj->canvas;
  3830. return 1;
  3831. } else {
  3832. return 0;
  3833. }
  3834. } else {
  3835. dol_print_error($this->db);
  3836. return -1;
  3837. }
  3838. }
  3839. /**
  3840. * Get special code of a line
  3841. *
  3842. * @param int $lineid Id of line
  3843. * @return int Special code
  3844. */
  3845. public function getSpecialCode($lineid)
  3846. {
  3847. $sql = "SELECT special_code FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  3848. $sql .= " WHERE rowid = ".((int) $lineid);
  3849. $resql = $this->db->query($sql);
  3850. if ($resql) {
  3851. $row = $this->db->fetch_row($resql);
  3852. return $row[0];
  3853. }
  3854. }
  3855. /**
  3856. * Function to check if an object is used by others.
  3857. * Check is done into this->childtables. There is no check into llx_element_element.
  3858. *
  3859. * @param int $id Force id of object
  3860. * @return int <0 if KO, 0 if not used, >0 if already used
  3861. */
  3862. public function isObjectUsed($id = 0)
  3863. {
  3864. global $langs;
  3865. if (empty($id)) {
  3866. $id = $this->id;
  3867. }
  3868. // Check parameters
  3869. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
  3870. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  3871. return -1;
  3872. }
  3873. $arraytoscan = $this->childtables;
  3874. // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
  3875. $tmparray = array_keys($this->childtables);
  3876. if (is_numeric($tmparray[0])) {
  3877. $arraytoscan = array_flip($this->childtables);
  3878. }
  3879. // Test if child exists
  3880. $haschild = 0;
  3881. foreach ($arraytoscan as $table => $elementname) {
  3882. //print $id.'-'.$table.'-'.$elementname.'<br>';
  3883. // Check if third party can be deleted
  3884. $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table;
  3885. $sql .= " WHERE ".$this->fk_element." = ".((int) $id);
  3886. $resql = $this->db->query($sql);
  3887. if ($resql) {
  3888. $obj = $this->db->fetch_object($resql);
  3889. if ($obj->nb > 0) {
  3890. $langs->load("errors");
  3891. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  3892. $haschild += $obj->nb;
  3893. if (is_numeric($elementname)) { // old usage
  3894. $this->errors[] = $langs->transnoentities("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
  3895. } else // new usage: $elementname=Translation key
  3896. {
  3897. $this->errors[] = $langs->transnoentities("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($elementname));
  3898. }
  3899. break; // We found at least one, we stop here
  3900. }
  3901. } else {
  3902. $this->errors[] = $this->db->lasterror();
  3903. return -1;
  3904. }
  3905. }
  3906. if ($haschild > 0) {
  3907. $this->errors[] = "ErrorRecordHasChildren";
  3908. return $haschild;
  3909. } else {
  3910. return 0;
  3911. }
  3912. }
  3913. /**
  3914. * Function to say how many lines object contains
  3915. *
  3916. * @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
  3917. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  3918. */
  3919. public function hasProductsOrServices($predefined = -1)
  3920. {
  3921. $nb = 0;
  3922. foreach ($this->lines as $key => $val) {
  3923. $qualified = 0;
  3924. if ($predefined == -1) {
  3925. $qualified = 1;
  3926. }
  3927. if ($predefined == 1 && $val->fk_product > 0) {
  3928. $qualified = 1;
  3929. }
  3930. if ($predefined == 0 && $val->fk_product <= 0) {
  3931. $qualified = 1;
  3932. }
  3933. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
  3934. $qualified = 1;
  3935. }
  3936. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
  3937. $qualified = 1;
  3938. }
  3939. if ($qualified) {
  3940. $nb++;
  3941. }
  3942. }
  3943. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  3944. return $nb;
  3945. }
  3946. /**
  3947. * Function that returns the total amount HT of discounts applied for all lines.
  3948. *
  3949. * @return float|string Total amout of discount
  3950. */
  3951. public function getTotalDiscount()
  3952. {
  3953. if (!empty($this->table_element_line) ) {
  3954. $total_discount = 0.00;
  3955. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  3956. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  3957. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3958. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  3959. $resql = $this->db->query($sql);
  3960. if ($resql) {
  3961. $num = $this->db->num_rows($resql);
  3962. $i = 0;
  3963. while ($i < $num) {
  3964. $obj = $this->db->fetch_object($resql);
  3965. $pu_ht = $obj->pu_ht;
  3966. $qty = $obj->qty;
  3967. $total_ht = $obj->total_ht;
  3968. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  3969. $total_discount += $total_discount_line;
  3970. $i++;
  3971. }
  3972. }
  3973. //print $total_discount; exit;
  3974. return price2num($total_discount);
  3975. }
  3976. return null;
  3977. }
  3978. /**
  3979. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  3980. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  3981. *
  3982. * @return array array('weight'=>...,'volume'=>...)
  3983. */
  3984. public function getTotalWeightVolume()
  3985. {
  3986. $totalWeight = 0;
  3987. $totalVolume = 0;
  3988. // defined for shipment only
  3989. $totalOrdered = '';
  3990. // defined for shipment only
  3991. $totalToShip = '';
  3992. foreach ($this->lines as $line) {
  3993. if (isset($line->qty_asked)) {
  3994. if (empty($totalOrdered)) {
  3995. $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  3996. }
  3997. $totalOrdered += $line->qty_asked; // defined for shipment only
  3998. }
  3999. if (isset($line->qty_shipped)) {
  4000. if (empty($totalToShip)) {
  4001. $totalToShip = 0; // Avoid warning because $totalToShip is ''
  4002. }
  4003. $totalToShip += $line->qty_shipped; // defined for shipment only
  4004. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
  4005. if (empty($totalToShip)) {
  4006. $totalToShip = 0;
  4007. }
  4008. $totalToShip += $line->qty; // defined for reception only
  4009. }
  4010. // Define qty, weight, volume, weight_units, volume_units
  4011. if ($this->element == 'shipping') {
  4012. // for shipments
  4013. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  4014. } else {
  4015. $qty = $line->qty ? $line->qty : 0;
  4016. }
  4017. $weight = $line->weight ? $line->weight : 0;
  4018. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  4019. $volume = $line->volume ? $line->volume : 0;
  4020. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  4021. $weight_units = $line->weight_units;
  4022. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  4023. $volume_units = $line->volume_units;
  4024. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  4025. $weightUnit = 0;
  4026. $volumeUnit = 0;
  4027. if (!empty($weight_units)) {
  4028. $weightUnit = $weight_units;
  4029. }
  4030. if (!empty($volume_units)) {
  4031. $volumeUnit = $volume_units;
  4032. }
  4033. if (empty($totalWeight)) {
  4034. $totalWeight = 0; // Avoid warning because $totalWeight is ''
  4035. }
  4036. if (empty($totalVolume)) {
  4037. $totalVolume = 0; // Avoid warning because $totalVolume is ''
  4038. }
  4039. //var_dump($line->volume_units);
  4040. if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4041. $trueWeightUnit = pow(10, $weightUnit);
  4042. $totalWeight += $weight * $qty * $trueWeightUnit;
  4043. } else {
  4044. if ($weight_units == 99) {
  4045. // conversion 1 Pound = 0.45359237 KG
  4046. $trueWeightUnit = 0.45359237;
  4047. $totalWeight += $weight * $qty * $trueWeightUnit;
  4048. } elseif ($weight_units == 98) {
  4049. // conversion 1 Ounce = 0.0283495 KG
  4050. $trueWeightUnit = 0.0283495;
  4051. $totalWeight += $weight * $qty * $trueWeightUnit;
  4052. } else {
  4053. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  4054. }
  4055. }
  4056. if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4057. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  4058. $trueVolumeUnit = pow(10, $volumeUnit);
  4059. //print $line->volume;
  4060. $totalVolume += $volume * $qty * $trueVolumeUnit;
  4061. } else {
  4062. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  4063. }
  4064. }
  4065. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  4066. }
  4067. /**
  4068. * Set extra parameters
  4069. *
  4070. * @return int <0 if KO, >0 if OK
  4071. */
  4072. public function setExtraParameters()
  4073. {
  4074. $this->db->begin();
  4075. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  4076. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  4077. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  4078. $sql .= " WHERE rowid = ".((int) $this->id);
  4079. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  4080. $resql = $this->db->query($sql);
  4081. if (!$resql) {
  4082. $this->error = $this->db->lasterror();
  4083. $this->db->rollback();
  4084. return -1;
  4085. } else {
  4086. $this->db->commit();
  4087. return 1;
  4088. }
  4089. }
  4090. // --------------------
  4091. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  4092. // --------------------
  4093. /* This is to show add lines */
  4094. /**
  4095. * Show add free and predefined products/services form
  4096. *
  4097. * @param int $dateSelector 1=Show also date range input fields
  4098. * @param Societe $seller Object thirdparty who sell
  4099. * @param Societe $buyer Object thirdparty who buy
  4100. * @param string $defaulttpldir Directory where to find the template
  4101. * @return void
  4102. */
  4103. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  4104. {
  4105. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  4106. global $form;
  4107. // Line extrafield
  4108. if (!is_object($extrafields)) {
  4109. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4110. $extrafields = new ExtraFields($this->db);
  4111. }
  4112. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4113. // Output template part (modules that overwrite templates must declare this into descriptor)
  4114. // Use global variables + $dateSelector + $seller and $buyer
  4115. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  4116. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4117. foreach ($dirtpls as $module => $reldir) {
  4118. if (!empty($module)) {
  4119. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  4120. } else {
  4121. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  4122. }
  4123. if (empty($conf->file->strict_mode)) {
  4124. $res = @include $tpl;
  4125. } else {
  4126. $res = include $tpl; // for debug
  4127. }
  4128. if ($res) {
  4129. break;
  4130. }
  4131. }
  4132. }
  4133. /* This is to show array of line of details */
  4134. /**
  4135. * Return HTML table for object lines
  4136. * TODO Move this into an output class file (htmlline.class.php)
  4137. * If lines are into a template, title must also be into a template
  4138. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4139. *
  4140. * @param string $action Action code
  4141. * @param string $seller Object of seller third party
  4142. * @param string $buyer Object of buyer third party
  4143. * @param int $selected Object line selected
  4144. * @param int $dateSelector 1=Show also date range input fields
  4145. * @param string $defaulttpldir Directory where to find the template
  4146. * @return void
  4147. */
  4148. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  4149. {
  4150. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  4151. // TODO We should not use global var for this
  4152. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  4153. // Define usemargins
  4154. $usemargins = 0;
  4155. if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
  4156. $usemargins = 1;
  4157. }
  4158. $num = count($this->lines);
  4159. // Line extrafield
  4160. if (!is_object($extrafields)) {
  4161. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4162. $extrafields = new ExtraFields($this->db);
  4163. }
  4164. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4165. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  4166. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4167. if (empty($reshook)) {
  4168. // Output template part (modules that overwrite templates must declare this into descriptor)
  4169. // Use global variables + $dateSelector + $seller and $buyer
  4170. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  4171. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4172. foreach ($dirtpls as $module => $reldir) {
  4173. if (!empty($module)) {
  4174. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  4175. } else {
  4176. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  4177. }
  4178. if (empty($conf->file->strict_mode)) {
  4179. $res = @include $tpl;
  4180. } else {
  4181. $res = include $tpl; // for debug
  4182. }
  4183. if ($res) {
  4184. break;
  4185. }
  4186. }
  4187. }
  4188. $i = 0;
  4189. print "<!-- begin printObjectLines() --><tbody>\n";
  4190. foreach ($this->lines as $line) {
  4191. //Line extrafield
  4192. $line->fetch_optionals();
  4193. //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  4194. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4195. if (empty($line->fk_parent_line)) {
  4196. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  4197. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4198. } else {
  4199. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element, 'fk_parent_line'=>$line->fk_parent_line);
  4200. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4201. }
  4202. }
  4203. if (empty($reshook)) {
  4204. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  4205. }
  4206. $i++;
  4207. }
  4208. print "</tbody><!-- end printObjectLines() -->\n";
  4209. }
  4210. /**
  4211. * Return HTML content of a detail line
  4212. * TODO Move this into an output class file (htmlline.class.php)
  4213. *
  4214. * @param string $action GET/POST action
  4215. * @param CommonObjectLine $line Selected object line to output
  4216. * @param string $var Is it a an odd line (true)
  4217. * @param int $num Number of line (0)
  4218. * @param int $i I
  4219. * @param int $dateSelector 1=Show also date range input fields
  4220. * @param string $seller Object of seller third party
  4221. * @param string $buyer Object of buyer third party
  4222. * @param int $selected Object line selected
  4223. * @param Extrafields $extrafields Object of extrafields
  4224. * @param string $defaulttpldir Directory where to find the template (deprecated)
  4225. * @return void
  4226. */
  4227. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  4228. {
  4229. global $conf, $langs, $user, $object, $hookmanager;
  4230. global $form;
  4231. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  4232. $object_rights = $this->getRights();
  4233. $element = $this->element;
  4234. $text = '';
  4235. $description = '';
  4236. // Line in view mode
  4237. if ($action != 'editline' || $selected != $line->id) {
  4238. // Product
  4239. if ($line->fk_product > 0) {
  4240. $product_static = new Product($this->db);
  4241. $product_static->fetch($line->fk_product);
  4242. $product_static->ref = $line->ref; //can change ref in hook
  4243. $product_static->label = $line->label; //can change label in hook
  4244. $text = $product_static->getNomUrl(1);
  4245. // Define output language and label
  4246. if (!empty($conf->global->MAIN_MULTILANGS)) {
  4247. if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
  4248. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  4249. return;
  4250. }
  4251. $prod = new Product($this->db);
  4252. $prod->fetch($line->fk_product);
  4253. $outputlangs = $langs;
  4254. $newlang = '';
  4255. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  4256. $newlang = GETPOST('lang_id', 'aZ09');
  4257. }
  4258. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
  4259. $newlang = $this->thirdparty->default_lang; // To use language of customer
  4260. }
  4261. if (!empty($newlang)) {
  4262. $outputlangs = new Translate("", $conf);
  4263. $outputlangs->setDefaultLang($newlang);
  4264. }
  4265. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  4266. } else {
  4267. $label = $line->product_label;
  4268. }
  4269. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  4270. $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.
  4271. }
  4272. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4273. // Output template part (modules that overwrite templates must declare this into descriptor)
  4274. // Use global variables + $dateSelector + $seller and $buyer
  4275. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4276. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4277. foreach ($dirtpls as $module => $reldir) {
  4278. if (!empty($module)) {
  4279. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  4280. } else {
  4281. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  4282. }
  4283. if (empty($conf->file->strict_mode)) {
  4284. $res = @include $tpl;
  4285. } else {
  4286. $res = include $tpl; // for debug
  4287. }
  4288. if ($res) {
  4289. break;
  4290. }
  4291. }
  4292. }
  4293. // Line in update mode
  4294. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
  4295. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  4296. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4297. // Output template part (modules that overwrite templates must declare this into descriptor)
  4298. // Use global variables + $dateSelector + $seller and $buyer
  4299. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4300. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4301. foreach ($dirtpls as $module => $reldir) {
  4302. if (!empty($module)) {
  4303. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  4304. } else {
  4305. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  4306. }
  4307. if (empty($conf->file->strict_mode)) {
  4308. $res = @include $tpl;
  4309. } else {
  4310. $res = include $tpl; // for debug
  4311. }
  4312. if ($res) {
  4313. break;
  4314. }
  4315. }
  4316. }
  4317. }
  4318. /* This is to show array of line of details of source object */
  4319. /**
  4320. * Return HTML table table of source object lines
  4321. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4322. * If lines are into a template, title must also be into a template
  4323. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  4324. *
  4325. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  4326. * @param array $selectedLines Array of lines id for selected lines
  4327. * @return void
  4328. */
  4329. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  4330. {
  4331. global $langs, $hookmanager, $conf, $form;
  4332. print '<tr class="liste_titre">';
  4333. print '<td>'.$langs->trans('Ref').'</td>';
  4334. print '<td>'.$langs->trans('Description').'</td>';
  4335. print '<td class="right">'.$langs->trans('VATRate').'</td>';
  4336. print '<td class="right">'.$langs->trans('PriceUHT').'</td>';
  4337. if (!empty($conf->multicurrency->enabled)) {
  4338. print '<td class="right">'.$langs->trans('PriceUHTCurrency').'</td>';
  4339. }
  4340. print '<td class="right">'.$langs->trans('Qty').'</td>';
  4341. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4342. print '<td class="left">'.$langs->trans('Unit').'</td>';
  4343. }
  4344. print '<td class="right">'.$langs->trans('ReductionShort').'</td>';
  4345. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  4346. print '</tr>';
  4347. $i = 0;
  4348. if (!empty($this->lines)) {
  4349. foreach ($this->lines as $line) {
  4350. $reshook = 0;
  4351. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
  4352. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4353. if (empty($line->fk_parent_line)) {
  4354. $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
  4355. $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4356. } else {
  4357. $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines, 'fk_parent_line'=>$line->fk_parent_line);
  4358. $reshook = $hookmanager->executeHooks('printOriginObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4359. }
  4360. }
  4361. if (empty($reshook)) {
  4362. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  4363. }
  4364. $i++;
  4365. }
  4366. }
  4367. }
  4368. /**
  4369. * Return HTML with a line of table array of source object lines
  4370. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4371. * If lines are into a template, title must also be into a template
  4372. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4373. *
  4374. * @param CommonObjectLine $line Line
  4375. * @param string $var Var
  4376. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  4377. * @param string $defaulttpldir Directory where to find the template
  4378. * @param array $selectedLines Array of lines id for selected lines
  4379. * @return void
  4380. */
  4381. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  4382. {
  4383. global $langs, $conf;
  4384. //var_dump($line);
  4385. if (!empty($line->date_start)) {
  4386. $date_start = $line->date_start;
  4387. } else {
  4388. $date_start = $line->date_debut_prevue;
  4389. if ($line->date_debut_reel) {
  4390. $date_start = $line->date_debut_reel;
  4391. }
  4392. }
  4393. if (!empty($line->date_end)) {
  4394. $date_end = $line->date_end;
  4395. } else {
  4396. $date_end = $line->date_fin_prevue;
  4397. if ($line->date_fin_reel) {
  4398. $date_end = $line->date_fin_reel;
  4399. }
  4400. }
  4401. $this->tpl['id'] = $line->id;
  4402. $this->tpl['label'] = '';
  4403. if (!empty($line->fk_parent_line)) {
  4404. $this->tpl['label'] .= img_picto('', 'rightarrow');
  4405. }
  4406. if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
  4407. $discount = new DiscountAbsolute($this->db);
  4408. $discount->fk_soc = $this->socid;
  4409. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  4410. } elseif (!empty($line->fk_product)) {
  4411. $productstatic = new Product($this->db);
  4412. $productstatic->id = $line->fk_product;
  4413. $productstatic->ref = $line->ref;
  4414. $productstatic->type = $line->fk_product_type;
  4415. if (empty($productstatic->ref)) {
  4416. $line->fetch_product();
  4417. $productstatic = $line->product;
  4418. }
  4419. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  4420. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  4421. // Dates
  4422. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4423. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4424. }
  4425. } else {
  4426. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  4427. if (!empty($line->desc)) {
  4428. $this->tpl['label'] .= $line->desc;
  4429. } else {
  4430. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  4431. }
  4432. // Dates
  4433. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4434. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4435. }
  4436. }
  4437. if (!empty($line->desc)) {
  4438. if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
  4439. $discount = new DiscountAbsolute($this->db);
  4440. $discount->fetch($line->fk_remise_except);
  4441. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  4442. } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
  4443. $discount = new DiscountAbsolute($this->db);
  4444. $discount->fetch($line->fk_remise_except);
  4445. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  4446. } elseif ($line->desc == '(EXCESS RECEIVED)') {
  4447. $discount = new DiscountAbsolute($this->db);
  4448. $discount->fetch($line->fk_remise_except);
  4449. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  4450. } elseif ($line->desc == '(EXCESS PAID)') {
  4451. $discount = new DiscountAbsolute($this->db);
  4452. $discount->fetch($line->fk_remise_except);
  4453. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  4454. } else {
  4455. $this->tpl['description'] = dol_trunc($line->desc, 60);
  4456. }
  4457. } else {
  4458. $this->tpl['description'] = '&nbsp;';
  4459. }
  4460. // VAT Rate
  4461. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  4462. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  4463. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
  4464. $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  4465. }
  4466. $this->tpl['price'] = price($line->subprice);
  4467. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  4468. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  4469. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4470. $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  4471. }
  4472. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  4473. // Is the line strike or not
  4474. $this->tpl['strike'] = 0;
  4475. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
  4476. $this->tpl['strike'] = 1;
  4477. }
  4478. // Output template part (modules that overwrite templates must declare this into descriptor)
  4479. // Use global variables + $dateSelector + $seller and $buyer
  4480. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4481. foreach ($dirtpls as $module => $reldir) {
  4482. if (!empty($module)) {
  4483. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  4484. } else {
  4485. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  4486. }
  4487. if (empty($conf->file->strict_mode)) {
  4488. $res = @include $tpl;
  4489. } else {
  4490. $res = include $tpl; // for debug
  4491. }
  4492. if ($res) {
  4493. break;
  4494. }
  4495. }
  4496. }
  4497. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4498. /**
  4499. * Add resources to the current object : add entry into llx_element_resources
  4500. * Need $this->element & $this->id
  4501. *
  4502. * @param int $resource_id Resource id
  4503. * @param string $resource_type 'resource'
  4504. * @param int $busy Busy or not
  4505. * @param int $mandatory Mandatory or not
  4506. * @return int <=0 if KO, >0 if OK
  4507. */
  4508. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  4509. {
  4510. // phpcs:enable
  4511. $this->db->begin();
  4512. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources (";
  4513. $sql .= "resource_id";
  4514. $sql .= ", resource_type";
  4515. $sql .= ", element_id";
  4516. $sql .= ", element_type";
  4517. $sql .= ", busy";
  4518. $sql .= ", mandatory";
  4519. $sql .= ") VALUES (";
  4520. $sql .= $resource_id;
  4521. $sql .= ", '".$this->db->escape($resource_type)."'";
  4522. $sql .= ", '".$this->db->escape($this->id)."'";
  4523. $sql .= ", '".$this->db->escape($this->element)."'";
  4524. $sql .= ", '".$this->db->escape($busy)."'";
  4525. $sql .= ", '".$this->db->escape($mandatory)."'";
  4526. $sql .= ")";
  4527. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  4528. if ($this->db->query($sql)) {
  4529. $this->db->commit();
  4530. return 1;
  4531. } else {
  4532. $this->error = $this->db->lasterror();
  4533. $this->db->rollback();
  4534. return 0;
  4535. }
  4536. }
  4537. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4538. /**
  4539. * Delete a link to resource line
  4540. *
  4541. * @param int $rowid Id of resource line to delete
  4542. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  4543. * @param int $notrigger Disable all triggers
  4544. * @return int >0 if OK, <0 if KO
  4545. */
  4546. public function delete_resource($rowid, $element, $notrigger = 0)
  4547. {
  4548. // phpcs:enable
  4549. global $user;
  4550. $this->db->begin();
  4551. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
  4552. $sql .= " WHERE rowid = ".((int) $rowid);
  4553. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  4554. $resql = $this->db->query($sql);
  4555. if (!$resql) {
  4556. $this->error = $this->db->lasterror();
  4557. $this->db->rollback();
  4558. return -1;
  4559. } else {
  4560. if (!$notrigger) {
  4561. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  4562. if ($result < 0) {
  4563. $this->db->rollback();
  4564. return -1;
  4565. }
  4566. }
  4567. $this->db->commit();
  4568. return 1;
  4569. }
  4570. }
  4571. /**
  4572. * Overwrite magic function to solve problem of cloning object that are kept as references
  4573. *
  4574. * @return void
  4575. */
  4576. public function __clone()
  4577. {
  4578. // Force a copy of this->lines, otherwise it will point to same object.
  4579. if (isset($this->lines) && is_array($this->lines)) {
  4580. $nboflines = count($this->lines);
  4581. for ($i = 0; $i < $nboflines; $i++) {
  4582. $this->lines[$i] = clone $this->lines[$i];
  4583. }
  4584. }
  4585. }
  4586. /**
  4587. * Common function for all objects extending CommonObject for generating documents
  4588. *
  4589. * @param string $modelspath Relative folder where generators are placed
  4590. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4591. * @param Translate $outputlangs Output language to use
  4592. * @param int $hidedetails 1 to hide details. 0 by default
  4593. * @param int $hidedesc 1 to hide product description. 0 by default
  4594. * @param int $hideref 1 to hide product reference. 0 by default
  4595. * @param null|array $moreparams Array to provide more information
  4596. * @return int >0 if OK, <0 if KO
  4597. * @see addFileIntoDatabaseIndex()
  4598. */
  4599. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4600. {
  4601. global $conf, $langs, $user, $hookmanager, $action;
  4602. $srctemplatepath = '';
  4603. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  4604. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4605. if (empty($reshook)) {
  4606. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4607. if (empty($modele)) {
  4608. $this->error = 'BadValueForParameterModele';
  4609. return -1;
  4610. }
  4611. // Increase limit for PDF build
  4612. $err = error_reporting();
  4613. error_reporting(0);
  4614. @set_time_limit(120);
  4615. error_reporting($err);
  4616. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4617. $tmp = explode(':', $modele, 2);
  4618. if (!empty($tmp[1])) {
  4619. $modele = $tmp[0];
  4620. $srctemplatepath = $tmp[1];
  4621. }
  4622. // Search template files
  4623. $file = '';
  4624. $classname = '';
  4625. $filefound = '';
  4626. $dirmodels = array('/');
  4627. if (is_array($conf->modules_parts['models'])) {
  4628. $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4629. }
  4630. foreach ($dirmodels as $reldir) {
  4631. foreach (array('doc', 'pdf') as $prefix) {
  4632. if (in_array(get_class($this), array('Adherent'))) {
  4633. // Member module use prefix_modele.class.php
  4634. $file = $prefix."_".$modele.".class.php";
  4635. } else {
  4636. // Other module use prefix_modele.modules.php
  4637. $file = $prefix."_".$modele.".modules.php";
  4638. }
  4639. // On verifie l'emplacement du modele
  4640. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  4641. if (file_exists($file)) {
  4642. $filefound = $file;
  4643. $classname = $prefix.'_'.$modele;
  4644. break;
  4645. }
  4646. }
  4647. if ($filefound) {
  4648. break;
  4649. }
  4650. }
  4651. // If generator was found
  4652. if ($filefound) {
  4653. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4654. require_once $file;
  4655. $obj = new $classname($this->db);
  4656. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4657. if ($obj->type == 'odt' && empty($srctemplatepath)) {
  4658. $varfortemplatedir = $obj->scandir;
  4659. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
  4660. $dirtoscan = $conf->global->$varfortemplatedir;
  4661. $listoffiles = array();
  4662. // Now we add first model found in directories scanned
  4663. $listofdir = explode(',', $dirtoscan);
  4664. foreach ($listofdir as $key => $tmpdir) {
  4665. $tmpdir = trim($tmpdir);
  4666. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4667. if (!$tmpdir) {
  4668. unset($listofdir[$key]);
  4669. continue;
  4670. }
  4671. if (is_dir($tmpdir)) {
  4672. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4673. if (count($tmpfiles)) {
  4674. $listoffiles = array_merge($listoffiles, $tmpfiles);
  4675. }
  4676. }
  4677. }
  4678. if (count($listoffiles)) {
  4679. foreach ($listoffiles as $record) {
  4680. $srctemplatepath = $record['fullname'];
  4681. break;
  4682. }
  4683. }
  4684. }
  4685. if (empty($srctemplatepath)) {
  4686. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4687. return -1;
  4688. }
  4689. }
  4690. if ($obj->type == 'odt' && !empty($srctemplatepath)) {
  4691. if (!dol_is_file($srctemplatepath)) {
  4692. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  4693. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4694. return -1;
  4695. }
  4696. }
  4697. // We save charset_output to restore it because write_file can change it if needed for
  4698. // output format that does not support UTF8.
  4699. $sav_charset_output = $outputlangs->charset_output;
  4700. if (in_array(get_class($this), array('Adherent'))) {
  4701. $arrayofrecords = array(); // The write_file of templates of adherent class need this var
  4702. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams);
  4703. } else {
  4704. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4705. }
  4706. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4707. if ($resultwritefile > 0) {
  4708. $outputlangs->charset_output = $sav_charset_output;
  4709. // We delete old preview
  4710. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4711. dol_delete_preview($this);
  4712. // Index file in database
  4713. if (!empty($obj->result['fullpath'])) {
  4714. $destfull = $obj->result['fullpath'];
  4715. $upload_dir = dirname($destfull);
  4716. $destfile = basename($destfull);
  4717. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  4718. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  4719. $filename = basename($destfile);
  4720. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4721. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4722. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4723. $ecmfile = new EcmFiles($this->db);
  4724. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  4725. // Set the public "share" key
  4726. $setsharekey = false;
  4727. if ($this->element == 'propal') {
  4728. $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok
  4729. if ($useonlinesignature) {
  4730. $setsharekey = true;
  4731. }
  4732. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4733. $setsharekey = true;
  4734. }
  4735. }
  4736. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  4737. $setsharekey = true;
  4738. }
  4739. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  4740. $setsharekey = true;
  4741. }
  4742. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4743. $setsharekey = true;
  4744. }
  4745. if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4746. $setsharekey = true;
  4747. }
  4748. if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4749. $setsharekey = true;
  4750. }
  4751. if ($setsharekey) {
  4752. if (empty($ecmfile->share)) { // Because object not found or share not set yet
  4753. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  4754. $ecmfile->share = getRandomPassword(true);
  4755. }
  4756. }
  4757. if ($result > 0) {
  4758. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4759. $ecmfile->fullpath_orig = '';
  4760. $ecmfile->gen_or_uploaded = 'generated';
  4761. $ecmfile->description = ''; // indexed content
  4762. $ecmfile->keywords = ''; // keyword content
  4763. $result = $ecmfile->update($user);
  4764. if ($result < 0) {
  4765. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4766. }
  4767. } else {
  4768. $ecmfile->entity = $conf->entity;
  4769. $ecmfile->filepath = $rel_dir;
  4770. $ecmfile->filename = $filename;
  4771. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4772. $ecmfile->fullpath_orig = '';
  4773. $ecmfile->gen_or_uploaded = 'generated';
  4774. $ecmfile->description = ''; // indexed content
  4775. $ecmfile->keywords = ''; // keyword content
  4776. $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
  4777. $ecmfile->src_object_id = $this->id;
  4778. $result = $ecmfile->create($user);
  4779. if ($result < 0) {
  4780. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4781. }
  4782. }
  4783. /*$this->result['fullname']=$destfull;
  4784. $this->result['filepath']=$ecmfile->filepath;
  4785. $this->result['filename']=$ecmfile->filename;*/
  4786. //var_dump($obj->update_main_doc_field);exit;
  4787. // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
  4788. $update_main_doc_field = 0;
  4789. if (!empty($obj->update_main_doc_field)) {
  4790. $update_main_doc_field = 1;
  4791. }
  4792. if ($update_main_doc_field && !empty($this->table_element)) {
  4793. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
  4794. $sql .= " WHERE rowid = ".((int) $this->id);
  4795. $resql = $this->db->query($sql);
  4796. if (!$resql) {
  4797. dol_print_error($this->db);
  4798. } else {
  4799. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  4800. }
  4801. }
  4802. }
  4803. } else {
  4804. 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);
  4805. }
  4806. // Success in building document. We build meta file.
  4807. dol_meta_create($this);
  4808. return 1;
  4809. } else {
  4810. $outputlangs->charset_output = $sav_charset_output;
  4811. dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
  4812. return -1;
  4813. }
  4814. } else {
  4815. if (!$filefound) {
  4816. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4817. dol_print_error('', $this->error);
  4818. } else {
  4819. $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
  4820. dol_print_error('', $this->error);
  4821. }
  4822. return -1;
  4823. }
  4824. } else {
  4825. return $reshook;
  4826. }
  4827. }
  4828. /**
  4829. * Build thumb
  4830. * @todo Move this into files.lib.php
  4831. *
  4832. * @param string $file Path file in UTF8 to original file to create thumbs from.
  4833. * @return void
  4834. */
  4835. public function addThumbs($file)
  4836. {
  4837. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  4838. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  4839. $file_osencoded = dol_osencode($file);
  4840. if (file_exists($file_osencoded)) {
  4841. // Create small thumbs for company (Ratio is near 16/9)
  4842. // Used on logon for example
  4843. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  4844. // Create mini thumbs for company (Ratio is near 16/9)
  4845. // Used on menu or for setup page for example
  4846. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  4847. }
  4848. }
  4849. /* Functions common to commonobject and commonobjectline */
  4850. /* For default values */
  4851. /**
  4852. * Return the default value to use for a field when showing the create form of object.
  4853. * Return values in this order:
  4854. * 1) If parameter is available into POST, we return it first.
  4855. * 2) If not but an alternate value was provided as parameter of function, we return it.
  4856. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  4857. * 4) Return value found into database (TODO No yet implemented)
  4858. *
  4859. * @param string $fieldname Name of field
  4860. * @param string $alternatevalue Alternate value to use
  4861. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  4862. **/
  4863. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
  4864. {
  4865. global $conf, $_POST;
  4866. // If param here has been posted, we use this value first.
  4867. if (GETPOSTISSET($fieldname)) {
  4868. return GETPOST($fieldname, 'alphanohtml', 3);
  4869. }
  4870. if (isset($alternatevalue)) {
  4871. return $alternatevalue;
  4872. }
  4873. $newelement = $this->element;
  4874. if ($newelement == 'facture') {
  4875. $newelement = 'invoice';
  4876. }
  4877. if ($newelement == 'commande') {
  4878. $newelement = 'order';
  4879. }
  4880. if (empty($newelement)) {
  4881. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  4882. return '';
  4883. }
  4884. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  4885. //var_dump($keyforfieldname);
  4886. if (isset($conf->global->$keyforfieldname)) {
  4887. return $conf->global->$keyforfieldname;
  4888. }
  4889. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  4890. }
  4891. /* For triggers */
  4892. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4893. /**
  4894. * Call trigger based on this instance.
  4895. * Some context information may also be provided into array property this->context.
  4896. * NB: Error from trigger are stacked in interface->errors
  4897. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  4898. *
  4899. * @param string $triggerName trigger's name to execute
  4900. * @param User $user Object user
  4901. * @return int Result of run_triggers
  4902. */
  4903. public function call_trigger($triggerName, $user)
  4904. {
  4905. // phpcs:enable
  4906. global $langs, $conf;
  4907. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  4908. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4909. $langs = new Translate('', $conf);
  4910. }
  4911. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  4912. $interface = new Interfaces($this->db);
  4913. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  4914. if ($result < 0) {
  4915. if (!empty($this->errors)) {
  4916. $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.
  4917. } else {
  4918. $this->errors = $interface->errors;
  4919. }
  4920. }
  4921. return $result;
  4922. }
  4923. /* Functions for data in other language */
  4924. /**
  4925. * Function to get alternative languages of a data into $this->array_languages
  4926. * This method is NOT called by method fetch of objects but must be called separately.
  4927. *
  4928. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  4929. * @see fetch_optionnals()
  4930. */
  4931. public function fetchValuesForExtraLanguages()
  4932. {
  4933. // To avoid SQL errors. Probably not the better solution though
  4934. if (!$this->element) {
  4935. return 0;
  4936. }
  4937. if (!($this->id > 0)) {
  4938. return 0;
  4939. }
  4940. if (is_array($this->array_languages)) {
  4941. return 1;
  4942. }
  4943. $this->array_languages = array();
  4944. $element = $this->element;
  4945. if ($element == 'categorie') {
  4946. $element = 'categories'; // For compatibility
  4947. }
  4948. // Request to get translation values for object
  4949. $sql = "SELECT rowid, property, lang , value";
  4950. $sql .= " FROM ".MAIN_DB_PREFIX."object_lang";
  4951. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  4952. $sql .= " AND fk_object = ".((int) $this->id);
  4953. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  4954. $resql = $this->db->query($sql);
  4955. if ($resql) {
  4956. $numrows = $this->db->num_rows($resql);
  4957. if ($numrows) {
  4958. $i = 0;
  4959. while ($i < $numrows) {
  4960. $obj = $this->db->fetch_object($resql);
  4961. $key = $obj->property;
  4962. $value = $obj->value;
  4963. $codelang = $obj->lang;
  4964. $type = $this->fields[$key]['type'];
  4965. // we can add this attribute to object
  4966. if (preg_match('/date/', $type)) {
  4967. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  4968. } else {
  4969. $this->array_languages[$key][$codelang] = $value;
  4970. }
  4971. $i++;
  4972. }
  4973. }
  4974. $this->db->free($resql);
  4975. if ($numrows) {
  4976. return $numrows;
  4977. } else {
  4978. return 0;
  4979. }
  4980. } else {
  4981. dol_print_error($this->db);
  4982. return -1;
  4983. }
  4984. }
  4985. /**
  4986. * Fill array_options property of object by extrafields value (using for data sent by forms)
  4987. *
  4988. * @param string $onlykey Only the following key is filled. When we make update of only one language field ($action = 'update_languages'), calling page must set this to avoid to have other languages being reset.
  4989. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  4990. */
  4991. public function setValuesForExtraLanguages($onlykey = '')
  4992. {
  4993. global $_POST, $langs;
  4994. // Get extra fields
  4995. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  4996. $tmparray = explode('-', $postfieldkey);
  4997. if ($tmparray[0] != 'field') {
  4998. continue;
  4999. }
  5000. $element = $tmparray[1];
  5001. $key = $tmparray[2];
  5002. $codelang = $tmparray[3];
  5003. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  5004. if (!empty($onlykey) && $key != $onlykey) {
  5005. continue;
  5006. }
  5007. if ($element != $this->element) {
  5008. continue;
  5009. }
  5010. $key_type = $this->fields[$key]['type'];
  5011. $enabled = 1;
  5012. if (isset($this->fields[$key]['enabled'])) {
  5013. $enabled = dol_eval($this->fields[$key]['enabled'], 1);
  5014. }
  5015. /*$perms = 1;
  5016. if (isset($this->fields[$key]['perms']))
  5017. {
  5018. $perms = dol_eval($this->fields[$key]['perms'], 1);
  5019. }*/
  5020. if (empty($enabled)) {
  5021. continue;
  5022. }
  5023. //if (empty($perms)) continue;
  5024. if (in_array($key_type, array('date'))) {
  5025. // Clean parameters
  5026. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5027. $value_key = dol_mktime(0, 0, 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]);
  5028. } elseif (in_array($key_type, array('datetime'))) {
  5029. // Clean parameters
  5030. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5031. $value_key = dol_mktime($_POST[$postfieldkey."hour"], $_POST[$postfieldkey."min"], 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]);
  5032. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  5033. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  5034. if (!empty($value_arr)) {
  5035. $value_key = implode(',', $value_arr);
  5036. } else {
  5037. $value_key = '';
  5038. }
  5039. } elseif (in_array($key_type, array('price', 'double'))) {
  5040. $value_arr = GETPOST($postfieldkey, 'alpha');
  5041. $value_key = price2num($value_arr);
  5042. } else {
  5043. $value_key = GETPOST($postfieldkey);
  5044. if (in_array($key_type, array('link')) && $value_key == '-1') {
  5045. $value_key = '';
  5046. }
  5047. }
  5048. $this->array_languages[$key][$codelang] = $value_key;
  5049. /*if ($nofillrequired) {
  5050. $langs->load('errors');
  5051. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  5052. return -1;
  5053. }*/
  5054. }
  5055. return 1;
  5056. }
  5057. /* Functions for extrafields */
  5058. /**
  5059. * Function to make a fetch but set environment to avoid to load computed values before.
  5060. *
  5061. * @param int $id ID of object
  5062. * @return int >0 if OK, 0 if not found, <0 if KO
  5063. */
  5064. public function fetchNoCompute($id)
  5065. {
  5066. global $conf;
  5067. $savDisableCompute = $conf->disable_compute;
  5068. $conf->disable_compute = 1;
  5069. $ret = $this->fetch($id);
  5070. $conf->disable_compute = $savDisableCompute;
  5071. return $ret;
  5072. }
  5073. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5074. /**
  5075. * Function to get extra fields of an object into $this->array_options
  5076. * This method is in most cases called by method fetch of objects but you can call it separately.
  5077. *
  5078. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  5079. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  5080. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  5081. * @see fetchValuesForExtraLanguages()
  5082. */
  5083. public function fetch_optionals($rowid = null, $optionsArray = null)
  5084. {
  5085. // phpcs:enable
  5086. global $conf, $extrafields;
  5087. if (empty($rowid)) {
  5088. $rowid = $this->id;
  5089. }
  5090. if (empty($rowid) && isset($this->rowid)) {
  5091. $rowid = $this->rowid; // deprecated
  5092. }
  5093. // To avoid SQL errors. Probably not the better solution though
  5094. if (!$this->table_element) {
  5095. return 0;
  5096. }
  5097. $this->array_options = array();
  5098. if (!is_array($optionsArray)) {
  5099. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  5100. if (!isset($extrafields) || !is_object($extrafields)) {
  5101. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5102. $extrafields = new ExtraFields($this->db);
  5103. }
  5104. // Load array of extrafields for elementype = $this->table_element
  5105. if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
  5106. $extrafields->fetch_name_optionals_label($this->table_element);
  5107. }
  5108. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  5109. } else {
  5110. global $extrafields;
  5111. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  5112. }
  5113. $table_element = $this->table_element;
  5114. if ($table_element == 'categorie') {
  5115. $table_element = 'categories'; // For compatibility
  5116. }
  5117. // Request to get complementary values
  5118. if (is_array($optionsArray) && count($optionsArray) > 0) {
  5119. $sql = "SELECT rowid";
  5120. foreach ($optionsArray as $name => $label) {
  5121. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
  5122. $sql .= ", ".$name;
  5123. }
  5124. }
  5125. $sql .= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
  5126. $sql .= " WHERE fk_object = ".((int) $rowid);
  5127. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5128. $resql = $this->db->query($sql);
  5129. if ($resql) {
  5130. $numrows = $this->db->num_rows($resql);
  5131. if ($numrows) {
  5132. $tab = $this->db->fetch_array($resql);
  5133. foreach ($tab as $key => $value) {
  5134. // 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)
  5135. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
  5136. // we can add this attribute to object
  5137. if (!empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
  5138. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  5139. $this->array_options["options_".$key] = $this->db->jdate($value);
  5140. } else {
  5141. $this->array_options["options_".$key] = $value;
  5142. }
  5143. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  5144. }
  5145. }
  5146. // If field is a computed field, value must become result of compute
  5147. foreach ($tab as $key => $value) {
  5148. if (!empty($extrafields) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
  5149. //var_dump($conf->disable_compute);
  5150. if (empty($conf->disable_compute)) {
  5151. $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0);
  5152. }
  5153. }
  5154. }
  5155. }
  5156. $this->db->free($resql);
  5157. if ($numrows) {
  5158. return $numrows;
  5159. } else {
  5160. return 0;
  5161. }
  5162. } else {
  5163. $this->errors[]=$this->db->lasterror;
  5164. return -1;
  5165. }
  5166. }
  5167. return 0;
  5168. }
  5169. /**
  5170. * Delete all extra fields values for the current object.
  5171. *
  5172. * @return int <0 if KO, >0 if OK
  5173. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  5174. */
  5175. public function deleteExtraFields()
  5176. {
  5177. global $conf;
  5178. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5179. return 0;
  5180. }
  5181. $this->db->begin();
  5182. $table_element = $this->table_element;
  5183. if ($table_element == 'categorie') {
  5184. $table_element = 'categories'; // For compatibility
  5185. }
  5186. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  5187. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5188. $resql = $this->db->query($sql_del);
  5189. if (!$resql) {
  5190. $this->error = $this->db->lasterror();
  5191. $this->db->rollback();
  5192. return -1;
  5193. } else {
  5194. $this->db->commit();
  5195. return 1;
  5196. }
  5197. }
  5198. /**
  5199. * Add/Update all extra fields values for the current object.
  5200. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5201. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5202. *
  5203. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5204. * @param User $userused Object user
  5205. * @return int -1=error, O=did nothing, 1=OK
  5206. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  5207. */
  5208. public function insertExtraFields($trigger = '', $userused = null)
  5209. {
  5210. global $conf, $langs, $user;
  5211. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5212. return 0;
  5213. }
  5214. if (empty($userused)) {
  5215. $userused = $user;
  5216. }
  5217. $error = 0;
  5218. if (!empty($this->array_options)) {
  5219. // Check parameters
  5220. $langs->load('admin');
  5221. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5222. $extrafields = new ExtraFields($this->db);
  5223. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  5224. // Eliminate copied source object extra fields that do not exist in target object
  5225. $new_array_options = array();
  5226. foreach ($this->array_options as $key => $value) {
  5227. if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
  5228. $new_array_options[$key] = $value;
  5229. } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
  5230. $new_array_options['options_'.$key] = $value;
  5231. }
  5232. }
  5233. foreach ($new_array_options as $key => $value) {
  5234. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5235. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  5236. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  5237. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  5238. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  5239. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  5240. // Similar code than into insertExtraFields
  5241. if ($attributeRequired) {
  5242. $mandatorypb = false;
  5243. if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
  5244. $mandatorypb = true;
  5245. }
  5246. if ($this->array_options[$key] === '') {
  5247. $mandatorypb = true;
  5248. }
  5249. if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
  5250. $mandatorypb = true;
  5251. }
  5252. if ($mandatorypb) {
  5253. $langs->load("errors");
  5254. dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
  5255. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5256. return -1;
  5257. }
  5258. }
  5259. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5260. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5261. if (!empty($attrfieldcomputed)) {
  5262. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5263. $value = dol_eval($attrfieldcomputed, 1, 0);
  5264. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5265. $new_array_options[$key] = $value;
  5266. } else {
  5267. $new_array_options[$key] = null;
  5268. }
  5269. }
  5270. switch ($attributeType) {
  5271. case 'int':
  5272. if (!is_numeric($value) && $value != '') {
  5273. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5274. return -1;
  5275. } elseif ($value == '') {
  5276. $new_array_options[$key] = null;
  5277. }
  5278. break;
  5279. case 'price':
  5280. case 'double':
  5281. $value = price2num($value);
  5282. if (!is_numeric($value) && $value != '') {
  5283. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5284. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5285. return -1;
  5286. } elseif ($value == '') {
  5287. $new_array_options[$key] = null;
  5288. }
  5289. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5290. $new_array_options[$key] = $value;
  5291. break;
  5292. /*case 'select': // Not required, we chosed value='0' for undefined values
  5293. if ($value=='-1')
  5294. {
  5295. $this->array_options[$key] = null;
  5296. }
  5297. break;*/
  5298. case 'password':
  5299. $algo = '';
  5300. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
  5301. // If there is an encryption choice, we use it to crypt data before insert
  5302. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  5303. $algo = reset($tmparrays);
  5304. if ($algo != '') {
  5305. //global $action; // $action may be 'create', 'update', 'update_extras'...
  5306. //var_dump($action);
  5307. //var_dump($this->oldcopy);exit;
  5308. 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
  5309. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  5310. 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.
  5311. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5312. } else {
  5313. // var_dump($algo);
  5314. $newvalue = dol_hash($this->array_options[$key], $algo);
  5315. $new_array_options[$key] = $newvalue;
  5316. }
  5317. } else {
  5318. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5319. }
  5320. }
  5321. } else // Common usage
  5322. {
  5323. $new_array_options[$key] = $this->array_options[$key];
  5324. }
  5325. break;
  5326. case 'date':
  5327. case 'datetime':
  5328. // If data is a string instead of a timestamp, we convert it
  5329. if (!is_int($this->array_options[$key])) {
  5330. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5331. }
  5332. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  5333. break;
  5334. case 'link':
  5335. $param_list = array_keys($attributeParam['options']);
  5336. // 0 : ObjectName
  5337. // 1 : classPath
  5338. $InfoFieldList = explode(":", $param_list[0]);
  5339. dol_include_once($InfoFieldList[1]);
  5340. if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
  5341. if ($value == '-1') { // -1 is key for no defined in combo list of objects
  5342. $new_array_options[$key] = '';
  5343. } elseif ($value) {
  5344. $object = new $InfoFieldList[0]($this->db);
  5345. if (is_numeric($value)) {
  5346. $res = $object->fetch($value); // Common case
  5347. } else {
  5348. $res = $object->fetch('', $value); // For compatibility
  5349. }
  5350. if ($res > 0) {
  5351. $new_array_options[$key] = $object->id;
  5352. } else {
  5353. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5354. $this->db->rollback();
  5355. return -1;
  5356. }
  5357. }
  5358. } else {
  5359. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5360. }
  5361. break;
  5362. }
  5363. }
  5364. $this->db->begin();
  5365. $table_element = $this->table_element;
  5366. if ($table_element == 'categorie') {
  5367. $table_element = 'categories'; // For compatibility
  5368. }
  5369. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  5370. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5371. $this->db->query($sql_del);
  5372. $sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object";
  5373. foreach ($new_array_options as $key => $value) {
  5374. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5375. // Add field of attribut
  5376. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
  5377. $sql .= ",".$attributeKey;
  5378. }
  5379. }
  5380. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5381. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5382. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5383. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5384. $sql .= ",".$tmpkey;
  5385. }
  5386. }
  5387. }
  5388. $sql .= ") VALUES (".$this->id;
  5389. foreach ($new_array_options as $key => $value) {
  5390. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5391. // Add field of attribute
  5392. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
  5393. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
  5394. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  5395. } else {
  5396. $sql .= ",null";
  5397. }
  5398. }
  5399. }
  5400. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5401. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5402. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5403. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5404. if (in_array($tmpval, array('int', 'double', 'price'))) {
  5405. $sql .= ", 0";
  5406. } else {
  5407. $sql .= ", ''";
  5408. }
  5409. }
  5410. }
  5411. }
  5412. $sql .= ")";
  5413. $resql = $this->db->query($sql);
  5414. if (!$resql) {
  5415. $this->error = $this->db->lasterror();
  5416. $error++;
  5417. }
  5418. if (!$error && $trigger) {
  5419. // Call trigger
  5420. $this->context = array('extrafieldaddupdate'=>1);
  5421. $result = $this->call_trigger($trigger, $userused);
  5422. if ($result < 0) {
  5423. $error++;
  5424. }
  5425. // End call trigger
  5426. }
  5427. if ($error) {
  5428. $this->db->rollback();
  5429. return -1;
  5430. } else {
  5431. $this->db->commit();
  5432. return 1;
  5433. }
  5434. } else {
  5435. return 0;
  5436. }
  5437. }
  5438. /**
  5439. * Add/Update all extra fields values for the current object.
  5440. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5441. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5442. *
  5443. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5444. * @param User $userused Object user
  5445. * @return int -1=error, O=did nothing, 1=OK
  5446. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  5447. */
  5448. public function insertExtraLanguages($trigger = '', $userused = null)
  5449. {
  5450. global $conf, $langs, $user;
  5451. if (empty($userused)) {
  5452. $userused = $user;
  5453. }
  5454. $error = 0;
  5455. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5456. return 0; // For avoid conflicts if trigger used
  5457. }
  5458. if (is_array($this->array_languages)) {
  5459. $new_array_languages = $this->array_languages;
  5460. foreach ($new_array_languages as $key => $value) {
  5461. $attributeKey = $key;
  5462. $attributeType = $this->fields[$attributeKey]['type'];
  5463. $attributeLabel = $this->fields[$attributeKey]['label'];
  5464. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5465. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5466. switch ($attributeType) {
  5467. case 'int':
  5468. if (!is_numeric($value) && $value != '') {
  5469. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5470. return -1;
  5471. } elseif ($value == '') {
  5472. $new_array_languages[$key] = null;
  5473. }
  5474. break;
  5475. case 'double':
  5476. $value = price2num($value);
  5477. if (!is_numeric($value) && $value != '') {
  5478. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5479. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5480. return -1;
  5481. } elseif ($value == '') {
  5482. $new_array_languages[$key] = null;
  5483. }
  5484. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5485. $new_array_languages[$key] = $value;
  5486. break;
  5487. /*case 'select': // Not required, we chosed value='0' for undefined values
  5488. if ($value=='-1')
  5489. {
  5490. $this->array_options[$key] = null;
  5491. }
  5492. break;*/
  5493. }
  5494. }
  5495. $this->db->begin();
  5496. $table_element = $this->table_element;
  5497. if ($table_element == 'categorie') {
  5498. $table_element = 'categories'; // For compatibility
  5499. }
  5500. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  5501. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  5502. foreach ($langcodearray as $langcode => $value) {
  5503. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX."object_lang";
  5504. $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  5505. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  5506. $this->db->query($sql_del);
  5507. if ($value !== '') {
  5508. $sql = "INSERT INTO ".MAIN_DB_PREFIX."object_lang (fk_object, property, type_object, lang, value";
  5509. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  5510. $sql .= ")";
  5511. $resql = $this->db->query($sql);
  5512. if (!$resql) {
  5513. $this->error = $this->db->lasterror();
  5514. $error++;
  5515. break;
  5516. }
  5517. }
  5518. }
  5519. }
  5520. if (!$error && $trigger) {
  5521. // Call trigger
  5522. $this->context = array('extralanguagesaddupdate'=>1);
  5523. $result = $this->call_trigger($trigger, $userused);
  5524. if ($result < 0) {
  5525. $error++;
  5526. }
  5527. // End call trigger
  5528. }
  5529. if ($error) {
  5530. $this->db->rollback();
  5531. return -1;
  5532. } else {
  5533. $this->db->commit();
  5534. return 1;
  5535. }
  5536. } else {
  5537. return 0;
  5538. }
  5539. }
  5540. /**
  5541. * Update 1 extra field value for the current object. Keep other fields unchanged.
  5542. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5543. *
  5544. * @param string $key Key of the extrafield to update (without starting 'options_')
  5545. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5546. * @param User $userused Object user
  5547. * @return int -1=error, O=did nothing, 1=OK
  5548. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  5549. */
  5550. public function updateExtraField($key, $trigger = null, $userused = null)
  5551. {
  5552. global $conf, $langs, $user;
  5553. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5554. return 0;
  5555. }
  5556. if (empty($userused)) {
  5557. $userused = $user;
  5558. }
  5559. $error = 0;
  5560. if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
  5561. // Check parameters
  5562. $langs->load('admin');
  5563. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5564. $extrafields = new ExtraFields($this->db);
  5565. $extrafields->fetch_name_optionals_label($this->table_element);
  5566. $value = $this->array_options["options_".$key];
  5567. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  5568. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  5569. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  5570. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  5571. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  5572. // Similar code than into insertExtraFields
  5573. if ($attributeRequired) {
  5574. $mandatorypb = false;
  5575. if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
  5576. $mandatorypb = true;
  5577. }
  5578. if ($this->array_options["options_".$key] === '') {
  5579. $mandatorypb = true;
  5580. }
  5581. if ($mandatorypb) {
  5582. $langs->load("errors");
  5583. dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
  5584. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5585. return -1;
  5586. }
  5587. }
  5588. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5589. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5590. if (!empty($attrfieldcomputed)) {
  5591. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5592. $value = dol_eval($attrfieldcomputed, 1, 0);
  5593. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5594. $this->array_options["options_".$key] = $value;
  5595. } else {
  5596. $this->array_options["options_".$key] = null;
  5597. }
  5598. }
  5599. switch ($attributeType) {
  5600. case 'int':
  5601. if (!is_numeric($value) && $value != '') {
  5602. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5603. return -1;
  5604. } elseif ($value === '') {
  5605. $this->array_options["options_".$key] = null;
  5606. }
  5607. break;
  5608. case 'double':
  5609. $value = price2num($value);
  5610. if (!is_numeric($value) && $value != '') {
  5611. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5612. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5613. return -1;
  5614. } elseif ($value === '') {
  5615. $this->array_options["options_".$key] = null;
  5616. }
  5617. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5618. $this->array_options["options_".$key] = $value;
  5619. break;
  5620. /*case 'select': // Not required, we chosed value='0' for undefined values
  5621. if ($value=='-1')
  5622. {
  5623. $this->array_options[$key] = null;
  5624. }
  5625. break;*/
  5626. case 'price':
  5627. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  5628. break;
  5629. case 'date':
  5630. case 'datetime':
  5631. if (empty($this->array_options["options_".$key])) {
  5632. $this->array_options["options_".$key] = null;
  5633. } else {
  5634. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5635. }
  5636. break;
  5637. case 'boolean':
  5638. if (empty($this->array_options["options_".$key])) {
  5639. $this->array_options["options_".$key] = null;
  5640. }
  5641. break;
  5642. /*
  5643. case 'link':
  5644. $param_list = array_keys($attributeParam['options']);
  5645. // 0 : ObjectName
  5646. // 1 : classPath
  5647. $InfoFieldList = explode(":", $param_list[0]);
  5648. dol_include_once($InfoFieldList[1]);
  5649. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  5650. {
  5651. if ($value == '-1') // -1 is key for no defined in combo list of objects
  5652. {
  5653. $new_array_options[$key] = '';
  5654. } elseif ($value) {
  5655. $object = new $InfoFieldList[0]($this->db);
  5656. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  5657. else $res = $object->fetch('', $value); // For compatibility
  5658. if ($res > 0) $new_array_options[$key] = $object->id;
  5659. else {
  5660. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5661. $this->db->rollback();
  5662. return -1;
  5663. }
  5664. }
  5665. } else {
  5666. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5667. }
  5668. break;
  5669. */
  5670. }
  5671. $this->db->begin();
  5672. $linealreadyfound = 0;
  5673. // Check if there is already a line for this object (in most cases, it is, but sometimes it is not, for example when extra field has been created after), so we must keep this overload)
  5674. $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5675. $resql = $this->db->query($sql);
  5676. if ($resql) {
  5677. $tmpobj = $this->db->fetch_object($resql);
  5678. if ($tmpobj) {
  5679. $linealreadyfound = $tmpobj->nb;
  5680. }
  5681. }
  5682. if ($linealreadyfound) {
  5683. if ($this->array_options["options_".$key] === null) {
  5684. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key." = null";
  5685. } else {
  5686. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
  5687. }
  5688. $sql .= " WHERE fk_object = ".((int) $this->id);
  5689. } else {
  5690. $result = $this->insertExtraFields('', $user);
  5691. if ($result < 0) {
  5692. $error++;
  5693. }
  5694. }
  5695. $resql = $this->db->query($sql);
  5696. if (!$resql) {
  5697. $error++;
  5698. $this->error = $this->db->lasterror();
  5699. }
  5700. if (!$error && $trigger) {
  5701. // Call trigger
  5702. $this->context = array('extrafieldupdate'=>1);
  5703. $result = $this->call_trigger($trigger, $userused);
  5704. if ($result < 0) {
  5705. $error++;
  5706. }
  5707. // End call trigger
  5708. }
  5709. if ($error) {
  5710. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  5711. $this->db->rollback();
  5712. return -1;
  5713. } else {
  5714. $this->db->commit();
  5715. return 1;
  5716. }
  5717. } else {
  5718. return 0;
  5719. }
  5720. }
  5721. /**
  5722. * Update an extra language value for the current object.
  5723. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5724. *
  5725. * @param string $key Key of the extrafield (without starting 'options_')
  5726. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5727. * @param User $userused Object user
  5728. * @return int -1=error, O=did nothing, 1=OK
  5729. * @see updateExtraFields(), insertExtraLanguages()
  5730. */
  5731. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  5732. {
  5733. global $conf, $langs, $user;
  5734. if (empty($userused)) {
  5735. $userused = $user;
  5736. }
  5737. $error = 0;
  5738. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5739. return 0; // For avoid conflicts if trigger used
  5740. }
  5741. return 0;
  5742. }
  5743. /**
  5744. * Return HTML string to put an input field into a page
  5745. * Code very similar with showInputField of extra fields
  5746. *
  5747. * @param array $val Array of properties for field to show (used only if ->fields not defined)
  5748. * @param string $key Key of attribute
  5749. * @param string|array $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, for array type must be array)
  5750. * @param string $moreparam To add more parameters on html input tag
  5751. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5752. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5753. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  5754. * @param int $nonewbutton Force to not show the new button on field that are links to object
  5755. * @return string
  5756. */
  5757. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  5758. {
  5759. global $conf, $langs, $form;
  5760. if (!is_object($form)) {
  5761. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  5762. $form = new Form($this->db);
  5763. }
  5764. if (!empty($this->fields)) {
  5765. $val = $this->fields[$key];
  5766. }
  5767. // Validation tests and output
  5768. $fieldValidationErrorMsg = '';
  5769. $validationClass = '';
  5770. $fieldValidationErrorMsg = $this->getFieldError($key);
  5771. if (!empty($fieldValidationErrorMsg)) {
  5772. $validationClass = ' --error'; // the -- is use as class state in css : .--error can't be be defined alone it must be define with another class like .my-class.--error or input.--error
  5773. } else {
  5774. $validationClass = ' --success'; // the -- is use as class state in css : .--success can't be be defined alone it must be define with another class like .my-class.--success or input.--success
  5775. }
  5776. $out = '';
  5777. $type = '';
  5778. $isDependList = 0;
  5779. $param = array();
  5780. $param['options'] = array();
  5781. $reg = array();
  5782. $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
  5783. // Because we work on extrafields
  5784. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5785. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5786. $type = 'link';
  5787. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5788. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5789. $type = 'link';
  5790. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  5791. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5792. $type = 'link';
  5793. } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5794. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5795. $type = 'sellist';
  5796. } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5797. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5798. $type = 'sellist';
  5799. } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
  5800. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5801. $type = 'sellist';
  5802. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  5803. $param['options'] = array();
  5804. $type = 'varchar';
  5805. $size = $reg[1];
  5806. } elseif (preg_match('/varchar/', $val['type'])) {
  5807. $param['options'] = array();
  5808. $type = 'varchar';
  5809. } else {
  5810. $param['options'] = array();
  5811. $type = $this->fields[$key]['type'];
  5812. }
  5813. // Special case that force options and type ($type can be integer, varchar, ...)
  5814. if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
  5815. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  5816. $type = 'select';
  5817. }
  5818. $label = $this->fields[$key]['label'];
  5819. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  5820. $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
  5821. $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
  5822. $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
  5823. $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
  5824. $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
  5825. $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
  5826. $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
  5827. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  5828. $objectid = $this->id;
  5829. if ($computed) {
  5830. if (!preg_match('/^search_/', $keyprefix)) {
  5831. return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  5832. } else {
  5833. return '';
  5834. }
  5835. }
  5836. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  5837. if (empty($morecss) && !empty($val['css'])) {
  5838. $morecss = $val['css'];
  5839. } elseif (empty($morecss)) {
  5840. if ($type == 'date') {
  5841. $morecss = 'minwidth100imp';
  5842. } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
  5843. $morecss = 'minwidth200imp';
  5844. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  5845. $morecss = 'maxwidth75';
  5846. } elseif ($type == 'url') {
  5847. $morecss = 'minwidth400';
  5848. } elseif ($type == 'boolean') {
  5849. $morecss = '';
  5850. } else {
  5851. if (round($size) < 12) {
  5852. $morecss = 'minwidth100';
  5853. } elseif (round($size) <= 48) {
  5854. $morecss = 'minwidth200';
  5855. } else {
  5856. $morecss = 'minwidth400';
  5857. }
  5858. }
  5859. }
  5860. // Add validation state class
  5861. if (!empty($validationClass)) {
  5862. $morecss.= ' '.$validationClass;
  5863. }
  5864. if (in_array($type, array('date'))) {
  5865. $tmp = explode(',', $size);
  5866. $newsize = $tmp[0];
  5867. $showtime = 0;
  5868. // Do not show current date when field not required (see selectDate() method)
  5869. if (!$required && $value == '') {
  5870. $value = '-1';
  5871. }
  5872. // TODO Must also support $moreparam
  5873. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  5874. } elseif (in_array($type, array('datetime'))) {
  5875. $tmp = explode(',', $size);
  5876. $newsize = $tmp[0];
  5877. $showtime = 1;
  5878. // Do not show current date when field not required (see selectDate() method)
  5879. if (!$required && $value == '') $value = '-1';
  5880. // TODO Must also support $moreparam
  5881. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
  5882. } elseif (in_array($type, array('duration'))) {
  5883. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  5884. } elseif (in_array($type, array('int', 'integer'))) {
  5885. $tmp = explode(',', $size);
  5886. $newsize = $tmp[0];
  5887. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"'.($newsize > 0 ? ' maxlength="'.$newsize.'"' : '').' value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5888. } elseif (in_array($type, array('real'))) {
  5889. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5890. } elseif (preg_match('/varchar/', $type)) {
  5891. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"'.($size > 0 ? ' maxlength="'.$size.'"' : '').' value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5892. } elseif (in_array($type, array('mail', 'phone', 'url'))) {
  5893. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5894. } elseif (preg_match('/^text/', $type)) {
  5895. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  5896. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5897. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  5898. $out = $doleditor->Create(1);
  5899. } else {
  5900. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5901. }
  5902. } elseif (preg_match('/^html/', $type)) {
  5903. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  5904. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5905. $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%');
  5906. $out = $doleditor->Create(1);
  5907. } else {
  5908. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5909. }
  5910. } elseif ($type == 'boolean') {
  5911. $checked = '';
  5912. if (!empty($value)) {
  5913. $checked = ' checked value="1" ';
  5914. } else {
  5915. $checked = ' value="1" ';
  5916. }
  5917. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  5918. } elseif ($type == 'price') {
  5919. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5920. $value = price($value);
  5921. }
  5922. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  5923. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  5924. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5925. $value = price($value);
  5926. }
  5927. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  5928. } elseif ($type == 'select') {
  5929. $out = '';
  5930. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  5931. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5932. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  5933. }
  5934. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  5935. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
  5936. $out .= '<option value="0">&nbsp;</option>';
  5937. }
  5938. foreach ($param['options'] as $key => $val) {
  5939. if ((string) $key == '') {
  5940. continue;
  5941. }
  5942. list($val, $parent) = explode('|', $val);
  5943. $out .= '<option value="'.$key.'"';
  5944. $out .= (((string) $value == (string) $key) ? ' selected' : '');
  5945. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  5946. $out .= '>'.$val.'</option>';
  5947. }
  5948. $out .= '</select>';
  5949. } elseif ($type == 'sellist') {
  5950. $out = '';
  5951. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  5952. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5953. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  5954. }
  5955. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  5956. if (is_array($param['options'])) {
  5957. $param_list = array_keys($param['options']);
  5958. $InfoFieldList = explode(":", $param_list[0]);
  5959. $parentName = '';
  5960. $parentField = '';
  5961. // 0 : tableName
  5962. // 1 : label field name
  5963. // 2 : key fields name (if differ of rowid)
  5964. // 3 : key field parent (for dependent lists)
  5965. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  5966. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  5967. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  5968. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  5969. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  5970. } else {
  5971. $keyList = $InfoFieldList[2].' as rowid';
  5972. }
  5973. }
  5974. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  5975. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  5976. $keyList .= ', '.$parentField;
  5977. }
  5978. $fields_label = explode('|', $InfoFieldList[1]);
  5979. if (is_array($fields_label)) {
  5980. $keyList .= ', ';
  5981. $keyList .= implode(', ', $fields_label);
  5982. }
  5983. $sqlwhere = '';
  5984. $sql = "SELECT ".$keyList;
  5985. $sql .= " FROM ".MAIN_DB_PREFIX.$InfoFieldList[0];
  5986. if (!empty($InfoFieldList[4])) {
  5987. // can use SELECT request
  5988. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  5989. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  5990. }
  5991. // current object id can be use into filter
  5992. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  5993. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  5994. } else {
  5995. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  5996. }
  5997. //We have to join on extrafield table
  5998. if (strpos($InfoFieldList[4], 'extra') !== false) {
  5999. $sql .= " as main, ".MAIN_DB_PREFIX.$InfoFieldList[0]."_extrafields as extra";
  6000. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  6001. } else {
  6002. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  6003. }
  6004. } else {
  6005. $sqlwhere .= ' WHERE 1=1';
  6006. }
  6007. // Some tables may have field, some other not. For the moment we disable it.
  6008. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6009. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  6010. }
  6011. $sql .= $sqlwhere;
  6012. //print $sql;
  6013. $sql .= ' ORDER BY '.implode(', ', $fields_label);
  6014. dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
  6015. $resql = $this->db->query($sql);
  6016. if ($resql) {
  6017. $out .= '<option value="0">&nbsp;</option>';
  6018. $num = $this->db->num_rows($resql);
  6019. $i = 0;
  6020. while ($i < $num) {
  6021. $labeltoshow = '';
  6022. $obj = $this->db->fetch_object($resql);
  6023. // Several field into label (eq table:code|libelle:rowid)
  6024. $notrans = false;
  6025. $fields_label = explode('|', $InfoFieldList[1]);
  6026. if (count($fields_label) > 1) {
  6027. $notrans = true;
  6028. foreach ($fields_label as $field_toshow) {
  6029. $labeltoshow .= $obj->$field_toshow.' ';
  6030. }
  6031. } else {
  6032. $labeltoshow = $obj->{$InfoFieldList[1]};
  6033. }
  6034. $labeltoshow = dol_trunc($labeltoshow, 45);
  6035. if ($value == $obj->rowid) {
  6036. foreach ($fields_label as $field_toshow) {
  6037. $translabel = $langs->trans($obj->$field_toshow);
  6038. if ($translabel != $obj->$field_toshow) {
  6039. $labeltoshow = dol_trunc($translabel).' ';
  6040. } else {
  6041. $labeltoshow = dol_trunc($obj->$field_toshow).' ';
  6042. }
  6043. }
  6044. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6045. } else {
  6046. if (!$notrans) {
  6047. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6048. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6049. $labeltoshow = dol_trunc($translabel, 18);
  6050. } else {
  6051. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
  6052. }
  6053. }
  6054. if (empty($labeltoshow)) {
  6055. $labeltoshow = '(not defined)';
  6056. }
  6057. if ($value == $obj->rowid) {
  6058. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6059. }
  6060. if (!empty($InfoFieldList[3]) && $parentField) {
  6061. $parent = $parentName.':'.$obj->{$parentField};
  6062. $isDependList = 1;
  6063. }
  6064. $out .= '<option value="'.$obj->rowid.'"';
  6065. $out .= ($value == $obj->rowid ? ' selected' : '');
  6066. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6067. $out .= '>'.$labeltoshow.'</option>';
  6068. }
  6069. $i++;
  6070. }
  6071. $this->db->free($resql);
  6072. } else {
  6073. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6074. }
  6075. }
  6076. $out .= '</select>';
  6077. } elseif ($type == 'checkbox') {
  6078. $value_arr = explode(',', $value);
  6079. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
  6080. } elseif ($type == 'radio') {
  6081. $out = '';
  6082. foreach ($param['options'] as $keyopt => $val) {
  6083. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  6084. $out .= ' value="'.$keyopt.'"';
  6085. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  6086. $out .= ($value == $keyopt ? 'checked' : '');
  6087. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
  6088. }
  6089. } elseif ($type == 'chkbxlst') {
  6090. if (is_array($value)) {
  6091. $value_arr = $value;
  6092. } else {
  6093. $value_arr = explode(',', $value);
  6094. }
  6095. if (is_array($param['options'])) {
  6096. $param_list = array_keys($param['options']);
  6097. $InfoFieldList = explode(":", $param_list[0]);
  6098. $parentName = '';
  6099. $parentField = '';
  6100. // 0 : tableName
  6101. // 1 : label field name
  6102. // 2 : key fields name (if differ of rowid)
  6103. // 3 : key field parent (for dependent lists)
  6104. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6105. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6106. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6107. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6108. $keyList .= ', '.$parentField;
  6109. }
  6110. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6111. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6112. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6113. } else {
  6114. $keyList = $InfoFieldList[2].' as rowid';
  6115. }
  6116. }
  6117. $fields_label = explode('|', $InfoFieldList[1]);
  6118. if (is_array($fields_label)) {
  6119. $keyList .= ', ';
  6120. $keyList .= implode(', ', $fields_label);
  6121. }
  6122. $sqlwhere = '';
  6123. $sql = "SELECT ".$keyList;
  6124. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6125. if (!empty($InfoFieldList[4])) {
  6126. // can use SELECT request
  6127. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6128. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6129. }
  6130. // current object id can be use into filter
  6131. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6132. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6133. } else {
  6134. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6135. }
  6136. // We have to join on extrafield table
  6137. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6138. $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
  6139. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  6140. } else {
  6141. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  6142. }
  6143. } else {
  6144. $sqlwhere .= ' WHERE 1=1';
  6145. }
  6146. // Some tables may have field, some other not. For the moment we disable it.
  6147. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6148. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  6149. }
  6150. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  6151. // print $sql;
  6152. $sql .= $sqlwhere;
  6153. dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
  6154. $resql = $this->db->query($sql);
  6155. if ($resql) {
  6156. $num = $this->db->num_rows($resql);
  6157. $i = 0;
  6158. $data = array();
  6159. while ($i < $num) {
  6160. $labeltoshow = '';
  6161. $obj = $this->db->fetch_object($resql);
  6162. $notrans = false;
  6163. // Several field into label (eq table:code|libelle:rowid)
  6164. $fields_label = explode('|', $InfoFieldList[1]);
  6165. if (count($fields_label) > 1) {
  6166. $notrans = true;
  6167. foreach ($fields_label as $field_toshow) {
  6168. $labeltoshow .= $obj->$field_toshow.' ';
  6169. }
  6170. } else {
  6171. $labeltoshow = $obj->{$InfoFieldList[1]};
  6172. }
  6173. $labeltoshow = dol_trunc($labeltoshow, 45);
  6174. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6175. foreach ($fields_label as $field_toshow) {
  6176. $translabel = $langs->trans($obj->$field_toshow);
  6177. if ($translabel != $obj->$field_toshow) {
  6178. $labeltoshow = dol_trunc($translabel, 18).' ';
  6179. } else {
  6180. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  6181. }
  6182. }
  6183. $data[$obj->rowid] = $labeltoshow;
  6184. } else {
  6185. if (!$notrans) {
  6186. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6187. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6188. $labeltoshow = dol_trunc($translabel, 18);
  6189. } else {
  6190. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  6191. }
  6192. }
  6193. if (empty($labeltoshow)) {
  6194. $labeltoshow = '(not defined)';
  6195. }
  6196. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6197. $data[$obj->rowid] = $labeltoshow;
  6198. }
  6199. if (!empty($InfoFieldList[3]) && $parentField) {
  6200. $parent = $parentName.':'.$obj->{$parentField};
  6201. $isDependList = 1;
  6202. }
  6203. $data[$obj->rowid] = $labeltoshow;
  6204. }
  6205. $i++;
  6206. }
  6207. $this->db->free($resql);
  6208. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
  6209. } else {
  6210. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6211. }
  6212. }
  6213. } elseif ($type == 'link') {
  6214. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
  6215. $param_list_array = explode(':', $param_list[0]);
  6216. $showempty = (($required && $default != '') ? 0 : 1);
  6217. if (!preg_match('/search_/', $keyprefix)) {
  6218. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6219. if (!empty($this->fields[$key]['picto'])) {
  6220. $morecss .= ' widthcentpercentminusxx';
  6221. } else {
  6222. $morecss .= ' widthcentpercentminusx';
  6223. }
  6224. } else {
  6225. if (!empty($this->fields[$key]['picto'])) {
  6226. $morecss .= ' widthcentpercentminusx';
  6227. }
  6228. }
  6229. }
  6230. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  6231. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6232. if (!GETPOSTISSET('backtopage') && empty($val['disabled']) && empty($nonewbutton)) { // To avoid to open several times the 'Create Object' button and to avoid to have button if field is protected by a "disabled".
  6233. list($class, $classfile) = explode(':', $param_list[0]);
  6234. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
  6235. $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  6236. } else {
  6237. $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  6238. }
  6239. $paramforthenewlink = '';
  6240. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  6241. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  6242. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  6243. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  6244. $out .= '<a class="butActionNew" title="'.$langs->trans("New").'" href="'.$url_path.'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF'].($paramforthenewlink ? '?'.$paramforthenewlink : '')).'"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6245. }
  6246. }
  6247. } elseif ($type == 'password') {
  6248. // If prefix is 'search_', field is used as a filter, we use a common text field.
  6249. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  6250. } elseif ($type == 'array') {
  6251. $newval = $val;
  6252. $newval['type'] = 'varchar(256)';
  6253. $out = '';
  6254. if (!empty($value)) {
  6255. foreach ($value as $option) {
  6256. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6257. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  6258. }
  6259. }
  6260. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6261. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6262. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  6263. if (!empty($conf->use_javascript_ajax)) {
  6264. $out .= '
  6265. <script>
  6266. $(document).ready(function() {
  6267. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  6268. $("'.dol_escape_js($newInput).'").insertBefore(this);
  6269. });
  6270. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  6271. $(this).parent().remove();
  6272. });
  6273. });
  6274. </script>';
  6275. }
  6276. }
  6277. if (!empty($hidden)) {
  6278. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  6279. }
  6280. if ($isDependList==1) {
  6281. $out .= $this->getJSListDependancies('_common');
  6282. }
  6283. /* Add comments
  6284. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  6285. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  6286. */
  6287. // Display error message for field
  6288. if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
  6289. $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
  6290. }
  6291. return $out;
  6292. }
  6293. /**
  6294. * Return HTML string to show a field into a page
  6295. * Code very similar with showOutputField of extra fields
  6296. *
  6297. * @param array $val Array of properties of field to show
  6298. * @param string $key Key of attribute
  6299. * @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)
  6300. * @param string $moreparam To add more parametes on html input tag
  6301. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6302. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6303. * @param mixed $morecss Value for css to define size. May also be a numeric.
  6304. * @return string
  6305. */
  6306. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  6307. {
  6308. global $conf, $langs, $form;
  6309. if (!is_object($form)) {
  6310. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6311. $form = new Form($this->db);
  6312. }
  6313. $objectid = $this->id; // Not used ???
  6314. $label = empty($val['label']) ? '' : $val['label'];
  6315. $type = empty($val['type']) ? '' : $val['type'];
  6316. $size = empty($val['css']) ? '' : $val['css'];
  6317. $reg = array();
  6318. // Convert var to be able to share same code than showOutputField of extrafields
  6319. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6320. $type = 'varchar'; // convert varchar(xx) int varchar
  6321. $size = $reg[1];
  6322. } elseif (preg_match('/varchar/', $type)) {
  6323. $type = 'varchar'; // convert varchar(xx) int varchar
  6324. }
  6325. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6326. $type = 'select';
  6327. }
  6328. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6329. $type = 'link';
  6330. }
  6331. $default = empty($val['default']) ? '' : $val['default'];
  6332. $computed = empty($val['computed']) ? '' : $val['computed'];
  6333. $unique = empty($val['unique']) ? '' : $val['unique'];
  6334. $required = empty($val['required']) ? '' : $val['required'];
  6335. $param = array();
  6336. $param['options'] = array();
  6337. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6338. $param['options'] = $val['arrayofkeyval'];
  6339. }
  6340. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6341. $type = 'link';
  6342. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6343. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6344. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6345. $type = 'sellist';
  6346. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6347. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6348. $type = 'sellist';
  6349. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6350. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6351. $type = 'sellist';
  6352. }
  6353. $langfile = empty($val['langfile']) ? '' : $val['langfile'];
  6354. $list = (empty($val['list']) ? '' : $val['list']);
  6355. $help = (empty($val['help']) ? '' : $val['help']);
  6356. $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)
  6357. if ($hidden) {
  6358. return '';
  6359. }
  6360. // If field is a computed field, value must become result of compute
  6361. if ($computed) {
  6362. // Make the eval of compute string
  6363. //var_dump($computed);
  6364. $value = dol_eval($computed, 1, 0);
  6365. }
  6366. if (empty($morecss)) {
  6367. if ($type == 'date') {
  6368. $morecss = 'minwidth100imp';
  6369. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6370. $morecss = 'minwidth200imp';
  6371. } elseif (in_array($type, array('int', 'double', 'price'))) {
  6372. $morecss = 'maxwidth75';
  6373. } elseif ($type == 'url') {
  6374. $morecss = 'minwidth400';
  6375. } elseif ($type == 'boolean') {
  6376. $morecss = '';
  6377. } else {
  6378. if (is_numeric($size) && round($size) < 12) {
  6379. $morecss = 'minwidth100';
  6380. } elseif (is_numeric($size) && round($size) <= 48) {
  6381. $morecss = 'minwidth200';
  6382. } else {
  6383. $morecss = 'minwidth400';
  6384. }
  6385. }
  6386. }
  6387. // Format output value differently according to properties of field
  6388. if ($key == 'ref' && method_exists($this, 'getNomUrl')) {
  6389. $value = $this->getNomUrl(1, '', 0, '', 1);
  6390. } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
  6391. $value = $this->getLibStatut(3);
  6392. } elseif ($type == 'date') {
  6393. if (!empty($value)) {
  6394. $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
  6395. } else {
  6396. $value = '';
  6397. }
  6398. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6399. if (!empty($value)) {
  6400. $value = dol_print_date($value, 'dayhour', 'tzuserrel');
  6401. } else {
  6402. $value = '';
  6403. }
  6404. } elseif ($type == 'duration') {
  6405. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6406. if (!is_null($value) && $value !== '') {
  6407. $value = convertSecondToTime($value, 'allhourmin');
  6408. }
  6409. } elseif ($type == 'double' || $type == 'real') {
  6410. if (!is_null($value) && $value !== '') {
  6411. $value = price($value);
  6412. }
  6413. } elseif ($type == 'boolean') {
  6414. $checked = '';
  6415. if (!empty($value)) {
  6416. $checked = ' checked ';
  6417. }
  6418. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  6419. } elseif ($type == 'mail') {
  6420. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  6421. } elseif ($type == 'url') {
  6422. $value = dol_print_url($value, '_blank', 32, 1);
  6423. } elseif ($type == 'phone') {
  6424. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
  6425. } elseif ($type == 'price') {
  6426. if (!is_null($value) && $value !== '') {
  6427. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  6428. }
  6429. } elseif ($type == 'select') {
  6430. $value = $param['options'][$value];
  6431. } elseif ($type == 'sellist') {
  6432. $param_list = array_keys($param['options']);
  6433. $InfoFieldList = explode(":", $param_list[0]);
  6434. $selectkey = "rowid";
  6435. $keyList = 'rowid';
  6436. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6437. $selectkey = $InfoFieldList[2];
  6438. $keyList = $InfoFieldList[2].' as rowid';
  6439. }
  6440. $fields_label = explode('|', $InfoFieldList[1]);
  6441. if (is_array($fields_label)) {
  6442. $keyList .= ', ';
  6443. $keyList .= implode(', ', $fields_label);
  6444. }
  6445. $sql = "SELECT ".$keyList;
  6446. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6447. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6448. $sql .= ' as main';
  6449. }
  6450. if ($selectkey == 'rowid' && empty($value)) {
  6451. $sql .= " WHERE ".$selectkey." = 0";
  6452. } elseif ($selectkey == 'rowid') {
  6453. $sql .= " WHERE ".$selectkey." = ".((int) $value);
  6454. } else {
  6455. $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
  6456. }
  6457. //$sql.= ' AND entity = '.$conf->entity;
  6458. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  6459. $resql = $this->db->query($sql);
  6460. if ($resql) {
  6461. $value = ''; // value was used, so now we reste it to use it to build final output
  6462. $obj = $this->db->fetch_object($resql);
  6463. // Several field into label (eq table:code|libelle:rowid)
  6464. $fields_label = explode('|', $InfoFieldList[1]);
  6465. if (is_array($fields_label) && count($fields_label) > 1) {
  6466. foreach ($fields_label as $field_toshow) {
  6467. $translabel = '';
  6468. if (!empty($obj->$field_toshow)) {
  6469. $translabel = $langs->trans($obj->$field_toshow);
  6470. }
  6471. if ($translabel != $field_toshow) {
  6472. $value .= dol_trunc($translabel, 18).' ';
  6473. } else {
  6474. $value .= $obj->$field_toshow.' ';
  6475. }
  6476. }
  6477. } else {
  6478. $translabel = '';
  6479. if (!empty($obj->{$InfoFieldList[1]})) {
  6480. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6481. }
  6482. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6483. $value = dol_trunc($translabel, 18);
  6484. } else {
  6485. $value = $obj->{$InfoFieldList[1]};
  6486. }
  6487. }
  6488. } else {
  6489. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6490. }
  6491. } elseif ($type == 'radio') {
  6492. $value = $param['options'][$value];
  6493. } elseif ($type == 'checkbox') {
  6494. $value_arr = explode(',', $value);
  6495. $value = '';
  6496. if (is_array($value_arr) && count($value_arr) > 0) {
  6497. $toprint = array();
  6498. foreach ($value_arr as $keyval => $valueval) {
  6499. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  6500. }
  6501. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6502. }
  6503. } elseif ($type == 'chkbxlst') {
  6504. $value_arr = explode(',', $value);
  6505. $param_list = array_keys($param['options']);
  6506. $InfoFieldList = explode(":", $param_list[0]);
  6507. $selectkey = "rowid";
  6508. $keyList = 'rowid';
  6509. if (count($InfoFieldList) >= 3) {
  6510. $selectkey = $InfoFieldList[2];
  6511. $keyList = $InfoFieldList[2].' as rowid';
  6512. }
  6513. $fields_label = explode('|', $InfoFieldList[1]);
  6514. if (is_array($fields_label)) {
  6515. $keyList .= ', ';
  6516. $keyList .= implode(', ', $fields_label);
  6517. }
  6518. $sql = "SELECT ".$keyList;
  6519. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6520. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6521. $sql .= ' as main';
  6522. }
  6523. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  6524. // $sql.= ' AND entity = '.$conf->entity;
  6525. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  6526. $resql = $this->db->query($sql);
  6527. if ($resql) {
  6528. $value = ''; // value was used, so now we reste it to use it to build final output
  6529. $toprint = array();
  6530. while ($obj = $this->db->fetch_object($resql)) {
  6531. // Several field into label (eq table:code|libelle:rowid)
  6532. $fields_label = explode('|', $InfoFieldList[1]);
  6533. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6534. if (is_array($fields_label) && count($fields_label) > 1) {
  6535. foreach ($fields_label as $field_toshow) {
  6536. $translabel = '';
  6537. if (!empty($obj->$field_toshow)) {
  6538. $translabel = $langs->trans($obj->$field_toshow);
  6539. }
  6540. if ($translabel != $field_toshow) {
  6541. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6542. } else {
  6543. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->$field_toshow.'</li>';
  6544. }
  6545. }
  6546. } else {
  6547. $translabel = '';
  6548. if (!empty($obj->{$InfoFieldList[1]})) {
  6549. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6550. }
  6551. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6552. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6553. } else {
  6554. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->{$InfoFieldList[1]}.'</li>';
  6555. }
  6556. }
  6557. }
  6558. }
  6559. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6560. } else {
  6561. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6562. }
  6563. } elseif ($type == 'link') {
  6564. $out = '';
  6565. // only if something to display (perf)
  6566. if ($value) {
  6567. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6568. $InfoFieldList = explode(":", $param_list[0]);
  6569. $classname = $InfoFieldList[0];
  6570. $classpath = $InfoFieldList[1];
  6571. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  6572. $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
  6573. if (!empty($classpath)) {
  6574. dol_include_once($InfoFieldList[1]);
  6575. if ($classname && class_exists($classname)) {
  6576. $object = new $classname($this->db);
  6577. if ($object->element === 'product') { // Special cas for product because default valut of fetch are wrong
  6578. $object->fetch($value, '', '', '', 0, 1, 1);
  6579. } else {
  6580. $object->fetch($value);
  6581. }
  6582. $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
  6583. }
  6584. } else {
  6585. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  6586. return 'Error bad setup of extrafield';
  6587. }
  6588. } else {
  6589. $value = '';
  6590. }
  6591. } elseif (preg_match('/^(text|html)/', $type)) {
  6592. $value = dol_htmlentitiesbr($value);
  6593. } elseif ($type == 'password') {
  6594. $value = preg_replace('/./i', '*', $value);
  6595. } elseif ($type == 'array') {
  6596. $value = implode('<br>', $value);
  6597. }
  6598. //print $type.'-'.$size.'-'.$value;
  6599. $out = $value;
  6600. return $out;
  6601. }
  6602. /**
  6603. * clear validation message result for a field
  6604. *
  6605. * @param string $fieldKey Key of attribute to clear
  6606. * @return null
  6607. */
  6608. public function clearFieldError($fieldKey)
  6609. {
  6610. $this->error = '';
  6611. unset($this->validateFieldsErrors[$fieldKey]);
  6612. }
  6613. /**
  6614. * set validation error message a field
  6615. *
  6616. * @param string $fieldKey Key of attribute
  6617. * @param string $msg the field error message
  6618. * @return null
  6619. */
  6620. public function setFieldError($fieldKey, $msg = '')
  6621. {
  6622. global $langs;
  6623. if (empty($msg)) { $msg = $langs->trans("UnknowError"); }
  6624. $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
  6625. }
  6626. /**
  6627. * get field error message
  6628. *
  6629. * @param string $fieldKey Key of attribute
  6630. * @return string
  6631. */
  6632. public function getFieldError($fieldKey)
  6633. {
  6634. if (!empty($this->validateFieldsErrors[$fieldKey])) {
  6635. return $this->validateFieldsErrors[$fieldKey];
  6636. }
  6637. return '';
  6638. }
  6639. /**
  6640. * Return validation test result for a field
  6641. *
  6642. * @param array $val Array of properties of field to show
  6643. * @param string $fieldKey Key of attribute
  6644. * @param string $fieldValue value of attribute
  6645. * @return bool return false if fail true on success, see $this->error for error message
  6646. */
  6647. public function validateField($val, $fieldKey, $fieldValue)
  6648. {
  6649. global $langs;
  6650. if (!class_exists('Validate')) { require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php'; }
  6651. $this->clearFieldError($fieldKey);
  6652. if (!isset($val[$fieldKey])) {
  6653. $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
  6654. return false;
  6655. }
  6656. $param = array();
  6657. $param['options'] = array();
  6658. $type = $val[$fieldKey]['type'];
  6659. $required = false;
  6660. if (isset($val[$fieldKey]['notnull']) && $val[$fieldKey]['notnull'] === 1) {
  6661. // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  6662. $required = true;
  6663. }
  6664. $maxSize = 0;
  6665. $minSize = 0;
  6666. //
  6667. // PREPARE Elements
  6668. //
  6669. // Convert var to be able to share same code than showOutputField of extrafields
  6670. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6671. $type = 'varchar'; // convert varchar(xx) int varchar
  6672. $maxSize = $reg[1];
  6673. } elseif (preg_match('/varchar/', $type)) {
  6674. $type = 'varchar'; // convert varchar(xx) int varchar
  6675. }
  6676. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6677. $type = 'select';
  6678. }
  6679. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6680. $type = 'link';
  6681. }
  6682. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6683. $param['options'] = $val['arrayofkeyval'];
  6684. }
  6685. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6686. $type = 'link';
  6687. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6688. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6689. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6690. $type = 'sellist';
  6691. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6692. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6693. $type = 'sellist';
  6694. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6695. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6696. $type = 'sellist';
  6697. }
  6698. //
  6699. // TEST Value
  6700. //
  6701. // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
  6702. $validate = new Validate($this->db, $langs);
  6703. // little trick : to perform tests with good performances sort tests by quick to low
  6704. //
  6705. // COMMON TESTS
  6706. //
  6707. // Required test and empty value
  6708. if ($required && !$validate->isNotEmptyString($fieldValue)) {
  6709. $this->setFieldError($fieldKey, $validate->error);
  6710. return false;
  6711. } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
  6712. // if no value sent and the field is not mandatory, no need to perform tests
  6713. return true;
  6714. }
  6715. // MAX Size test
  6716. if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
  6717. $this->setFieldError($fieldKey, $validate->error);
  6718. return false;
  6719. }
  6720. // MIN Size test
  6721. if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
  6722. $this->setFieldError($fieldKey, $validate->error);
  6723. return false;
  6724. }
  6725. //
  6726. // TESTS for TYPE
  6727. //
  6728. if (in_array($type, array('date', 'datetime', 'timestamp'))) {
  6729. if (!$validate->isTimestamp($fieldValue)) {
  6730. $this->setFieldError($fieldKey, $validate->error);
  6731. return false;
  6732. } else { return true; }
  6733. } elseif ($type == 'duration') {
  6734. if (!$validate->isDuration($fieldValue)) {
  6735. $this->setFieldError($fieldKey, $validate->error);
  6736. return false;
  6737. } else { return true; }
  6738. } elseif (in_array($type, array('double', 'real', 'price'))) {
  6739. // is numeric
  6740. if (!$validate->isDuration($fieldValue)) {
  6741. $this->setFieldError($fieldKey, $validate->error);
  6742. return false;
  6743. } else { return true; }
  6744. } elseif ($type == 'boolean') {
  6745. if (!$validate->isBool($fieldValue)) {
  6746. $this->setFieldError($fieldKey, $validate->error);
  6747. return false;
  6748. } else { return true; }
  6749. } elseif ($type == 'mail') {
  6750. if (!$validate->isEmail($fieldValue)) {
  6751. $this->setFieldError($fieldKey, $validate->error);
  6752. return false;
  6753. }
  6754. } elseif ($type == 'url') {
  6755. if (!$validate->isUrl($fieldValue)) {
  6756. $this->setFieldError($fieldKey, $validate->error);
  6757. return false;
  6758. } else { return true; }
  6759. } elseif ($type == 'phone') {
  6760. if (!$validate->isPhone($fieldValue)) {
  6761. $this->setFieldError($fieldKey, $validate->error);
  6762. return false;
  6763. } else { return true; }
  6764. } elseif ($type == 'select' || $type == 'radio') {
  6765. if (!isset($param['options'][$fieldValue])) {
  6766. $this->error = $langs->trans('RequireValidValue');
  6767. return false;
  6768. } else { return true; }
  6769. } elseif ($type == 'sellist' || $type == 'chkbxlst') {
  6770. $param_list = array_keys($param['options']);
  6771. $InfoFieldList = explode(":", $param_list[0]);
  6772. $value_arr = explode(',', $fieldValue);
  6773. $value_arr = array_map(array($this->db, 'escape'), $value_arr);
  6774. $selectkey = "rowid";
  6775. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6776. $selectkey = $InfoFieldList[2];
  6777. }
  6778. if (!isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
  6779. $this->setFieldError($fieldKey, $validate->error);
  6780. return false;
  6781. } else { return true; }
  6782. } elseif ($type == 'link') {
  6783. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6784. $InfoFieldList = explode(":", $param_list[0]);
  6785. $classname = $InfoFieldList[0];
  6786. $classpath = $InfoFieldList[1];
  6787. if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
  6788. $this->setFieldError($fieldKey, $validate->error);
  6789. return false;
  6790. } else { return true; }
  6791. }
  6792. // if no test failled all is ok
  6793. return true;
  6794. }
  6795. /**
  6796. * Function to show lines of extrafields with output datas.
  6797. * This function is responsible to output the <tr> and <td> according to correct number of columns received into $params['colspan'] or <div> according to $display_type
  6798. *
  6799. * @param Extrafields $extrafields Extrafield Object
  6800. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  6801. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  6802. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  6803. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  6804. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  6805. * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...)
  6806. * @return string
  6807. */
  6808. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
  6809. {
  6810. global $db, $conf, $langs, $action, $form, $hookmanager;
  6811. if (!is_object($form)) {
  6812. $form = new Form($db);
  6813. }
  6814. $out = '';
  6815. $parameters = array();
  6816. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  6817. if (empty($reshook)) {
  6818. if (key_exists('label', $extrafields->attributes[$this->table_element]) && is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0) {
  6819. $out .= "\n";
  6820. $out .= '<!-- showOptionals --> ';
  6821. $out .= "\n";
  6822. $extrafields_collapse_num = '';
  6823. $e = 0;
  6824. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
  6825. // Show only the key field in params
  6826. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
  6827. continue;
  6828. }
  6829. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  6830. $enabled = 1;
  6831. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  6832. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1);
  6833. }
  6834. if (empty($enabled)) {
  6835. continue;
  6836. }
  6837. $visibility = 1;
  6838. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  6839. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1);
  6840. }
  6841. $perms = 1;
  6842. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  6843. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1);
  6844. }
  6845. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
  6846. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  6847. } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
  6848. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  6849. } elseif ($mode == 'view' && empty($visibility)) {
  6850. continue;
  6851. }
  6852. if (empty($perms)) {
  6853. continue;
  6854. }
  6855. // Load language if required
  6856. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  6857. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  6858. }
  6859. $colspan = 0;
  6860. if (is_array($params) && count($params) > 0 && $display_type=='card') {
  6861. if (array_key_exists('cols', $params)) {
  6862. $colspan = $params['cols'];
  6863. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  6864. $reg = array();
  6865. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  6866. $colspan = $reg[1];
  6867. } else {
  6868. $colspan = $params['colspan'];
  6869. }
  6870. }
  6871. }
  6872. $colspan = intval($colspan);
  6873. switch ($mode) {
  6874. case "view":
  6875. $value = $this->array_options["options_".$key.$keysuffix]; // Value may be clean or formated later
  6876. break;
  6877. case "create":
  6878. case "edit":
  6879. // We get the value of property found with GETPOST so it takes into account:
  6880. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  6881. $check = 'alphanohtml';
  6882. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  6883. $check = 'restricthtml';
  6884. }
  6885. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  6886. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  6887. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
  6888. if (is_array($getposttemp)) {
  6889. // $getposttemp is an array but following code expects a comma separated string
  6890. $value = implode(",", $getposttemp);
  6891. } else {
  6892. $value = $getposttemp;
  6893. }
  6894. } else {
  6895. $value = (!empty($this->array_options["options_".$key]) ? $this->array_options["options_".$key] : ''); // No GET, no POST, no default value, so we take value of object.
  6896. }
  6897. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  6898. break;
  6899. }
  6900. // Output value of the current field
  6901. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  6902. $extrafields_collapse_num = '';
  6903. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  6904. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  6905. $extrafield_param_list = array_keys($extrafield_param['options']);
  6906. if (count($extrafield_param_list) > 0) {
  6907. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  6908. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  6909. $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  6910. }
  6911. }
  6912. }
  6913. $out .= $extrafields->showSeparator($key, $this, ($colspan + 1), $display_type);
  6914. } else {
  6915. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  6916. $csstyle = '';
  6917. if (is_array($params) && count($params) > 0) {
  6918. if (array_key_exists('class', $params)) {
  6919. $class .= $params['class'].' ';
  6920. }
  6921. if (array_key_exists('style', $params)) {
  6922. $csstyle = $params['style'];
  6923. }
  6924. }
  6925. // add html5 elements
  6926. $domData = ' data-element="extrafield"';
  6927. $domData .= ' data-targetelement="'.$this->element.'"';
  6928. $domData .= ' data-targetid="'.$this->id.'"';
  6929. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  6930. if ($display_type=='card') {
  6931. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
  6932. $colspan = 0;
  6933. }
  6934. if ($action == 'selectlines') {
  6935. $colspan++;
  6936. }
  6937. }
  6938. // Convert date into timestamp format (value in memory must be a timestamp)
  6939. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
  6940. $datenotinstring = $this->array_options['options_'.$key];
  6941. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  6942. $datenotinstring = $this->db->jdate($datenotinstring);
  6943. }
  6944. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) ? dol_mktime(12, 0, 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;
  6945. }
  6946. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
  6947. $datenotinstring = $this->array_options['options_'.$key];
  6948. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  6949. $datenotinstring = $this->db->jdate($datenotinstring);
  6950. }
  6951. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) ? dol_mktime(GETPOST($keyprefix.'options_'.$key.$keysuffix."hour", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."min", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."sec", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."month", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."day", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."year", 'int', 3), 'tzuserrel') : $datenotinstring;
  6952. }
  6953. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  6954. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
  6955. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? price2num($value) : $this->array_options['options_'.$key];
  6956. }
  6957. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  6958. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int'))) {
  6959. if ($action == 'create') {
  6960. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  6961. }
  6962. }
  6963. $labeltoshow = $langs->trans($label);
  6964. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  6965. if ($display_type == 'card') {
  6966. $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="valuefieldcreate '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >';
  6967. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action == 'view' || $action == 'valid' || $action == 'editline')) {
  6968. $out .= '<td></td>';
  6969. }
  6970. $out .= '<td class="wordbreak';
  6971. } elseif ($display_type == 'line') {
  6972. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="valuefieldlinecreate '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >';
  6973. $out .= '<div style="display: inline-block; padding-right:4px" class="wordbreak';
  6974. }
  6975. //$out .= "titlefield";
  6976. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  6977. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  6978. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  6979. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  6980. $out .= '">';
  6981. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  6982. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  6983. } else {
  6984. $out .= $labeltoshow;
  6985. }
  6986. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  6987. $out .= '&nbsp;<span style="color: red">*</span>';
  6988. }
  6989. } else {
  6990. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  6991. $out .= ' fieldrequired';
  6992. }
  6993. $out .= '">';
  6994. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  6995. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  6996. } else {
  6997. $out .= $labeltoshow;
  6998. }
  6999. }
  7000. $out .= ($display_type == 'card' ? '</td>' : '</div>');
  7001. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  7002. if ($display_type == 'card') {
  7003. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="'.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  7004. } elseif ($display_type == 'line') {
  7005. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').' style="display: inline-block" class="'.$this->element.'_extras_'.$key.'">';
  7006. }
  7007. switch ($mode) {
  7008. case "view":
  7009. $out .= $extrafields->showOutputField($key, $value);
  7010. break;
  7011. case "create":
  7012. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7013. break;
  7014. case "edit":
  7015. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7016. break;
  7017. }
  7018. $out .= ($display_type=='card' ? '</td>' : '</div>');
  7019. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
  7020. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7021. } else {
  7022. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7023. }
  7024. $e++;
  7025. }
  7026. }
  7027. $out .= "\n";
  7028. // Add code to manage list depending on others
  7029. if (!empty($conf->use_javascript_ajax)) {
  7030. $out .= $this->getJSListDependancies();
  7031. }
  7032. $out .= '<!-- /showOptionals --> '."\n";
  7033. }
  7034. }
  7035. $out .= $hookmanager->resPrint;
  7036. return $out;
  7037. }
  7038. /**
  7039. * @param string $type Type for prefix
  7040. * @return string Javacript code to manage dependency
  7041. */
  7042. public function getJSListDependancies($type = '_extra')
  7043. {
  7044. $out = '
  7045. <script>
  7046. jQuery(document).ready(function() {
  7047. function showOptions'.$type.'(child_list, parent_list, orig_select)
  7048. {
  7049. var val = $("select[name=\""+parent_list+"\"]").val();
  7050. var parentVal = parent_list + ":" + val;
  7051. if(typeof val == "string"){
  7052. if(val != "") {
  7053. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7054. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7055. $("select[name=\""+child_list+"\"]").append(options);
  7056. } else {
  7057. var options = orig_select.find("option[parent]").clone();
  7058. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7059. $("select[name=\""+child_list+"\"]").append(options);
  7060. }
  7061. } else if(val > 0) {
  7062. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7063. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7064. $("select[name=\""+child_list+"\"]").append(options);
  7065. } else {
  7066. var options = orig_select.find("option[parent]").clone();
  7067. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7068. $("select[name=\""+child_list+"\"]").append(options);
  7069. }
  7070. }
  7071. function setListDependencies'.$type.'() {
  7072. jQuery("select option[parent]").parent().each(function() {
  7073. var orig_select = {};
  7074. var child_list = $(this).attr("name");
  7075. orig_select[child_list] = $(this).clone();
  7076. var parent = $(this).find("option[parent]:first").attr("parent");
  7077. var infos = parent.split(":");
  7078. var parent_list = infos[0];
  7079. //Hide daughters lists
  7080. if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
  7081. $("#"+child_list).hide();
  7082. //Show mother lists
  7083. } else if ($("#"+parent_list).val() != 0){
  7084. $("#"+parent_list).show();
  7085. }
  7086. //Show the child list if the parent list value is selected
  7087. $("select[name=\""+parent_list+"\"]").click(function() {
  7088. if ($(this).val() != 0){
  7089. $("#"+child_list).show()
  7090. }
  7091. });
  7092. //When we change parent list
  7093. $("select[name=\""+parent_list+"\"]").change(function() {
  7094. showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
  7095. //Select the value 0 on child list after a change on the parent list
  7096. $("#"+child_list).val(0).trigger("change");
  7097. //Hide child lists if the parent value is set to 0
  7098. if ($(this).val() == 0){
  7099. $("#"+child_list).hide();
  7100. }
  7101. });
  7102. });
  7103. }
  7104. setListDependencies'.$type.'();
  7105. });
  7106. </script>'."\n";
  7107. return $out;
  7108. }
  7109. /**
  7110. * Returns the rights used for this class
  7111. * @return stdClass
  7112. */
  7113. public function getRights()
  7114. {
  7115. global $user;
  7116. $element = $this->element;
  7117. if ($element == 'facturerec') {
  7118. $element = 'facture';
  7119. }
  7120. return $user->rights->{$element};
  7121. }
  7122. /**
  7123. * Function used to replace a thirdparty id with another one.
  7124. * This function is meant to be called from replaceThirdparty with the appropiate tables
  7125. * Column name fk_soc MUST be used to identify thirdparties
  7126. *
  7127. * @param DoliDB $db Database handler
  7128. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  7129. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  7130. * @param string[] $tables Tables that need to be changed
  7131. * @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)
  7132. * @return bool True if success, False if error
  7133. */
  7134. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7135. {
  7136. foreach ($tables as $table) {
  7137. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
  7138. if (!$db->query($sql)) {
  7139. if ($ignoreerrors) {
  7140. 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.
  7141. }
  7142. //$this->errors = $db->lasterror();
  7143. return false;
  7144. }
  7145. }
  7146. return true;
  7147. }
  7148. /**
  7149. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  7150. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  7151. * else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  7152. * else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  7153. * else set min buy price as buy price
  7154. *
  7155. * @param float $unitPrice Product unit price
  7156. * @param float $discountPercent Line discount percent
  7157. * @param int $fk_product Product id
  7158. * @return float <0 if KO, buyprice if OK
  7159. */
  7160. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  7161. {
  7162. global $conf;
  7163. $buyPrice = 0;
  7164. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
  7165. // When ForceBuyingPriceIfNull is set
  7166. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  7167. } else {
  7168. // Get cost price for margin calculation
  7169. if (!empty($fk_product) && $fk_product > 0) {
  7170. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
  7171. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7172. $product = new Product($this->db);
  7173. $result = $product->fetch($fk_product);
  7174. if ($result <= 0) {
  7175. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7176. return -1;
  7177. }
  7178. if ($product->cost_price > 0) {
  7179. $buyPrice = $product->cost_price;
  7180. } elseif ($product->pmp > 0) {
  7181. $buyPrice = $product->pmp;
  7182. }
  7183. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
  7184. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7185. $product = new Product($this->db);
  7186. $result = $product->fetch($fk_product);
  7187. if ($result <= 0) {
  7188. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7189. return -1;
  7190. }
  7191. if ($product->pmp > 0) {
  7192. $buyPrice = $product->pmp;
  7193. }
  7194. }
  7195. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
  7196. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  7197. $productFournisseur = new ProductFournisseur($this->db);
  7198. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
  7199. $buyPrice = $productFournisseur->fourn_unitprice;
  7200. } elseif ($result < 0) {
  7201. $this->errors[] = $productFournisseur->error;
  7202. return -2;
  7203. }
  7204. }
  7205. }
  7206. }
  7207. return $buyPrice;
  7208. }
  7209. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7210. /**
  7211. * Show photos of an object (nbmax maximum), into several columns
  7212. *
  7213. * @param string $modulepart 'product', 'ticket', ...
  7214. * @param string $sdir Directory to scan (full absolute path)
  7215. * @param int $size 0=original size, 1='small' use thumbnail if possible
  7216. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  7217. * @param int $nbbyrow Number of image per line or -1 to use div. Used only if size=1.
  7218. * @param int $showfilename 1=Show filename
  7219. * @param int $showaction 1=Show icon with action links (resize, delete)
  7220. * @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.
  7221. * @param int $maxWidth Max width of original image when size='small'
  7222. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  7223. * @param int $notitle Do not add title tag on image
  7224. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  7225. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  7226. */
  7227. public 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)
  7228. {
  7229. // phpcs:enable
  7230. global $conf, $user, $langs;
  7231. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7232. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  7233. $sortfield = 'position_name';
  7234. $sortorder = 'asc';
  7235. $dir = $sdir.'/';
  7236. $pdir = '/';
  7237. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7238. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7239. // For backward compatibility
  7240. if ($modulepart == 'product') {
  7241. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  7242. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7243. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7244. }
  7245. }
  7246. // Defined relative dir to DOL_DATA_ROOT
  7247. $relativedir = '';
  7248. if ($dir) {
  7249. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  7250. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  7251. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  7252. }
  7253. $dirthumb = $dir.'thumbs/';
  7254. $pdirthumb = $pdir.'thumbs/';
  7255. $return = '<!-- Photo -->'."\n";
  7256. $nbphoto = 0;
  7257. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  7258. /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
  7259. {
  7260. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  7261. $filearray=array_merge($filearray, $filearrayold);
  7262. }*/
  7263. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  7264. if (count($filearray)) {
  7265. if ($sortfield && $sortorder) {
  7266. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  7267. }
  7268. foreach ($filearray as $key => $val) {
  7269. $photo = '';
  7270. $file = $val['name'];
  7271. //if (! utf8_check($file)) $file=utf8_encode($file); // To be sure file is stored in UTF8 in memory
  7272. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  7273. if (image_format_supported($file) >= 0) {
  7274. $nbphoto++;
  7275. $photo = $file;
  7276. $viewfilename = $file;
  7277. if ($size == 1 || $size == 'small') { // Format vignette
  7278. // Find name of thumb file
  7279. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  7280. if (!dol_is_file($dirthumb.$photo_vignette)) {
  7281. $photo_vignette = '';
  7282. }
  7283. // Get filesize of original file
  7284. $imgarray = dol_getImageSize($dir.$photo);
  7285. if ($nbbyrow > 0) {
  7286. if ($nbphoto == 1) {
  7287. $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  7288. }
  7289. if ($nbphoto % $nbbyrow == 1) {
  7290. $return .= '<tr class="center valignmiddle" style="border: 1px">';
  7291. }
  7292. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
  7293. } elseif ($nbbyrow < 0) {
  7294. $return .= '<div class="inline-block">';
  7295. }
  7296. $return .= "\n";
  7297. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  7298. if (empty($nolink)) {
  7299. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  7300. if ($urladvanced) {
  7301. $return .= '<a href="'.$urladvanced.'">';
  7302. } else {
  7303. $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
  7304. }
  7305. }
  7306. // Show image (width height=$maxHeight)
  7307. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  7308. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  7309. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  7310. if ($notitle) {
  7311. $alt = '';
  7312. }
  7313. if ($usesharelink) {
  7314. if ($val['share']) {
  7315. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7316. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  7317. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7318. } else {
  7319. $return .= '<!-- Show original file -->';
  7320. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7321. }
  7322. } else {
  7323. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  7324. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  7325. }
  7326. } else {
  7327. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7328. $return .= '<!-- Show thumb -->';
  7329. $return .= '<img class="photo photowithmargin maxwidth150onsmartphone maxwidth200" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdirthumb.$photo_vignette).'" title="'.dol_escape_htmltag($alt).'">';
  7330. } else {
  7331. $return .= '<!-- Show original file -->';
  7332. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" title="'.dol_escape_htmltag($alt).'">';
  7333. }
  7334. }
  7335. if (empty($nolink)) {
  7336. $return .= '</a>';
  7337. }
  7338. $return .= "\n";
  7339. if ($showfilename) {
  7340. $return .= '<br>'.$viewfilename;
  7341. }
  7342. if ($showaction) {
  7343. $return .= '<br>';
  7344. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  7345. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
  7346. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=addthumb&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'), 'refresh').'&nbsp;&nbsp;</a>';
  7347. }
  7348. // Special cas for product
  7349. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7350. // Link to resize
  7351. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  7352. // Link to delete
  7353. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7354. $return .= img_delete().'</a>';
  7355. }
  7356. }
  7357. $return .= "\n";
  7358. if ($nbbyrow > 0) {
  7359. $return .= '</td>';
  7360. if (($nbphoto % $nbbyrow) == 0) {
  7361. $return .= '</tr>';
  7362. }
  7363. } elseif ($nbbyrow < 0) {
  7364. $return .= '</div>';
  7365. }
  7366. }
  7367. if (empty($size)) { // Format origine
  7368. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  7369. if ($showfilename) {
  7370. $return .= '<br>'.$viewfilename;
  7371. }
  7372. if ($showaction) {
  7373. // Special case for product
  7374. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7375. // Link to resize
  7376. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  7377. // Link to delete
  7378. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7379. $return .= img_delete().'</a>';
  7380. }
  7381. }
  7382. }
  7383. // On continue ou on arrete de boucler ?
  7384. if ($nbmax && $nbphoto >= $nbmax) {
  7385. break;
  7386. }
  7387. }
  7388. }
  7389. if ($size == 1 || $size == 'small') {
  7390. if ($nbbyrow > 0) {
  7391. // Ferme tableau
  7392. while ($nbphoto % $nbbyrow) {
  7393. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  7394. $nbphoto++;
  7395. }
  7396. if ($nbphoto) {
  7397. $return .= '</table>';
  7398. }
  7399. }
  7400. }
  7401. }
  7402. $this->nbphoto = $nbphoto;
  7403. return $return;
  7404. }
  7405. /**
  7406. * Function test if type is array
  7407. *
  7408. * @param array $info content informations of field
  7409. * @return bool true if array
  7410. */
  7411. protected function isArray($info)
  7412. {
  7413. if (is_array($info)) {
  7414. if (isset($info['type']) && $info['type'] == 'array') {
  7415. return true;
  7416. } else {
  7417. return false;
  7418. }
  7419. }
  7420. return false;
  7421. }
  7422. /**
  7423. * Function test if type is date
  7424. *
  7425. * @param array $info content informations of field
  7426. * @return bool true if date
  7427. */
  7428. public function isDate($info)
  7429. {
  7430. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
  7431. return true;
  7432. }
  7433. return false;
  7434. }
  7435. /**
  7436. * Function test if type is duration
  7437. *
  7438. * @param array $info content informations of field
  7439. * @return bool true if field of type duration
  7440. */
  7441. public function isDuration($info)
  7442. {
  7443. if (is_array($info)) {
  7444. if (isset($info['type']) && ($info['type'] == 'duration')) {
  7445. return true;
  7446. } else {
  7447. return false;
  7448. }
  7449. } else {
  7450. return false;
  7451. }
  7452. }
  7453. /**
  7454. * Function test if type is integer
  7455. *
  7456. * @param array $info content informations of field
  7457. * @return bool true if integer
  7458. */
  7459. public function isInt($info)
  7460. {
  7461. if (is_array($info)) {
  7462. if (isset($info['type']) && ($info['type'] == 'int' || preg_match('/^integer/i', $info['type']))) {
  7463. return true;
  7464. } else {
  7465. return false;
  7466. }
  7467. } else {
  7468. return false;
  7469. }
  7470. }
  7471. /**
  7472. * Function test if type is float
  7473. *
  7474. * @param array $info content informations of field
  7475. * @return bool true if float
  7476. */
  7477. public function isFloat($info)
  7478. {
  7479. if (is_array($info)) {
  7480. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
  7481. return true;
  7482. } else {
  7483. return false;
  7484. }
  7485. }
  7486. return false;
  7487. }
  7488. /**
  7489. * Function test if type is text
  7490. *
  7491. * @param array $info content informations of field
  7492. * @return bool true if type text
  7493. */
  7494. public function isText($info)
  7495. {
  7496. if (is_array($info)) {
  7497. if (isset($info['type']) && $info['type'] == 'text') {
  7498. return true;
  7499. } else {
  7500. return false;
  7501. }
  7502. }
  7503. return false;
  7504. }
  7505. /**
  7506. * Function test if field can be null
  7507. *
  7508. * @param array $info content informations of field
  7509. * @return bool true if it can be null
  7510. */
  7511. protected function canBeNull($info)
  7512. {
  7513. if (is_array($info)) {
  7514. if (isset($info['notnull']) && $info['notnull'] != '1') {
  7515. return true;
  7516. } else {
  7517. return false;
  7518. }
  7519. }
  7520. return true;
  7521. }
  7522. /**
  7523. * Function test if field is forced to null if zero or empty
  7524. *
  7525. * @param array $info content informations of field
  7526. * @return bool true if forced to null
  7527. */
  7528. protected function isForcedToNullIfZero($info)
  7529. {
  7530. if (is_array($info)) {
  7531. if (isset($info['notnull']) && $info['notnull'] == '-1') {
  7532. return true;
  7533. } else {
  7534. return false;
  7535. }
  7536. }
  7537. return false;
  7538. }
  7539. /**
  7540. * Function test if is indexed
  7541. *
  7542. * @param array $info content informations of field
  7543. * @return bool
  7544. */
  7545. protected function isIndex($info)
  7546. {
  7547. if (is_array($info)) {
  7548. if (isset($info['index']) && $info['index'] == true) {
  7549. return true;
  7550. } else {
  7551. return false;
  7552. }
  7553. }
  7554. return false;
  7555. }
  7556. /**
  7557. * Function to prepare a part of the query for insert.
  7558. * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
  7559. * $this->${field} should be a clean value. The page can run
  7560. *
  7561. * @return array
  7562. */
  7563. protected function setSaveQuery()
  7564. {
  7565. global $conf;
  7566. $queryarray = array();
  7567. foreach ($this->fields as $field => $info) { // Loop on definition of fields
  7568. // Depending on field type ('datetime', ...)
  7569. if ($this->isDate($info)) {
  7570. if (empty($this->{$field})) {
  7571. $queryarray[$field] = null;
  7572. } else {
  7573. $queryarray[$field] = $this->db->idate($this->{$field});
  7574. }
  7575. } elseif ($this->isDuration($info)) {
  7576. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7577. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7578. if (!isset($this->{$field})) {
  7579. $queryarray[$field] = 0;
  7580. } else {
  7581. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7582. }
  7583. } else {
  7584. $queryarray[$field] = null;
  7585. }
  7586. } elseif ($this->isInt($info) || $this->isFloat($info)) {
  7587. if ($field == 'entity' && is_null($this->{$field})) {
  7588. $queryarray[$field] = $conf->entity;
  7589. } else {
  7590. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7591. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7592. if (!isset($this->{$field})) {
  7593. $queryarray[$field] = 0;
  7594. } elseif ($this->isInt($info)) {
  7595. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7596. } elseif ($this->isFloat($info)) {
  7597. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7598. }
  7599. } else {
  7600. $queryarray[$field] = null;
  7601. }
  7602. }
  7603. } else {
  7604. $queryarray[$field] = $this->{$field};
  7605. }
  7606. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
  7607. unset($queryarray[$field]);
  7608. }
  7609. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
  7610. $queryarray[$field] = null; // May force 0 to null
  7611. }
  7612. }
  7613. return $queryarray;
  7614. }
  7615. /**
  7616. * Function to load data from a SQL pointer into properties of current object $this
  7617. *
  7618. * @param stdClass $obj Contain data of object from database
  7619. * @return void
  7620. */
  7621. public function setVarsFromFetchObj(&$obj)
  7622. {
  7623. global $db;
  7624. foreach ($this->fields as $field => $info) {
  7625. if ($this->isDate($info)) {
  7626. if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
  7627. $this->{$field} = '';
  7628. } else {
  7629. $this->{$field} = $db->jdate($obj->{$field});
  7630. }
  7631. } elseif ($this->isInt($info)) {
  7632. if ($field == 'rowid') {
  7633. $this->id = (int) $obj->{$field};
  7634. } else {
  7635. if ($this->isForcedToNullIfZero($info)) {
  7636. if (empty($obj->{$field})) {
  7637. $this->{$field} = null;
  7638. } else {
  7639. $this->{$field} = (double) $obj->{$field};
  7640. }
  7641. } else {
  7642. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7643. $this->{$field} = (int) $obj->{$field};
  7644. } else {
  7645. $this->{$field} = null;
  7646. }
  7647. }
  7648. }
  7649. } elseif ($this->isFloat($info)) {
  7650. if ($this->isForcedToNullIfZero($info)) {
  7651. if (empty($obj->{$field})) {
  7652. $this->{$field} = null;
  7653. } else {
  7654. $this->{$field} = (double) $obj->{$field};
  7655. }
  7656. } else {
  7657. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7658. $this->{$field} = (double) $obj->{$field};
  7659. } else {
  7660. $this->{$field} = null;
  7661. }
  7662. }
  7663. } else {
  7664. $this->{$field} = $obj->{$field};
  7665. }
  7666. }
  7667. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  7668. if (!isset($this->fields['ref']) && isset($this->id)) {
  7669. $this->ref = $this->id;
  7670. }
  7671. }
  7672. /**
  7673. * Function to concat keys of fields
  7674. *
  7675. * @param string $alias String of alias of table for fields. For example 't'.
  7676. * @return string list of alias fields
  7677. */
  7678. public function getFieldList($alias = '')
  7679. {
  7680. $keys = array_keys($this->fields);
  7681. if (!empty($alias)) {
  7682. $keys_with_alias = array();
  7683. foreach ($keys as $fieldname) {
  7684. $keys_with_alias[] = $alias . '.' . $fieldname;
  7685. }
  7686. return implode(',', $keys_with_alias);
  7687. } else {
  7688. return implode(',', $keys);
  7689. }
  7690. }
  7691. /**
  7692. * Add quote to field value if necessary
  7693. *
  7694. * @param string|int $value Value to protect
  7695. * @param array $fieldsentry Properties of field
  7696. * @return string
  7697. */
  7698. protected function quote($value, $fieldsentry)
  7699. {
  7700. if (is_null($value)) {
  7701. return 'NULL';
  7702. } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
  7703. return price2num("$value");
  7704. } elseif ($fieldsentry['type'] == 'boolean') {
  7705. if ($value) {
  7706. return 'true';
  7707. } else {
  7708. return 'false';
  7709. }
  7710. } else {
  7711. return "'".$this->db->escape($value)."'";
  7712. }
  7713. }
  7714. /**
  7715. * Create object into database
  7716. *
  7717. * @param User $user User that creates
  7718. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7719. * @return int <0 if KO, Id of created object if OK
  7720. */
  7721. public function createCommon(User $user, $notrigger = false)
  7722. {
  7723. global $langs;
  7724. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  7725. $error = 0;
  7726. $now = dol_now();
  7727. $fieldvalues = $this->setSaveQuery();
  7728. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
  7729. $fieldvalues['date_creation'] = $this->db->idate($now);
  7730. }
  7731. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
  7732. $fieldvalues['fk_user_creat'] = $user->id;
  7733. }
  7734. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  7735. if (array_key_exists('ref', $fieldvalues)) {
  7736. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  7737. }
  7738. $keys = array();
  7739. $values = array(); // Array to store string forged for SQL syntax
  7740. foreach ($fieldvalues as $k => $v) {
  7741. $keys[$k] = $k;
  7742. $value = $this->fields[$k];
  7743. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  7744. }
  7745. // Clean and check mandatory
  7746. foreach ($keys as $key) {
  7747. // If field is an implicit foreign key field
  7748. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  7749. $values[$key] = '';
  7750. }
  7751. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  7752. $values[$key] = '';
  7753. }
  7754. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
  7755. $error++;
  7756. $langs->load("errors");
  7757. dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
  7758. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  7759. }
  7760. // If value is null and there is a default value for field
  7761. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
  7762. $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
  7763. }
  7764. // If field is an implicit foreign key field
  7765. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  7766. if (isset($this->fields[$key]['default'])) {
  7767. $values[$key] = ((int) $this->fields[$key]['default']);
  7768. } else {
  7769. $values[$key] = 'null';
  7770. }
  7771. }
  7772. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
  7773. $values[$key] = 'null';
  7774. }
  7775. }
  7776. if ($error) {
  7777. return -1;
  7778. }
  7779. $this->db->begin();
  7780. if (!$error) {
  7781. $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element;
  7782. $sql .= " (".implode(", ", $keys).')';
  7783. $sql .= " VALUES (".implode(", ", $values).")"; // $values can contains 'abc' or 123
  7784. $res = $this->db->query($sql);
  7785. if ($res === false) {
  7786. $error++;
  7787. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  7788. $this->errors[] = "ErrorRefAlreadyExists";
  7789. } else {
  7790. $this->errors[] = $this->db->lasterror();
  7791. }
  7792. }
  7793. }
  7794. if (!$error) {
  7795. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
  7796. }
  7797. // If we have a field ref with a default value of (PROV)
  7798. if (!$error) {
  7799. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
  7800. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
  7801. $resqlupdate = $this->db->query($sql);
  7802. if ($resqlupdate === false) {
  7803. $error++;
  7804. $this->errors[] = $this->db->lasterror();
  7805. } else {
  7806. $this->ref = '(PROV'.$this->id.')';
  7807. }
  7808. }
  7809. }
  7810. // Create extrafields
  7811. if (!$error) {
  7812. $result = $this->insertExtraFields();
  7813. if ($result < 0) {
  7814. $error++;
  7815. }
  7816. }
  7817. // Create lines
  7818. if (!empty($this->table_element_line) && !empty($this->fk_element)) {
  7819. $num = (is_array($this->lines) ? count($this->lines) : 0);
  7820. for ($i = 0; $i < $num; $i++) {
  7821. $line = $this->lines[$i];
  7822. $keyforparent = $this->fk_element;
  7823. $line->$keyforparent = $this->id;
  7824. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  7825. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  7826. if (!is_object($line)) {
  7827. $line = (object) $line;
  7828. }
  7829. $result = $line->create($user, 1);
  7830. if ($result < 0) {
  7831. $this->error = $line->error;
  7832. $this->db->rollback();
  7833. return -1;
  7834. }
  7835. }
  7836. }
  7837. // Triggers
  7838. if (!$error && !$notrigger) {
  7839. // Call triggers
  7840. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  7841. if ($result < 0) {
  7842. $error++;
  7843. }
  7844. // End call triggers
  7845. }
  7846. // Commit or rollback
  7847. if ($error) {
  7848. $this->db->rollback();
  7849. return -1;
  7850. } else {
  7851. $this->db->commit();
  7852. return $this->id;
  7853. }
  7854. }
  7855. /**
  7856. * Load object in memory from the database
  7857. *
  7858. * @param int $id Id object
  7859. * @param string $ref Ref
  7860. * @param string $morewhere More SQL filters (' AND ...')
  7861. * @return int <0 if KO, 0 if not found, >0 if OK
  7862. */
  7863. public function fetchCommon($id, $ref = null, $morewhere = '')
  7864. {
  7865. if (empty($id) && empty($ref) && empty($morewhere)) {
  7866. return -1;
  7867. }
  7868. $fieldlist = $this->getFieldList('t');
  7869. if (empty($fieldlist)) {
  7870. return 0;
  7871. }
  7872. $sql = "SELECT ".$fieldlist;
  7873. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element.' as t';
  7874. if (!empty($id)) {
  7875. $sql .= ' WHERE t.rowid = '.((int) $id);
  7876. } elseif (!empty($ref)) {
  7877. $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
  7878. } else {
  7879. $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  7880. }
  7881. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  7882. $sql .= ' AND t.entity IN ('.getEntity($this->table_element).')';
  7883. }
  7884. if ($morewhere) {
  7885. $sql .= $morewhere;
  7886. }
  7887. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  7888. $res = $this->db->query($sql);
  7889. if ($res) {
  7890. $obj = $this->db->fetch_object($res);
  7891. if ($obj) {
  7892. $this->setVarsFromFetchObj($obj);
  7893. // Retrieve all extrafield
  7894. // fetch optionals attributes and labels
  7895. $this->fetch_optionals();
  7896. return $this->id;
  7897. } else {
  7898. return 0;
  7899. }
  7900. } else {
  7901. $this->error = $this->db->lasterror();
  7902. $this->errors[] = $this->error;
  7903. return -1;
  7904. }
  7905. }
  7906. /**
  7907. * Load object in memory from the database
  7908. *
  7909. * @param string $morewhere More SQL filters (' AND ...')
  7910. * @return int <0 if KO, 0 if not found, >0 if OK
  7911. */
  7912. public function fetchLinesCommon($morewhere = '')
  7913. {
  7914. $objectlineclassname = get_class($this).'Line';
  7915. if (!class_exists($objectlineclassname)) {
  7916. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  7917. return -1;
  7918. }
  7919. $objectline = new $objectlineclassname($this->db);
  7920. $sql = "SELECT ".$objectline->getFieldList('l');
  7921. $sql .= " FROM ".MAIN_DB_PREFIX.$objectline->table_element." as l";
  7922. $sql .= " WHERE l.fk_".$this->db->escape($this->element)." = ".((int) $this->id);
  7923. if ($morewhere) {
  7924. $sql .= $morewhere;
  7925. }
  7926. if (isset($objectline->fields['position'])) {
  7927. $sql .= $this->db->order('position', 'ASC');
  7928. }
  7929. $resql = $this->db->query($sql);
  7930. if ($resql) {
  7931. $num_rows = $this->db->num_rows($resql);
  7932. $i = 0;
  7933. while ($i < $num_rows) {
  7934. $obj = $this->db->fetch_object($resql);
  7935. if ($obj) {
  7936. $newline = new $objectlineclassname($this->db);
  7937. $newline->setVarsFromFetchObj($obj);
  7938. $this->lines[] = $newline;
  7939. }
  7940. $i++;
  7941. }
  7942. return 1;
  7943. } else {
  7944. $this->error = $this->db->lasterror();
  7945. $this->errors[] = $this->error;
  7946. return -1;
  7947. }
  7948. }
  7949. /**
  7950. * Update object into database
  7951. *
  7952. * @param User $user User that modifies
  7953. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7954. * @return int <0 if KO, >0 if OK
  7955. */
  7956. public function updateCommon(User $user, $notrigger = false)
  7957. {
  7958. global $conf, $langs;
  7959. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  7960. $error = 0;
  7961. $now = dol_now();
  7962. $fieldvalues = $this->setSaveQuery();
  7963. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
  7964. $fieldvalues['date_modification'] = $this->db->idate($now);
  7965. }
  7966. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
  7967. $fieldvalues['fk_user_modif'] = $user->id;
  7968. }
  7969. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  7970. if (array_key_exists('ref', $fieldvalues)) {
  7971. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  7972. }
  7973. // Add quotes and escape on fields with type string
  7974. $keys = array();
  7975. $values = array();
  7976. $tmp = array();
  7977. foreach ($fieldvalues as $k => $v) {
  7978. $keys[$k] = $k;
  7979. $value = $this->fields[$k];
  7980. $values[$k] = $this->quote($v, $value);
  7981. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  7982. }
  7983. // Clean and check mandatory fields
  7984. foreach ($keys as $key) {
  7985. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  7986. $values[$key] = ''; // This is an implicit foreign key field
  7987. }
  7988. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  7989. $values[$key] = ''; // This is an explicit foreign key field
  7990. }
  7991. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  7992. /*
  7993. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  7994. {
  7995. $error++;
  7996. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  7997. }*/
  7998. }
  7999. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
  8000. $this->db->begin();
  8001. if (!$error) {
  8002. $res = $this->db->query($sql);
  8003. if ($res === false) {
  8004. $error++;
  8005. $this->errors[] = $this->db->lasterror();
  8006. }
  8007. }
  8008. // Update extrafield
  8009. if (!$error) {
  8010. $result = $this->insertExtraFields();
  8011. if ($result < 0) {
  8012. $error++;
  8013. }
  8014. }
  8015. // Triggers
  8016. if (!$error && !$notrigger) {
  8017. // Call triggers
  8018. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  8019. if ($result < 0) {
  8020. $error++;
  8021. } //Do also here what you must do to rollback action if trigger fail
  8022. // End call triggers
  8023. }
  8024. // Commit or rollback
  8025. if ($error) {
  8026. $this->db->rollback();
  8027. return -1;
  8028. } else {
  8029. $this->db->commit();
  8030. return $this->id;
  8031. }
  8032. }
  8033. /**
  8034. * Delete object in database
  8035. *
  8036. * @param User $user User that deletes
  8037. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8038. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  8039. * @return int <=0 if KO, 0=Nothing done because object has child, >0 if OK
  8040. */
  8041. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  8042. {
  8043. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  8044. $error = 0;
  8045. $this->db->begin();
  8046. if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
  8047. foreach ($this->childtables as $table) {
  8048. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8049. $resql = $this->db->query($sql);
  8050. if (!$resql) {
  8051. $this->error = $this->db->lasterror();
  8052. $this->errors[] = $this->error;
  8053. $this->db->rollback();
  8054. return -1;
  8055. }
  8056. }
  8057. } elseif (!empty($this->fk_element) && !empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
  8058. $objectisused = $this->isObjectUsed($this->id);
  8059. if (!empty($objectisused)) {
  8060. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  8061. $this->error = 'ErrorRecordHasChildren';
  8062. $this->errors[] = $this->error;
  8063. $this->db->rollback();
  8064. return 0;
  8065. }
  8066. }
  8067. // Delete cascade first
  8068. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  8069. foreach ($this->childtablesoncascade as $table) {
  8070. $deleteFromObject = explode(':', $table);
  8071. if (count($deleteFromObject) >= 2) {
  8072. $className = str_replace('@', '', $deleteFromObject[0]);
  8073. $filePath = $deleteFromObject[1];
  8074. $columnName = $deleteFromObject[2];
  8075. $TMoreSQL = array();
  8076. $more_sql = $deleteFromObject[3];
  8077. if (!empty($more_sql)) {
  8078. $TMoreSQL['customsql'] = $more_sql;
  8079. }
  8080. if (dol_include_once($filePath)) {
  8081. $childObject = new $className($this->db);
  8082. if (method_exists($childObject, 'deleteByParentField')) {
  8083. $result = $childObject->deleteByParentField($this->id, $columnName, $TMoreSQL);
  8084. if ($result < 0) {
  8085. $error++;
  8086. $this->errors[] = $childObject->error;
  8087. break;
  8088. }
  8089. } else {
  8090. $error++;
  8091. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  8092. break;
  8093. }
  8094. } else {
  8095. $error++;
  8096. $this->errors[] = 'Cannot include child class file '.$filePath;
  8097. break;
  8098. }
  8099. } else {
  8100. // Delete record in child table
  8101. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8102. $resql = $this->db->query($sql);
  8103. if (!$resql) {
  8104. $error++;
  8105. $this->error = $this->db->lasterror();
  8106. $this->errors[] = $this->error;
  8107. break;
  8108. }
  8109. }
  8110. }
  8111. }
  8112. if (!$error) {
  8113. if (!$notrigger) {
  8114. // Call triggers
  8115. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  8116. if ($result < 0) {
  8117. $error++;
  8118. } // Do also here what you must do to rollback action if trigger fail
  8119. // End call triggers
  8120. }
  8121. }
  8122. // Delete llx_ecm_files
  8123. if (!$error) {
  8124. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  8125. if (!$res) {
  8126. $error++;
  8127. }
  8128. }
  8129. if (!$error && !empty($this->isextrafieldmanaged)) {
  8130. $result = $this->deleteExtraFields();
  8131. if ($result < 0) {
  8132. $error++;
  8133. }
  8134. }
  8135. if (!$error) {
  8136. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.((int) $this->id);
  8137. $resql = $this->db->query($sql);
  8138. if (!$resql) {
  8139. $error++;
  8140. $this->errors[] = $this->db->lasterror();
  8141. }
  8142. }
  8143. // Commit or rollback
  8144. if ($error) {
  8145. $this->db->rollback();
  8146. return -1;
  8147. } else {
  8148. $this->db->commit();
  8149. return 1;
  8150. }
  8151. }
  8152. /**
  8153. * Delete all child object from a parent ID
  8154. *
  8155. * @param int $parentId Parent Id
  8156. * @param string $parentField Name of Foreign key parent column
  8157. * @param array $filter an array filter
  8158. * @param string $filtermode AND or OR
  8159. * @return int <0 if KO, >0 if OK
  8160. * @throws Exception
  8161. */
  8162. public function deleteByParentField($parentId = 0, $parentField = '', $filter = array(), $filtermode = "AND")
  8163. {
  8164. global $user;
  8165. $error = 0;
  8166. $deleted = 0;
  8167. if (!empty($parentId) && !empty($parentField)) {
  8168. $this->db->begin();
  8169. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$this->table_element;
  8170. $sql .= " WHERE ".$parentField." = ".(int) $parentId;
  8171. // Manage filters
  8172. $sqlwhere = array();
  8173. if (count($filter) > 0) {
  8174. foreach ($filter as $key => $value) {
  8175. if ($key == 'customsql') {
  8176. $sqlwhere[] = $value;
  8177. } elseif (strpos($value, '%') === false) {
  8178. $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
  8179. } else {
  8180. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  8181. }
  8182. }
  8183. }
  8184. if (count($sqlwhere) > 0) {
  8185. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  8186. }
  8187. $resql = $this->db->query($sql);
  8188. if (!$resql) {
  8189. $this->errors[] = $this->db->lasterror();
  8190. $error++;
  8191. } else {
  8192. while ($obj = $this->db->fetch_object($resql)) {
  8193. $result = $this->fetch($obj->rowid);
  8194. if ($result < 0) {
  8195. $error++;
  8196. $this->errors[] = $this->error;
  8197. } else {
  8198. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  8199. $result = $this->delete();
  8200. } else {
  8201. $result = $this->delete($user);
  8202. }
  8203. if ($result < 0) {
  8204. $error++;
  8205. $this->errors[] = $this->error;
  8206. } else {
  8207. $deleted++;
  8208. }
  8209. }
  8210. }
  8211. }
  8212. if (empty($error)) {
  8213. $this->db->commit();
  8214. return $deleted;
  8215. } else {
  8216. $this->error = implode(', ', $this->errors);
  8217. $this->db->rollback();
  8218. return $error * -1;
  8219. }
  8220. }
  8221. return $deleted;
  8222. }
  8223. /**
  8224. * Delete a line of object in database
  8225. *
  8226. * @param User $user User that delete
  8227. * @param int $idline Id of line to delete
  8228. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8229. * @return int >0 if OK, <0 if KO
  8230. */
  8231. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  8232. {
  8233. global $conf;
  8234. $error = 0;
  8235. $tmpforobjectclass = get_class($this);
  8236. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  8237. // Call trigger
  8238. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  8239. if ($result < 0) {
  8240. return -1;
  8241. }
  8242. // End call triggers
  8243. $this->db->begin();
  8244. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  8245. $sql .= " WHERE rowid = ".((int) $idline);
  8246. dol_syslog(get_class($this)."::deleteLineCommon", LOG_DEBUG);
  8247. $resql = $this->db->query($sql);
  8248. if (!$resql) {
  8249. $this->error = "Error ".$this->db->lasterror();
  8250. $error++;
  8251. }
  8252. if (empty($error)) {
  8253. // Remove extrafields
  8254. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  8255. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  8256. $tmpobjectline->id = $idline;
  8257. $result = $tmpobjectline->deleteExtraFields();
  8258. if ($result < 0) {
  8259. $error++;
  8260. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  8261. }
  8262. }
  8263. }
  8264. if (empty($error)) {
  8265. $this->db->commit();
  8266. return 1;
  8267. } else {
  8268. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  8269. $this->db->rollback();
  8270. return -1;
  8271. }
  8272. }
  8273. /**
  8274. * Set to a status
  8275. *
  8276. * @param User $user Object user that modify
  8277. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  8278. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  8279. * @param string $triggercode Trigger code to use
  8280. * @return int <0 if KO, >0 if OK
  8281. */
  8282. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  8283. {
  8284. $error = 0;
  8285. $this->db->begin();
  8286. $statusfield = 'status';
  8287. if ($this->element == 'don' || $this->element == 'donation') {
  8288. $statusfield = 'fk_statut';
  8289. }
  8290. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  8291. $sql .= " SET ".$statusfield." = ".((int) $status);
  8292. $sql .= " WHERE rowid = ".((int) $this->id);
  8293. if ($this->db->query($sql)) {
  8294. if (!$error) {
  8295. $this->oldcopy = clone $this;
  8296. }
  8297. if (!$error && !$notrigger) {
  8298. // Call trigger
  8299. $result = $this->call_trigger($triggercode, $user);
  8300. if ($result < 0) {
  8301. $error++;
  8302. }
  8303. }
  8304. if (!$error) {
  8305. $this->status = $status;
  8306. $this->db->commit();
  8307. return 1;
  8308. } else {
  8309. $this->db->rollback();
  8310. return -1;
  8311. }
  8312. } else {
  8313. $this->error = $this->db->error();
  8314. $this->db->rollback();
  8315. return -1;
  8316. }
  8317. }
  8318. /**
  8319. * Initialise object with example values
  8320. * Id must be 0 if object instance is a specimen
  8321. *
  8322. * @return int
  8323. */
  8324. public function initAsSpecimenCommon()
  8325. {
  8326. global $user;
  8327. $this->id = 0;
  8328. $this->specimen = 1;
  8329. $fields = array(
  8330. 'label' => 'This is label',
  8331. 'ref' => 'ABCD1234',
  8332. 'description' => 'This is a description',
  8333. 'qty' => 123.12,
  8334. 'note_public' => 'Public note',
  8335. 'note_private' => 'Private note',
  8336. 'date_creation' => (dol_now() - 3600 * 48),
  8337. 'date_modification' => (dol_now() - 3600 * 24),
  8338. 'fk_user_creat' => $user->id,
  8339. 'fk_user_modif' => $user->id,
  8340. 'date' => dol_now(),
  8341. );
  8342. foreach ($fields as $key => $value) {
  8343. if (array_key_exists($key, $this->fields)) {
  8344. $this->{$key} = $value;
  8345. }
  8346. }
  8347. return 1;
  8348. }
  8349. /* Part for comments */
  8350. /**
  8351. * Load comments linked with current task
  8352. * @return boolean 1 if ok
  8353. */
  8354. public function fetchComments()
  8355. {
  8356. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  8357. $comment = new Comment($this->db);
  8358. $result = $comment->fetchAllFor($this->element, $this->id);
  8359. if ($result < 0) {
  8360. $this->errors = array_merge($this->errors, $comment->errors);
  8361. return -1;
  8362. } else {
  8363. $this->comments = $comment->comments;
  8364. }
  8365. return count($this->comments);
  8366. }
  8367. /**
  8368. * Return nb comments already posted
  8369. *
  8370. * @return int
  8371. */
  8372. public function getNbComments()
  8373. {
  8374. return count($this->comments);
  8375. }
  8376. /**
  8377. * Trim object parameters
  8378. *
  8379. * @param string[] $parameters array of parameters to trim
  8380. * @return void
  8381. */
  8382. public function trimParameters($parameters)
  8383. {
  8384. if (!is_array($parameters)) {
  8385. return;
  8386. }
  8387. foreach ($parameters as $parameter) {
  8388. if (isset($this->$parameter)) {
  8389. $this->$parameter = trim($this->$parameter);
  8390. }
  8391. }
  8392. }
  8393. /* Part for categories/tags */
  8394. /**
  8395. * Sets object to given categories.
  8396. *
  8397. * Deletes object from existing categories not supplied.
  8398. * Adds it to non existing supplied categories.
  8399. * Existing categories are left untouch.
  8400. *
  8401. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  8402. * @return int Array of category objects or < 0 if KO
  8403. */
  8404. public function getCategoriesCommon($type_categ)
  8405. {
  8406. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8407. // Get current categories
  8408. $c = new Categorie($this->db);
  8409. $existing = $c->containing($this->id, $type_categ, 'id');
  8410. return $existing;
  8411. }
  8412. /**
  8413. * Sets object to given categories.
  8414. *
  8415. * Adds it to non existing supplied categories.
  8416. * Deletes object from existing categories not supplied (if remove_existing==true).
  8417. * Existing categories are left untouch.
  8418. *
  8419. * @param int[]|int $categories Category ID or array of Categories IDs
  8420. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) definied into const class Categorie type
  8421. * @param boolean $remove_existing True: Remove existings categories from Object if not supplies by $categories, False: let them
  8422. * @return int <0 if KO, >0 if OK
  8423. */
  8424. public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
  8425. {
  8426. // Handle single category
  8427. if (!is_array($categories)) {
  8428. $categories = array($categories);
  8429. }
  8430. dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
  8431. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8432. if (empty($type_categ)) {
  8433. dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
  8434. return -1;
  8435. }
  8436. // Get current categories
  8437. $c = new Categorie($this->db);
  8438. $existing = $c->containing($this->id, $type_categ, 'id');
  8439. if ($remove_existing) {
  8440. // Diff
  8441. if (is_array($existing)) {
  8442. $to_del = array_diff($existing, $categories);
  8443. $to_add = array_diff($categories, $existing);
  8444. } else {
  8445. $to_del = array(); // Nothing to delete
  8446. $to_add = $categories;
  8447. }
  8448. } else {
  8449. $to_del = array(); // Nothing to delete
  8450. $to_add = array_diff($categories, $existing);
  8451. }
  8452. $error = 0;
  8453. $ok = 0;
  8454. // Process
  8455. foreach ($to_del as $del) {
  8456. if ($c->fetch($del) > 0) {
  8457. $result=$c->del_type($this, $type_categ);
  8458. if ($result < 0) {
  8459. $error++;
  8460. $this->error = $c->error;
  8461. $this->errors = $c->errors;
  8462. break;
  8463. } else {
  8464. $ok += $result;
  8465. }
  8466. }
  8467. }
  8468. foreach ($to_add as $add) {
  8469. if ($c->fetch($add) > 0) {
  8470. $result = $c->add_type($this, $type_categ);
  8471. if ($result < 0) {
  8472. $error++;
  8473. $this->error = $c->error;
  8474. $this->errors = $c->errors;
  8475. break;
  8476. } else {
  8477. $ok += $result;
  8478. }
  8479. }
  8480. }
  8481. return $error ? -1 * $error : $ok;
  8482. }
  8483. /**
  8484. * Copy related categories to another object
  8485. *
  8486. * @param int $fromId Id object source
  8487. * @param int $toId Id object cible
  8488. * @param string $type Type of category ('product', ...)
  8489. * @return int < 0 if error, > 0 if ok
  8490. */
  8491. public function cloneCategories($fromId, $toId, $type = '')
  8492. {
  8493. $this->db->begin();
  8494. if (empty($type)) {
  8495. $type = $this->table_element;
  8496. }
  8497. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8498. $categorystatic = new Categorie($this->db);
  8499. $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  8500. $sql .= " SELECT fk_categorie, $toId FROM ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  8501. $sql .= " WHERE fk_product = ".((int) $fromId);
  8502. if (!$this->db->query($sql)) {
  8503. $this->error = $this->db->lasterror();
  8504. $this->db->rollback();
  8505. return -1;
  8506. }
  8507. $this->db->commit();
  8508. return 1;
  8509. }
  8510. /**
  8511. * Delete related files of object in database
  8512. *
  8513. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  8514. * @return bool True if OK, False if KO
  8515. */
  8516. public function deleteEcmFiles($mode = 0)
  8517. {
  8518. global $conf;
  8519. $this->db->begin();
  8520. // Delete in database with mode 0
  8521. if ($mode == 0) {
  8522. switch ($this->element) {
  8523. case 'propal':
  8524. $element = 'propale';
  8525. break;
  8526. case 'product':
  8527. $element = 'produit';
  8528. break;
  8529. case 'order_supplier':
  8530. $element = 'fournisseur/commande';
  8531. break;
  8532. case 'invoice_supplier':
  8533. $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  8534. break;
  8535. case 'shipping':
  8536. $element = 'expedition/sending';
  8537. break;
  8538. default:
  8539. $element = $this->element;
  8540. }
  8541. // Delete ecm_files extrafields
  8542. $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files_extrafields WHERE fk_object IN (";
  8543. $sql .= " SELECT rowid FROM ".MAIN_DB_PREFIX."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8544. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  8545. $sql .= ")";
  8546. if (!$this->db->query($sql)) {
  8547. $this->error = $this->db->lasterror();
  8548. $this->db->rollback();
  8549. return false;
  8550. }
  8551. // Delete ecm_files
  8552. $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files";
  8553. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8554. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  8555. if (!$this->db->query($sql)) {
  8556. $this->error = $this->db->lasterror();
  8557. $this->db->rollback();
  8558. return false;
  8559. }
  8560. }
  8561. // Delete in database with mode 1
  8562. if ($mode == 1) {
  8563. $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files_extrafields";
  8564. $sql .= " WHERE fk_object IN (SELECT rowid FROM ".MAIN_DB_PREFIX."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id).")";
  8565. $resql = $this->db->query($sql);
  8566. if (!$resql) {
  8567. $this->error = $this->db->lasterror();
  8568. $this->db->rollback();
  8569. return false;
  8570. }
  8571. $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files";
  8572. $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
  8573. $resql = $this->db->query($sql);
  8574. if (!$resql) {
  8575. $this->error = $this->db->lasterror();
  8576. $this->db->rollback();
  8577. return false;
  8578. }
  8579. }
  8580. $this->db->commit();
  8581. return true;
  8582. }
  8583. }