commonobject.class.php 330 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676
  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) { // Because the same ref can exists in 2 different entities, we force the current one in priority
  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_array($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 if null)
  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. Use '' means automatic but it not recommended and is deprecated.
  3710. * @param string $fieldstatus Name of status field in this->table_element
  3711. * @return int <0 if KO, >0 if OK
  3712. */
  3713. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
  3714. {
  3715. global $user, $langs, $conf;
  3716. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3717. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3718. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3719. $this->db->begin();
  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. // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
  3745. if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
  3746. $sql .= ", fk_user_valid = ".((int) $user->id);
  3747. }
  3748. if ($status == 1 && in_array($elementTable, array('expensereport'))) {
  3749. $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
  3750. }
  3751. if ($status == 1 && in_array($elementTable, array('inventory'))) {
  3752. $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
  3753. }
  3754. $sql .= " WHERE rowid=".((int) $elementId);
  3755. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  3756. if ($this->db->query($sql)) {
  3757. $error = 0;
  3758. // Try autoset of trigkey
  3759. if (empty($trigkey)) {
  3760. if ($this->element == 'supplier_proposal' && $status == 2) {
  3761. $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3762. }
  3763. if ($this->element == 'supplier_proposal' && $status == 3) {
  3764. $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3765. }
  3766. if ($this->element == 'supplier_proposal' && $status == 4) {
  3767. $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3768. }
  3769. if ($this->element == 'fichinter' && $status == 3) {
  3770. $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3771. }
  3772. if ($this->element == 'fichinter' && $status == 2) {
  3773. $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3774. }
  3775. if ($this->element == 'fichinter' && $status == 1) {
  3776. $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3777. }
  3778. }
  3779. if ($trigkey) {
  3780. // Call trigger
  3781. $result = $this->call_trigger($trigkey, $user);
  3782. if ($result < 0) {
  3783. $error++;
  3784. }
  3785. // End call triggers
  3786. }
  3787. if (!$error) {
  3788. $this->db->commit();
  3789. if (empty($savElementId)) {
  3790. // If the element we update is $this (so $elementId was provided as null)
  3791. if ($fieldstatus == 'tosell') {
  3792. $this->status = $status;
  3793. } elseif ($fieldstatus == 'tobuy') {
  3794. $this->status_buy = $status;
  3795. } else {
  3796. $this->statut = $status;
  3797. $this->status = $status;
  3798. }
  3799. }
  3800. return 1;
  3801. } else {
  3802. $this->db->rollback();
  3803. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  3804. return -1;
  3805. }
  3806. } else {
  3807. $this->error = $this->db->lasterror();
  3808. $this->db->rollback();
  3809. return -1;
  3810. }
  3811. }
  3812. /**
  3813. * Load type of canvas of an object if it exists
  3814. *
  3815. * @param int $id Record id
  3816. * @param string $ref Record ref
  3817. * @return int <0 if KO, 0 if nothing done, >0 if OK
  3818. */
  3819. public function getCanvas($id = 0, $ref = '')
  3820. {
  3821. global $conf;
  3822. if (empty($id) && empty($ref)) {
  3823. return 0;
  3824. }
  3825. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
  3826. return 0; // To increase speed. Not enabled by default.
  3827. }
  3828. // Clean parameters
  3829. $ref = trim($ref);
  3830. $sql = "SELECT rowid, canvas";
  3831. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
  3832. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  3833. if (!empty($id)) {
  3834. $sql .= " AND rowid = ".((int) $id);
  3835. }
  3836. if (!empty($ref)) {
  3837. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  3838. }
  3839. $resql = $this->db->query($sql);
  3840. if ($resql) {
  3841. $obj = $this->db->fetch_object($resql);
  3842. if ($obj) {
  3843. $this->canvas = $obj->canvas;
  3844. return 1;
  3845. } else {
  3846. return 0;
  3847. }
  3848. } else {
  3849. dol_print_error($this->db);
  3850. return -1;
  3851. }
  3852. }
  3853. /**
  3854. * Get special code of a line
  3855. *
  3856. * @param int $lineid Id of line
  3857. * @return int Special code
  3858. */
  3859. public function getSpecialCode($lineid)
  3860. {
  3861. $sql = "SELECT special_code FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  3862. $sql .= " WHERE rowid = ".((int) $lineid);
  3863. $resql = $this->db->query($sql);
  3864. if ($resql) {
  3865. $row = $this->db->fetch_row($resql);
  3866. return $row[0];
  3867. }
  3868. }
  3869. /**
  3870. * Function to check if an object is used by others.
  3871. * Check is done into this->childtables. There is no check into llx_element_element.
  3872. *
  3873. * @param int $id Force id of object
  3874. * @return int <0 if KO, 0 if not used, >0 if already used
  3875. */
  3876. public function isObjectUsed($id = 0)
  3877. {
  3878. global $langs;
  3879. if (empty($id)) {
  3880. $id = $this->id;
  3881. }
  3882. // Check parameters
  3883. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
  3884. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  3885. return -1;
  3886. }
  3887. $arraytoscan = $this->childtables;
  3888. // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
  3889. $tmparray = array_keys($this->childtables);
  3890. if (is_numeric($tmparray[0])) {
  3891. $arraytoscan = array_flip($this->childtables);
  3892. }
  3893. // Test if child exists
  3894. $haschild = 0;
  3895. foreach ($arraytoscan as $table => $elementname) {
  3896. //print $id.'-'.$table.'-'.$elementname.'<br>';
  3897. // Check if third party can be deleted
  3898. $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table;
  3899. $sql .= " WHERE ".$this->fk_element." = ".((int) $id);
  3900. $resql = $this->db->query($sql);
  3901. if ($resql) {
  3902. $obj = $this->db->fetch_object($resql);
  3903. if ($obj->nb > 0) {
  3904. $langs->load("errors");
  3905. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  3906. $haschild += $obj->nb;
  3907. if (is_numeric($elementname)) { // old usage
  3908. $this->errors[] = $langs->transnoentities("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
  3909. } else // new usage: $elementname=Translation key
  3910. {
  3911. $this->errors[] = $langs->transnoentities("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($elementname));
  3912. }
  3913. break; // We found at least one, we stop here
  3914. }
  3915. } else {
  3916. $this->errors[] = $this->db->lasterror();
  3917. return -1;
  3918. }
  3919. }
  3920. if ($haschild > 0) {
  3921. $this->errors[] = "ErrorRecordHasChildren";
  3922. return $haschild;
  3923. } else {
  3924. return 0;
  3925. }
  3926. }
  3927. /**
  3928. * Function to say how many lines object contains
  3929. *
  3930. * @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
  3931. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  3932. */
  3933. public function hasProductsOrServices($predefined = -1)
  3934. {
  3935. $nb = 0;
  3936. foreach ($this->lines as $key => $val) {
  3937. $qualified = 0;
  3938. if ($predefined == -1) {
  3939. $qualified = 1;
  3940. }
  3941. if ($predefined == 1 && $val->fk_product > 0) {
  3942. $qualified = 1;
  3943. }
  3944. if ($predefined == 0 && $val->fk_product <= 0) {
  3945. $qualified = 1;
  3946. }
  3947. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
  3948. $qualified = 1;
  3949. }
  3950. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
  3951. $qualified = 1;
  3952. }
  3953. if ($qualified) {
  3954. $nb++;
  3955. }
  3956. }
  3957. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  3958. return $nb;
  3959. }
  3960. /**
  3961. * Function that returns the total amount HT of discounts applied for all lines.
  3962. *
  3963. * @return float|string Total amout of discount
  3964. */
  3965. public function getTotalDiscount()
  3966. {
  3967. if (!empty($this->table_element_line) ) {
  3968. $total_discount = 0.00;
  3969. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  3970. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  3971. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3972. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  3973. $resql = $this->db->query($sql);
  3974. if ($resql) {
  3975. $num = $this->db->num_rows($resql);
  3976. $i = 0;
  3977. while ($i < $num) {
  3978. $obj = $this->db->fetch_object($resql);
  3979. $pu_ht = $obj->pu_ht;
  3980. $qty = $obj->qty;
  3981. $total_ht = $obj->total_ht;
  3982. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  3983. $total_discount += $total_discount_line;
  3984. $i++;
  3985. }
  3986. }
  3987. //print $total_discount; exit;
  3988. return price2num($total_discount);
  3989. }
  3990. return null;
  3991. }
  3992. /**
  3993. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  3994. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  3995. *
  3996. * @return array array('weight'=>...,'volume'=>...)
  3997. */
  3998. public function getTotalWeightVolume()
  3999. {
  4000. $totalWeight = 0;
  4001. $totalVolume = 0;
  4002. // defined for shipment only
  4003. $totalOrdered = '';
  4004. // defined for shipment only
  4005. $totalToShip = '';
  4006. foreach ($this->lines as $line) {
  4007. if (isset($line->qty_asked)) {
  4008. if (empty($totalOrdered)) {
  4009. $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  4010. }
  4011. $totalOrdered += $line->qty_asked; // defined for shipment only
  4012. }
  4013. if (isset($line->qty_shipped)) {
  4014. if (empty($totalToShip)) {
  4015. $totalToShip = 0; // Avoid warning because $totalToShip is ''
  4016. }
  4017. $totalToShip += $line->qty_shipped; // defined for shipment only
  4018. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
  4019. if (empty($totalToShip)) {
  4020. $totalToShip = 0;
  4021. }
  4022. $totalToShip += $line->qty; // defined for reception only
  4023. }
  4024. // Define qty, weight, volume, weight_units, volume_units
  4025. if ($this->element == 'shipping') {
  4026. // for shipments
  4027. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  4028. } else {
  4029. $qty = $line->qty ? $line->qty : 0;
  4030. }
  4031. $weight = !empty($line->weight) ? $line->weight : 0;
  4032. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  4033. $volume = !empty($line->volume) ? $line->volume : 0;
  4034. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  4035. $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
  4036. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  4037. $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
  4038. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  4039. $weightUnit = 0;
  4040. $volumeUnit = 0;
  4041. if (!empty($weight_units)) {
  4042. $weightUnit = $weight_units;
  4043. }
  4044. if (!empty($volume_units)) {
  4045. $volumeUnit = $volume_units;
  4046. }
  4047. if (empty($totalWeight)) {
  4048. $totalWeight = 0; // Avoid warning because $totalWeight is ''
  4049. }
  4050. if (empty($totalVolume)) {
  4051. $totalVolume = 0; // Avoid warning because $totalVolume is ''
  4052. }
  4053. //var_dump($line->volume_units);
  4054. if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4055. $trueWeightUnit = pow(10, $weightUnit);
  4056. $totalWeight += $weight * $qty * $trueWeightUnit;
  4057. } else {
  4058. if ($weight_units == 99) {
  4059. // conversion 1 Pound = 0.45359237 KG
  4060. $trueWeightUnit = 0.45359237;
  4061. $totalWeight += $weight * $qty * $trueWeightUnit;
  4062. } elseif ($weight_units == 98) {
  4063. // conversion 1 Ounce = 0.0283495 KG
  4064. $trueWeightUnit = 0.0283495;
  4065. $totalWeight += $weight * $qty * $trueWeightUnit;
  4066. } else {
  4067. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  4068. }
  4069. }
  4070. if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4071. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  4072. $trueVolumeUnit = pow(10, $volumeUnit);
  4073. //print $line->volume;
  4074. $totalVolume += $volume * $qty * $trueVolumeUnit;
  4075. } else {
  4076. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  4077. }
  4078. }
  4079. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  4080. }
  4081. /**
  4082. * Set extra parameters
  4083. *
  4084. * @return int <0 if KO, >0 if OK
  4085. */
  4086. public function setExtraParameters()
  4087. {
  4088. $this->db->begin();
  4089. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  4090. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  4091. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  4092. $sql .= " WHERE rowid = ".((int) $this->id);
  4093. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  4094. $resql = $this->db->query($sql);
  4095. if (!$resql) {
  4096. $this->error = $this->db->lasterror();
  4097. $this->db->rollback();
  4098. return -1;
  4099. } else {
  4100. $this->db->commit();
  4101. return 1;
  4102. }
  4103. }
  4104. // --------------------
  4105. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  4106. // --------------------
  4107. /* This is to show add lines */
  4108. /**
  4109. * Show add free and predefined products/services form
  4110. *
  4111. * @param int $dateSelector 1=Show also date range input fields
  4112. * @param Societe $seller Object thirdparty who sell
  4113. * @param Societe $buyer Object thirdparty who buy
  4114. * @param string $defaulttpldir Directory where to find the template
  4115. * @return void
  4116. */
  4117. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  4118. {
  4119. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  4120. global $form;
  4121. // Line extrafield
  4122. if (!is_object($extrafields)) {
  4123. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4124. $extrafields = new ExtraFields($this->db);
  4125. }
  4126. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4127. // Output template part (modules that overwrite templates must declare this into descriptor)
  4128. // Use global variables + $dateSelector + $seller and $buyer
  4129. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  4130. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4131. foreach ($dirtpls as $module => $reldir) {
  4132. if (!empty($module)) {
  4133. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  4134. } else {
  4135. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  4136. }
  4137. if (empty($conf->file->strict_mode)) {
  4138. $res = @include $tpl;
  4139. } else {
  4140. $res = include $tpl; // for debug
  4141. }
  4142. if ($res) {
  4143. break;
  4144. }
  4145. }
  4146. }
  4147. /* This is to show array of line of details */
  4148. /**
  4149. * Return HTML table for object lines
  4150. * TODO Move this into an output class file (htmlline.class.php)
  4151. * If lines are into a template, title must also be into a template
  4152. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4153. *
  4154. * @param string $action Action code
  4155. * @param string $seller Object of seller third party
  4156. * @param string $buyer Object of buyer third party
  4157. * @param int $selected Object line selected
  4158. * @param int $dateSelector 1=Show also date range input fields
  4159. * @param string $defaulttpldir Directory where to find the template
  4160. * @return void
  4161. */
  4162. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  4163. {
  4164. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  4165. // TODO We should not use global var for this
  4166. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  4167. // Define usemargins
  4168. $usemargins = 0;
  4169. if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
  4170. $usemargins = 1;
  4171. }
  4172. $num = count($this->lines);
  4173. // Line extrafield
  4174. if (!is_object($extrafields)) {
  4175. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4176. $extrafields = new ExtraFields($this->db);
  4177. }
  4178. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4179. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  4180. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4181. if (empty($reshook)) {
  4182. // Output template part (modules that overwrite templates must declare this into descriptor)
  4183. // Use global variables + $dateSelector + $seller and $buyer
  4184. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  4185. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4186. foreach ($dirtpls as $module => $reldir) {
  4187. if (!empty($module)) {
  4188. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  4189. } else {
  4190. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  4191. }
  4192. if (empty($conf->file->strict_mode)) {
  4193. $res = @include $tpl;
  4194. } else {
  4195. $res = include $tpl; // for debug
  4196. }
  4197. if ($res) {
  4198. break;
  4199. }
  4200. }
  4201. }
  4202. $i = 0;
  4203. print "<!-- begin printObjectLines() --><tbody>\n";
  4204. foreach ($this->lines as $line) {
  4205. //Line extrafield
  4206. $line->fetch_optionals();
  4207. //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  4208. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4209. if (empty($line->fk_parent_line)) {
  4210. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  4211. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4212. } else {
  4213. $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);
  4214. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4215. }
  4216. }
  4217. if (empty($reshook)) {
  4218. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  4219. }
  4220. $i++;
  4221. }
  4222. print "</tbody><!-- end printObjectLines() -->\n";
  4223. }
  4224. /**
  4225. * Return HTML content of a detail line
  4226. * TODO Move this into an output class file (htmlline.class.php)
  4227. *
  4228. * @param string $action GET/POST action
  4229. * @param CommonObjectLine $line Selected object line to output
  4230. * @param string $var Is it a an odd line (true)
  4231. * @param int $num Number of line (0)
  4232. * @param int $i I
  4233. * @param int $dateSelector 1=Show also date range input fields
  4234. * @param string $seller Object of seller third party
  4235. * @param string $buyer Object of buyer third party
  4236. * @param int $selected Object line selected
  4237. * @param Extrafields $extrafields Object of extrafields
  4238. * @param string $defaulttpldir Directory where to find the template (deprecated)
  4239. * @return void
  4240. */
  4241. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  4242. {
  4243. global $conf, $langs, $user, $object, $hookmanager;
  4244. global $form;
  4245. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  4246. $object_rights = $this->getRights();
  4247. $element = $this->element;
  4248. $text = '';
  4249. $description = '';
  4250. // Line in view mode
  4251. if ($action != 'editline' || $selected != $line->id) {
  4252. // Product
  4253. if ($line->fk_product > 0) {
  4254. $product_static = new Product($this->db);
  4255. $product_static->fetch($line->fk_product);
  4256. $product_static->ref = $line->ref; //can change ref in hook
  4257. $product_static->label = $line->label; //can change label in hook
  4258. $text = $product_static->getNomUrl(1);
  4259. // Define output language and label
  4260. if (!empty($conf->global->MAIN_MULTILANGS)) {
  4261. if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
  4262. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  4263. return;
  4264. }
  4265. $prod = new Product($this->db);
  4266. $prod->fetch($line->fk_product);
  4267. $outputlangs = $langs;
  4268. $newlang = '';
  4269. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  4270. $newlang = GETPOST('lang_id', 'aZ09');
  4271. }
  4272. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
  4273. $newlang = $this->thirdparty->default_lang; // To use language of customer
  4274. }
  4275. if (!empty($newlang)) {
  4276. $outputlangs = new Translate("", $conf);
  4277. $outputlangs->setDefaultLang($newlang);
  4278. }
  4279. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  4280. } else {
  4281. $label = $line->product_label;
  4282. }
  4283. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  4284. $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.
  4285. }
  4286. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4287. // Output template part (modules that overwrite templates must declare this into descriptor)
  4288. // Use global variables + $dateSelector + $seller and $buyer
  4289. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4290. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4291. foreach ($dirtpls as $module => $reldir) {
  4292. if (!empty($module)) {
  4293. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  4294. } else {
  4295. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  4296. }
  4297. if (empty($conf->file->strict_mode)) {
  4298. $res = @include $tpl;
  4299. } else {
  4300. $res = include $tpl; // for debug
  4301. }
  4302. if ($res) {
  4303. break;
  4304. }
  4305. }
  4306. }
  4307. // Line in update mode
  4308. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
  4309. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  4310. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4311. // Output template part (modules that overwrite templates must declare this into descriptor)
  4312. // Use global variables + $dateSelector + $seller and $buyer
  4313. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4314. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4315. foreach ($dirtpls as $module => $reldir) {
  4316. if (!empty($module)) {
  4317. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  4318. } else {
  4319. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  4320. }
  4321. if (empty($conf->file->strict_mode)) {
  4322. $res = @include $tpl;
  4323. } else {
  4324. $res = include $tpl; // for debug
  4325. }
  4326. if ($res) {
  4327. break;
  4328. }
  4329. }
  4330. }
  4331. }
  4332. /* This is to show array of line of details of source object */
  4333. /**
  4334. * Return HTML table table of source object lines
  4335. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4336. * If lines are into a template, title must also be into a template
  4337. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  4338. *
  4339. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  4340. * @param array $selectedLines Array of lines id for selected lines
  4341. * @return void
  4342. */
  4343. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  4344. {
  4345. global $langs, $hookmanager, $conf, $form, $action;
  4346. print '<tr class="liste_titre">';
  4347. print '<td>'.$langs->trans('Ref').'</td>';
  4348. print '<td>'.$langs->trans('Description').'</td>';
  4349. print '<td class="right">'.$langs->trans('VATRate').'</td>';
  4350. print '<td class="right">'.$langs->trans('PriceUHT').'</td>';
  4351. if (!empty($conf->multicurrency->enabled)) {
  4352. print '<td class="right">'.$langs->trans('PriceUHTCurrency').'</td>';
  4353. }
  4354. print '<td class="right">'.$langs->trans('Qty').'</td>';
  4355. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4356. print '<td class="left">'.$langs->trans('Unit').'</td>';
  4357. }
  4358. print '<td class="right">'.$langs->trans('ReductionShort').'</td>';
  4359. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  4360. print '</tr>';
  4361. $i = 0;
  4362. if (!empty($this->lines)) {
  4363. foreach ($this->lines as $line) {
  4364. $reshook = 0;
  4365. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
  4366. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4367. $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
  4368. if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
  4369. $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4370. }
  4371. if (empty($reshook)) {
  4372. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  4373. }
  4374. $i++;
  4375. }
  4376. }
  4377. }
  4378. /**
  4379. * Return HTML with a line of table array of source object lines
  4380. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4381. * If lines are into a template, title must also be into a template
  4382. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4383. *
  4384. * @param CommonObjectLine $line Line
  4385. * @param string $var Var
  4386. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  4387. * @param string $defaulttpldir Directory where to find the template
  4388. * @param array $selectedLines Array of lines id for selected lines
  4389. * @return void
  4390. */
  4391. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  4392. {
  4393. global $langs, $conf;
  4394. //var_dump($line);
  4395. if (!empty($line->date_start)) {
  4396. $date_start = $line->date_start;
  4397. } else {
  4398. $date_start = $line->date_debut_prevue;
  4399. if ($line->date_debut_reel) {
  4400. $date_start = $line->date_debut_reel;
  4401. }
  4402. }
  4403. if (!empty($line->date_end)) {
  4404. $date_end = $line->date_end;
  4405. } else {
  4406. $date_end = $line->date_fin_prevue;
  4407. if ($line->date_fin_reel) {
  4408. $date_end = $line->date_fin_reel;
  4409. }
  4410. }
  4411. $this->tpl['id'] = $line->id;
  4412. $this->tpl['label'] = '';
  4413. if (!empty($line->fk_parent_line)) {
  4414. $this->tpl['label'] .= img_picto('', 'rightarrow');
  4415. }
  4416. if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
  4417. $discount = new DiscountAbsolute($this->db);
  4418. $discount->fk_soc = $this->socid;
  4419. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  4420. } elseif (!empty($line->fk_product)) {
  4421. $productstatic = new Product($this->db);
  4422. $productstatic->id = $line->fk_product;
  4423. $productstatic->ref = $line->ref;
  4424. $productstatic->type = $line->fk_product_type;
  4425. if (empty($productstatic->ref)) {
  4426. $line->fetch_product();
  4427. $productstatic = $line->product;
  4428. }
  4429. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  4430. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  4431. // Dates
  4432. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4433. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4434. }
  4435. } else {
  4436. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  4437. if (!empty($line->desc)) {
  4438. $this->tpl['label'] .= $line->desc;
  4439. } else {
  4440. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  4441. }
  4442. // Dates
  4443. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4444. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4445. }
  4446. }
  4447. if (!empty($line->desc)) {
  4448. if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
  4449. $discount = new DiscountAbsolute($this->db);
  4450. $discount->fetch($line->fk_remise_except);
  4451. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  4452. } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
  4453. $discount = new DiscountAbsolute($this->db);
  4454. $discount->fetch($line->fk_remise_except);
  4455. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  4456. } elseif ($line->desc == '(EXCESS RECEIVED)') {
  4457. $discount = new DiscountAbsolute($this->db);
  4458. $discount->fetch($line->fk_remise_except);
  4459. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  4460. } elseif ($line->desc == '(EXCESS PAID)') {
  4461. $discount = new DiscountAbsolute($this->db);
  4462. $discount->fetch($line->fk_remise_except);
  4463. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  4464. } else {
  4465. $this->tpl['description'] = dol_trunc($line->desc, 60);
  4466. }
  4467. } else {
  4468. $this->tpl['description'] = '&nbsp;';
  4469. }
  4470. // VAT Rate
  4471. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  4472. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  4473. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
  4474. $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  4475. }
  4476. $this->tpl['price'] = price($line->subprice);
  4477. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  4478. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  4479. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4480. $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  4481. }
  4482. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  4483. // Is the line strike or not
  4484. $this->tpl['strike'] = 0;
  4485. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
  4486. $this->tpl['strike'] = 1;
  4487. }
  4488. // Output template part (modules that overwrite templates must declare this into descriptor)
  4489. // Use global variables + $dateSelector + $seller and $buyer
  4490. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4491. foreach ($dirtpls as $module => $reldir) {
  4492. if (!empty($module)) {
  4493. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  4494. } else {
  4495. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  4496. }
  4497. if (empty($conf->file->strict_mode)) {
  4498. $res = @include $tpl;
  4499. } else {
  4500. $res = include $tpl; // for debug
  4501. }
  4502. if ($res) {
  4503. break;
  4504. }
  4505. }
  4506. }
  4507. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4508. /**
  4509. * Add resources to the current object : add entry into llx_element_resources
  4510. * Need $this->element & $this->id
  4511. *
  4512. * @param int $resource_id Resource id
  4513. * @param string $resource_type 'resource'
  4514. * @param int $busy Busy or not
  4515. * @param int $mandatory Mandatory or not
  4516. * @return int <=0 if KO, >0 if OK
  4517. */
  4518. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  4519. {
  4520. // phpcs:enable
  4521. $this->db->begin();
  4522. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources (";
  4523. $sql .= "resource_id";
  4524. $sql .= ", resource_type";
  4525. $sql .= ", element_id";
  4526. $sql .= ", element_type";
  4527. $sql .= ", busy";
  4528. $sql .= ", mandatory";
  4529. $sql .= ") VALUES (";
  4530. $sql .= $resource_id;
  4531. $sql .= ", '".$this->db->escape($resource_type)."'";
  4532. $sql .= ", '".$this->db->escape($this->id)."'";
  4533. $sql .= ", '".$this->db->escape($this->element)."'";
  4534. $sql .= ", '".$this->db->escape($busy)."'";
  4535. $sql .= ", '".$this->db->escape($mandatory)."'";
  4536. $sql .= ")";
  4537. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  4538. if ($this->db->query($sql)) {
  4539. $this->db->commit();
  4540. return 1;
  4541. } else {
  4542. $this->error = $this->db->lasterror();
  4543. $this->db->rollback();
  4544. return 0;
  4545. }
  4546. }
  4547. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4548. /**
  4549. * Delete a link to resource line
  4550. *
  4551. * @param int $rowid Id of resource line to delete
  4552. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  4553. * @param int $notrigger Disable all triggers
  4554. * @return int >0 if OK, <0 if KO
  4555. */
  4556. public function delete_resource($rowid, $element, $notrigger = 0)
  4557. {
  4558. // phpcs:enable
  4559. global $user;
  4560. $this->db->begin();
  4561. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
  4562. $sql .= " WHERE rowid = ".((int) $rowid);
  4563. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  4564. $resql = $this->db->query($sql);
  4565. if (!$resql) {
  4566. $this->error = $this->db->lasterror();
  4567. $this->db->rollback();
  4568. return -1;
  4569. } else {
  4570. if (!$notrigger) {
  4571. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  4572. if ($result < 0) {
  4573. $this->db->rollback();
  4574. return -1;
  4575. }
  4576. }
  4577. $this->db->commit();
  4578. return 1;
  4579. }
  4580. }
  4581. /**
  4582. * Overwrite magic function to solve problem of cloning object that are kept as references
  4583. *
  4584. * @return void
  4585. */
  4586. public function __clone()
  4587. {
  4588. // Force a copy of this->lines, otherwise it will point to same object.
  4589. if (isset($this->lines) && is_array($this->lines)) {
  4590. $nboflines = count($this->lines);
  4591. for ($i = 0; $i < $nboflines; $i++) {
  4592. $this->lines[$i] = clone $this->lines[$i];
  4593. }
  4594. }
  4595. }
  4596. /**
  4597. * Common function for all objects extending CommonObject for generating documents
  4598. *
  4599. * @param string $modelspath Relative folder where generators are placed
  4600. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4601. * @param Translate $outputlangs Output language to use
  4602. * @param int $hidedetails 1 to hide details. 0 by default
  4603. * @param int $hidedesc 1 to hide product description. 0 by default
  4604. * @param int $hideref 1 to hide product reference. 0 by default
  4605. * @param null|array $moreparams Array to provide more information
  4606. * @return int >0 if OK, <0 if KO
  4607. * @see addFileIntoDatabaseIndex()
  4608. */
  4609. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4610. {
  4611. global $conf, $langs, $user, $hookmanager, $action;
  4612. $srctemplatepath = '';
  4613. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  4614. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4615. if (empty($reshook)) {
  4616. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4617. if (empty($modele)) {
  4618. $this->error = 'BadValueForParameterModele';
  4619. return -1;
  4620. }
  4621. // Increase limit for PDF build
  4622. $err = error_reporting();
  4623. error_reporting(0);
  4624. @set_time_limit(120);
  4625. error_reporting($err);
  4626. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4627. $tmp = explode(':', $modele, 2);
  4628. if (!empty($tmp[1])) {
  4629. $modele = $tmp[0];
  4630. $srctemplatepath = $tmp[1];
  4631. }
  4632. // Search template files
  4633. $file = '';
  4634. $classname = '';
  4635. $filefound = '';
  4636. $dirmodels = array('/');
  4637. if (is_array($conf->modules_parts['models'])) {
  4638. $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4639. }
  4640. foreach ($dirmodels as $reldir) {
  4641. foreach (array('doc', 'pdf') as $prefix) {
  4642. if (in_array(get_class($this), array('Adherent'))) {
  4643. // Member module use prefix_modele.class.php
  4644. $file = $prefix."_".$modele.".class.php";
  4645. } else {
  4646. // Other module use prefix_modele.modules.php
  4647. $file = $prefix."_".$modele.".modules.php";
  4648. }
  4649. // On verifie l'emplacement du modele
  4650. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  4651. if (file_exists($file)) {
  4652. $filefound = $file;
  4653. $classname = $prefix.'_'.$modele;
  4654. break;
  4655. }
  4656. }
  4657. if ($filefound) {
  4658. break;
  4659. }
  4660. }
  4661. // If generator was found
  4662. if ($filefound) {
  4663. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4664. require_once $file;
  4665. $obj = new $classname($this->db);
  4666. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4667. if ($obj->type == 'odt' && empty($srctemplatepath)) {
  4668. $varfortemplatedir = $obj->scandir;
  4669. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
  4670. $dirtoscan = $conf->global->$varfortemplatedir;
  4671. $listoffiles = array();
  4672. // Now we add first model found in directories scanned
  4673. $listofdir = explode(',', $dirtoscan);
  4674. foreach ($listofdir as $key => $tmpdir) {
  4675. $tmpdir = trim($tmpdir);
  4676. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4677. if (!$tmpdir) {
  4678. unset($listofdir[$key]);
  4679. continue;
  4680. }
  4681. if (is_dir($tmpdir)) {
  4682. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4683. if (count($tmpfiles)) {
  4684. $listoffiles = array_merge($listoffiles, $tmpfiles);
  4685. }
  4686. }
  4687. }
  4688. if (count($listoffiles)) {
  4689. foreach ($listoffiles as $record) {
  4690. $srctemplatepath = $record['fullname'];
  4691. break;
  4692. }
  4693. }
  4694. }
  4695. if (empty($srctemplatepath)) {
  4696. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4697. return -1;
  4698. }
  4699. }
  4700. if ($obj->type == 'odt' && !empty($srctemplatepath)) {
  4701. if (!dol_is_file($srctemplatepath)) {
  4702. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  4703. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4704. return -1;
  4705. }
  4706. }
  4707. // We save charset_output to restore it because write_file can change it if needed for
  4708. // output format that does not support UTF8.
  4709. $sav_charset_output = $outputlangs->charset_output;
  4710. if (in_array(get_class($this), array('Adherent'))) {
  4711. $arrayofrecords = array(); // The write_file of templates of adherent class need this var
  4712. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams);
  4713. } else {
  4714. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4715. }
  4716. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4717. if ($resultwritefile > 0) {
  4718. $outputlangs->charset_output = $sav_charset_output;
  4719. // We delete old preview
  4720. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4721. dol_delete_preview($this);
  4722. // Index file in database
  4723. if (!empty($obj->result['fullpath'])) {
  4724. $destfull = $obj->result['fullpath'];
  4725. // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
  4726. $update_main_doc_field = 0;
  4727. if (!empty($obj->update_main_doc_field)) {
  4728. $update_main_doc_field = 1;
  4729. }
  4730. $this->indexFile($destfull, $update_main_doc_field);
  4731. } else {
  4732. 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);
  4733. }
  4734. // Success in building document. We build meta file.
  4735. dol_meta_create($this);
  4736. return 1;
  4737. } else {
  4738. $outputlangs->charset_output = $sav_charset_output;
  4739. dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
  4740. return -1;
  4741. }
  4742. } else {
  4743. if (!$filefound) {
  4744. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4745. dol_print_error('', $this->error);
  4746. } else {
  4747. $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
  4748. dol_print_error('', $this->error);
  4749. }
  4750. return -1;
  4751. }
  4752. } else {
  4753. return $reshook;
  4754. }
  4755. }
  4756. /**
  4757. * Index a file into the ECM database
  4758. *
  4759. * @param string $destfull Full path of file to index
  4760. * @param int $update_main_doc_field Update field main_doc file into table of object
  4761. * @return int <0 if KO, >0 if OK
  4762. */
  4763. public function indexFile($destfull, $update_main_doc_field)
  4764. {
  4765. global $conf, $user;
  4766. $upload_dir = dirname($destfull);
  4767. $destfile = basename($destfull);
  4768. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  4769. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  4770. $filename = basename($destfile);
  4771. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4772. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4773. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4774. $ecmfile = new EcmFiles($this->db);
  4775. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  4776. // Set the public "share" key
  4777. $setsharekey = false;
  4778. if ($this->element == 'propal' || $this->element == 'proposal') {
  4779. if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
  4780. $setsharekey = true; // feature to make online signature is not set or set to on (default)
  4781. }
  4782. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4783. $setsharekey = true;
  4784. }
  4785. }
  4786. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  4787. $setsharekey = true;
  4788. }
  4789. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  4790. $setsharekey = true;
  4791. }
  4792. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4793. $setsharekey = true;
  4794. }
  4795. if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4796. $setsharekey = true;
  4797. }
  4798. if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4799. $setsharekey = true;
  4800. }
  4801. if ($setsharekey) {
  4802. if (empty($ecmfile->share)) { // Because object not found or share not set yet
  4803. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  4804. $ecmfile->share = getRandomPassword(true);
  4805. }
  4806. }
  4807. if ($result > 0) {
  4808. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4809. $ecmfile->fullpath_orig = '';
  4810. $ecmfile->gen_or_uploaded = 'generated';
  4811. $ecmfile->description = ''; // indexed content
  4812. $ecmfile->keywords = ''; // keyword content
  4813. $result = $ecmfile->update($user);
  4814. if ($result < 0) {
  4815. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4816. return -1;
  4817. }
  4818. } else {
  4819. $ecmfile->entity = $conf->entity;
  4820. $ecmfile->filepath = $rel_dir;
  4821. $ecmfile->filename = $filename;
  4822. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4823. $ecmfile->fullpath_orig = '';
  4824. $ecmfile->gen_or_uploaded = 'generated';
  4825. $ecmfile->description = ''; // indexed content
  4826. $ecmfile->keywords = ''; // keyword content
  4827. $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
  4828. $ecmfile->src_object_id = $this->id;
  4829. $result = $ecmfile->create($user);
  4830. if ($result < 0) {
  4831. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4832. return -1;
  4833. }
  4834. }
  4835. /*$this->result['fullname']=$destfull;
  4836. $this->result['filepath']=$ecmfile->filepath;
  4837. $this->result['filename']=$ecmfile->filename;*/
  4838. //var_dump($obj->update_main_doc_field);exit;
  4839. if ($update_main_doc_field && !empty($this->table_element)) {
  4840. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
  4841. $sql .= " WHERE rowid = ".((int) $this->id);
  4842. $resql = $this->db->query($sql);
  4843. if (!$resql) {
  4844. dol_print_error($this->db);
  4845. return -1;
  4846. } else {
  4847. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  4848. }
  4849. }
  4850. }
  4851. return 1;
  4852. }
  4853. /**
  4854. * Build thumb
  4855. * @todo Move this into files.lib.php
  4856. *
  4857. * @param string $file Path file in UTF8 to original file to create thumbs from.
  4858. * @return void
  4859. */
  4860. public function addThumbs($file)
  4861. {
  4862. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  4863. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  4864. $file_osencoded = dol_osencode($file);
  4865. if (file_exists($file_osencoded)) {
  4866. // Create small thumbs for company (Ratio is near 16/9)
  4867. // Used on logon for example
  4868. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  4869. // Create mini thumbs for company (Ratio is near 16/9)
  4870. // Used on menu or for setup page for example
  4871. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  4872. }
  4873. }
  4874. /* Functions common to commonobject and commonobjectline */
  4875. /* For default values */
  4876. /**
  4877. * Return the default value to use for a field when showing the create form of object.
  4878. * Return values in this order:
  4879. * 1) If parameter is available into POST, we return it first.
  4880. * 2) If not but an alternate value was provided as parameter of function, we return it.
  4881. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  4882. * 4) Return value found into database (TODO No yet implemented)
  4883. *
  4884. * @param string $fieldname Name of field
  4885. * @param string $alternatevalue Alternate value to use
  4886. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  4887. **/
  4888. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
  4889. {
  4890. global $conf, $_POST;
  4891. // If param here has been posted, we use this value first.
  4892. if (GETPOSTISSET($fieldname)) {
  4893. return GETPOST($fieldname, 'alphanohtml', 3);
  4894. }
  4895. if (isset($alternatevalue)) {
  4896. return $alternatevalue;
  4897. }
  4898. $newelement = $this->element;
  4899. if ($newelement == 'facture') {
  4900. $newelement = 'invoice';
  4901. }
  4902. if ($newelement == 'commande') {
  4903. $newelement = 'order';
  4904. }
  4905. if (empty($newelement)) {
  4906. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  4907. return '';
  4908. }
  4909. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  4910. //var_dump($keyforfieldname);
  4911. if (isset($conf->global->$keyforfieldname)) {
  4912. return $conf->global->$keyforfieldname;
  4913. }
  4914. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  4915. }
  4916. /* For triggers */
  4917. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4918. /**
  4919. * Call trigger based on this instance.
  4920. * Some context information may also be provided into array property this->context.
  4921. * NB: Error from trigger are stacked in interface->errors
  4922. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  4923. *
  4924. * @param string $triggerName trigger's name to execute
  4925. * @param User $user Object user
  4926. * @return int Result of run_triggers
  4927. */
  4928. public function call_trigger($triggerName, $user)
  4929. {
  4930. // phpcs:enable
  4931. global $langs, $conf;
  4932. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  4933. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4934. $langs = new Translate('', $conf);
  4935. }
  4936. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  4937. $interface = new Interfaces($this->db);
  4938. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  4939. if ($result < 0) {
  4940. if (!empty($this->errors)) {
  4941. $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.
  4942. } else {
  4943. $this->errors = $interface->errors;
  4944. }
  4945. }
  4946. return $result;
  4947. }
  4948. /* Functions for data in other language */
  4949. /**
  4950. * Function to get alternative languages of a data into $this->array_languages
  4951. * This method is NOT called by method fetch of objects but must be called separately.
  4952. *
  4953. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  4954. * @see fetch_optionnals()
  4955. */
  4956. public function fetchValuesForExtraLanguages()
  4957. {
  4958. // To avoid SQL errors. Probably not the better solution though
  4959. if (!$this->element) {
  4960. return 0;
  4961. }
  4962. if (!($this->id > 0)) {
  4963. return 0;
  4964. }
  4965. if (is_array($this->array_languages)) {
  4966. return 1;
  4967. }
  4968. $this->array_languages = array();
  4969. $element = $this->element;
  4970. if ($element == 'categorie') {
  4971. $element = 'categories'; // For compatibility
  4972. }
  4973. // Request to get translation values for object
  4974. $sql = "SELECT rowid, property, lang , value";
  4975. $sql .= " FROM ".MAIN_DB_PREFIX."object_lang";
  4976. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  4977. $sql .= " AND fk_object = ".((int) $this->id);
  4978. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  4979. $resql = $this->db->query($sql);
  4980. if ($resql) {
  4981. $numrows = $this->db->num_rows($resql);
  4982. if ($numrows) {
  4983. $i = 0;
  4984. while ($i < $numrows) {
  4985. $obj = $this->db->fetch_object($resql);
  4986. $key = $obj->property;
  4987. $value = $obj->value;
  4988. $codelang = $obj->lang;
  4989. $type = $this->fields[$key]['type'];
  4990. // we can add this attribute to object
  4991. if (preg_match('/date/', $type)) {
  4992. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  4993. } else {
  4994. $this->array_languages[$key][$codelang] = $value;
  4995. }
  4996. $i++;
  4997. }
  4998. }
  4999. $this->db->free($resql);
  5000. if ($numrows) {
  5001. return $numrows;
  5002. } else {
  5003. return 0;
  5004. }
  5005. } else {
  5006. dol_print_error($this->db);
  5007. return -1;
  5008. }
  5009. }
  5010. /**
  5011. * Fill array_options property of object by extrafields value (using for data sent by forms)
  5012. *
  5013. * @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.
  5014. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  5015. */
  5016. public function setValuesForExtraLanguages($onlykey = '')
  5017. {
  5018. global $_POST, $langs;
  5019. // Get extra fields
  5020. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  5021. $tmparray = explode('-', $postfieldkey);
  5022. if ($tmparray[0] != 'field') {
  5023. continue;
  5024. }
  5025. $element = $tmparray[1];
  5026. $key = $tmparray[2];
  5027. $codelang = $tmparray[3];
  5028. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  5029. if (!empty($onlykey) && $key != $onlykey) {
  5030. continue;
  5031. }
  5032. if ($element != $this->element) {
  5033. continue;
  5034. }
  5035. $key_type = $this->fields[$key]['type'];
  5036. $enabled = 1;
  5037. if (isset($this->fields[$key]['enabled'])) {
  5038. $enabled = dol_eval($this->fields[$key]['enabled'], 1);
  5039. }
  5040. /*$perms = 1;
  5041. if (isset($this->fields[$key]['perms']))
  5042. {
  5043. $perms = dol_eval($this->fields[$key]['perms'], 1);
  5044. }*/
  5045. if (empty($enabled)) {
  5046. continue;
  5047. }
  5048. //if (empty($perms)) continue;
  5049. if (in_array($key_type, array('date'))) {
  5050. // Clean parameters
  5051. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5052. $value_key = dol_mktime(0, 0, 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]);
  5053. } elseif (in_array($key_type, array('datetime'))) {
  5054. // Clean parameters
  5055. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5056. $value_key = dol_mktime($_POST[$postfieldkey."hour"], $_POST[$postfieldkey."min"], 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]);
  5057. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  5058. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  5059. if (!empty($value_arr)) {
  5060. $value_key = implode(',', $value_arr);
  5061. } else {
  5062. $value_key = '';
  5063. }
  5064. } elseif (in_array($key_type, array('price', 'double'))) {
  5065. $value_arr = GETPOST($postfieldkey, 'alpha');
  5066. $value_key = price2num($value_arr);
  5067. } else {
  5068. $value_key = GETPOST($postfieldkey);
  5069. if (in_array($key_type, array('link')) && $value_key == '-1') {
  5070. $value_key = '';
  5071. }
  5072. }
  5073. $this->array_languages[$key][$codelang] = $value_key;
  5074. /*if ($nofillrequired) {
  5075. $langs->load('errors');
  5076. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  5077. return -1;
  5078. }*/
  5079. }
  5080. return 1;
  5081. }
  5082. /* Functions for extrafields */
  5083. /**
  5084. * Function to make a fetch but set environment to avoid to load computed values before.
  5085. *
  5086. * @param int $id ID of object
  5087. * @return int >0 if OK, 0 if not found, <0 if KO
  5088. */
  5089. public function fetchNoCompute($id)
  5090. {
  5091. global $conf;
  5092. $savDisableCompute = $conf->disable_compute;
  5093. $conf->disable_compute = 1;
  5094. $ret = $this->fetch($id);
  5095. $conf->disable_compute = $savDisableCompute;
  5096. return $ret;
  5097. }
  5098. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5099. /**
  5100. * Function to get extra fields of an object into $this->array_options
  5101. * This method is in most cases called by method fetch of objects but you can call it separately.
  5102. *
  5103. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  5104. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  5105. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  5106. * @see fetchValuesForExtraLanguages()
  5107. */
  5108. public function fetch_optionals($rowid = null, $optionsArray = null)
  5109. {
  5110. // phpcs:enable
  5111. global $conf, $extrafields;
  5112. if (empty($rowid)) {
  5113. $rowid = $this->id;
  5114. }
  5115. if (empty($rowid) && isset($this->rowid)) {
  5116. $rowid = $this->rowid; // deprecated
  5117. }
  5118. // To avoid SQL errors. Probably not the better solution though
  5119. if (!$this->table_element) {
  5120. return 0;
  5121. }
  5122. $this->array_options = array();
  5123. if (!is_array($optionsArray)) {
  5124. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  5125. if (!isset($extrafields) || !is_object($extrafields)) {
  5126. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5127. $extrafields = new ExtraFields($this->db);
  5128. }
  5129. // Load array of extrafields for elementype = $this->table_element
  5130. if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
  5131. $extrafields->fetch_name_optionals_label($this->table_element);
  5132. }
  5133. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  5134. } else {
  5135. global $extrafields;
  5136. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  5137. }
  5138. $table_element = $this->table_element;
  5139. if ($table_element == 'categorie') {
  5140. $table_element = 'categories'; // For compatibility
  5141. }
  5142. // Request to get complementary values
  5143. if (is_array($optionsArray) && count($optionsArray) > 0) {
  5144. $sql = "SELECT rowid";
  5145. foreach ($optionsArray as $name => $label) {
  5146. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
  5147. $sql .= ", ".$name;
  5148. }
  5149. }
  5150. $sql .= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
  5151. $sql .= " WHERE fk_object = ".((int) $rowid);
  5152. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5153. $resql = $this->db->query($sql);
  5154. if ($resql) {
  5155. $numrows = $this->db->num_rows($resql);
  5156. if ($numrows) {
  5157. $tab = $this->db->fetch_array($resql);
  5158. foreach ($tab as $key => $value) {
  5159. // 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)
  5160. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
  5161. // we can add this attribute to object
  5162. if (!empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
  5163. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  5164. $this->array_options["options_".$key] = $this->db->jdate($value);
  5165. } else {
  5166. $this->array_options["options_".$key] = $value;
  5167. }
  5168. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  5169. }
  5170. }
  5171. // If field is a computed field, value must become result of compute
  5172. foreach ($tab as $key => $value) {
  5173. if (!empty($extrafields) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
  5174. //var_dump($conf->disable_compute);
  5175. if (empty($conf->disable_compute)) {
  5176. $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0);
  5177. }
  5178. }
  5179. }
  5180. }
  5181. $this->db->free($resql);
  5182. if ($numrows) {
  5183. return $numrows;
  5184. } else {
  5185. return 0;
  5186. }
  5187. } else {
  5188. $this->errors[]=$this->db->lasterror;
  5189. return -1;
  5190. }
  5191. }
  5192. return 0;
  5193. }
  5194. /**
  5195. * Delete all extra fields values for the current object.
  5196. *
  5197. * @return int <0 if KO, >0 if OK
  5198. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  5199. */
  5200. public function deleteExtraFields()
  5201. {
  5202. global $conf;
  5203. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5204. return 0;
  5205. }
  5206. $this->db->begin();
  5207. $table_element = $this->table_element;
  5208. if ($table_element == 'categorie') {
  5209. $table_element = 'categories'; // For compatibility
  5210. }
  5211. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  5212. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5213. $resql = $this->db->query($sql_del);
  5214. if (!$resql) {
  5215. $this->error = $this->db->lasterror();
  5216. $this->db->rollback();
  5217. return -1;
  5218. } else {
  5219. $this->db->commit();
  5220. return 1;
  5221. }
  5222. }
  5223. /**
  5224. * Add/Update all extra fields values for the current object.
  5225. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5226. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5227. *
  5228. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5229. * @param User $userused Object user
  5230. * @return int -1=error, O=did nothing, 1=OK
  5231. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  5232. */
  5233. public function insertExtraFields($trigger = '', $userused = null)
  5234. {
  5235. global $conf, $langs, $user;
  5236. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5237. return 0;
  5238. }
  5239. if (empty($userused)) {
  5240. $userused = $user;
  5241. }
  5242. $error = 0;
  5243. if (!empty($this->array_options)) {
  5244. // Check parameters
  5245. $langs->load('admin');
  5246. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5247. $extrafields = new ExtraFields($this->db);
  5248. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  5249. // Eliminate copied source object extra fields that do not exist in target object
  5250. $new_array_options = array();
  5251. foreach ($this->array_options as $key => $value) {
  5252. if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
  5253. $new_array_options[$key] = $value;
  5254. } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
  5255. $new_array_options['options_'.$key] = $value;
  5256. }
  5257. }
  5258. foreach ($new_array_options as $key => $value) {
  5259. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5260. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  5261. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  5262. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  5263. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  5264. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  5265. // Similar code than into insertExtraFields
  5266. if ($attributeRequired) {
  5267. $mandatorypb = false;
  5268. if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
  5269. $mandatorypb = true;
  5270. }
  5271. if ($this->array_options[$key] === '') {
  5272. $mandatorypb = true;
  5273. }
  5274. if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
  5275. $mandatorypb = true;
  5276. }
  5277. if ($mandatorypb) {
  5278. $langs->load("errors");
  5279. dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
  5280. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5281. return -1;
  5282. }
  5283. }
  5284. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5285. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5286. if (!empty($attrfieldcomputed)) {
  5287. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5288. $value = dol_eval($attrfieldcomputed, 1, 0);
  5289. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5290. $new_array_options[$key] = $value;
  5291. } else {
  5292. $new_array_options[$key] = null;
  5293. }
  5294. }
  5295. switch ($attributeType) {
  5296. case 'int':
  5297. if (!is_numeric($value) && $value != '') {
  5298. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5299. return -1;
  5300. } elseif ($value == '') {
  5301. $new_array_options[$key] = null;
  5302. }
  5303. break;
  5304. case 'price':
  5305. case 'double':
  5306. $value = price2num($value);
  5307. if (!is_numeric($value) && $value != '') {
  5308. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5309. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5310. return -1;
  5311. } elseif ($value == '') {
  5312. $new_array_options[$key] = null;
  5313. }
  5314. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5315. $new_array_options[$key] = $value;
  5316. break;
  5317. /*case 'select': // Not required, we chosed value='0' for undefined values
  5318. if ($value=='-1')
  5319. {
  5320. $this->array_options[$key] = null;
  5321. }
  5322. break;*/
  5323. case 'password':
  5324. $algo = '';
  5325. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
  5326. // If there is an encryption choice, we use it to crypt data before insert
  5327. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  5328. $algo = reset($tmparrays);
  5329. if ($algo != '') {
  5330. //global $action; // $action may be 'create', 'update', 'update_extras'...
  5331. //var_dump($action);
  5332. //var_dump($this->oldcopy);exit;
  5333. 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
  5334. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  5335. 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.
  5336. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5337. } else {
  5338. // var_dump($algo);
  5339. $newvalue = dol_hash($this->array_options[$key], $algo);
  5340. $new_array_options[$key] = $newvalue;
  5341. }
  5342. } else {
  5343. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5344. }
  5345. }
  5346. } else // Common usage
  5347. {
  5348. $new_array_options[$key] = $this->array_options[$key];
  5349. }
  5350. break;
  5351. case 'date':
  5352. case 'datetime':
  5353. // If data is a string instead of a timestamp, we convert it
  5354. if (!is_int($this->array_options[$key])) {
  5355. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5356. }
  5357. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  5358. break;
  5359. case 'link':
  5360. $param_list = array_keys($attributeParam['options']);
  5361. // 0 : ObjectName
  5362. // 1 : classPath
  5363. $InfoFieldList = explode(":", $param_list[0]);
  5364. dol_include_once($InfoFieldList[1]);
  5365. if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
  5366. if ($value == '-1') { // -1 is key for no defined in combo list of objects
  5367. $new_array_options[$key] = '';
  5368. } elseif ($value) {
  5369. $object = new $InfoFieldList[0]($this->db);
  5370. if (is_numeric($value)) {
  5371. $res = $object->fetch($value); // Common case
  5372. } else {
  5373. $res = $object->fetch('', $value); // For compatibility
  5374. }
  5375. if ($res > 0) {
  5376. $new_array_options[$key] = $object->id;
  5377. } else {
  5378. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5379. $this->db->rollback();
  5380. return -1;
  5381. }
  5382. }
  5383. } else {
  5384. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5385. }
  5386. break;
  5387. }
  5388. }
  5389. $this->db->begin();
  5390. $table_element = $this->table_element;
  5391. if ($table_element == 'categorie') {
  5392. $table_element = 'categories'; // For compatibility
  5393. }
  5394. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  5395. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5396. $this->db->query($sql_del);
  5397. $sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object";
  5398. foreach ($new_array_options as $key => $value) {
  5399. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5400. // Add field of attribut
  5401. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
  5402. $sql .= ",".$attributeKey;
  5403. }
  5404. }
  5405. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5406. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5407. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5408. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5409. $sql .= ",".$tmpkey;
  5410. }
  5411. }
  5412. }
  5413. $sql .= ") VALUES (".$this->id;
  5414. foreach ($new_array_options as $key => $value) {
  5415. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5416. // Add field of attribute
  5417. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
  5418. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
  5419. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  5420. } else {
  5421. $sql .= ",null";
  5422. }
  5423. }
  5424. }
  5425. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5426. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5427. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5428. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5429. if (in_array($tmpval, array('int', 'double', 'price'))) {
  5430. $sql .= ", 0";
  5431. } else {
  5432. $sql .= ", ''";
  5433. }
  5434. }
  5435. }
  5436. }
  5437. $sql .= ")";
  5438. $resql = $this->db->query($sql);
  5439. if (!$resql) {
  5440. $this->error = $this->db->lasterror();
  5441. $error++;
  5442. }
  5443. if (!$error && $trigger) {
  5444. // Call trigger
  5445. $this->context = array('extrafieldaddupdate'=>1);
  5446. $result = $this->call_trigger($trigger, $userused);
  5447. if ($result < 0) {
  5448. $error++;
  5449. }
  5450. // End call trigger
  5451. }
  5452. if ($error) {
  5453. $this->db->rollback();
  5454. return -1;
  5455. } else {
  5456. $this->db->commit();
  5457. return 1;
  5458. }
  5459. } else {
  5460. return 0;
  5461. }
  5462. }
  5463. /**
  5464. * Add/Update all extra fields values for the current object.
  5465. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5466. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5467. *
  5468. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5469. * @param User $userused Object user
  5470. * @return int -1=error, O=did nothing, 1=OK
  5471. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  5472. */
  5473. public function insertExtraLanguages($trigger = '', $userused = null)
  5474. {
  5475. global $conf, $langs, $user;
  5476. if (empty($userused)) {
  5477. $userused = $user;
  5478. }
  5479. $error = 0;
  5480. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5481. return 0; // For avoid conflicts if trigger used
  5482. }
  5483. if (is_array($this->array_languages)) {
  5484. $new_array_languages = $this->array_languages;
  5485. foreach ($new_array_languages as $key => $value) {
  5486. $attributeKey = $key;
  5487. $attributeType = $this->fields[$attributeKey]['type'];
  5488. $attributeLabel = $this->fields[$attributeKey]['label'];
  5489. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5490. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5491. switch ($attributeType) {
  5492. case 'int':
  5493. if (!is_numeric($value) && $value != '') {
  5494. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5495. return -1;
  5496. } elseif ($value == '') {
  5497. $new_array_languages[$key] = null;
  5498. }
  5499. break;
  5500. case 'double':
  5501. $value = price2num($value);
  5502. if (!is_numeric($value) && $value != '') {
  5503. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5504. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5505. return -1;
  5506. } elseif ($value == '') {
  5507. $new_array_languages[$key] = null;
  5508. }
  5509. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5510. $new_array_languages[$key] = $value;
  5511. break;
  5512. /*case 'select': // Not required, we chosed value='0' for undefined values
  5513. if ($value=='-1')
  5514. {
  5515. $this->array_options[$key] = null;
  5516. }
  5517. break;*/
  5518. }
  5519. }
  5520. $this->db->begin();
  5521. $table_element = $this->table_element;
  5522. if ($table_element == 'categorie') {
  5523. $table_element = 'categories'; // For compatibility
  5524. }
  5525. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  5526. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  5527. foreach ($langcodearray as $langcode => $value) {
  5528. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX."object_lang";
  5529. $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  5530. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  5531. $this->db->query($sql_del);
  5532. if ($value !== '') {
  5533. $sql = "INSERT INTO ".MAIN_DB_PREFIX."object_lang (fk_object, property, type_object, lang, value";
  5534. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  5535. $sql .= ")";
  5536. $resql = $this->db->query($sql);
  5537. if (!$resql) {
  5538. $this->error = $this->db->lasterror();
  5539. $error++;
  5540. break;
  5541. }
  5542. }
  5543. }
  5544. }
  5545. if (!$error && $trigger) {
  5546. // Call trigger
  5547. $this->context = array('extralanguagesaddupdate'=>1);
  5548. $result = $this->call_trigger($trigger, $userused);
  5549. if ($result < 0) {
  5550. $error++;
  5551. }
  5552. // End call trigger
  5553. }
  5554. if ($error) {
  5555. $this->db->rollback();
  5556. return -1;
  5557. } else {
  5558. $this->db->commit();
  5559. return 1;
  5560. }
  5561. } else {
  5562. return 0;
  5563. }
  5564. }
  5565. /**
  5566. * Update 1 extra field value for the current object. Keep other fields unchanged.
  5567. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5568. *
  5569. * @param string $key Key of the extrafield to update (without starting 'options_')
  5570. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5571. * @param User $userused Object user
  5572. * @return int -1=error, O=did nothing, 1=OK
  5573. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  5574. */
  5575. public function updateExtraField($key, $trigger = null, $userused = null)
  5576. {
  5577. global $conf, $langs, $user;
  5578. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5579. return 0;
  5580. }
  5581. if (empty($userused)) {
  5582. $userused = $user;
  5583. }
  5584. $error = 0;
  5585. if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
  5586. // Check parameters
  5587. $langs->load('admin');
  5588. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5589. $extrafields = new ExtraFields($this->db);
  5590. $extrafields->fetch_name_optionals_label($this->table_element);
  5591. $value = $this->array_options["options_".$key];
  5592. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  5593. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  5594. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  5595. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  5596. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  5597. // Similar code than into insertExtraFields
  5598. if ($attributeRequired) {
  5599. $mandatorypb = false;
  5600. if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
  5601. $mandatorypb = true;
  5602. }
  5603. if ($this->array_options["options_".$key] === '') {
  5604. $mandatorypb = true;
  5605. }
  5606. if ($mandatorypb) {
  5607. $langs->load("errors");
  5608. dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
  5609. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5610. return -1;
  5611. }
  5612. }
  5613. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5614. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5615. if (!empty($attrfieldcomputed)) {
  5616. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5617. $value = dol_eval($attrfieldcomputed, 1, 0);
  5618. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5619. $this->array_options["options_".$key] = $value;
  5620. } else {
  5621. $this->array_options["options_".$key] = null;
  5622. }
  5623. }
  5624. switch ($attributeType) {
  5625. case 'int':
  5626. if (!is_numeric($value) && $value != '') {
  5627. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5628. return -1;
  5629. } elseif ($value === '') {
  5630. $this->array_options["options_".$key] = null;
  5631. }
  5632. break;
  5633. case 'double':
  5634. $value = price2num($value);
  5635. if (!is_numeric($value) && $value != '') {
  5636. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5637. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5638. return -1;
  5639. } elseif ($value === '') {
  5640. $this->array_options["options_".$key] = null;
  5641. }
  5642. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5643. $this->array_options["options_".$key] = $value;
  5644. break;
  5645. /*case 'select': // Not required, we chosed value='0' for undefined values
  5646. if ($value=='-1')
  5647. {
  5648. $this->array_options[$key] = null;
  5649. }
  5650. break;*/
  5651. case 'price':
  5652. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  5653. break;
  5654. case 'date':
  5655. case 'datetime':
  5656. if (empty($this->array_options["options_".$key])) {
  5657. $this->array_options["options_".$key] = null;
  5658. } else {
  5659. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5660. }
  5661. break;
  5662. case 'boolean':
  5663. if (empty($this->array_options["options_".$key])) {
  5664. $this->array_options["options_".$key] = null;
  5665. }
  5666. break;
  5667. /*
  5668. case 'link':
  5669. $param_list = array_keys($attributeParam['options']);
  5670. // 0 : ObjectName
  5671. // 1 : classPath
  5672. $InfoFieldList = explode(":", $param_list[0]);
  5673. dol_include_once($InfoFieldList[1]);
  5674. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  5675. {
  5676. if ($value == '-1') // -1 is key for no defined in combo list of objects
  5677. {
  5678. $new_array_options[$key] = '';
  5679. } elseif ($value) {
  5680. $object = new $InfoFieldList[0]($this->db);
  5681. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  5682. else $res = $object->fetch('', $value); // For compatibility
  5683. if ($res > 0) $new_array_options[$key] = $object->id;
  5684. else {
  5685. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5686. $this->db->rollback();
  5687. return -1;
  5688. }
  5689. }
  5690. } else {
  5691. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5692. }
  5693. break;
  5694. */
  5695. }
  5696. $this->db->begin();
  5697. $linealreadyfound = 0;
  5698. // 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)
  5699. $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5700. $resql = $this->db->query($sql);
  5701. if ($resql) {
  5702. $tmpobj = $this->db->fetch_object($resql);
  5703. if ($tmpobj) {
  5704. $linealreadyfound = $tmpobj->nb;
  5705. }
  5706. }
  5707. if ($linealreadyfound) {
  5708. if ($this->array_options["options_".$key] === null) {
  5709. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key." = null";
  5710. } else {
  5711. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
  5712. }
  5713. $sql .= " WHERE fk_object = ".((int) $this->id);
  5714. } else {
  5715. $result = $this->insertExtraFields('', $user);
  5716. if ($result < 0) {
  5717. $error++;
  5718. }
  5719. }
  5720. $resql = $this->db->query($sql);
  5721. if (!$resql) {
  5722. $error++;
  5723. $this->error = $this->db->lasterror();
  5724. }
  5725. if (!$error && $trigger) {
  5726. // Call trigger
  5727. $this->context = array('extrafieldupdate'=>1);
  5728. $result = $this->call_trigger($trigger, $userused);
  5729. if ($result < 0) {
  5730. $error++;
  5731. }
  5732. // End call trigger
  5733. }
  5734. if ($error) {
  5735. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  5736. $this->db->rollback();
  5737. return -1;
  5738. } else {
  5739. $this->db->commit();
  5740. return 1;
  5741. }
  5742. } else {
  5743. return 0;
  5744. }
  5745. }
  5746. /**
  5747. * Update an extra language value for the current object.
  5748. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5749. *
  5750. * @param string $key Key of the extrafield (without starting 'options_')
  5751. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5752. * @param User $userused Object user
  5753. * @return int -1=error, O=did nothing, 1=OK
  5754. * @see updateExtraFields(), insertExtraLanguages()
  5755. */
  5756. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  5757. {
  5758. global $conf, $langs, $user;
  5759. if (empty($userused)) {
  5760. $userused = $user;
  5761. }
  5762. $error = 0;
  5763. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5764. return 0; // For avoid conflicts if trigger used
  5765. }
  5766. return 0;
  5767. }
  5768. /**
  5769. * Return HTML string to put an input field into a page
  5770. * Code very similar with showInputField of extra fields
  5771. *
  5772. * @param array $val Array of properties for field to show (used only if ->fields not defined)
  5773. * @param string $key Key of attribute
  5774. * @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)
  5775. * @param string $moreparam To add more parameters on html input tag
  5776. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5777. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5778. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  5779. * @param int $nonewbutton Force to not show the new button on field that are links to object
  5780. * @return string
  5781. */
  5782. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  5783. {
  5784. global $conf, $langs, $form;
  5785. if (!is_object($form)) {
  5786. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  5787. $form = new Form($this->db);
  5788. }
  5789. if (!empty($this->fields)) {
  5790. $val = $this->fields[$key];
  5791. }
  5792. // Validation tests and output
  5793. $fieldValidationErrorMsg = '';
  5794. $validationClass = '';
  5795. $fieldValidationErrorMsg = $this->getFieldError($key);
  5796. if (!empty($fieldValidationErrorMsg)) {
  5797. $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
  5798. } else {
  5799. $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
  5800. }
  5801. $out = '';
  5802. $type = '';
  5803. $isDependList = 0;
  5804. $param = array();
  5805. $param['options'] = array();
  5806. $reg = array();
  5807. $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
  5808. // Because we work on extrafields
  5809. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5810. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5811. $type = 'link';
  5812. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5813. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5814. $type = 'link';
  5815. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  5816. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5817. $type = 'link';
  5818. } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5819. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5820. $type = 'sellist';
  5821. } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5822. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5823. $type = 'sellist';
  5824. } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
  5825. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5826. $type = 'sellist';
  5827. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  5828. $param['options'] = array();
  5829. $type = 'varchar';
  5830. $size = $reg[1];
  5831. } elseif (preg_match('/varchar/', $val['type'])) {
  5832. $param['options'] = array();
  5833. $type = 'varchar';
  5834. } else {
  5835. $param['options'] = array();
  5836. $type = $this->fields[$key]['type'];
  5837. }
  5838. // Special case that force options and type ($type can be integer, varchar, ...)
  5839. if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
  5840. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  5841. $type = 'select';
  5842. }
  5843. $label = $this->fields[$key]['label'];
  5844. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  5845. $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
  5846. $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
  5847. $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
  5848. $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
  5849. $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
  5850. $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
  5851. $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
  5852. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  5853. $objectid = $this->id;
  5854. if ($computed) {
  5855. if (!preg_match('/^search_/', $keyprefix)) {
  5856. return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  5857. } else {
  5858. return '';
  5859. }
  5860. }
  5861. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  5862. if (empty($morecss) && !empty($val['css'])) {
  5863. $morecss = $val['css'];
  5864. } elseif (empty($morecss)) {
  5865. if ($type == 'date') {
  5866. $morecss = 'minwidth100imp';
  5867. } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
  5868. $morecss = 'minwidth200imp';
  5869. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  5870. $morecss = 'maxwidth75';
  5871. } elseif ($type == 'url') {
  5872. $morecss = 'minwidth400';
  5873. } elseif ($type == 'boolean') {
  5874. $morecss = '';
  5875. } else {
  5876. if (round($size) < 12) {
  5877. $morecss = 'minwidth100';
  5878. } elseif (round($size) <= 48) {
  5879. $morecss = 'minwidth200';
  5880. } else {
  5881. $morecss = 'minwidth400';
  5882. }
  5883. }
  5884. }
  5885. // Add validation state class
  5886. if (!empty($validationClass)) {
  5887. $morecss.= ' '.$validationClass;
  5888. }
  5889. if (in_array($type, array('date'))) {
  5890. $tmp = explode(',', $size);
  5891. $newsize = $tmp[0];
  5892. $showtime = 0;
  5893. // Do not show current date when field not required (see selectDate() method)
  5894. if (!$required && $value == '') {
  5895. $value = '-1';
  5896. }
  5897. // TODO Must also support $moreparam
  5898. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  5899. } elseif (in_array($type, array('datetime'))) {
  5900. $tmp = explode(',', $size);
  5901. $newsize = $tmp[0];
  5902. $showtime = 1;
  5903. // Do not show current date when field not required (see selectDate() method)
  5904. if (!$required && $value == '') $value = '-1';
  5905. // TODO Must also support $moreparam
  5906. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
  5907. } elseif (in_array($type, array('duration'))) {
  5908. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  5909. } elseif (in_array($type, array('int', 'integer'))) {
  5910. $tmp = explode(',', $size);
  5911. $newsize = $tmp[0];
  5912. $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' : '').'>';
  5913. } elseif (in_array($type, array('real'))) {
  5914. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5915. } elseif (preg_match('/varchar/', $type)) {
  5916. $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' : '').'>';
  5917. } elseif (in_array($type, array('mail', 'phone', 'url'))) {
  5918. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5919. } elseif (preg_match('/^text/', $type)) {
  5920. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  5921. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5922. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  5923. $out = $doleditor->Create(1);
  5924. } else {
  5925. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5926. }
  5927. } elseif (preg_match('/^html/', $type)) {
  5928. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  5929. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5930. $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%');
  5931. $out = $doleditor->Create(1);
  5932. } else {
  5933. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5934. }
  5935. } elseif ($type == 'boolean') {
  5936. $checked = '';
  5937. if (!empty($value)) {
  5938. $checked = ' checked value="1" ';
  5939. } else {
  5940. $checked = ' value="1" ';
  5941. }
  5942. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  5943. } elseif ($type == 'price') {
  5944. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5945. $value = price($value);
  5946. }
  5947. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  5948. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  5949. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5950. $value = price($value);
  5951. }
  5952. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  5953. } elseif ($type == 'select') {
  5954. $out = '';
  5955. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  5956. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5957. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  5958. }
  5959. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  5960. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
  5961. $out .= '<option value="0">&nbsp;</option>';
  5962. }
  5963. foreach ($param['options'] as $key => $val) {
  5964. if ((string) $key == '') {
  5965. continue;
  5966. }
  5967. list($val, $parent) = explode('|', $val);
  5968. $out .= '<option value="'.$key.'"';
  5969. $out .= (((string) $value == (string) $key) ? ' selected' : '');
  5970. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  5971. $out .= '>'.$val.'</option>';
  5972. }
  5973. $out .= '</select>';
  5974. } elseif ($type == 'sellist') {
  5975. $out = '';
  5976. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  5977. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5978. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  5979. }
  5980. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  5981. if (is_array($param['options'])) {
  5982. $param_list = array_keys($param['options']);
  5983. $InfoFieldList = explode(":", $param_list[0]);
  5984. $parentName = '';
  5985. $parentField = '';
  5986. // 0 : tableName
  5987. // 1 : label field name
  5988. // 2 : key fields name (if differ of rowid)
  5989. // 3 : key field parent (for dependent lists)
  5990. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  5991. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  5992. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  5993. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  5994. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  5995. } else {
  5996. $keyList = $InfoFieldList[2].' as rowid';
  5997. }
  5998. }
  5999. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6000. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6001. $keyList .= ', '.$parentField;
  6002. }
  6003. $fields_label = explode('|', $InfoFieldList[1]);
  6004. if (is_array($fields_label)) {
  6005. $keyList .= ', ';
  6006. $keyList .= implode(', ', $fields_label);
  6007. }
  6008. $sqlwhere = '';
  6009. $sql = "SELECT ".$keyList;
  6010. $sql .= " FROM ".MAIN_DB_PREFIX.$InfoFieldList[0];
  6011. if (!empty($InfoFieldList[4])) {
  6012. // can use SELECT request
  6013. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6014. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6015. }
  6016. // current object id can be use into filter
  6017. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6018. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6019. } else {
  6020. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6021. }
  6022. //We have to join on extrafield table
  6023. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6024. $sql .= " as main, ".MAIN_DB_PREFIX.$InfoFieldList[0]."_extrafields as extra";
  6025. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  6026. } else {
  6027. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  6028. }
  6029. } else {
  6030. $sqlwhere .= ' WHERE 1=1';
  6031. }
  6032. // Some tables may have field, some other not. For the moment we disable it.
  6033. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6034. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  6035. }
  6036. $sql .= $sqlwhere;
  6037. //print $sql;
  6038. $sql .= ' ORDER BY '.implode(', ', $fields_label);
  6039. dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
  6040. $resql = $this->db->query($sql);
  6041. if ($resql) {
  6042. $out .= '<option value="0">&nbsp;</option>';
  6043. $num = $this->db->num_rows($resql);
  6044. $i = 0;
  6045. while ($i < $num) {
  6046. $labeltoshow = '';
  6047. $obj = $this->db->fetch_object($resql);
  6048. // Several field into label (eq table:code|libelle:rowid)
  6049. $notrans = false;
  6050. $fields_label = explode('|', $InfoFieldList[1]);
  6051. if (count($fields_label) > 1) {
  6052. $notrans = true;
  6053. foreach ($fields_label as $field_toshow) {
  6054. $labeltoshow .= $obj->$field_toshow.' ';
  6055. }
  6056. } else {
  6057. $labeltoshow = $obj->{$InfoFieldList[1]};
  6058. }
  6059. $labeltoshow = dol_trunc($labeltoshow, 45);
  6060. if ($value == $obj->rowid) {
  6061. foreach ($fields_label as $field_toshow) {
  6062. $translabel = $langs->trans($obj->$field_toshow);
  6063. if ($translabel != $obj->$field_toshow) {
  6064. $labeltoshow = dol_trunc($translabel).' ';
  6065. } else {
  6066. $labeltoshow = dol_trunc($obj->$field_toshow).' ';
  6067. }
  6068. }
  6069. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6070. } else {
  6071. if (!$notrans) {
  6072. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6073. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6074. $labeltoshow = dol_trunc($translabel, 18);
  6075. } else {
  6076. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
  6077. }
  6078. }
  6079. if (empty($labeltoshow)) {
  6080. $labeltoshow = '(not defined)';
  6081. }
  6082. if ($value == $obj->rowid) {
  6083. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6084. }
  6085. if (!empty($InfoFieldList[3]) && $parentField) {
  6086. $parent = $parentName.':'.$obj->{$parentField};
  6087. $isDependList = 1;
  6088. }
  6089. $out .= '<option value="'.$obj->rowid.'"';
  6090. $out .= ($value == $obj->rowid ? ' selected' : '');
  6091. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6092. $out .= '>'.$labeltoshow.'</option>';
  6093. }
  6094. $i++;
  6095. }
  6096. $this->db->free($resql);
  6097. } else {
  6098. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6099. }
  6100. }
  6101. $out .= '</select>';
  6102. } elseif ($type == 'checkbox') {
  6103. $value_arr = explode(',', $value);
  6104. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
  6105. } elseif ($type == 'radio') {
  6106. $out = '';
  6107. foreach ($param['options'] as $keyopt => $val) {
  6108. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  6109. $out .= ' value="'.$keyopt.'"';
  6110. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  6111. $out .= ($value == $keyopt ? 'checked' : '');
  6112. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
  6113. }
  6114. } elseif ($type == 'chkbxlst') {
  6115. if (is_array($value)) {
  6116. $value_arr = $value;
  6117. } else {
  6118. $value_arr = explode(',', $value);
  6119. }
  6120. if (is_array($param['options'])) {
  6121. $param_list = array_keys($param['options']);
  6122. $InfoFieldList = explode(":", $param_list[0]);
  6123. $parentName = '';
  6124. $parentField = '';
  6125. // 0 : tableName
  6126. // 1 : label field name
  6127. // 2 : key fields name (if differ of rowid)
  6128. // 3 : key field parent (for dependent lists)
  6129. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6130. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6131. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6132. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6133. $keyList .= ', '.$parentField;
  6134. }
  6135. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6136. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6137. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6138. } else {
  6139. $keyList = $InfoFieldList[2].' as rowid';
  6140. }
  6141. }
  6142. $fields_label = explode('|', $InfoFieldList[1]);
  6143. if (is_array($fields_label)) {
  6144. $keyList .= ', ';
  6145. $keyList .= implode(', ', $fields_label);
  6146. }
  6147. $sqlwhere = '';
  6148. $sql = "SELECT ".$keyList;
  6149. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6150. if (!empty($InfoFieldList[4])) {
  6151. // can use SELECT request
  6152. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6153. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6154. }
  6155. // current object id can be use into filter
  6156. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6157. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6158. } else {
  6159. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6160. }
  6161. // We have to join on extrafield table
  6162. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6163. $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
  6164. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  6165. } else {
  6166. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  6167. }
  6168. } else {
  6169. $sqlwhere .= ' WHERE 1=1';
  6170. }
  6171. // Some tables may have field, some other not. For the moment we disable it.
  6172. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6173. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  6174. }
  6175. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  6176. // print $sql;
  6177. $sql .= $sqlwhere;
  6178. dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
  6179. $resql = $this->db->query($sql);
  6180. if ($resql) {
  6181. $num = $this->db->num_rows($resql);
  6182. $i = 0;
  6183. $data = array();
  6184. while ($i < $num) {
  6185. $labeltoshow = '';
  6186. $obj = $this->db->fetch_object($resql);
  6187. $notrans = false;
  6188. // Several field into label (eq table:code|libelle:rowid)
  6189. $fields_label = explode('|', $InfoFieldList[1]);
  6190. if (count($fields_label) > 1) {
  6191. $notrans = true;
  6192. foreach ($fields_label as $field_toshow) {
  6193. $labeltoshow .= $obj->$field_toshow.' ';
  6194. }
  6195. } else {
  6196. $labeltoshow = $obj->{$InfoFieldList[1]};
  6197. }
  6198. $labeltoshow = dol_trunc($labeltoshow, 45);
  6199. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6200. foreach ($fields_label as $field_toshow) {
  6201. $translabel = $langs->trans($obj->$field_toshow);
  6202. if ($translabel != $obj->$field_toshow) {
  6203. $labeltoshow = dol_trunc($translabel, 18).' ';
  6204. } else {
  6205. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  6206. }
  6207. }
  6208. $data[$obj->rowid] = $labeltoshow;
  6209. } else {
  6210. if (!$notrans) {
  6211. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6212. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6213. $labeltoshow = dol_trunc($translabel, 18);
  6214. } else {
  6215. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  6216. }
  6217. }
  6218. if (empty($labeltoshow)) {
  6219. $labeltoshow = '(not defined)';
  6220. }
  6221. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6222. $data[$obj->rowid] = $labeltoshow;
  6223. }
  6224. if (!empty($InfoFieldList[3]) && $parentField) {
  6225. $parent = $parentName.':'.$obj->{$parentField};
  6226. $isDependList = 1;
  6227. }
  6228. $data[$obj->rowid] = $labeltoshow;
  6229. }
  6230. $i++;
  6231. }
  6232. $this->db->free($resql);
  6233. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
  6234. } else {
  6235. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6236. }
  6237. }
  6238. } elseif ($type == 'link') {
  6239. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
  6240. $param_list_array = explode(':', $param_list[0]);
  6241. $showempty = (($required && $default != '') ? 0 : 1);
  6242. if (!preg_match('/search_/', $keyprefix)) {
  6243. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6244. if (!empty($this->fields[$key]['picto'])) {
  6245. $morecss .= ' widthcentpercentminusxx';
  6246. } else {
  6247. $morecss .= ' widthcentpercentminusx';
  6248. }
  6249. } else {
  6250. if (!empty($this->fields[$key]['picto'])) {
  6251. $morecss .= ' widthcentpercentminusx';
  6252. }
  6253. }
  6254. }
  6255. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  6256. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6257. 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".
  6258. list($class, $classfile) = explode(':', $param_list[0]);
  6259. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
  6260. $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  6261. } else {
  6262. $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  6263. }
  6264. $paramforthenewlink = '';
  6265. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  6266. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  6267. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  6268. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  6269. $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>';
  6270. }
  6271. }
  6272. } elseif ($type == 'password') {
  6273. // If prefix is 'search_', field is used as a filter, we use a common text field.
  6274. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  6275. } elseif ($type == 'array') {
  6276. $newval = $val;
  6277. $newval['type'] = 'varchar(256)';
  6278. $out = '';
  6279. if (!empty($value)) {
  6280. foreach ($value as $option) {
  6281. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6282. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  6283. }
  6284. }
  6285. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6286. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6287. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  6288. if (!empty($conf->use_javascript_ajax)) {
  6289. $out .= '
  6290. <script>
  6291. $(document).ready(function() {
  6292. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  6293. $("'.dol_escape_js($newInput).'").insertBefore(this);
  6294. });
  6295. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  6296. $(this).parent().remove();
  6297. });
  6298. });
  6299. </script>';
  6300. }
  6301. }
  6302. if (!empty($hidden)) {
  6303. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  6304. }
  6305. if ($isDependList==1) {
  6306. $out .= $this->getJSListDependancies('_common');
  6307. }
  6308. /* Add comments
  6309. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  6310. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  6311. */
  6312. // Display error message for field
  6313. if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
  6314. $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
  6315. }
  6316. return $out;
  6317. }
  6318. /**
  6319. * Return HTML string to show a field into a page
  6320. * Code very similar with showOutputField of extra fields
  6321. *
  6322. * @param array $val Array of properties of field to show
  6323. * @param string $key Key of attribute
  6324. * @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)
  6325. * @param string $moreparam To add more parametes on html input tag
  6326. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6327. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6328. * @param mixed $morecss Value for css to define size. May also be a numeric.
  6329. * @return string
  6330. */
  6331. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  6332. {
  6333. global $conf, $langs, $form;
  6334. if (!is_object($form)) {
  6335. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6336. $form = new Form($this->db);
  6337. }
  6338. $objectid = $this->id; // Not used ???
  6339. $label = empty($val['label']) ? '' : $val['label'];
  6340. $type = empty($val['type']) ? '' : $val['type'];
  6341. $size = empty($val['css']) ? '' : $val['css'];
  6342. $reg = array();
  6343. // Convert var to be able to share same code than showOutputField of extrafields
  6344. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6345. $type = 'varchar'; // convert varchar(xx) int varchar
  6346. $size = $reg[1];
  6347. } elseif (preg_match('/varchar/', $type)) {
  6348. $type = 'varchar'; // convert varchar(xx) int varchar
  6349. }
  6350. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6351. $type = 'select';
  6352. }
  6353. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6354. $type = 'link';
  6355. }
  6356. $default = empty($val['default']) ? '' : $val['default'];
  6357. $computed = empty($val['computed']) ? '' : $val['computed'];
  6358. $unique = empty($val['unique']) ? '' : $val['unique'];
  6359. $required = empty($val['required']) ? '' : $val['required'];
  6360. $param = array();
  6361. $param['options'] = array();
  6362. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6363. $param['options'] = $val['arrayofkeyval'];
  6364. }
  6365. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6366. $type = 'link';
  6367. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6368. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6369. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6370. $type = 'sellist';
  6371. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6372. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6373. $type = 'sellist';
  6374. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6375. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6376. $type = 'sellist';
  6377. }
  6378. $langfile = empty($val['langfile']) ? '' : $val['langfile'];
  6379. $list = (empty($val['list']) ? '' : $val['list']);
  6380. $help = (empty($val['help']) ? '' : $val['help']);
  6381. $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)
  6382. if ($hidden) {
  6383. return '';
  6384. }
  6385. // If field is a computed field, value must become result of compute
  6386. if ($computed) {
  6387. // Make the eval of compute string
  6388. //var_dump($computed);
  6389. $value = dol_eval($computed, 1, 0);
  6390. }
  6391. if (empty($morecss)) {
  6392. if ($type == 'date') {
  6393. $morecss = 'minwidth100imp';
  6394. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6395. $morecss = 'minwidth200imp';
  6396. } elseif (in_array($type, array('int', 'double', 'price'))) {
  6397. $morecss = 'maxwidth75';
  6398. } elseif ($type == 'url') {
  6399. $morecss = 'minwidth400';
  6400. } elseif ($type == 'boolean') {
  6401. $morecss = '';
  6402. } else {
  6403. if (is_numeric($size) && round($size) < 12) {
  6404. $morecss = 'minwidth100';
  6405. } elseif (is_numeric($size) && round($size) <= 48) {
  6406. $morecss = 'minwidth200';
  6407. } else {
  6408. $morecss = 'minwidth400';
  6409. }
  6410. }
  6411. }
  6412. // Format output value differently according to properties of field
  6413. if ($key == 'ref' && method_exists($this, 'getNomUrl')) {
  6414. $value = $this->getNomUrl(1, '', 0, '', 1);
  6415. } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
  6416. $value = $this->getLibStatut(3);
  6417. } elseif ($type == 'date') {
  6418. if (!empty($value)) {
  6419. $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
  6420. } else {
  6421. $value = '';
  6422. }
  6423. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6424. if (!empty($value)) {
  6425. $value = dol_print_date($value, 'dayhour', 'tzuserrel');
  6426. } else {
  6427. $value = '';
  6428. }
  6429. } elseif ($type == 'duration') {
  6430. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6431. if (!is_null($value) && $value !== '') {
  6432. $value = convertSecondToTime($value, 'allhourmin');
  6433. }
  6434. } elseif ($type == 'double' || $type == 'real') {
  6435. if (!is_null($value) && $value !== '') {
  6436. $value = price($value);
  6437. }
  6438. } elseif ($type == 'boolean') {
  6439. $checked = '';
  6440. if (!empty($value)) {
  6441. $checked = ' checked ';
  6442. }
  6443. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  6444. } elseif ($type == 'mail') {
  6445. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  6446. } elseif ($type == 'url') {
  6447. $value = dol_print_url($value, '_blank', 32, 1);
  6448. } elseif ($type == 'phone') {
  6449. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
  6450. } elseif ($type == 'price') {
  6451. if (!is_null($value) && $value !== '') {
  6452. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  6453. }
  6454. } elseif ($type == 'select') {
  6455. $value = $param['options'][$value];
  6456. } elseif ($type == 'sellist') {
  6457. $param_list = array_keys($param['options']);
  6458. $InfoFieldList = explode(":", $param_list[0]);
  6459. $selectkey = "rowid";
  6460. $keyList = 'rowid';
  6461. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6462. $selectkey = $InfoFieldList[2];
  6463. $keyList = $InfoFieldList[2].' as rowid';
  6464. }
  6465. $fields_label = explode('|', $InfoFieldList[1]);
  6466. if (is_array($fields_label)) {
  6467. $keyList .= ', ';
  6468. $keyList .= implode(', ', $fields_label);
  6469. }
  6470. $sql = "SELECT ".$keyList;
  6471. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6472. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6473. $sql .= ' as main';
  6474. }
  6475. if ($selectkey == 'rowid' && empty($value)) {
  6476. $sql .= " WHERE ".$selectkey." = 0";
  6477. } elseif ($selectkey == 'rowid') {
  6478. $sql .= " WHERE ".$selectkey." = ".((int) $value);
  6479. } else {
  6480. $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
  6481. }
  6482. //$sql.= ' AND entity = '.$conf->entity;
  6483. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  6484. $resql = $this->db->query($sql);
  6485. if ($resql) {
  6486. $value = ''; // value was used, so now we reste it to use it to build final output
  6487. $obj = $this->db->fetch_object($resql);
  6488. // Several field into label (eq table:code|libelle:rowid)
  6489. $fields_label = explode('|', $InfoFieldList[1]);
  6490. if (is_array($fields_label) && count($fields_label) > 1) {
  6491. foreach ($fields_label as $field_toshow) {
  6492. $translabel = '';
  6493. if (!empty($obj->$field_toshow)) {
  6494. $translabel = $langs->trans($obj->$field_toshow);
  6495. }
  6496. if ($translabel != $field_toshow) {
  6497. $value .= dol_trunc($translabel, 18).' ';
  6498. } else {
  6499. $value .= $obj->$field_toshow.' ';
  6500. }
  6501. }
  6502. } else {
  6503. $translabel = '';
  6504. if (!empty($obj->{$InfoFieldList[1]})) {
  6505. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6506. }
  6507. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6508. $value = dol_trunc($translabel, 18);
  6509. } else {
  6510. $value = $obj->{$InfoFieldList[1]};
  6511. }
  6512. }
  6513. } else {
  6514. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6515. }
  6516. } elseif ($type == 'radio') {
  6517. $value = $param['options'][$value];
  6518. } elseif ($type == 'checkbox') {
  6519. $value_arr = explode(',', $value);
  6520. $value = '';
  6521. if (is_array($value_arr) && count($value_arr) > 0) {
  6522. $toprint = array();
  6523. foreach ($value_arr as $keyval => $valueval) {
  6524. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  6525. }
  6526. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6527. }
  6528. } elseif ($type == 'chkbxlst') {
  6529. $value_arr = explode(',', $value);
  6530. $param_list = array_keys($param['options']);
  6531. $InfoFieldList = explode(":", $param_list[0]);
  6532. $selectkey = "rowid";
  6533. $keyList = 'rowid';
  6534. if (count($InfoFieldList) >= 3) {
  6535. $selectkey = $InfoFieldList[2];
  6536. $keyList = $InfoFieldList[2].' as rowid';
  6537. }
  6538. $fields_label = explode('|', $InfoFieldList[1]);
  6539. if (is_array($fields_label)) {
  6540. $keyList .= ', ';
  6541. $keyList .= implode(', ', $fields_label);
  6542. }
  6543. $sql = "SELECT ".$keyList;
  6544. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6545. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6546. $sql .= ' as main';
  6547. }
  6548. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  6549. // $sql.= ' AND entity = '.$conf->entity;
  6550. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  6551. $resql = $this->db->query($sql);
  6552. if ($resql) {
  6553. $value = ''; // value was used, so now we reste it to use it to build final output
  6554. $toprint = array();
  6555. while ($obj = $this->db->fetch_object($resql)) {
  6556. // Several field into label (eq table:code|libelle:rowid)
  6557. $fields_label = explode('|', $InfoFieldList[1]);
  6558. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6559. if (is_array($fields_label) && count($fields_label) > 1) {
  6560. foreach ($fields_label as $field_toshow) {
  6561. $translabel = '';
  6562. if (!empty($obj->$field_toshow)) {
  6563. $translabel = $langs->trans($obj->$field_toshow);
  6564. }
  6565. if ($translabel != $field_toshow) {
  6566. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6567. } else {
  6568. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->$field_toshow.'</li>';
  6569. }
  6570. }
  6571. } else {
  6572. $translabel = '';
  6573. if (!empty($obj->{$InfoFieldList[1]})) {
  6574. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6575. }
  6576. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6577. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6578. } else {
  6579. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->{$InfoFieldList[1]}.'</li>';
  6580. }
  6581. }
  6582. }
  6583. }
  6584. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6585. } else {
  6586. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6587. }
  6588. } elseif ($type == 'link') {
  6589. $out = '';
  6590. // only if something to display (perf)
  6591. if ($value) {
  6592. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6593. $InfoFieldList = explode(":", $param_list[0]);
  6594. $classname = $InfoFieldList[0];
  6595. $classpath = $InfoFieldList[1];
  6596. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  6597. $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
  6598. if (!empty($classpath)) {
  6599. dol_include_once($InfoFieldList[1]);
  6600. if ($classname && class_exists($classname)) {
  6601. $object = new $classname($this->db);
  6602. if ($object->element === 'product') { // Special cas for product because default valut of fetch are wrong
  6603. $object->fetch($value, '', '', '', 0, 1, 1);
  6604. } else {
  6605. $object->fetch($value);
  6606. }
  6607. $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
  6608. }
  6609. } else {
  6610. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  6611. return 'Error bad setup of extrafield';
  6612. }
  6613. } else {
  6614. $value = '';
  6615. }
  6616. } elseif (preg_match('/^(text|html)/', $type)) {
  6617. $value = dol_htmlentitiesbr($value);
  6618. } elseif ($type == 'password') {
  6619. $value = preg_replace('/./i', '*', $value);
  6620. } elseif ($type == 'array') {
  6621. $value = implode('<br>', $value);
  6622. }
  6623. //print $type.'-'.$size.'-'.$value;
  6624. $out = $value;
  6625. return $out;
  6626. }
  6627. /**
  6628. * clear validation message result for a field
  6629. *
  6630. * @param string $fieldKey Key of attribute to clear
  6631. * @return null
  6632. */
  6633. public function clearFieldError($fieldKey)
  6634. {
  6635. $this->error = '';
  6636. unset($this->validateFieldsErrors[$fieldKey]);
  6637. }
  6638. /**
  6639. * set validation error message a field
  6640. *
  6641. * @param string $fieldKey Key of attribute
  6642. * @param string $msg the field error message
  6643. * @return null
  6644. */
  6645. public function setFieldError($fieldKey, $msg = '')
  6646. {
  6647. global $langs;
  6648. if (empty($msg)) { $msg = $langs->trans("UnknowError"); }
  6649. $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
  6650. }
  6651. /**
  6652. * get field error message
  6653. *
  6654. * @param string $fieldKey Key of attribute
  6655. * @return string
  6656. */
  6657. public function getFieldError($fieldKey)
  6658. {
  6659. if (!empty($this->validateFieldsErrors[$fieldKey])) {
  6660. return $this->validateFieldsErrors[$fieldKey];
  6661. }
  6662. return '';
  6663. }
  6664. /**
  6665. * Return validation test result for a field
  6666. *
  6667. * @param array $val Array of properties of field to show
  6668. * @param string $fieldKey Key of attribute
  6669. * @param string $fieldValue value of attribute
  6670. * @return bool return false if fail true on success, see $this->error for error message
  6671. */
  6672. public function validateField($val, $fieldKey, $fieldValue)
  6673. {
  6674. global $langs;
  6675. if (!class_exists('Validate')) { require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php'; }
  6676. $this->clearFieldError($fieldKey);
  6677. if (!isset($val[$fieldKey])) {
  6678. $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
  6679. return false;
  6680. }
  6681. $param = array();
  6682. $param['options'] = array();
  6683. $type = $val[$fieldKey]['type'];
  6684. $required = false;
  6685. if (isset($val[$fieldKey]['notnull']) && $val[$fieldKey]['notnull'] === 1) {
  6686. // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  6687. $required = true;
  6688. }
  6689. $maxSize = 0;
  6690. $minSize = 0;
  6691. //
  6692. // PREPARE Elements
  6693. //
  6694. // Convert var to be able to share same code than showOutputField of extrafields
  6695. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6696. $type = 'varchar'; // convert varchar(xx) int varchar
  6697. $maxSize = $reg[1];
  6698. } elseif (preg_match('/varchar/', $type)) {
  6699. $type = 'varchar'; // convert varchar(xx) int varchar
  6700. }
  6701. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6702. $type = 'select';
  6703. }
  6704. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6705. $type = 'link';
  6706. }
  6707. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6708. $param['options'] = $val['arrayofkeyval'];
  6709. }
  6710. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6711. $type = 'link';
  6712. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6713. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6714. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6715. $type = 'sellist';
  6716. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6717. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6718. $type = 'sellist';
  6719. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6720. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6721. $type = 'sellist';
  6722. }
  6723. //
  6724. // TEST Value
  6725. //
  6726. // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
  6727. $validate = new Validate($this->db, $langs);
  6728. // little trick : to perform tests with good performances sort tests by quick to low
  6729. //
  6730. // COMMON TESTS
  6731. //
  6732. // Required test and empty value
  6733. if ($required && !$validate->isNotEmptyString($fieldValue)) {
  6734. $this->setFieldError($fieldKey, $validate->error);
  6735. return false;
  6736. } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
  6737. // if no value sent and the field is not mandatory, no need to perform tests
  6738. return true;
  6739. }
  6740. // MAX Size test
  6741. if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
  6742. $this->setFieldError($fieldKey, $validate->error);
  6743. return false;
  6744. }
  6745. // MIN Size test
  6746. if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
  6747. $this->setFieldError($fieldKey, $validate->error);
  6748. return false;
  6749. }
  6750. //
  6751. // TESTS for TYPE
  6752. //
  6753. if (in_array($type, array('date', 'datetime', 'timestamp'))) {
  6754. if (!$validate->isTimestamp($fieldValue)) {
  6755. $this->setFieldError($fieldKey, $validate->error);
  6756. return false;
  6757. } else { return true; }
  6758. } elseif ($type == 'duration') {
  6759. if (!$validate->isDuration($fieldValue)) {
  6760. $this->setFieldError($fieldKey, $validate->error);
  6761. return false;
  6762. } else { return true; }
  6763. } elseif (in_array($type, array('double', 'real', 'price'))) {
  6764. // is numeric
  6765. if (!$validate->isDuration($fieldValue)) {
  6766. $this->setFieldError($fieldKey, $validate->error);
  6767. return false;
  6768. } else { return true; }
  6769. } elseif ($type == 'boolean') {
  6770. if (!$validate->isBool($fieldValue)) {
  6771. $this->setFieldError($fieldKey, $validate->error);
  6772. return false;
  6773. } else { return true; }
  6774. } elseif ($type == 'mail') {
  6775. if (!$validate->isEmail($fieldValue)) {
  6776. $this->setFieldError($fieldKey, $validate->error);
  6777. return false;
  6778. }
  6779. } elseif ($type == 'url') {
  6780. if (!$validate->isUrl($fieldValue)) {
  6781. $this->setFieldError($fieldKey, $validate->error);
  6782. return false;
  6783. } else { return true; }
  6784. } elseif ($type == 'phone') {
  6785. if (!$validate->isPhone($fieldValue)) {
  6786. $this->setFieldError($fieldKey, $validate->error);
  6787. return false;
  6788. } else { return true; }
  6789. } elseif ($type == 'select' || $type == 'radio') {
  6790. if (!isset($param['options'][$fieldValue])) {
  6791. $this->error = $langs->trans('RequireValidValue');
  6792. return false;
  6793. } else { return true; }
  6794. } elseif ($type == 'sellist' || $type == 'chkbxlst') {
  6795. $param_list = array_keys($param['options']);
  6796. $InfoFieldList = explode(":", $param_list[0]);
  6797. $value_arr = explode(',', $fieldValue);
  6798. $value_arr = array_map(array($this->db, 'escape'), $value_arr);
  6799. $selectkey = "rowid";
  6800. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6801. $selectkey = $InfoFieldList[2];
  6802. }
  6803. if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
  6804. $this->setFieldError($fieldKey, $validate->error);
  6805. return false;
  6806. } else { return true; }
  6807. } elseif ($type == 'link') {
  6808. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6809. $InfoFieldList = explode(":", $param_list[0]);
  6810. $classname = $InfoFieldList[0];
  6811. $classpath = $InfoFieldList[1];
  6812. if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
  6813. $this->setFieldError($fieldKey, $validate->error);
  6814. return false;
  6815. } else { return true; }
  6816. }
  6817. // if no test failled all is ok
  6818. return true;
  6819. }
  6820. /**
  6821. * Function to show lines of extrafields with output datas.
  6822. * 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
  6823. *
  6824. * @param Extrafields $extrafields Extrafield Object
  6825. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  6826. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  6827. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  6828. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  6829. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  6830. * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...)
  6831. * @return string
  6832. */
  6833. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
  6834. {
  6835. global $db, $conf, $langs, $action, $form, $hookmanager;
  6836. if (!is_object($form)) {
  6837. $form = new Form($db);
  6838. }
  6839. $out = '';
  6840. $parameters = array();
  6841. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  6842. if (empty($reshook)) {
  6843. 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) {
  6844. $out .= "\n";
  6845. $out .= '<!-- showOptionals --> ';
  6846. $out .= "\n";
  6847. $extrafields_collapse_num = '';
  6848. $e = 0;
  6849. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
  6850. // Show only the key field in params
  6851. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
  6852. continue;
  6853. }
  6854. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  6855. $enabled = 1;
  6856. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  6857. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1);
  6858. }
  6859. if (empty($enabled)) {
  6860. continue;
  6861. }
  6862. $visibility = 1;
  6863. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  6864. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1);
  6865. }
  6866. $perms = 1;
  6867. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  6868. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1);
  6869. }
  6870. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
  6871. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  6872. } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
  6873. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  6874. } elseif ($mode == 'view' && empty($visibility)) {
  6875. continue;
  6876. }
  6877. if (empty($perms)) {
  6878. continue;
  6879. }
  6880. // Load language if required
  6881. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  6882. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  6883. }
  6884. $colspan = 0;
  6885. if (is_array($params) && count($params) > 0 && $display_type=='card') {
  6886. if (array_key_exists('cols', $params)) {
  6887. $colspan = $params['cols'];
  6888. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  6889. $reg = array();
  6890. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  6891. $colspan = $reg[1];
  6892. } else {
  6893. $colspan = $params['colspan'];
  6894. }
  6895. }
  6896. }
  6897. $colspan = intval($colspan);
  6898. switch ($mode) {
  6899. case "view":
  6900. $value = $this->array_options["options_".$key.$keysuffix]; // Value may be clean or formated later
  6901. break;
  6902. case "create":
  6903. case "edit":
  6904. // We get the value of property found with GETPOST so it takes into account:
  6905. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  6906. $check = 'alphanohtml';
  6907. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  6908. $check = 'restricthtml';
  6909. }
  6910. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  6911. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  6912. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
  6913. if (is_array($getposttemp)) {
  6914. // $getposttemp is an array but following code expects a comma separated string
  6915. $value = implode(",", $getposttemp);
  6916. } else {
  6917. $value = $getposttemp;
  6918. }
  6919. } else {
  6920. $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.
  6921. }
  6922. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  6923. break;
  6924. }
  6925. // Output value of the current field
  6926. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  6927. $extrafields_collapse_num = '';
  6928. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  6929. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  6930. $extrafield_param_list = array_keys($extrafield_param['options']);
  6931. if (count($extrafield_param_list) > 0) {
  6932. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  6933. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  6934. $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  6935. }
  6936. }
  6937. }
  6938. // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
  6939. $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type);
  6940. } else {
  6941. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  6942. $csstyle = '';
  6943. if (is_array($params) && count($params) > 0) {
  6944. if (array_key_exists('class', $params)) {
  6945. $class .= $params['class'].' ';
  6946. }
  6947. if (array_key_exists('style', $params)) {
  6948. $csstyle = $params['style'];
  6949. }
  6950. }
  6951. // add html5 elements
  6952. $domData = ' data-element="extrafield"';
  6953. $domData .= ' data-targetelement="'.$this->element.'"';
  6954. $domData .= ' data-targetid="'.$this->id.'"';
  6955. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  6956. if ($display_type=='card') {
  6957. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
  6958. $colspan = 0;
  6959. }
  6960. if ($action == 'selectlines') {
  6961. $colspan++;
  6962. }
  6963. }
  6964. // Convert date into timestamp format (value in memory must be a timestamp)
  6965. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
  6966. $datenotinstring = $this->array_options['options_'.$key];
  6967. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  6968. $datenotinstring = $this->db->jdate($datenotinstring);
  6969. }
  6970. $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;
  6971. }
  6972. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
  6973. $datenotinstring = $this->array_options['options_'.$key];
  6974. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  6975. $datenotinstring = $this->db->jdate($datenotinstring);
  6976. }
  6977. $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;
  6978. }
  6979. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  6980. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
  6981. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? price2num($value) : $this->array_options['options_'.$key];
  6982. }
  6983. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  6984. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int'))) {
  6985. if ($action == 'create') {
  6986. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  6987. }
  6988. }
  6989. $labeltoshow = $langs->trans($label);
  6990. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  6991. if ($display_type == 'card') {
  6992. $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.' >';
  6993. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action == 'view' || $action == 'valid' || $action == 'editline')) {
  6994. $out .= '<td></td>';
  6995. }
  6996. $out .= '<td class="wordbreak';
  6997. } elseif ($display_type == 'line') {
  6998. $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.' >';
  6999. $out .= '<div style="display: inline-block; padding-right:4px" class="wordbreak';
  7000. }
  7001. //$out .= "titlefield";
  7002. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  7003. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  7004. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  7005. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  7006. $out .= '">';
  7007. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7008. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7009. } else {
  7010. $out .= $labeltoshow;
  7011. }
  7012. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7013. $out .= '&nbsp;<span style="color: red">*</span>';
  7014. }
  7015. } else {
  7016. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7017. $out .= ' fieldrequired';
  7018. }
  7019. $out .= '">';
  7020. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7021. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7022. } else {
  7023. $out .= $labeltoshow;
  7024. }
  7025. }
  7026. $out .= ($display_type == 'card' ? '</td>' : '</div>');
  7027. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  7028. if ($display_type == 'card') {
  7029. // a first td column was already output (and may be another on before if MAIN_VIEW_LINE_NUMBER set), so this td is the next one
  7030. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="'.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  7031. } elseif ($display_type == 'line') {
  7032. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').' style="display: inline-block" class="'.$this->element.'_extras_'.$key.'">';
  7033. }
  7034. switch ($mode) {
  7035. case "view":
  7036. $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
  7037. break;
  7038. case "create":
  7039. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7040. break;
  7041. case "edit":
  7042. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7043. break;
  7044. }
  7045. $out .= ($display_type=='card' ? '</td>' : '</div>');
  7046. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
  7047. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7048. } else {
  7049. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7050. }
  7051. $e++;
  7052. }
  7053. }
  7054. $out .= "\n";
  7055. // Add code to manage list depending on others
  7056. if (!empty($conf->use_javascript_ajax)) {
  7057. $out .= $this->getJSListDependancies();
  7058. }
  7059. $out .= '<!-- /showOptionals --> '."\n";
  7060. }
  7061. }
  7062. $out .= $hookmanager->resPrint;
  7063. return $out;
  7064. }
  7065. /**
  7066. * @param string $type Type for prefix
  7067. * @return string Javacript code to manage dependency
  7068. */
  7069. public function getJSListDependancies($type = '_extra')
  7070. {
  7071. $out = '
  7072. <script>
  7073. jQuery(document).ready(function() {
  7074. function showOptions'.$type.'(child_list, parent_list, orig_select)
  7075. {
  7076. var val = $("select[name=\""+parent_list+"\"]").val();
  7077. var parentVal = parent_list + ":" + val;
  7078. if(typeof val == "string"){
  7079. if(val != "") {
  7080. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7081. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7082. $("select[name=\""+child_list+"\"]").append(options);
  7083. } else {
  7084. var options = orig_select.find("option[parent]").clone();
  7085. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7086. $("select[name=\""+child_list+"\"]").append(options);
  7087. }
  7088. } else if(val > 0) {
  7089. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7090. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7091. $("select[name=\""+child_list+"\"]").append(options);
  7092. } else {
  7093. var options = orig_select.find("option[parent]").clone();
  7094. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7095. $("select[name=\""+child_list+"\"]").append(options);
  7096. }
  7097. }
  7098. function setListDependencies'.$type.'() {
  7099. jQuery("select option[parent]").parent().each(function() {
  7100. var orig_select = {};
  7101. var child_list = $(this).attr("name");
  7102. orig_select[child_list] = $(this).clone();
  7103. var parent = $(this).find("option[parent]:first").attr("parent");
  7104. var infos = parent.split(":");
  7105. var parent_list = infos[0];
  7106. //Hide daughters lists
  7107. if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
  7108. $("#"+child_list).hide();
  7109. //Show mother lists
  7110. } else if ($("#"+parent_list).val() != 0){
  7111. $("#"+parent_list).show();
  7112. }
  7113. //Show the child list if the parent list value is selected
  7114. $("select[name=\""+parent_list+"\"]").click(function() {
  7115. if ($(this).val() != 0){
  7116. $("#"+child_list).show()
  7117. }
  7118. });
  7119. //When we change parent list
  7120. $("select[name=\""+parent_list+"\"]").change(function() {
  7121. showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
  7122. //Select the value 0 on child list after a change on the parent list
  7123. $("#"+child_list).val(0).trigger("change");
  7124. //Hide child lists if the parent value is set to 0
  7125. if ($(this).val() == 0){
  7126. $("#"+child_list).hide();
  7127. }
  7128. });
  7129. });
  7130. }
  7131. setListDependencies'.$type.'();
  7132. });
  7133. </script>'."\n";
  7134. return $out;
  7135. }
  7136. /**
  7137. * Returns the rights used for this class
  7138. * @return stdClass
  7139. */
  7140. public function getRights()
  7141. {
  7142. global $user;
  7143. $element = $this->element;
  7144. if ($element == 'facturerec') {
  7145. $element = 'facture';
  7146. }
  7147. return $user->rights->{$element};
  7148. }
  7149. /**
  7150. * Function used to replace a thirdparty id with another one.
  7151. * This function is meant to be called from replaceThirdparty with the appropiate tables
  7152. * Column name fk_soc MUST be used to identify thirdparties
  7153. *
  7154. * @param DoliDB $db Database handler
  7155. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  7156. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  7157. * @param string[] $tables Tables that need to be changed
  7158. * @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)
  7159. * @return bool True if success, False if error
  7160. */
  7161. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7162. {
  7163. foreach ($tables as $table) {
  7164. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
  7165. if (!$db->query($sql)) {
  7166. if ($ignoreerrors) {
  7167. 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.
  7168. }
  7169. //$this->errors = $db->lasterror();
  7170. return false;
  7171. }
  7172. }
  7173. return true;
  7174. }
  7175. /**
  7176. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  7177. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  7178. * else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  7179. * else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  7180. * else set min buy price as buy price
  7181. *
  7182. * @param float $unitPrice Product unit price
  7183. * @param float $discountPercent Line discount percent
  7184. * @param int $fk_product Product id
  7185. * @return float <0 if KO, buyprice if OK
  7186. */
  7187. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  7188. {
  7189. global $conf;
  7190. $buyPrice = 0;
  7191. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
  7192. // When ForceBuyingPriceIfNull is set
  7193. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  7194. } else {
  7195. // Get cost price for margin calculation
  7196. if (!empty($fk_product) && $fk_product > 0) {
  7197. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
  7198. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7199. $product = new Product($this->db);
  7200. $result = $product->fetch($fk_product);
  7201. if ($result <= 0) {
  7202. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7203. return -1;
  7204. }
  7205. if ($product->cost_price > 0) {
  7206. $buyPrice = $product->cost_price;
  7207. } elseif ($product->pmp > 0) {
  7208. $buyPrice = $product->pmp;
  7209. }
  7210. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
  7211. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7212. $product = new Product($this->db);
  7213. $result = $product->fetch($fk_product);
  7214. if ($result <= 0) {
  7215. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7216. return -1;
  7217. }
  7218. if ($product->pmp > 0) {
  7219. $buyPrice = $product->pmp;
  7220. }
  7221. }
  7222. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
  7223. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  7224. $productFournisseur = new ProductFournisseur($this->db);
  7225. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
  7226. $buyPrice = $productFournisseur->fourn_unitprice;
  7227. } elseif ($result < 0) {
  7228. $this->errors[] = $productFournisseur->error;
  7229. return -2;
  7230. }
  7231. }
  7232. }
  7233. }
  7234. return $buyPrice;
  7235. }
  7236. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7237. /**
  7238. * Show photos of an object (nbmax maximum), into several columns
  7239. *
  7240. * @param string $modulepart 'product', 'ticket', ...
  7241. * @param string $sdir Directory to scan (full absolute path)
  7242. * @param int $size 0=original size, 1='small' use thumbnail if possible
  7243. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  7244. * @param int $nbbyrow Number of image per line or -1 to use div separator or 0 to use no separator. Used only if size=1 or 'small'.
  7245. * @param int $showfilename 1=Show filename
  7246. * @param int $showaction 1=Show icon with action links (resize, delete)
  7247. * @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.
  7248. * @param int $maxWidth Max width of original image when size='small'
  7249. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  7250. * @param int $notitle Do not add title tag on image
  7251. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  7252. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  7253. */
  7254. 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)
  7255. {
  7256. // phpcs:enable
  7257. global $conf, $user, $langs;
  7258. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7259. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  7260. $sortfield = 'position_name';
  7261. $sortorder = 'asc';
  7262. $dir = $sdir.'/';
  7263. $pdir = '/';
  7264. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7265. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7266. // For backward compatibility
  7267. if ($modulepart == 'product') {
  7268. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  7269. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7270. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7271. }
  7272. }
  7273. // Defined relative dir to DOL_DATA_ROOT
  7274. $relativedir = '';
  7275. if ($dir) {
  7276. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  7277. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  7278. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  7279. }
  7280. $dirthumb = $dir.'thumbs/';
  7281. $pdirthumb = $pdir.'thumbs/';
  7282. $return = '<!-- Photo -->'."\n";
  7283. $nbphoto = 0;
  7284. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  7285. /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
  7286. {
  7287. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  7288. $filearray=array_merge($filearray, $filearrayold);
  7289. }*/
  7290. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  7291. if (count($filearray)) {
  7292. if ($sortfield && $sortorder) {
  7293. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  7294. }
  7295. foreach ($filearray as $key => $val) {
  7296. $photo = '';
  7297. $file = $val['name'];
  7298. //if (! utf8_check($file)) $file=utf8_encode($file); // To be sure file is stored in UTF8 in memory
  7299. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  7300. if (image_format_supported($file) >= 0) {
  7301. $nbphoto++;
  7302. $photo = $file;
  7303. $viewfilename = $file;
  7304. if ($size == 1 || $size == 'small') { // Format vignette
  7305. // Find name of thumb file
  7306. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  7307. if (!dol_is_file($dirthumb.$photo_vignette)) {
  7308. $photo_vignette = '';
  7309. }
  7310. // Get filesize of original file
  7311. $imgarray = dol_getImageSize($dir.$photo);
  7312. if ($nbbyrow > 0) {
  7313. if ($nbphoto == 1) {
  7314. $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  7315. }
  7316. if ($nbphoto % $nbbyrow == 1) {
  7317. $return .= '<tr class="center valignmiddle" style="border: 1px">';
  7318. }
  7319. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
  7320. } elseif ($nbbyrow < 0) {
  7321. $return .= '<div class="inline-block">';
  7322. }
  7323. $return .= "\n";
  7324. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  7325. if (empty($nolink)) {
  7326. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  7327. if ($urladvanced) {
  7328. $return .= '<a href="'.$urladvanced.'">';
  7329. } else {
  7330. $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
  7331. }
  7332. }
  7333. // Show image (width height=$maxHeight)
  7334. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  7335. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  7336. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  7337. if ($notitle) {
  7338. $alt = '';
  7339. }
  7340. $addphotorefcss = 1;
  7341. if ($usesharelink) {
  7342. if ($val['share']) {
  7343. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7344. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  7345. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7346. } else {
  7347. $return .= '<!-- Show original file -->';
  7348. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7349. }
  7350. } else {
  7351. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  7352. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  7353. }
  7354. } else {
  7355. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7356. $return .= '<!-- Show thumb -->';
  7357. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').' 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).'">';
  7358. } else {
  7359. $return .= '<!-- Show original file -->';
  7360. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" title="'.dol_escape_htmltag($alt).'">';
  7361. }
  7362. }
  7363. if (empty($nolink)) {
  7364. $return .= '</a>';
  7365. }
  7366. $return .= "\n";
  7367. if ($showfilename) {
  7368. $return .= '<br>'.$viewfilename;
  7369. }
  7370. if ($showaction) {
  7371. $return .= '<br>';
  7372. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  7373. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
  7374. $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>';
  7375. }
  7376. // Special cas for product
  7377. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7378. // Link to resize
  7379. $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; ';
  7380. // Link to delete
  7381. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7382. $return .= img_delete().'</a>';
  7383. }
  7384. }
  7385. $return .= "\n";
  7386. if ($nbbyrow > 0) {
  7387. $return .= '</td>';
  7388. if (($nbphoto % $nbbyrow) == 0) {
  7389. $return .= '</tr>';
  7390. }
  7391. } elseif ($nbbyrow < 0) {
  7392. $return .= '</div>';
  7393. }
  7394. }
  7395. if (empty($size)) { // Format origine
  7396. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  7397. if ($showfilename) {
  7398. $return .= '<br>'.$viewfilename;
  7399. }
  7400. if ($showaction) {
  7401. // Special case for product
  7402. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7403. // Link to resize
  7404. $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; ';
  7405. // Link to delete
  7406. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7407. $return .= img_delete().'</a>';
  7408. }
  7409. }
  7410. }
  7411. // On continue ou on arrete de boucler ?
  7412. if ($nbmax && $nbphoto >= $nbmax) {
  7413. break;
  7414. }
  7415. }
  7416. }
  7417. if ($size == 1 || $size == 'small') {
  7418. if ($nbbyrow > 0) {
  7419. // Ferme tableau
  7420. while ($nbphoto % $nbbyrow) {
  7421. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  7422. $nbphoto++;
  7423. }
  7424. if ($nbphoto) {
  7425. $return .= '</table>';
  7426. }
  7427. }
  7428. }
  7429. }
  7430. $this->nbphoto = $nbphoto;
  7431. return $return;
  7432. }
  7433. /**
  7434. * Function test if type is array
  7435. *
  7436. * @param array $info content informations of field
  7437. * @return bool true if array
  7438. */
  7439. protected function isArray($info)
  7440. {
  7441. if (is_array($info)) {
  7442. if (isset($info['type']) && $info['type'] == 'array') {
  7443. return true;
  7444. } else {
  7445. return false;
  7446. }
  7447. }
  7448. return false;
  7449. }
  7450. /**
  7451. * Function test if type is date
  7452. *
  7453. * @param array $info content informations of field
  7454. * @return bool true if date
  7455. */
  7456. public function isDate($info)
  7457. {
  7458. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
  7459. return true;
  7460. }
  7461. return false;
  7462. }
  7463. /**
  7464. * Function test if type is duration
  7465. *
  7466. * @param array $info content informations of field
  7467. * @return bool true if field of type duration
  7468. */
  7469. public function isDuration($info)
  7470. {
  7471. if (is_array($info)) {
  7472. if (isset($info['type']) && ($info['type'] == 'duration')) {
  7473. return true;
  7474. } else {
  7475. return false;
  7476. }
  7477. } else {
  7478. return false;
  7479. }
  7480. }
  7481. /**
  7482. * Function test if type is integer
  7483. *
  7484. * @param array $info content informations of field
  7485. * @return bool true if integer
  7486. */
  7487. public function isInt($info)
  7488. {
  7489. if (is_array($info)) {
  7490. if (isset($info['type']) && ($info['type'] == 'int' || preg_match('/^integer/i', $info['type']))) {
  7491. return true;
  7492. } else {
  7493. return false;
  7494. }
  7495. } else {
  7496. return false;
  7497. }
  7498. }
  7499. /**
  7500. * Function test if type is float
  7501. *
  7502. * @param array $info content informations of field
  7503. * @return bool true if float
  7504. */
  7505. public function isFloat($info)
  7506. {
  7507. if (is_array($info)) {
  7508. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
  7509. return true;
  7510. } else {
  7511. return false;
  7512. }
  7513. }
  7514. return false;
  7515. }
  7516. /**
  7517. * Function test if type is text
  7518. *
  7519. * @param array $info content informations of field
  7520. * @return bool true if type text
  7521. */
  7522. public function isText($info)
  7523. {
  7524. if (is_array($info)) {
  7525. if (isset($info['type']) && $info['type'] == 'text') {
  7526. return true;
  7527. } else {
  7528. return false;
  7529. }
  7530. }
  7531. return false;
  7532. }
  7533. /**
  7534. * Function test if field can be null
  7535. *
  7536. * @param array $info content informations of field
  7537. * @return bool true if it can be null
  7538. */
  7539. protected function canBeNull($info)
  7540. {
  7541. if (is_array($info)) {
  7542. if (isset($info['notnull']) && $info['notnull'] != '1') {
  7543. return true;
  7544. } else {
  7545. return false;
  7546. }
  7547. }
  7548. return true;
  7549. }
  7550. /**
  7551. * Function test if field is forced to null if zero or empty
  7552. *
  7553. * @param array $info content informations of field
  7554. * @return bool true if forced to null
  7555. */
  7556. protected function isForcedToNullIfZero($info)
  7557. {
  7558. if (is_array($info)) {
  7559. if (isset($info['notnull']) && $info['notnull'] == '-1') {
  7560. return true;
  7561. } else {
  7562. return false;
  7563. }
  7564. }
  7565. return false;
  7566. }
  7567. /**
  7568. * Function test if is indexed
  7569. *
  7570. * @param array $info content informations of field
  7571. * @return bool
  7572. */
  7573. protected function isIndex($info)
  7574. {
  7575. if (is_array($info)) {
  7576. if (isset($info['index']) && $info['index'] == true) {
  7577. return true;
  7578. } else {
  7579. return false;
  7580. }
  7581. }
  7582. return false;
  7583. }
  7584. /**
  7585. * Function to prepare a part of the query for insert.
  7586. * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
  7587. * $this->${field} should be a clean value. The page can run
  7588. *
  7589. * @return array
  7590. */
  7591. protected function setSaveQuery()
  7592. {
  7593. global $conf;
  7594. $queryarray = array();
  7595. foreach ($this->fields as $field => $info) { // Loop on definition of fields
  7596. // Depending on field type ('datetime', ...)
  7597. if ($this->isDate($info)) {
  7598. if (empty($this->{$field})) {
  7599. $queryarray[$field] = null;
  7600. } else {
  7601. $queryarray[$field] = $this->db->idate($this->{$field});
  7602. }
  7603. } elseif ($this->isDuration($info)) {
  7604. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7605. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7606. if (!isset($this->{$field})) {
  7607. $queryarray[$field] = 0;
  7608. } else {
  7609. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7610. }
  7611. } else {
  7612. $queryarray[$field] = null;
  7613. }
  7614. } elseif ($this->isInt($info) || $this->isFloat($info)) {
  7615. if ($field == 'entity' && is_null($this->{$field})) {
  7616. $queryarray[$field] = $conf->entity;
  7617. } else {
  7618. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7619. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7620. if (!isset($this->{$field})) {
  7621. $queryarray[$field] = 0;
  7622. } elseif ($this->isInt($info)) {
  7623. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7624. } elseif ($this->isFloat($info)) {
  7625. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7626. }
  7627. } else {
  7628. $queryarray[$field] = null;
  7629. }
  7630. }
  7631. } else {
  7632. // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
  7633. // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
  7634. $queryarray[$field] = $this->{$field};
  7635. }
  7636. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
  7637. unset($queryarray[$field]);
  7638. }
  7639. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
  7640. $queryarray[$field] = null; // May force 0 to null
  7641. }
  7642. }
  7643. return $queryarray;
  7644. }
  7645. /**
  7646. * Function to load data from a SQL pointer into properties of current object $this
  7647. *
  7648. * @param stdClass $obj Contain data of object from database
  7649. * @return void
  7650. */
  7651. public function setVarsFromFetchObj(&$obj)
  7652. {
  7653. global $db;
  7654. foreach ($this->fields as $field => $info) {
  7655. if ($this->isDate($info)) {
  7656. if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
  7657. $this->{$field} = '';
  7658. } else {
  7659. $this->{$field} = $db->jdate($obj->{$field});
  7660. }
  7661. } elseif ($this->isInt($info)) {
  7662. if ($field == 'rowid') {
  7663. $this->id = (int) $obj->{$field};
  7664. } else {
  7665. if ($this->isForcedToNullIfZero($info)) {
  7666. if (empty($obj->{$field})) {
  7667. $this->{$field} = null;
  7668. } else {
  7669. $this->{$field} = (double) $obj->{$field};
  7670. }
  7671. } else {
  7672. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7673. $this->{$field} = (int) $obj->{$field};
  7674. } else {
  7675. $this->{$field} = null;
  7676. }
  7677. }
  7678. }
  7679. } elseif ($this->isFloat($info)) {
  7680. if ($this->isForcedToNullIfZero($info)) {
  7681. if (empty($obj->{$field})) {
  7682. $this->{$field} = null;
  7683. } else {
  7684. $this->{$field} = (double) $obj->{$field};
  7685. }
  7686. } else {
  7687. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7688. $this->{$field} = (double) $obj->{$field};
  7689. } else {
  7690. $this->{$field} = null;
  7691. }
  7692. }
  7693. } else {
  7694. $this->{$field} = $obj->{$field};
  7695. }
  7696. }
  7697. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  7698. if (!isset($this->fields['ref']) && isset($this->id)) {
  7699. $this->ref = $this->id;
  7700. }
  7701. }
  7702. /**
  7703. * Function to concat keys of fields
  7704. *
  7705. * @param string $alias String of alias of table for fields. For example 't'.
  7706. * @return string list of alias fields
  7707. */
  7708. public function getFieldList($alias = '')
  7709. {
  7710. $keys = array_keys($this->fields);
  7711. if (!empty($alias)) {
  7712. $keys_with_alias = array();
  7713. foreach ($keys as $fieldname) {
  7714. $keys_with_alias[] = $alias . '.' . $fieldname;
  7715. }
  7716. return implode(',', $keys_with_alias);
  7717. } else {
  7718. return implode(',', $keys);
  7719. }
  7720. }
  7721. /**
  7722. * Add quote to field value if necessary
  7723. *
  7724. * @param string|int $value Value to protect
  7725. * @param array $fieldsentry Properties of field
  7726. * @return string
  7727. */
  7728. protected function quote($value, $fieldsentry)
  7729. {
  7730. if (is_null($value)) {
  7731. return 'NULL';
  7732. } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
  7733. return price2num("$value");
  7734. } elseif ($fieldsentry['type'] == 'boolean') {
  7735. if ($value) {
  7736. return 'true';
  7737. } else {
  7738. return 'false';
  7739. }
  7740. } else {
  7741. return "'".$this->db->escape($value)."'";
  7742. }
  7743. }
  7744. /**
  7745. * Create object into database
  7746. *
  7747. * @param User $user User that creates
  7748. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7749. * @return int <0 if KO, Id of created object if OK
  7750. */
  7751. public function createCommon(User $user, $notrigger = false)
  7752. {
  7753. global $langs;
  7754. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  7755. $error = 0;
  7756. $now = dol_now();
  7757. $fieldvalues = $this->setSaveQuery();
  7758. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
  7759. $fieldvalues['date_creation'] = $this->db->idate($now);
  7760. }
  7761. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
  7762. $fieldvalues['fk_user_creat'] = $user->id;
  7763. }
  7764. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  7765. if (array_key_exists('ref', $fieldvalues)) {
  7766. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  7767. }
  7768. $keys = array();
  7769. $values = array(); // Array to store string forged for SQL syntax
  7770. foreach ($fieldvalues as $k => $v) {
  7771. $keys[$k] = $k;
  7772. $value = $this->fields[$k];
  7773. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  7774. }
  7775. // Clean and check mandatory
  7776. foreach ($keys as $key) {
  7777. // If field is an implicit foreign key field
  7778. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  7779. $values[$key] = '';
  7780. }
  7781. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  7782. $values[$key] = '';
  7783. }
  7784. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
  7785. $error++;
  7786. $langs->load("errors");
  7787. dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
  7788. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  7789. }
  7790. // If value is null and there is a default value for field
  7791. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
  7792. $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
  7793. }
  7794. // If field is an implicit foreign key field
  7795. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  7796. if (isset($this->fields[$key]['default'])) {
  7797. $values[$key] = ((int) $this->fields[$key]['default']);
  7798. } else {
  7799. $values[$key] = 'null';
  7800. }
  7801. }
  7802. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
  7803. $values[$key] = 'null';
  7804. }
  7805. }
  7806. if ($error) {
  7807. return -1;
  7808. }
  7809. $this->db->begin();
  7810. if (!$error) {
  7811. $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element;
  7812. $sql .= " (".implode(", ", $keys).')';
  7813. $sql .= " VALUES (".implode(", ", $values).")"; // $values can contains 'abc' or 123
  7814. $res = $this->db->query($sql);
  7815. if (!$res) {
  7816. $error++;
  7817. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  7818. $this->errors[] = "ErrorRefAlreadyExists";
  7819. } else {
  7820. $this->errors[] = $this->db->lasterror();
  7821. }
  7822. }
  7823. }
  7824. if (!$error) {
  7825. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
  7826. }
  7827. // If we have a field ref with a default value of (PROV)
  7828. if (!$error) {
  7829. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
  7830. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
  7831. $resqlupdate = $this->db->query($sql);
  7832. if ($resqlupdate === false) {
  7833. $error++;
  7834. $this->errors[] = $this->db->lasterror();
  7835. } else {
  7836. $this->ref = '(PROV'.$this->id.')';
  7837. }
  7838. }
  7839. }
  7840. // Create extrafields
  7841. if (!$error) {
  7842. $result = $this->insertExtraFields();
  7843. if ($result < 0) {
  7844. $error++;
  7845. }
  7846. }
  7847. // Create lines
  7848. if (!empty($this->table_element_line) && !empty($this->fk_element)) {
  7849. $num = (is_array($this->lines) ? count($this->lines) : 0);
  7850. for ($i = 0; $i < $num; $i++) {
  7851. $line = $this->lines[$i];
  7852. $keyforparent = $this->fk_element;
  7853. $line->$keyforparent = $this->id;
  7854. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  7855. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  7856. if (!is_object($line)) {
  7857. $line = (object) $line;
  7858. }
  7859. $result = $line->create($user, 1);
  7860. if ($result < 0) {
  7861. $this->error = $line->error;
  7862. $this->db->rollback();
  7863. return -1;
  7864. }
  7865. }
  7866. }
  7867. // Triggers
  7868. if (!$error && !$notrigger) {
  7869. // Call triggers
  7870. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  7871. if ($result < 0) {
  7872. $error++;
  7873. }
  7874. // End call triggers
  7875. }
  7876. // Commit or rollback
  7877. if ($error) {
  7878. $this->db->rollback();
  7879. return -1;
  7880. } else {
  7881. $this->db->commit();
  7882. return $this->id;
  7883. }
  7884. }
  7885. /**
  7886. * Load object in memory from the database
  7887. *
  7888. * @param int $id Id object
  7889. * @param string $ref Ref
  7890. * @param string $morewhere More SQL filters (' AND ...')
  7891. * @return int <0 if KO, 0 if not found, >0 if OK
  7892. */
  7893. public function fetchCommon($id, $ref = null, $morewhere = '')
  7894. {
  7895. if (empty($id) && empty($ref) && empty($morewhere)) {
  7896. return -1;
  7897. }
  7898. $fieldlist = $this->getFieldList('t');
  7899. if (empty($fieldlist)) {
  7900. return 0;
  7901. }
  7902. $sql = "SELECT ".$fieldlist;
  7903. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element.' as t';
  7904. if (!empty($id)) {
  7905. $sql .= ' WHERE t.rowid = '.((int) $id);
  7906. } elseif (!empty($ref)) {
  7907. $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
  7908. } else {
  7909. $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  7910. }
  7911. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  7912. $sql .= ' AND t.entity IN ('.getEntity($this->table_element).')';
  7913. }
  7914. if ($morewhere) {
  7915. $sql .= $morewhere;
  7916. }
  7917. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  7918. $res = $this->db->query($sql);
  7919. if ($res) {
  7920. $obj = $this->db->fetch_object($res);
  7921. if ($obj) {
  7922. $this->setVarsFromFetchObj($obj);
  7923. // Retrieve all extrafield
  7924. // fetch optionals attributes and labels
  7925. $this->fetch_optionals();
  7926. return $this->id;
  7927. } else {
  7928. return 0;
  7929. }
  7930. } else {
  7931. $this->error = $this->db->lasterror();
  7932. $this->errors[] = $this->error;
  7933. return -1;
  7934. }
  7935. }
  7936. /**
  7937. * Load object in memory from the database
  7938. *
  7939. * @param string $morewhere More SQL filters (' AND ...')
  7940. * @return int <0 if KO, 0 if not found, >0 if OK
  7941. */
  7942. public function fetchLinesCommon($morewhere = '')
  7943. {
  7944. $objectlineclassname = get_class($this).'Line';
  7945. if (!class_exists($objectlineclassname)) {
  7946. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  7947. return -1;
  7948. }
  7949. $objectline = new $objectlineclassname($this->db);
  7950. $sql = "SELECT ".$objectline->getFieldList('l');
  7951. $sql .= " FROM ".MAIN_DB_PREFIX.$objectline->table_element." as l";
  7952. $sql .= " WHERE l.fk_".$this->db->escape($this->element)." = ".((int) $this->id);
  7953. if ($morewhere) {
  7954. $sql .= $morewhere;
  7955. }
  7956. if (isset($objectline->fields['position'])) {
  7957. $sql .= $this->db->order('position', 'ASC');
  7958. }
  7959. $resql = $this->db->query($sql);
  7960. if ($resql) {
  7961. $num_rows = $this->db->num_rows($resql);
  7962. $i = 0;
  7963. while ($i < $num_rows) {
  7964. $obj = $this->db->fetch_object($resql);
  7965. if ($obj) {
  7966. $newline = new $objectlineclassname($this->db);
  7967. $newline->setVarsFromFetchObj($obj);
  7968. $this->lines[] = $newline;
  7969. }
  7970. $i++;
  7971. }
  7972. return 1;
  7973. } else {
  7974. $this->error = $this->db->lasterror();
  7975. $this->errors[] = $this->error;
  7976. return -1;
  7977. }
  7978. }
  7979. /**
  7980. * Update object into database
  7981. *
  7982. * @param User $user User that modifies
  7983. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7984. * @return int <0 if KO, >0 if OK
  7985. */
  7986. public function updateCommon(User $user, $notrigger = false)
  7987. {
  7988. global $conf, $langs;
  7989. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  7990. $error = 0;
  7991. $now = dol_now();
  7992. $fieldvalues = $this->setSaveQuery();
  7993. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
  7994. $fieldvalues['date_modification'] = $this->db->idate($now);
  7995. }
  7996. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
  7997. $fieldvalues['fk_user_modif'] = $user->id;
  7998. }
  7999. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  8000. if (array_key_exists('ref', $fieldvalues)) {
  8001. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8002. }
  8003. // Add quotes and escape on fields with type string
  8004. $keys = array();
  8005. $values = array();
  8006. $tmp = array();
  8007. foreach ($fieldvalues as $k => $v) {
  8008. $keys[$k] = $k;
  8009. $value = $this->fields[$k];
  8010. $values[$k] = $this->quote($v, $value);
  8011. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  8012. }
  8013. // Clean and check mandatory fields
  8014. foreach ($keys as $key) {
  8015. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8016. $values[$key] = ''; // This is an implicit foreign key field
  8017. }
  8018. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8019. $values[$key] = ''; // This is an explicit foreign key field
  8020. }
  8021. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  8022. /*
  8023. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  8024. {
  8025. $error++;
  8026. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8027. }*/
  8028. }
  8029. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
  8030. $this->db->begin();
  8031. if (!$error) {
  8032. $res = $this->db->query($sql);
  8033. if (!$res) {
  8034. $error++;
  8035. $this->errors[] = $this->db->lasterror();
  8036. }
  8037. }
  8038. // Update extrafield
  8039. if (!$error) {
  8040. $result = $this->insertExtraFields();
  8041. if ($result < 0) {
  8042. $error++;
  8043. }
  8044. }
  8045. // Triggers
  8046. if (!$error && !$notrigger) {
  8047. // Call triggers
  8048. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  8049. if ($result < 0) {
  8050. $error++;
  8051. } //Do also here what you must do to rollback action if trigger fail
  8052. // End call triggers
  8053. }
  8054. // Commit or rollback
  8055. if ($error) {
  8056. $this->db->rollback();
  8057. return -1;
  8058. } else {
  8059. $this->db->commit();
  8060. return $this->id;
  8061. }
  8062. }
  8063. /**
  8064. * Delete object in database
  8065. *
  8066. * @param User $user User that deletes
  8067. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8068. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  8069. * @return int <=0 if KO, 0=Nothing done because object has child, >0 if OK
  8070. */
  8071. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  8072. {
  8073. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  8074. $error = 0;
  8075. $this->db->begin();
  8076. if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
  8077. foreach ($this->childtables as $table) {
  8078. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8079. $resql = $this->db->query($sql);
  8080. if (!$resql) {
  8081. $this->error = $this->db->lasterror();
  8082. $this->errors[] = $this->error;
  8083. $this->db->rollback();
  8084. return -1;
  8085. }
  8086. }
  8087. } elseif (!empty($this->fk_element) && !empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
  8088. $objectisused = $this->isObjectUsed($this->id);
  8089. if (!empty($objectisused)) {
  8090. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  8091. $this->error = 'ErrorRecordHasChildren';
  8092. $this->errors[] = $this->error;
  8093. $this->db->rollback();
  8094. return 0;
  8095. }
  8096. }
  8097. // Delete cascade first
  8098. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  8099. foreach ($this->childtablesoncascade as $table) {
  8100. $deleteFromObject = explode(':', $table);
  8101. if (count($deleteFromObject) >= 2) {
  8102. $className = str_replace('@', '', $deleteFromObject[0]);
  8103. $filePath = $deleteFromObject[1];
  8104. $columnName = $deleteFromObject[2];
  8105. $TMoreSQL = array();
  8106. $more_sql = $deleteFromObject[3];
  8107. if (!empty($more_sql)) {
  8108. $TMoreSQL['customsql'] = $more_sql;
  8109. }
  8110. if (dol_include_once($filePath)) {
  8111. $childObject = new $className($this->db);
  8112. if (method_exists($childObject, 'deleteByParentField')) {
  8113. $result = $childObject->deleteByParentField($this->id, $columnName, $TMoreSQL);
  8114. if ($result < 0) {
  8115. $error++;
  8116. $this->errors[] = $childObject->error;
  8117. break;
  8118. }
  8119. } else {
  8120. $error++;
  8121. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  8122. break;
  8123. }
  8124. } else {
  8125. $error++;
  8126. $this->errors[] = 'Cannot include child class file '.$filePath;
  8127. break;
  8128. }
  8129. } else {
  8130. // Delete record in child table
  8131. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8132. $resql = $this->db->query($sql);
  8133. if (!$resql) {
  8134. $error++;
  8135. $this->error = $this->db->lasterror();
  8136. $this->errors[] = $this->error;
  8137. break;
  8138. }
  8139. }
  8140. }
  8141. }
  8142. if (!$error) {
  8143. if (!$notrigger) {
  8144. // Call triggers
  8145. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  8146. if ($result < 0) {
  8147. $error++;
  8148. } // Do also here what you must do to rollback action if trigger fail
  8149. // End call triggers
  8150. }
  8151. }
  8152. // Delete llx_ecm_files
  8153. if (!$error) {
  8154. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  8155. if (!$res) {
  8156. $error++;
  8157. }
  8158. }
  8159. if (!$error && !empty($this->isextrafieldmanaged)) {
  8160. $result = $this->deleteExtraFields();
  8161. if ($result < 0) {
  8162. $error++;
  8163. }
  8164. }
  8165. if (!$error) {
  8166. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.((int) $this->id);
  8167. $resql = $this->db->query($sql);
  8168. if (!$resql) {
  8169. $error++;
  8170. $this->errors[] = $this->db->lasterror();
  8171. }
  8172. }
  8173. // Commit or rollback
  8174. if ($error) {
  8175. $this->db->rollback();
  8176. return -1;
  8177. } else {
  8178. $this->db->commit();
  8179. return 1;
  8180. }
  8181. }
  8182. /**
  8183. * Delete all child object from a parent ID
  8184. *
  8185. * @param int $parentId Parent Id
  8186. * @param string $parentField Name of Foreign key parent column
  8187. * @param array $filter an array filter
  8188. * @param string $filtermode AND or OR
  8189. * @return int <0 if KO, >0 if OK
  8190. * @throws Exception
  8191. */
  8192. public function deleteByParentField($parentId = 0, $parentField = '', $filter = array(), $filtermode = "AND")
  8193. {
  8194. global $user;
  8195. $error = 0;
  8196. $deleted = 0;
  8197. if (!empty($parentId) && !empty($parentField)) {
  8198. $this->db->begin();
  8199. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$this->table_element;
  8200. $sql .= " WHERE ".$parentField." = ".(int) $parentId;
  8201. // Manage filters
  8202. $sqlwhere = array();
  8203. if (count($filter) > 0) {
  8204. foreach ($filter as $key => $value) {
  8205. if ($key == 'customsql') {
  8206. $sqlwhere[] = $value;
  8207. } elseif (strpos($value, '%') === false) {
  8208. $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
  8209. } else {
  8210. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  8211. }
  8212. }
  8213. }
  8214. if (count($sqlwhere) > 0) {
  8215. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  8216. }
  8217. $resql = $this->db->query($sql);
  8218. if (!$resql) {
  8219. $this->errors[] = $this->db->lasterror();
  8220. $error++;
  8221. } else {
  8222. while ($obj = $this->db->fetch_object($resql)) {
  8223. $result = $this->fetch($obj->rowid);
  8224. if ($result < 0) {
  8225. $error++;
  8226. $this->errors[] = $this->error;
  8227. } else {
  8228. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  8229. $result = $this->delete();
  8230. } else {
  8231. $result = $this->delete($user);
  8232. }
  8233. if ($result < 0) {
  8234. $error++;
  8235. $this->errors[] = $this->error;
  8236. } else {
  8237. $deleted++;
  8238. }
  8239. }
  8240. }
  8241. }
  8242. if (empty($error)) {
  8243. $this->db->commit();
  8244. return $deleted;
  8245. } else {
  8246. $this->error = implode(', ', $this->errors);
  8247. $this->db->rollback();
  8248. return $error * -1;
  8249. }
  8250. }
  8251. return $deleted;
  8252. }
  8253. /**
  8254. * Delete a line of object in database
  8255. *
  8256. * @param User $user User that delete
  8257. * @param int $idline Id of line to delete
  8258. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8259. * @return int >0 if OK, <0 if KO
  8260. */
  8261. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  8262. {
  8263. global $conf;
  8264. $error = 0;
  8265. $tmpforobjectclass = get_class($this);
  8266. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  8267. // Call trigger
  8268. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  8269. if ($result < 0) {
  8270. return -1;
  8271. }
  8272. // End call triggers
  8273. $this->db->begin();
  8274. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  8275. $sql .= " WHERE rowid = ".((int) $idline);
  8276. dol_syslog(get_class($this)."::deleteLineCommon", LOG_DEBUG);
  8277. $resql = $this->db->query($sql);
  8278. if (!$resql) {
  8279. $this->error = "Error ".$this->db->lasterror();
  8280. $error++;
  8281. }
  8282. if (empty($error)) {
  8283. // Remove extrafields
  8284. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  8285. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  8286. $tmpobjectline->id = $idline;
  8287. $result = $tmpobjectline->deleteExtraFields();
  8288. if ($result < 0) {
  8289. $error++;
  8290. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  8291. }
  8292. }
  8293. }
  8294. if (empty($error)) {
  8295. $this->db->commit();
  8296. return 1;
  8297. } else {
  8298. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  8299. $this->db->rollback();
  8300. return -1;
  8301. }
  8302. }
  8303. /**
  8304. * Set to a status
  8305. *
  8306. * @param User $user Object user that modify
  8307. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  8308. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  8309. * @param string $triggercode Trigger code to use
  8310. * @return int <0 if KO, >0 if OK
  8311. */
  8312. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  8313. {
  8314. $error = 0;
  8315. $this->db->begin();
  8316. $statusfield = 'status';
  8317. if ($this->element == 'don' || $this->element == 'donation') {
  8318. $statusfield = 'fk_statut';
  8319. }
  8320. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  8321. $sql .= " SET ".$statusfield." = ".((int) $status);
  8322. $sql .= " WHERE rowid = ".((int) $this->id);
  8323. if ($this->db->query($sql)) {
  8324. if (!$error) {
  8325. $this->oldcopy = clone $this;
  8326. }
  8327. if (!$error && !$notrigger) {
  8328. // Call trigger
  8329. $result = $this->call_trigger($triggercode, $user);
  8330. if ($result < 0) {
  8331. $error++;
  8332. }
  8333. }
  8334. if (!$error) {
  8335. $this->status = $status;
  8336. $this->db->commit();
  8337. return 1;
  8338. } else {
  8339. $this->db->rollback();
  8340. return -1;
  8341. }
  8342. } else {
  8343. $this->error = $this->db->error();
  8344. $this->db->rollback();
  8345. return -1;
  8346. }
  8347. }
  8348. /**
  8349. * Initialise object with example values
  8350. * Id must be 0 if object instance is a specimen
  8351. *
  8352. * @return int
  8353. */
  8354. public function initAsSpecimenCommon()
  8355. {
  8356. global $user;
  8357. $this->id = 0;
  8358. $this->specimen = 1;
  8359. $fields = array(
  8360. 'label' => 'This is label',
  8361. 'ref' => 'ABCD1234',
  8362. 'description' => 'This is a description',
  8363. 'qty' => 123.12,
  8364. 'note_public' => 'Public note',
  8365. 'note_private' => 'Private note',
  8366. 'date_creation' => (dol_now() - 3600 * 48),
  8367. 'date_modification' => (dol_now() - 3600 * 24),
  8368. 'fk_user_creat' => $user->id,
  8369. 'fk_user_modif' => $user->id,
  8370. 'date' => dol_now(),
  8371. );
  8372. foreach ($fields as $key => $value) {
  8373. if (array_key_exists($key, $this->fields)) {
  8374. $this->{$key} = $value;
  8375. }
  8376. }
  8377. return 1;
  8378. }
  8379. /* Part for comments */
  8380. /**
  8381. * Load comments linked with current task
  8382. * @return boolean 1 if ok
  8383. */
  8384. public function fetchComments()
  8385. {
  8386. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  8387. $comment = new Comment($this->db);
  8388. $result = $comment->fetchAllFor($this->element, $this->id);
  8389. if ($result < 0) {
  8390. $this->errors = array_merge($this->errors, $comment->errors);
  8391. return -1;
  8392. } else {
  8393. $this->comments = $comment->comments;
  8394. }
  8395. return count($this->comments);
  8396. }
  8397. /**
  8398. * Return nb comments already posted
  8399. *
  8400. * @return int
  8401. */
  8402. public function getNbComments()
  8403. {
  8404. return count($this->comments);
  8405. }
  8406. /**
  8407. * Trim object parameters
  8408. *
  8409. * @param string[] $parameters array of parameters to trim
  8410. * @return void
  8411. */
  8412. public function trimParameters($parameters)
  8413. {
  8414. if (!is_array($parameters)) {
  8415. return;
  8416. }
  8417. foreach ($parameters as $parameter) {
  8418. if (isset($this->$parameter)) {
  8419. $this->$parameter = trim($this->$parameter);
  8420. }
  8421. }
  8422. }
  8423. /* Part for categories/tags */
  8424. /**
  8425. * Sets object to given categories.
  8426. *
  8427. * Deletes object from existing categories not supplied.
  8428. * Adds it to non existing supplied categories.
  8429. * Existing categories are left untouch.
  8430. *
  8431. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  8432. * @return int Array of category objects or < 0 if KO
  8433. */
  8434. public function getCategoriesCommon($type_categ)
  8435. {
  8436. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8437. // Get current categories
  8438. $c = new Categorie($this->db);
  8439. $existing = $c->containing($this->id, $type_categ, 'id');
  8440. return $existing;
  8441. }
  8442. /**
  8443. * Sets object to given categories.
  8444. *
  8445. * Adds it to non existing supplied categories.
  8446. * Deletes object from existing categories not supplied (if remove_existing==true).
  8447. * Existing categories are left untouch.
  8448. *
  8449. * @param int[]|int $categories Category ID or array of Categories IDs
  8450. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) definied into const class Categorie type
  8451. * @param boolean $remove_existing True: Remove existings categories from Object if not supplies by $categories, False: let them
  8452. * @return int <0 if KO, >0 if OK
  8453. */
  8454. public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
  8455. {
  8456. // Handle single category
  8457. if (!is_array($categories)) {
  8458. $categories = array($categories);
  8459. }
  8460. dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
  8461. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8462. if (empty($type_categ)) {
  8463. dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
  8464. return -1;
  8465. }
  8466. // Get current categories
  8467. $c = new Categorie($this->db);
  8468. $existing = $c->containing($this->id, $type_categ, 'id');
  8469. if ($remove_existing) {
  8470. // Diff
  8471. if (is_array($existing)) {
  8472. $to_del = array_diff($existing, $categories);
  8473. $to_add = array_diff($categories, $existing);
  8474. } else {
  8475. $to_del = array(); // Nothing to delete
  8476. $to_add = $categories;
  8477. }
  8478. } else {
  8479. $to_del = array(); // Nothing to delete
  8480. $to_add = array_diff($categories, $existing);
  8481. }
  8482. $error = 0;
  8483. $ok = 0;
  8484. // Process
  8485. foreach ($to_del as $del) {
  8486. if ($c->fetch($del) > 0) {
  8487. $result=$c->del_type($this, $type_categ);
  8488. if ($result < 0) {
  8489. $error++;
  8490. $this->error = $c->error;
  8491. $this->errors = $c->errors;
  8492. break;
  8493. } else {
  8494. $ok += $result;
  8495. }
  8496. }
  8497. }
  8498. foreach ($to_add as $add) {
  8499. if ($c->fetch($add) > 0) {
  8500. $result = $c->add_type($this, $type_categ);
  8501. if ($result < 0) {
  8502. $error++;
  8503. $this->error = $c->error;
  8504. $this->errors = $c->errors;
  8505. break;
  8506. } else {
  8507. $ok += $result;
  8508. }
  8509. }
  8510. }
  8511. return $error ? -1 * $error : $ok;
  8512. }
  8513. /**
  8514. * Copy related categories to another object
  8515. *
  8516. * @param int $fromId Id object source
  8517. * @param int $toId Id object cible
  8518. * @param string $type Type of category ('product', ...)
  8519. * @return int < 0 if error, > 0 if ok
  8520. */
  8521. public function cloneCategories($fromId, $toId, $type = '')
  8522. {
  8523. $this->db->begin();
  8524. if (empty($type)) {
  8525. $type = $this->table_element;
  8526. }
  8527. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8528. $categorystatic = new Categorie($this->db);
  8529. $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  8530. $sql .= " SELECT fk_categorie, $toId FROM ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  8531. $sql .= " WHERE fk_product = ".((int) $fromId);
  8532. if (!$this->db->query($sql)) {
  8533. $this->error = $this->db->lasterror();
  8534. $this->db->rollback();
  8535. return -1;
  8536. }
  8537. $this->db->commit();
  8538. return 1;
  8539. }
  8540. /**
  8541. * Delete related files of object in database
  8542. *
  8543. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  8544. * @return bool True if OK, False if KO
  8545. */
  8546. public function deleteEcmFiles($mode = 0)
  8547. {
  8548. global $conf;
  8549. $this->db->begin();
  8550. // Delete in database with mode 0
  8551. if ($mode == 0) {
  8552. switch ($this->element) {
  8553. case 'propal':
  8554. $element = 'propale';
  8555. break;
  8556. case 'product':
  8557. $element = 'produit';
  8558. break;
  8559. case 'order_supplier':
  8560. $element = 'fournisseur/commande';
  8561. break;
  8562. case 'invoice_supplier':
  8563. $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  8564. break;
  8565. case 'shipping':
  8566. $element = 'expedition/sending';
  8567. break;
  8568. default:
  8569. $element = $this->element;
  8570. }
  8571. // Delete ecm_files extrafields
  8572. $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files_extrafields WHERE fk_object IN (";
  8573. $sql .= " SELECT rowid FROM ".MAIN_DB_PREFIX."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8574. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  8575. $sql .= ")";
  8576. if (!$this->db->query($sql)) {
  8577. $this->error = $this->db->lasterror();
  8578. $this->db->rollback();
  8579. return false;
  8580. }
  8581. // Delete ecm_files
  8582. $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files";
  8583. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8584. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  8585. if (!$this->db->query($sql)) {
  8586. $this->error = $this->db->lasterror();
  8587. $this->db->rollback();
  8588. return false;
  8589. }
  8590. }
  8591. // Delete in database with mode 1
  8592. if ($mode == 1) {
  8593. $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files_extrafields";
  8594. $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).")";
  8595. $resql = $this->db->query($sql);
  8596. if (!$resql) {
  8597. $this->error = $this->db->lasterror();
  8598. $this->db->rollback();
  8599. return false;
  8600. }
  8601. $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files";
  8602. $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
  8603. $resql = $this->db->query($sql);
  8604. if (!$resql) {
  8605. $this->error = $this->db->lasterror();
  8606. $this->db->rollback();
  8607. return false;
  8608. }
  8609. }
  8610. $this->db->commit();
  8611. return true;
  8612. }
  8613. }