commonobject.class.php 338 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811
  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-2022 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. * Copyright (C) 2021 Grégory Blémand <gregory.blemand@atm-consulting.fr>
  19. *
  20. * This program is free software; you can redistribute it and/or modify
  21. * it under the terms of the GNU General Public License as published by
  22. * the Free Software Foundation; either version 3 of the License, or
  23. * (at your option) any later version.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU General Public License
  31. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  32. */
  33. /**
  34. * \file htdocs/core/class/commonobject.class.php
  35. * \ingroup core
  36. * \brief File of parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  37. */
  38. /**
  39. * Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  40. */
  41. abstract class CommonObject
  42. {
  43. const TRIGGER_PREFIX = ''; // to be overriden in child class implementations, i.e. 'BILL', 'TASK', 'PROPAL', etc.
  44. /**
  45. * @var DoliDb Database handler (result of a new DoliDB)
  46. */
  47. public $db;
  48. /**
  49. * @var int The object identifier
  50. */
  51. public $id;
  52. /**
  53. * @var int The environment ID when using a multicompany module
  54. */
  55. public $entity;
  56. /**
  57. * @var string Error string
  58. * @see $errors
  59. */
  60. public $error;
  61. /**
  62. * @var string Error string that is hidden but can be used to store complementatry technical code.
  63. */
  64. public $errorhidden;
  65. /**
  66. * @var string[] Array of error strings
  67. */
  68. public $errors = array();
  69. /**
  70. * @var array To store error results of ->validateField()
  71. */
  72. public $validateFieldsErrors = array();
  73. /**
  74. * @var string ID to identify managed object
  75. */
  76. public $element;
  77. /**
  78. * @var string Name to use for 'features' parameter to check module permissions with restrictedArea(). Undefined means same value than $element.
  79. */
  80. public $element_for_permission;
  81. /**
  82. * @var string Name of table without prefix where object is stored
  83. */
  84. public $table_element;
  85. /**
  86. * @var string Name of subtable line
  87. */
  88. public $table_element_line = '';
  89. /**
  90. * @var string Key value used to track if data is coming from import wizard
  91. */
  92. public $import_key;
  93. /**
  94. * @var mixed Contains data to manage extrafields
  95. */
  96. public $array_options = array();
  97. /**
  98. * @var mixed Array to store alternative languages values of object
  99. */
  100. public $array_languages = null; // Value is array() when load already tried
  101. /**
  102. * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked
  103. */
  104. public $linkedObjectsIds;
  105. /**
  106. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  107. */
  108. public $linkedObjects;
  109. /**
  110. * @var boolean is linkedObjects full loaded. Loaded by ->fetchObjectLinked
  111. * important for pdf generation time reduction
  112. */
  113. public $linkedObjectsFullLoaded = false;
  114. /**
  115. * @var Object To store a cloned copy of object before to edit it and keep track of old properties
  116. */
  117. public $oldcopy;
  118. /**
  119. * @var string Column name of the ref field.
  120. */
  121. protected $table_ref_field = '';
  122. /**
  123. * @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
  124. */
  125. public $restrictiononfksoc = 0;
  126. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  127. /**
  128. * @var array<string,mixed> Can be used to pass information when only object is provided to method
  129. */
  130. public $context = array();
  131. /**
  132. * @var string Contains canvas name if record is an alternative canvas record
  133. */
  134. public $canvas;
  135. /**
  136. * @var Project The related project
  137. * @see fetch_projet()
  138. */
  139. public $project;
  140. /**
  141. * @var int The related project ID
  142. * @see setProject(), project
  143. */
  144. public $fk_project;
  145. /**
  146. * @deprecated
  147. * @see project
  148. */
  149. public $projet;
  150. /**
  151. * @var Contact a related contact
  152. * @see fetch_contact()
  153. */
  154. public $contact;
  155. /**
  156. * @var int The related contact ID
  157. * @see fetch_contact()
  158. */
  159. public $contact_id;
  160. /**
  161. * @var Societe A related thirdparty
  162. * @see fetch_thirdparty()
  163. */
  164. public $thirdparty;
  165. /**
  166. * @var User A related user
  167. * @see fetch_user()
  168. */
  169. public $user;
  170. /**
  171. * @var string The type of originating object ('commande', 'facture', ...)
  172. * @see fetch_origin()
  173. */
  174. public $origin;
  175. /**
  176. * @var int The id of originating object
  177. * @see fetch_origin()
  178. */
  179. public $origin_id;
  180. /**
  181. * @var string The object's reference
  182. */
  183. public $ref;
  184. /**
  185. * @var string An external reference for the object
  186. */
  187. public $ref_ext;
  188. /**
  189. * @var string The object's previous reference
  190. */
  191. public $ref_previous;
  192. /**
  193. * @var string The object's next reference
  194. */
  195. public $ref_next;
  196. /**
  197. * @var string Ref to store on object to save the new ref to use for example when making a validate() of an object
  198. */
  199. public $newref;
  200. /**
  201. * @var int The object's status
  202. * @see setStatut()
  203. */
  204. public $statut;
  205. /**
  206. * @var int The object's status
  207. * @see setStatut()
  208. */
  209. public $status;
  210. /**
  211. * @var string
  212. * @see getFullAddress()
  213. */
  214. public $country;
  215. /**
  216. * @var int
  217. * @see getFullAddress(), country
  218. */
  219. public $country_id;
  220. /**
  221. * @var string
  222. * @see getFullAddress(), isInEEC(), country
  223. */
  224. public $country_code;
  225. /**
  226. * @var string
  227. * @see getFullAddress()
  228. */
  229. public $state;
  230. /**
  231. * @var int
  232. * @see getFullAddress(), state
  233. */
  234. public $state_id;
  235. /**
  236. * @var string
  237. * @see getFullAddress(), $state
  238. */
  239. public $state_code;
  240. /**
  241. * @var int
  242. * @see getFullAddress(), $region_code, $region
  243. */
  244. public $region_id;
  245. /**
  246. * @var string
  247. * @see getFullAddress(), $region_id, $region
  248. */
  249. public $region_code;
  250. /**
  251. * @var string
  252. * @see getFullAddress(), $region_id, $region_code
  253. */
  254. public $region;
  255. /**
  256. * @var int
  257. * @see fetch_barcode()
  258. */
  259. public $barcode_type;
  260. /**
  261. * @var string
  262. * @see fetch_barcode(), barcode_type
  263. */
  264. public $barcode_type_code;
  265. /**
  266. * @var string
  267. * @see fetch_barcode(), barcode_type
  268. */
  269. public $barcode_type_label;
  270. /**
  271. * @var string
  272. * @see fetch_barcode(), barcode_type
  273. */
  274. public $barcode_type_coder;
  275. /**
  276. * @var int Payment method ID (cheque, cash, ...)
  277. * @see setPaymentMethods()
  278. */
  279. public $mode_reglement_id;
  280. /**
  281. * @var int Payment terms ID
  282. * @see setPaymentTerms()
  283. */
  284. public $cond_reglement_id;
  285. /**
  286. * @var int Demand reason ID
  287. */
  288. public $demand_reason_id;
  289. /**
  290. * @var int Transport mode ID (For module intracomm report)
  291. * @see setTransportMode()
  292. */
  293. public $transport_mode_id;
  294. /**
  295. * @var int Payment terms ID
  296. * @deprecated Kept for compatibility
  297. * @see cond_reglement_id;
  298. */
  299. public $cond_reglement;
  300. /**
  301. * @var int Delivery address ID
  302. * @see setDeliveryAddress()
  303. * @deprecated
  304. */
  305. public $fk_delivery_address;
  306. /**
  307. * @var int Shipping method ID
  308. * @see setShippingMethod()
  309. */
  310. public $shipping_method_id;
  311. /**
  312. * @var string
  313. * @see SetDocModel()
  314. */
  315. public $model_pdf;
  316. /**
  317. * @var string
  318. * @deprecated
  319. * @see $model_pdf
  320. */
  321. public $modelpdf;
  322. /**
  323. * @var string
  324. * Contains relative path of last generated main file
  325. */
  326. public $last_main_doc;
  327. /**
  328. * @var int Bank account ID sometimes, ID of record into llx_bank sometimes
  329. * @deprecated
  330. * @see $fk_account
  331. */
  332. public $fk_bank;
  333. /**
  334. * @var int Bank account ID
  335. * @see SetBankAccount()
  336. */
  337. public $fk_account;
  338. /**
  339. * @var string Open ID
  340. */
  341. public $openid;
  342. /**
  343. * @var string Public note
  344. * @see update_note()
  345. */
  346. public $note_public;
  347. /**
  348. * @var string Private note
  349. * @see update_note()
  350. */
  351. public $note_private;
  352. /**
  353. * @deprecated
  354. * @see $note_private
  355. */
  356. public $note;
  357. /**
  358. * @var float Total amount before taxes
  359. * @see update_price()
  360. */
  361. public $total_ht;
  362. /**
  363. * @var float Total VAT amount
  364. * @see update_price()
  365. */
  366. public $total_tva;
  367. /**
  368. * @var float Total local tax 1 amount
  369. * @see update_price()
  370. */
  371. public $total_localtax1;
  372. /**
  373. * @var float Total local tax 2 amount
  374. * @see update_price()
  375. */
  376. public $total_localtax2;
  377. /**
  378. * @var float Total amount with taxes
  379. * @see update_price()
  380. */
  381. public $total_ttc;
  382. /**
  383. * @var CommonObjectLine[]
  384. */
  385. public $lines;
  386. /**
  387. * @var mixed Contains comments
  388. * @see fetchComments()
  389. */
  390. public $comments = array();
  391. /**
  392. * @var string The name
  393. */
  394. public $name;
  395. /**
  396. * @var string The lastname
  397. */
  398. public $lastname;
  399. /**
  400. * @var string The firstname
  401. */
  402. public $firstname;
  403. /**
  404. * @var string The civility code, not an integer
  405. */
  406. public $civility_id;
  407. // Dates
  408. /**
  409. * @var integer|string date_creation
  410. */
  411. public $date_creation;
  412. /**
  413. * @var integer|string $date_validation;
  414. */
  415. public $date_validation; // Date validation
  416. /**
  417. * @var integer|string $date_modification;
  418. */
  419. public $date_modification; // Date last change (tms field)
  420. public $next_prev_filter;
  421. /**
  422. * @var int 1 if object is specimen
  423. */
  424. public $specimen = 0;
  425. /**
  426. * @var int Id of contact to send object (used by the trigger of module Agenda)
  427. */
  428. public $sendtoid;
  429. /**
  430. * @var float Amount already paid (used to show correct status)
  431. */
  432. public $alreadypaid;
  433. /**
  434. * @var array List of child tables. To test if we can delete object.
  435. */
  436. protected $childtables = array();
  437. /**
  438. * @var array List of child tables. To know object to delete on cascade.
  439. * If name is like '@ClassName:FilePathClass:ParentFkFieldName', it will
  440. * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object.
  441. */
  442. protected $childtablesoncascade = array();
  443. // No constructor as it is an abstract class
  444. /**
  445. * Check an object id/ref exists
  446. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  447. *
  448. * @param string $element String of element ('product', 'facture', ...)
  449. * @param int $id Id of object
  450. * @param string $ref Ref of object to check
  451. * @param string $ref_ext Ref ext of object to check
  452. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  453. */
  454. public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
  455. {
  456. global $db, $conf;
  457. $sql = "SELECT rowid, ref, ref_ext";
  458. $sql .= " FROM ".$db->prefix().$element;
  459. $sql .= " WHERE entity IN (".getEntity($element).")";
  460. if ($id > 0) {
  461. $sql .= " AND rowid = ".((int) $id);
  462. } elseif ($ref) {
  463. $sql .= " AND ref = '".$db->escape($ref)."'";
  464. } elseif ($ref_ext) {
  465. $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
  466. } else {
  467. $error = 'ErrorWrongParameters';
  468. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  469. return -1;
  470. }
  471. if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
  472. $sql .= " AND entity = ".((int) $conf->entity);
  473. }
  474. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  475. $resql = $db->query($sql);
  476. if ($resql) {
  477. $num = $db->num_rows($resql);
  478. if ($num > 0) {
  479. return 1;
  480. } else {
  481. return 0;
  482. }
  483. }
  484. return -1;
  485. }
  486. /**
  487. * Method to output saved errors
  488. *
  489. * @return string String with errors
  490. */
  491. public function errorsToString()
  492. {
  493. return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
  494. }
  495. /**
  496. * Return customer ref for screen output.
  497. *
  498. * @param string $objref Customer ref
  499. * @return string Customer ref formated
  500. */
  501. public function getFormatedCustomerRef($objref)
  502. {
  503. global $hookmanager;
  504. $parameters = array('objref'=>$objref);
  505. $action = '';
  506. $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  507. if ($reshook > 0) {
  508. return $hookmanager->resArray['objref'];
  509. }
  510. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  511. }
  512. /**
  513. * Return supplier ref for screen output.
  514. *
  515. * @param string $objref Supplier ref
  516. * @return string Supplier ref formated
  517. */
  518. public function getFormatedSupplierRef($objref)
  519. {
  520. global $hookmanager;
  521. $parameters = array('objref'=>$objref);
  522. $action = '';
  523. $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  524. if ($reshook > 0) {
  525. return $hookmanager->resArray['objref'];
  526. }
  527. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  528. }
  529. /**
  530. * Return full name (civility+' '+name+' '+lastname)
  531. *
  532. * @param Translate $langs Language object for translation of civility (used only if option is 1)
  533. * @param int $option 0=No option, 1=Add civility
  534. * @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
  535. * @param int $maxlen Maximum length
  536. * @return string String with full name
  537. */
  538. public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
  539. {
  540. //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
  541. $lastname = $this->lastname;
  542. $firstname = $this->firstname;
  543. if (empty($lastname)) {
  544. $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 : '')))));
  545. }
  546. $ret = '';
  547. if (!empty($option) && !empty($this->civility_code)) {
  548. if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) {
  549. $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
  550. } else {
  551. $ret .= $this->civility_code.' ';
  552. }
  553. }
  554. $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
  555. return dol_trunc($ret, $maxlen);
  556. }
  557. /**
  558. * Set to upper or ucwords/lower if needed
  559. *
  560. * @return void;
  561. */
  562. public function setUpperOrLowerCase()
  563. {
  564. global $conf;
  565. if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
  566. $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
  567. $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
  568. $this->name = dol_ucwords(dol_strtolower($this->name));
  569. $this->name_alias = dol_ucwords(dol_strtolower($this->name_alias));
  570. }
  571. if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
  572. $this->lastname = dol_strtoupper($this->lastname);
  573. $this->name = dol_strtoupper($this->name);
  574. $this->name_alias = dol_strtoupper($this->name_alias);
  575. }
  576. if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
  577. $this->address = dol_strtoupper($this->address);
  578. $this->town = dol_strtoupper($this->town);
  579. }
  580. }
  581. /**
  582. * Return clicable link of object (with eventually picto)
  583. *
  584. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  585. * @return string HTML Code for Kanban thumb.
  586. */
  587. public function getKanbanView($option = '')
  588. {
  589. $return = '<div class="box-flex-item box-flex-grow-zero">';
  590. $return .= '<div class="info-box info-box-sm">';
  591. $return .= '<span class="info-box-icon bg-infobox-action">';
  592. $return .= img_picto('', $this->picto);
  593. //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
  594. $return .= '</span>';
  595. $return .= '<div class="info-box-content">';
  596. $return .= '<span class="info-box-ref">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  597. if (property_exists($this, 'label')) {
  598. $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
  599. }
  600. if (method_exists($this, 'getLibStatut')) {
  601. $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(5).'</div>';
  602. }
  603. $return .= '</div>';
  604. $return .= '</div>';
  605. $return .= '</div>';
  606. return $return;
  607. }
  608. /**
  609. * Return full address of contact
  610. *
  611. * @param int $withcountry 1=Add country into address string
  612. * @param string $sep Separator to use to build string
  613. * @param int $withregion 1=Add region into address string
  614. * @param string $extralangcode User extralanguages as value
  615. * @return string Full address string
  616. */
  617. public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
  618. {
  619. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
  620. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  621. $tmparray = getCountry($this->country_id, 'all');
  622. $this->country_code = $tmparray['code'];
  623. $this->country = $tmparray['label'];
  624. }
  625. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
  626. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  627. $tmparray = getState($this->state_id, 'all', 0, 1);
  628. $this->state_code = $tmparray['code'];
  629. $this->state = $tmparray['label'];
  630. $this->region_code = $tmparray['region_code'];
  631. $this->region = $tmparray['region'];
  632. }
  633. return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
  634. }
  635. /**
  636. * Return full address for banner
  637. *
  638. * @param string $htmlkey HTML id to make banner content unique
  639. * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member)
  640. * @return string Full address string
  641. */
  642. public function getBannerAddress($htmlkey, $object)
  643. {
  644. global $conf, $langs, $form, $extralanguages;
  645. $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
  646. $contactid = 0;
  647. $thirdpartyid = 0;
  648. $elementforaltlanguage = $this->element;
  649. if ($this->element == 'societe') {
  650. $thirdpartyid = $this->id;
  651. }
  652. if ($this->element == 'contact') {
  653. $contactid = $this->id;
  654. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  655. }
  656. if ($this->element == 'user') {
  657. $contactid = $this->contact_id;
  658. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  659. }
  660. $out = '';
  661. $outdone = 0;
  662. $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
  663. if ($coords) {
  664. if (!empty($conf->use_javascript_ajax)) {
  665. // Add picto with tooltip on map
  666. $namecoords = '';
  667. if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
  668. $namecoords .= $object->name.'<br>';
  669. }
  670. $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
  671. // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
  672. $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
  673. $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
  674. $out .= '</a> ';
  675. }
  676. $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  677. $outdone++;
  678. $outdone++;
  679. // List of extra languages
  680. $arrayoflangcode = array();
  681. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  682. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  683. }
  684. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  685. if (!is_object($extralanguages)) {
  686. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  687. $extralanguages = new ExtraLanguages($this->db);
  688. }
  689. $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
  690. if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
  691. $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
  692. $this->fetchValuesForExtraLanguages();
  693. if (!is_object($form)) {
  694. $form = new Form($this->db);
  695. }
  696. $htmltext = '';
  697. // If there is extra languages
  698. foreach ($arrayoflangcode as $extralangcode) {
  699. $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  700. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
  701. $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  702. }
  703. $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  704. }
  705. }
  706. }
  707. 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
  708. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
  709. if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
  710. $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
  711. } else {
  712. $out .= ($outdone ? ' - ' : '').$this->state;
  713. }
  714. $outdone++;
  715. }
  716. 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)) {
  717. $out .= ($outdone ? '<br>' : '');
  718. }
  719. if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  720. $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  721. $outdone++;
  722. }
  723. if (!empty($this->phone_pro)) {
  724. $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  725. $outdone++;
  726. }
  727. if (!empty($this->phone_mobile)) {
  728. $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  729. $outdone++;
  730. }
  731. if (!empty($this->phone_perso)) {
  732. $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
  733. $outdone++;
  734. }
  735. if (!empty($this->office_phone)) {
  736. $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  737. $outdone++;
  738. }
  739. if (!empty($this->user_mobile)) {
  740. $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  741. $outdone++;
  742. }
  743. if (!empty($this->fax)) {
  744. $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  745. $outdone++;
  746. }
  747. if (!empty($this->office_fax)) {
  748. $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  749. $outdone++;
  750. }
  751. if ($out) {
  752. $out .= '<div style="clear: both;"></div>';
  753. }
  754. $outdone = 0;
  755. if (!empty($this->email)) {
  756. $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
  757. $outdone++;
  758. }
  759. if (!empty($this->url)) {
  760. //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
  761. $out .= dol_print_url($this->url, '_blank', 0, 1);
  762. $outdone++;
  763. }
  764. if (!empty($conf->socialnetworks->enabled)) {
  765. $outsocialnetwork = '';
  766. if (!empty($this->socialnetworks) && is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
  767. $socialnetworksdict = getArrayOfSocialNetworks();
  768. foreach ($this->socialnetworks as $key => $value) {
  769. if ($value) {
  770. $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
  771. }
  772. $outdone++;
  773. }
  774. } else { // Old code to remove
  775. if (!empty($this->skype)) {
  776. $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
  777. }
  778. $outdone++;
  779. if (!empty($this->jabberid)) {
  780. $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
  781. }
  782. $outdone++;
  783. if (!empty($this->twitter)) {
  784. $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
  785. }
  786. $outdone++;
  787. if (!empty($this->facebook)) {
  788. $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
  789. }
  790. $outdone++;
  791. if (!empty($this->linkedin)) {
  792. $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
  793. }
  794. $outdone++;
  795. }
  796. if ($outsocialnetwork) {
  797. $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
  798. }
  799. }
  800. if ($out) {
  801. return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
  802. } else {
  803. return '';
  804. }
  805. }
  806. /**
  807. * Return the link of last main doc file for direct public download.
  808. *
  809. * @param string $modulepart Module related to document
  810. * @param int $initsharekey Init the share key if it was not yet defined
  811. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  812. * @return string Link or empty string if there is no download link
  813. */
  814. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  815. {
  816. global $user, $dolibarr_main_url_root;
  817. if (empty($this->last_main_doc)) {
  818. return ''; // No way to known which document name to use
  819. }
  820. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  821. $ecmfile = new EcmFiles($this->db);
  822. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  823. if ($result < 0) {
  824. $this->error = $ecmfile->error;
  825. $this->errors = $ecmfile->errors;
  826. return -1;
  827. }
  828. if (empty($ecmfile->id)) {
  829. // Add entry into index
  830. if ($initsharekey) {
  831. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  832. // TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first
  833. /*
  834. $ecmfile->filepath = $rel_dir;
  835. $ecmfile->filename = $filename;
  836. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  837. $ecmfile->fullpath_orig = '';
  838. $ecmfile->gen_or_uploaded = 'generated';
  839. $ecmfile->description = ''; // indexed content
  840. $ecmfile->keywords = ''; // keyword content
  841. $ecmfile->share = getRandomPassword(true);
  842. $result = $ecmfile->create($user);
  843. if ($result < 0)
  844. {
  845. $this->error = $ecmfile->error;
  846. $this->errors = $ecmfile->errors;
  847. }
  848. */
  849. } else {
  850. return '';
  851. }
  852. } elseif (empty($ecmfile->share)) {
  853. // Add entry into index
  854. if ($initsharekey) {
  855. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  856. $ecmfile->share = getRandomPassword(true);
  857. $ecmfile->update($user);
  858. } else {
  859. return '';
  860. }
  861. }
  862. // Define $urlwithroot
  863. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  864. // This is to use external domain name found into config file
  865. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  866. //else
  867. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  868. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  869. $forcedownload = 0;
  870. $paramlink = '';
  871. //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  872. //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  873. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  874. if (!empty($ecmfile->share)) {
  875. $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
  876. }
  877. if ($forcedownload) {
  878. $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  879. }
  880. if ($relativelink) {
  881. $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
  882. } else {
  883. $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  884. }
  885. // Here $ecmfile->share is defined
  886. return $linktoreturn;
  887. }
  888. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  889. /**
  890. * Add a link between element $this->element and a contact
  891. *
  892. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  893. * @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
  894. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  895. * @param int $notrigger Disable all triggers
  896. * @return int <0 if KO, 0 if already added, >0 if OK
  897. */
  898. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  899. {
  900. // phpcs:enable
  901. global $user, $langs;
  902. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  903. // Check parameters
  904. if ($fk_socpeople <= 0) {
  905. $langs->load("errors");
  906. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  907. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  908. return -1;
  909. }
  910. if (!$type_contact) {
  911. $langs->load("errors");
  912. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  913. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  914. return -2;
  915. }
  916. $id_type_contact = 0;
  917. if (is_numeric($type_contact)) {
  918. $id_type_contact = $type_contact;
  919. } else {
  920. // We look for id type_contact
  921. $sql = "SELECT tc.rowid";
  922. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  923. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  924. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  925. $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  926. //print $sql;
  927. $resql = $this->db->query($sql);
  928. if ($resql) {
  929. $obj = $this->db->fetch_object($resql);
  930. if ($obj) {
  931. $id_type_contact = $obj->rowid;
  932. }
  933. }
  934. }
  935. if ($id_type_contact == 0) {
  936. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  937. 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");
  938. return -3;
  939. }
  940. $datecreate = dol_now();
  941. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  942. $TListeContacts = $this->liste_contact(-1, $source);
  943. $already_added = false;
  944. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  945. foreach ($TListeContacts as $array_contact) {
  946. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  947. $already_added = true;
  948. break;
  949. }
  950. }
  951. }
  952. if (!$already_added) {
  953. $this->db->begin();
  954. // Insert into database
  955. $sql = "INSERT INTO ".$this->db->prefix()."element_contact";
  956. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  957. $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
  958. $sql .= "'".$this->db->idate($datecreate)."'";
  959. $sql .= ", 4, ".((int) $id_type_contact);
  960. $sql .= ")";
  961. $resql = $this->db->query($sql);
  962. if ($resql) {
  963. if (!$notrigger) {
  964. $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  965. if ($result < 0) {
  966. $this->db->rollback();
  967. return -1;
  968. }
  969. }
  970. $this->db->commit();
  971. return 1;
  972. } else {
  973. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  974. $this->error = $this->db->errno();
  975. $this->db->rollback();
  976. return -2;
  977. } else {
  978. $this->error = $this->db->lasterror();
  979. $this->db->rollback();
  980. return -1;
  981. }
  982. }
  983. } else {
  984. return 0;
  985. }
  986. }
  987. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  988. /**
  989. * Copy contact from one element to current
  990. *
  991. * @param CommonObject $objFrom Source element
  992. * @param string $source Nature of contact ('internal' or 'external')
  993. * @return int >0 if OK, <0 if KO
  994. */
  995. public function copy_linked_contact($objFrom, $source = 'internal')
  996. {
  997. // phpcs:enable
  998. $contacts = $objFrom->liste_contact(-1, $source);
  999. foreach ($contacts as $contact) {
  1000. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
  1001. return -1;
  1002. }
  1003. }
  1004. return 1;
  1005. }
  1006. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1007. /**
  1008. * Update a link to contact line
  1009. *
  1010. * @param int $rowid Id of line contact-element
  1011. * @param int $statut New status of link
  1012. * @param int $type_contact_id Id of contact type (not modified if 0)
  1013. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  1014. * @return int <0 if KO, >= 0 if OK
  1015. */
  1016. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  1017. {
  1018. // phpcs:enable
  1019. // Insert into database
  1020. $sql = "UPDATE ".$this->db->prefix()."element_contact set";
  1021. $sql .= " statut = ".$statut;
  1022. if ($type_contact_id) {
  1023. $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
  1024. }
  1025. if ($fk_socpeople) {
  1026. $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
  1027. }
  1028. $sql .= " where rowid = ".((int) $rowid);
  1029. $resql = $this->db->query($sql);
  1030. if ($resql) {
  1031. return 0;
  1032. } else {
  1033. $this->error = $this->db->lasterror();
  1034. return -1;
  1035. }
  1036. }
  1037. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1038. /**
  1039. * Delete a link to contact line
  1040. *
  1041. * @param int $rowid Id of contact link line to delete
  1042. * @param int $notrigger Disable all triggers
  1043. * @return int >0 if OK, <0 if KO
  1044. */
  1045. public function delete_contact($rowid, $notrigger = 0)
  1046. {
  1047. // phpcs:enable
  1048. global $user;
  1049. $this->db->begin();
  1050. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1051. $sql .= " WHERE rowid = ".((int) $rowid);
  1052. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  1053. if ($this->db->query($sql)) {
  1054. if (!$notrigger) {
  1055. $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  1056. if ($result < 0) {
  1057. $this->db->rollback();
  1058. return -1;
  1059. }
  1060. }
  1061. $this->db->commit();
  1062. return 1;
  1063. } else {
  1064. $this->error = $this->db->lasterror();
  1065. $this->db->rollback();
  1066. return -1;
  1067. }
  1068. }
  1069. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1070. /**
  1071. * Delete all links between an object $this and all its contacts
  1072. *
  1073. * @param string $source '' or 'internal' or 'external'
  1074. * @param string $code Type of contact (code or id)
  1075. * @return int >0 if OK, <0 if KO
  1076. */
  1077. public function delete_linked_contact($source = '', $code = '')
  1078. {
  1079. // phpcs:enable
  1080. $listId = '';
  1081. $temp = array();
  1082. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  1083. if (!empty($typeContact)) {
  1084. foreach ($typeContact as $key => $value) {
  1085. array_push($temp, $key);
  1086. }
  1087. $listId = implode(",", $temp);
  1088. }
  1089. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1090. $sql .= " WHERE element_id = ".((int) $this->id);
  1091. if (!empty($listId)) {
  1092. $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
  1093. }
  1094. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  1095. if ($this->db->query($sql)) {
  1096. return 1;
  1097. } else {
  1098. $this->error = $this->db->lasterror();
  1099. return -1;
  1100. }
  1101. }
  1102. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1103. /**
  1104. * Get array of all contacts for an object
  1105. *
  1106. * @param int $status Status of links to get (-1=all)
  1107. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  1108. * @param int $list 0:Return array contains all properties, 1:Return array contains just id
  1109. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1110. * @return array|int Array of contacts, -1 if error
  1111. */
  1112. public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
  1113. {
  1114. // phpcs:enable
  1115. global $langs;
  1116. $tab = array();
  1117. $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
  1118. if ($source == 'internal') {
  1119. $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  1120. }
  1121. if ($source == 'external' || $source == 'thirdparty') {
  1122. $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1123. }
  1124. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  1125. $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
  1126. $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
  1127. $sql .= ", ".$this->db->prefix()."element_contact ec";
  1128. if ($source == 'internal') {
  1129. $sql .= " LEFT JOIN ".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid";
  1130. }
  1131. if ($source == 'external' || $source == 'thirdparty') {
  1132. $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid";
  1133. }
  1134. $sql .= " WHERE ec.element_id = ".((int) $this->id);
  1135. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1136. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1137. if ($code) {
  1138. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1139. }
  1140. if ($source == 'internal') {
  1141. $sql .= " AND tc.source = 'internal'";
  1142. }
  1143. if ($source == 'external' || $source == 'thirdparty') {
  1144. $sql .= " AND tc.source = 'external'";
  1145. }
  1146. $sql .= " AND tc.active=1";
  1147. if ($status >= 0) {
  1148. $sql .= " AND ec.statut = ".((int) $status);
  1149. }
  1150. $sql .= " ORDER BY t.lastname ASC";
  1151. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  1152. $resql = $this->db->query($sql);
  1153. if ($resql) {
  1154. $num = $this->db->num_rows($resql);
  1155. $i = 0;
  1156. while ($i < $num) {
  1157. $obj = $this->db->fetch_object($resql);
  1158. if (!$list) {
  1159. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1160. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1161. $tab[$i] = array(
  1162. 'source' => $obj->source,
  1163. 'socid' => $obj->socid,
  1164. 'id' => $obj->id,
  1165. 'nom' => $obj->lastname, // For backward compatibility
  1166. 'civility' => $obj->civility,
  1167. 'lastname' => $obj->lastname,
  1168. 'firstname' => $obj->firstname,
  1169. 'email'=>$obj->email,
  1170. 'login'=> (empty($obj->login) ? '' : $obj->login),
  1171. 'photo' => (empty($obj->photo) ? '' : $obj->photo),
  1172. 'statuscontact' => $obj->statuscontact,
  1173. 'rowid' => $obj->rowid,
  1174. 'code' => $obj->code,
  1175. 'libelle' => $libelle_type,
  1176. 'status' => $obj->statuslink,
  1177. 'fk_c_type_contact' => $obj->fk_c_type_contact
  1178. );
  1179. } else {
  1180. $tab[$i] = $obj->id;
  1181. }
  1182. $i++;
  1183. }
  1184. return $tab;
  1185. } else {
  1186. $this->error = $this->db->lasterror();
  1187. dol_print_error($this->db);
  1188. return -1;
  1189. }
  1190. }
  1191. /**
  1192. * Update status of a contact linked to object
  1193. *
  1194. * @param int $rowid Id of link between object and contact
  1195. * @return int <0 if KO, >=0 if OK
  1196. */
  1197. public function swapContactStatus($rowid)
  1198. {
  1199. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1200. $sql .= " tc.code, tc.libelle";
  1201. $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
  1202. $sql .= " WHERE ec.rowid =".((int) $rowid);
  1203. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1204. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1205. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  1206. $resql = $this->db->query($sql);
  1207. if ($resql) {
  1208. $obj = $this->db->fetch_object($resql);
  1209. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1210. $result = $this->update_contact($rowid, $newstatut);
  1211. $this->db->free($resql);
  1212. return $result;
  1213. } else {
  1214. $this->error = $this->db->error();
  1215. dol_print_error($this->db);
  1216. return -1;
  1217. }
  1218. }
  1219. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1220. /**
  1221. * Return array with list of possible values for type of contacts
  1222. *
  1223. * @param string $source 'internal', 'external' or 'all'
  1224. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  1225. * @param int $option 0=Return array id->label, 1=Return array code->label
  1226. * @param int $activeonly 0=all status of contact, 1=only the active
  1227. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1228. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1229. */
  1230. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1231. {
  1232. // phpcs:enable
  1233. global $langs;
  1234. if (empty($order)) {
  1235. $order = 'position';
  1236. }
  1237. if ($order == 'position') {
  1238. $order .= ',code';
  1239. }
  1240. $tab = array();
  1241. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  1242. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1243. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1244. if ($activeonly == 1) {
  1245. $sql .= " AND tc.active=1"; // only the active types
  1246. }
  1247. if (!empty($source) && $source != 'all') {
  1248. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1249. }
  1250. if (!empty($code)) {
  1251. $sql .= " AND tc.code='".$this->db->escape($code)."'";
  1252. }
  1253. $sql .= $this->db->order($order, 'ASC');
  1254. //print "sql=".$sql;
  1255. $resql = $this->db->query($sql);
  1256. if ($resql) {
  1257. $num = $this->db->num_rows($resql);
  1258. $i = 0;
  1259. while ($i < $num) {
  1260. $obj = $this->db->fetch_object($resql);
  1261. $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
  1262. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1263. if (empty($option)) {
  1264. $tab[$obj->rowid] = $libelle_type;
  1265. } else {
  1266. $tab[$obj->code] = $libelle_type;
  1267. }
  1268. $i++;
  1269. }
  1270. return $tab;
  1271. } else {
  1272. $this->error = $this->db->lasterror();
  1273. //dol_print_error($this->db);
  1274. return null;
  1275. }
  1276. }
  1277. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1278. /**
  1279. * Return array with list of possible values for type of contacts
  1280. *
  1281. * @param string $source 'internal', 'external' or 'all'
  1282. * @param int $option 0=Return array id->label, 1=Return array code->label
  1283. * @param int $activeonly 0=all status of contact, 1=only the active
  1284. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1285. * @param string $element Filter on 1 element type
  1286. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1287. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1288. */
  1289. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1290. {
  1291. // phpcs:enable
  1292. global $langs, $conf;
  1293. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1294. $tab = array();
  1295. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
  1296. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1297. $sqlWhere = array();
  1298. if (!empty($element)) {
  1299. $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
  1300. }
  1301. if (!empty($excludeelement)) {
  1302. $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
  1303. }
  1304. if ($activeonly == 1) {
  1305. $sqlWhere[] = " tc.active=1"; // only the active types
  1306. }
  1307. if (!empty($source) && $source != 'all') {
  1308. $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
  1309. }
  1310. if (!empty($code)) {
  1311. $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
  1312. }
  1313. if (count($sqlWhere) > 0) {
  1314. $sql .= " WHERE ".implode(' AND ', $sqlWhere);
  1315. }
  1316. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1317. dol_syslog(__METHOD__, LOG_DEBUG);
  1318. $resql = $this->db->query($sql);
  1319. if ($resql) {
  1320. $num = $this->db->num_rows($resql);
  1321. if ($num > 0) {
  1322. $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
  1323. while ($obj = $this->db->fetch_object($resql)) {
  1324. $modulename = $obj->element;
  1325. if (strpos($obj->element, 'project') !== false) {
  1326. $modulename = 'projet';
  1327. } elseif ($obj->element == 'contrat') {
  1328. $element = 'contract';
  1329. } elseif ($obj->element == 'action') {
  1330. $modulename = 'agenda';
  1331. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1332. $modulename = 'fournisseur';
  1333. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1334. $modulename = 'fournisseur';
  1335. }
  1336. if (!empty($conf->{$modulename}->enabled)) {
  1337. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1338. $tmpelement = $obj->element;
  1339. $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
  1340. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1341. if (empty($option)) {
  1342. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1343. } else {
  1344. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1345. }
  1346. }
  1347. }
  1348. }
  1349. return $tab;
  1350. } else {
  1351. $this->error = $this->db->lasterror();
  1352. return null;
  1353. }
  1354. }
  1355. /**
  1356. * Return id of contacts for a source and a contact code.
  1357. * Example: contact client de facturation ('external', 'BILLING')
  1358. * Example: contact client de livraison ('external', 'SHIPPING')
  1359. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1360. *
  1361. * @param string $source 'external' or 'internal'
  1362. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1363. * @param int $status limited to a certain status
  1364. * @return array List of id for such contacts
  1365. */
  1366. public function getIdContact($source, $code, $status = 0)
  1367. {
  1368. global $conf;
  1369. $result = array();
  1370. $i = 0;
  1371. //cas particulier pour les expeditions
  1372. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1373. $id = $this->origin_id;
  1374. $element = 'commande';
  1375. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1376. $id = $this->origin_id;
  1377. $element = 'order_supplier';
  1378. } else {
  1379. $id = $this->id;
  1380. $element = $this->element;
  1381. }
  1382. $sql = "SELECT ec.fk_socpeople";
  1383. $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
  1384. if ($source == 'internal') {
  1385. $sql .= " ".$this->db->prefix()."user as c,";
  1386. }
  1387. if ($source == 'external') {
  1388. $sql .= " ".$this->db->prefix()."socpeople as c,";
  1389. }
  1390. $sql .= " ".$this->db->prefix()."c_type_contact as tc";
  1391. $sql .= " WHERE ec.element_id = ".((int) $id);
  1392. $sql .= " AND ec.fk_socpeople = c.rowid";
  1393. if ($source == 'internal') {
  1394. $sql .= " AND c.entity IN (".getEntity('user').")";
  1395. }
  1396. if ($source == 'external') {
  1397. $sql .= " AND c.entity IN (".getEntity('societe').")";
  1398. }
  1399. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1400. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1401. $sql .= " AND tc.source = '".$this->db->escape($source)."'";
  1402. if ($code) {
  1403. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1404. }
  1405. $sql .= " AND tc.active = 1";
  1406. if ($status) {
  1407. $sql .= " AND ec.statut = ".((int) $status);
  1408. }
  1409. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1410. $resql = $this->db->query($sql);
  1411. if ($resql) {
  1412. while ($obj = $this->db->fetch_object($resql)) {
  1413. $result[$i] = $obj->fk_socpeople;
  1414. $i++;
  1415. }
  1416. } else {
  1417. $this->error = $this->db->error();
  1418. return null;
  1419. }
  1420. return $result;
  1421. }
  1422. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1423. /**
  1424. * Load object contact with id=$this->contact_id into $this->contact
  1425. *
  1426. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1427. * @return int <0 if KO, >0 if OK
  1428. */
  1429. public function fetch_contact($contactid = null)
  1430. {
  1431. // phpcs:enable
  1432. if (empty($contactid)) {
  1433. $contactid = $this->contact_id;
  1434. }
  1435. if (empty($contactid)) {
  1436. return 0;
  1437. }
  1438. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1439. $contact = new Contact($this->db);
  1440. $result = $contact->fetch($contactid);
  1441. $this->contact = $contact;
  1442. return $result;
  1443. }
  1444. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1445. /**
  1446. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1447. *
  1448. * @param int $force_thirdparty_id Force thirdparty id
  1449. * @return int <0 if KO, >0 if OK
  1450. */
  1451. public function fetch_thirdparty($force_thirdparty_id = 0)
  1452. {
  1453. // phpcs:enable
  1454. global $conf;
  1455. if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) {
  1456. return 0;
  1457. }
  1458. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1459. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
  1460. if ($force_thirdparty_id) {
  1461. $idtofetch = $force_thirdparty_id;
  1462. }
  1463. if ($idtofetch) {
  1464. $thirdparty = new Societe($this->db);
  1465. $result = $thirdparty->fetch($idtofetch);
  1466. if ($result<0) {
  1467. $this->errors=array_merge($this->errors, $thirdparty->errors);
  1468. }
  1469. $this->thirdparty = $thirdparty;
  1470. // Use first price level if level not defined for third party
  1471. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1472. $this->thirdparty->price_level = 1;
  1473. }
  1474. return $result;
  1475. } else {
  1476. return -1;
  1477. }
  1478. }
  1479. /**
  1480. * Looks for an object with ref matching the wildcard provided
  1481. * It does only work when $this->table_ref_field is set
  1482. *
  1483. * @param string $ref Wildcard
  1484. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1485. */
  1486. public function fetchOneLike($ref)
  1487. {
  1488. if (!$this->table_ref_field) {
  1489. return 0;
  1490. }
  1491. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element." WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."' LIMIT 1";
  1492. $query = $this->db->query($sql);
  1493. if (!$this->db->num_rows($query)) {
  1494. return 0;
  1495. }
  1496. $result = $this->db->fetch_object($query);
  1497. return $this->fetch($result->rowid);
  1498. }
  1499. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1500. /**
  1501. * Load data for barcode into properties ->barcode_type*
  1502. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1503. * if it is not defined, ->element must be defined to know default barcode type.
  1504. *
  1505. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1506. */
  1507. public function fetch_barcode()
  1508. {
  1509. // phpcs:enable
  1510. global $conf;
  1511. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1512. $idtype = $this->barcode_type;
  1513. 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
  1514. if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
  1515. $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1516. } elseif ($this->element == 'societe') {
  1517. $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1518. } else {
  1519. dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1520. }
  1521. }
  1522. if ($idtype > 0) {
  1523. 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
  1524. $sql = "SELECT rowid, code, libelle as label, coder";
  1525. $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
  1526. $sql .= " WHERE rowid = ".((int) $idtype);
  1527. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1528. $resql = $this->db->query($sql);
  1529. if ($resql) {
  1530. $obj = $this->db->fetch_object($resql);
  1531. $this->barcode_type = $obj->rowid;
  1532. $this->barcode_type_code = $obj->code;
  1533. $this->barcode_type_label = $obj->label;
  1534. $this->barcode_type_coder = $obj->coder;
  1535. return 1;
  1536. } else {
  1537. dol_print_error($this->db);
  1538. return -1;
  1539. }
  1540. }
  1541. }
  1542. return 0;
  1543. }
  1544. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1545. /**
  1546. * Load the project with id $this->fk_project into this->project
  1547. *
  1548. * @return int <0 if KO, >=0 if OK
  1549. */
  1550. public function fetch_project()
  1551. {
  1552. // phpcs:enable
  1553. return $this->fetch_projet();
  1554. }
  1555. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1556. /**
  1557. * Load the project with id $this->fk_project into this->project
  1558. *
  1559. * @return int <0 if KO, >=0 if OK
  1560. */
  1561. public function fetch_projet()
  1562. {
  1563. // phpcs:enable
  1564. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1565. if (empty($this->fk_project) && !empty($this->fk_projet)) {
  1566. $this->fk_project = $this->fk_projet; // For backward compatibility
  1567. }
  1568. if (empty($this->fk_project)) {
  1569. return 0;
  1570. }
  1571. $project = new Project($this->db);
  1572. $result = $project->fetch($this->fk_project);
  1573. $this->projet = $project; // deprecated
  1574. $this->project = $project;
  1575. return $result;
  1576. }
  1577. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1578. /**
  1579. * Load the product with id $this->fk_product into this->product
  1580. *
  1581. * @return int <0 if KO, >=0 if OK
  1582. */
  1583. public function fetch_product()
  1584. {
  1585. // phpcs:enable
  1586. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1587. if (empty($this->fk_product)) {
  1588. return 0;
  1589. }
  1590. $product = new Product($this->db);
  1591. $result = $product->fetch($this->fk_product);
  1592. $this->product = $product;
  1593. return $result;
  1594. }
  1595. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1596. /**
  1597. * Load the user with id $userid into this->user
  1598. *
  1599. * @param int $userid Id du contact
  1600. * @return int <0 if KO, >0 if OK
  1601. */
  1602. public function fetch_user($userid)
  1603. {
  1604. // phpcs:enable
  1605. $user = new User($this->db);
  1606. $result = $user->fetch($userid);
  1607. $this->user = $user;
  1608. return $result;
  1609. }
  1610. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1611. /**
  1612. * Read linked origin object
  1613. *
  1614. * @return void
  1615. */
  1616. public function fetch_origin()
  1617. {
  1618. // phpcs:enable
  1619. if ($this->origin == 'shipping') {
  1620. $this->origin = 'expedition';
  1621. }
  1622. if ($this->origin == 'delivery') {
  1623. $this->origin = 'livraison';
  1624. }
  1625. if ($this->origin == 'order_supplier') {
  1626. $this->origin = 'commandeFournisseur';
  1627. }
  1628. $origin = $this->origin;
  1629. $classname = ucfirst($origin);
  1630. $this->$origin = new $classname($this->db);
  1631. $this->$origin->fetch($this->origin_id);
  1632. }
  1633. /**
  1634. * Load object from specific field
  1635. *
  1636. * @param string $table Table element or element line
  1637. * @param string $field Field selected
  1638. * @param string $key Import key
  1639. * @param string $element Element name
  1640. * @return int <0 if KO, >0 if OK
  1641. */
  1642. public function fetchObjectFrom($table, $field, $key, $element = null)
  1643. {
  1644. global $conf;
  1645. $result = false;
  1646. $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
  1647. $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
  1648. if (!empty($element)) {
  1649. $sql .= " AND entity IN (".getEntity($element).")";
  1650. } else {
  1651. $sql .= " AND entity = ".((int) $conf->entity);
  1652. }
  1653. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1654. $resql = $this->db->query($sql);
  1655. if ($resql) {
  1656. $row = $this->db->fetch_row($resql);
  1657. // Test for avoid error -1
  1658. if ($row[0] > 0) {
  1659. $result = $this->fetch($row[0]);
  1660. }
  1661. }
  1662. return $result;
  1663. }
  1664. /**
  1665. * Getter generic. Load value from a specific field
  1666. *
  1667. * @param string $table Table of element or element line
  1668. * @param int $id Element id
  1669. * @param string $field Field selected
  1670. * @return int <0 if KO, >0 if OK
  1671. */
  1672. public function getValueFrom($table, $id, $field)
  1673. {
  1674. $result = false;
  1675. if (!empty($id) && !empty($field) && !empty($table)) {
  1676. $sql = "SELECT ".$field." FROM ".$this->db->prefix().$table;
  1677. $sql .= " WHERE rowid = ".((int) $id);
  1678. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1679. $resql = $this->db->query($sql);
  1680. if ($resql) {
  1681. $row = $this->db->fetch_row($resql);
  1682. $result = $row[0];
  1683. }
  1684. }
  1685. return $result;
  1686. }
  1687. /**
  1688. * Setter generic. Update a specific field into database.
  1689. * Warning: Trigger is run only if param trigkey is provided.
  1690. *
  1691. * @param string $field Field to update
  1692. * @param mixed $value New value
  1693. * @param string $table To force other table element or element line (should not be used)
  1694. * @param int $id To force other object id (should not be used)
  1695. * @param string $format Data format ('text', 'date'). 'text' is used if not defined
  1696. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1697. * @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'
  1698. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1699. * @param string $fk_user_field Name of field to save user id making change
  1700. * @return int <0 if KO, >0 if OK
  1701. * @see updateExtraField()
  1702. */
  1703. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1704. {
  1705. global $user, $langs, $conf;
  1706. if (empty($table)) {
  1707. $table = $this->table_element;
  1708. }
  1709. if (empty($id)) {
  1710. $id = $this->id;
  1711. }
  1712. if (empty($format)) {
  1713. $format = 'text';
  1714. }
  1715. if (empty($id_field)) {
  1716. $id_field = 'rowid';
  1717. }
  1718. $error = 0;
  1719. $this->db->begin();
  1720. // Special case
  1721. if ($table == 'product' && $field == 'note_private') {
  1722. $field = 'note';
  1723. }
  1724. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  1725. $fk_user_field = 'fk_user_mod';
  1726. }
  1727. $sql = "UPDATE ".$this->db->prefix().$table." SET ";
  1728. if ($format == 'text') {
  1729. $sql .= $field." = '".$this->db->escape($value)."'";
  1730. } elseif ($format == 'int') {
  1731. $sql .= $field." = ".((int) $value);
  1732. } elseif ($format == 'date') {
  1733. $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1734. }
  1735. if ($fk_user_field) {
  1736. if (!empty($fuser) && is_object($fuser)) {
  1737. $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
  1738. } elseif (empty($fuser) || $fuser != 'none') {
  1739. $sql .= ", ".$fk_user_field." = ".((int) $user->id);
  1740. }
  1741. }
  1742. $sql .= " WHERE ".$id_field." = ".((int) $id);
  1743. dol_syslog(__METHOD__."", LOG_DEBUG);
  1744. $resql = $this->db->query($sql);
  1745. if ($resql) {
  1746. if ($trigkey) {
  1747. // call trigger with updated object values
  1748. if (empty($this->fields) && method_exists($this, 'fetch')) {
  1749. $result = $this->fetch($id);
  1750. } else {
  1751. $result = $this->fetchCommon($id);
  1752. }
  1753. if ($result >= 0) {
  1754. $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1755. }
  1756. if ($result < 0) {
  1757. $error++;
  1758. }
  1759. }
  1760. if (!$error) {
  1761. if (property_exists($this, $field)) {
  1762. $this->$field = $value;
  1763. }
  1764. $this->db->commit();
  1765. return 1;
  1766. } else {
  1767. $this->db->rollback();
  1768. return -2;
  1769. }
  1770. } else {
  1771. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1772. $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
  1773. } else {
  1774. $this->error = $this->db->lasterror();
  1775. }
  1776. $this->db->rollback();
  1777. return -1;
  1778. }
  1779. }
  1780. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1781. /**
  1782. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1783. *
  1784. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')". Do not allow user input data here.
  1785. * @param string $fieldid Name of field to use for the select MAX and MIN
  1786. * @param int $nodbprefix Do not include DB prefix to forge table name
  1787. * @return int <0 if KO, >0 if OK
  1788. */
  1789. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1790. {
  1791. // phpcs:enable
  1792. global $conf, $user;
  1793. if (!$this->table_element) {
  1794. dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1795. return -1;
  1796. }
  1797. if ($fieldid == 'none') {
  1798. return 1;
  1799. }
  1800. // For backward compatibility
  1801. if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
  1802. $fieldid = 'titre';
  1803. }
  1804. // Security on socid
  1805. $socid = 0;
  1806. if ($user->socid > 0) {
  1807. $socid = $user->socid;
  1808. }
  1809. // this->ismultientitymanaged contains
  1810. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1811. $aliastablesociete = 's';
  1812. if ($this->element == 'societe') {
  1813. $aliastablesociete = 'te'; // te as table_element
  1814. }
  1815. $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
  1816. $sql = "SELECT MAX(te.".$fieldid.")";
  1817. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1818. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1819. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1820. }
  1821. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1822. $tmparray = explode('@', $this->ismultientitymanaged);
  1823. $sql .= ", ".$this->db->prefix().$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1824. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1825. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1826. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1827. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1828. }
  1829. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1830. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1831. }
  1832. $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)
  1833. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1834. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1835. }
  1836. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1837. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1838. }
  1839. if (!empty($filter)) {
  1840. if (!preg_match('/^\s*AND/i', $filter)) {
  1841. $sql .= " AND "; // For backward compatibility
  1842. }
  1843. $sql .= $filter;
  1844. }
  1845. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1846. $tmparray = explode('@', $this->ismultientitymanaged);
  1847. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1848. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1849. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1850. }
  1851. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1852. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1853. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1854. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1855. } else {
  1856. $sql .= " AND ug.fk_user = te.rowid";
  1857. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1858. }
  1859. } else {
  1860. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1861. }
  1862. }
  1863. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1864. $tmparray = explode('@', $this->ismultientitymanaged);
  1865. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1866. }
  1867. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1868. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1869. }
  1870. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1871. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1872. }
  1873. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1874. $sql .= ' AND te.rowid = '.((int) $socid);
  1875. }
  1876. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1877. $result = $this->db->query($sql);
  1878. if (!$result) {
  1879. $this->error = $this->db->lasterror();
  1880. return -1;
  1881. }
  1882. $row = $this->db->fetch_row($result);
  1883. $this->ref_previous = $row[0];
  1884. $sql = "SELECT MIN(te.".$fieldid.")";
  1885. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1886. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1887. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1888. }
  1889. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1890. $tmparray = explode('@', $this->ismultientitymanaged);
  1891. $sql .= ", ".$this->db->prefix().$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1892. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1893. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1894. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1895. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1896. }
  1897. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1898. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1899. }
  1900. $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)
  1901. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1902. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1903. }
  1904. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1905. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1906. }
  1907. if (!empty($filter)) {
  1908. if (!preg_match('/^\s*AND/i', $filter)) {
  1909. $sql .= " AND "; // For backward compatibility
  1910. }
  1911. $sql .= $filter;
  1912. }
  1913. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1914. $tmparray = explode('@', $this->ismultientitymanaged);
  1915. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1916. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1917. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1918. }
  1919. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1920. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1921. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1922. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1923. } else {
  1924. $sql .= " AND ug.fk_user = te.rowid";
  1925. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1926. }
  1927. } else {
  1928. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1929. }
  1930. }
  1931. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1932. $tmparray = explode('@', $this->ismultientitymanaged);
  1933. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1934. }
  1935. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1936. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1937. }
  1938. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1939. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1940. }
  1941. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1942. $sql .= ' AND te.rowid = '.((int) $socid);
  1943. }
  1944. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1945. // 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
  1946. $result = $this->db->query($sql);
  1947. if (!$result) {
  1948. $this->error = $this->db->lasterror();
  1949. return -2;
  1950. }
  1951. $row = $this->db->fetch_row($result);
  1952. $this->ref_next = $row[0];
  1953. return 1;
  1954. }
  1955. /**
  1956. * Return list of id of contacts of object
  1957. *
  1958. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  1959. * @return array Array of id of contacts (if source=external or internal)
  1960. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  1961. */
  1962. public function getListContactId($source = 'external')
  1963. {
  1964. $contactAlreadySelected = array();
  1965. $tab = $this->liste_contact(-1, $source);
  1966. $num = count($tab);
  1967. $i = 0;
  1968. while ($i < $num) {
  1969. if ($source == 'thirdparty') {
  1970. $contactAlreadySelected[$i] = $tab[$i]['socid'];
  1971. } else {
  1972. $contactAlreadySelected[$i] = $tab[$i]['id'];
  1973. }
  1974. $i++;
  1975. }
  1976. return $contactAlreadySelected;
  1977. }
  1978. /**
  1979. * Link element with a project
  1980. *
  1981. * @param int $projectid Project id to link element to
  1982. * @return int <0 if KO, >0 if OK
  1983. */
  1984. public function setProject($projectid)
  1985. {
  1986. if (!$this->table_element) {
  1987. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  1988. return -1;
  1989. }
  1990. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  1991. if (!empty($this->fields['fk_project'])) { // Common case
  1992. if ($projectid) {
  1993. $sql .= " SET fk_project = ".((int) $projectid);
  1994. } else {
  1995. $sql .= " SET fk_project = NULL";
  1996. }
  1997. $sql .= ' WHERE rowid = '.((int) $this->id);
  1998. } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
  1999. if ($projectid) {
  2000. $sql .= " SET fk_project = ".((int) $projectid);
  2001. } else {
  2002. $sql .= " SET fk_project = NULL";
  2003. }
  2004. $sql .= ' WHERE id = '.((int) $this->id);
  2005. } else // Special case for old architecture objects
  2006. {
  2007. if ($projectid) {
  2008. $sql .= ' SET fk_projet = '.((int) $projectid);
  2009. } else {
  2010. $sql .= ' SET fk_projet = NULL';
  2011. }
  2012. $sql .= " WHERE rowid = ".((int) $this->id);
  2013. }
  2014. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  2015. if ($this->db->query($sql)) {
  2016. $this->fk_project = ((int) $projectid);
  2017. return 1;
  2018. } else {
  2019. dol_print_error($this->db);
  2020. return -1;
  2021. }
  2022. }
  2023. /**
  2024. * Change the payments methods
  2025. *
  2026. * @param int $id Id of new payment method
  2027. * @return int >0 if OK, <0 if KO
  2028. */
  2029. public function setPaymentMethods($id)
  2030. {
  2031. global $user;
  2032. $error = 0; $notrigger = 0;
  2033. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  2034. if ($this->statut >= 0 || $this->element == 'societe') {
  2035. // TODO uniformize field name
  2036. $fieldname = 'fk_mode_reglement';
  2037. if ($this->element == 'societe') {
  2038. $fieldname = 'mode_reglement';
  2039. }
  2040. if (get_class($this) == 'Fournisseur') {
  2041. $fieldname = 'mode_reglement_supplier';
  2042. }
  2043. if (get_class($this) == 'Tva') {
  2044. $fieldname = 'fk_typepayment';
  2045. }
  2046. if (get_class($this) == 'Salary') {
  2047. $fieldname = 'fk_typepayment';
  2048. }
  2049. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2050. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2051. $sql .= ' WHERE rowid='.((int) $this->id);
  2052. if ($this->db->query($sql)) {
  2053. $this->mode_reglement_id = $id;
  2054. // for supplier
  2055. if (get_class($this) == 'Fournisseur') {
  2056. $this->mode_reglement_supplier_id = $id;
  2057. }
  2058. // Triggers
  2059. if (!$error && !$notrigger) {
  2060. // Call triggers
  2061. if (get_class($this) == 'Commande') {
  2062. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2063. } else {
  2064. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  2065. }
  2066. if ($result < 0) {
  2067. $error++;
  2068. }
  2069. // End call triggers
  2070. }
  2071. return 1;
  2072. } else {
  2073. dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
  2074. $this->error = $this->db->error();
  2075. return -1;
  2076. }
  2077. } else {
  2078. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  2079. $this->error = 'Status of the object is incompatible '.$this->statut;
  2080. return -2;
  2081. }
  2082. }
  2083. /**
  2084. * Change the multicurrency code
  2085. *
  2086. * @param string $code multicurrency code
  2087. * @return int >0 if OK, <0 if KO
  2088. */
  2089. public function setMulticurrencyCode($code)
  2090. {
  2091. dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
  2092. if ($this->statut >= 0 || $this->element == 'societe') {
  2093. $fieldname = 'multicurrency_code';
  2094. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2095. $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
  2096. $sql .= ' WHERE rowid='.((int) $this->id);
  2097. if ($this->db->query($sql)) {
  2098. $this->multicurrency_code = $code;
  2099. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  2100. if ($rate) {
  2101. $this->setMulticurrencyRate($rate, 2);
  2102. }
  2103. return 1;
  2104. } else {
  2105. dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
  2106. $this->error = $this->db->error();
  2107. return -1;
  2108. }
  2109. } else {
  2110. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  2111. $this->error = 'Status of the object is incompatible '.$this->statut;
  2112. return -2;
  2113. }
  2114. }
  2115. /**
  2116. * Change the multicurrency rate
  2117. *
  2118. * @param double $rate multicurrency rate
  2119. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  2120. * @return int >0 if OK, <0 if KO
  2121. */
  2122. public function setMulticurrencyRate($rate, $mode = 1)
  2123. {
  2124. dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
  2125. if ($this->statut >= 0 || $this->element == 'societe') {
  2126. $fieldname = 'multicurrency_tx';
  2127. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2128. $sql .= " SET ".$fieldname." = ".((float) $rate);
  2129. $sql .= ' WHERE rowid='.((int) $this->id);
  2130. if ($this->db->query($sql)) {
  2131. $this->multicurrency_tx = $rate;
  2132. // Update line price
  2133. if (!empty($this->lines)) {
  2134. foreach ($this->lines as &$line) {
  2135. // Amounts in company currency will be recalculated
  2136. if ($mode == 1) {
  2137. $line->subprice = 0;
  2138. }
  2139. // Amounts in foreign currency will be recalculated
  2140. if ($mode == 2) {
  2141. $line->multicurrency_subprice = 0;
  2142. }
  2143. switch ($this->element) {
  2144. case 'propal':
  2145. $this->updateline(
  2146. $line->id,
  2147. $line->subprice,
  2148. $line->qty,
  2149. $line->remise_percent,
  2150. $line->tva_tx,
  2151. $line->localtax1_tx,
  2152. $line->localtax2_tx,
  2153. ($line->description ? $line->description : $line->desc),
  2154. 'HT',
  2155. $line->info_bits,
  2156. $line->special_code,
  2157. $line->fk_parent_line,
  2158. $line->skip_update_total,
  2159. $line->fk_fournprice,
  2160. $line->pa_ht,
  2161. $line->label,
  2162. $line->product_type,
  2163. $line->date_start,
  2164. $line->date_end,
  2165. $line->array_options,
  2166. $line->fk_unit,
  2167. $line->multicurrency_subprice
  2168. );
  2169. break;
  2170. case 'commande':
  2171. $this->updateline(
  2172. $line->id,
  2173. ($line->description ? $line->description : $line->desc),
  2174. $line->subprice,
  2175. $line->qty,
  2176. $line->remise_percent,
  2177. $line->tva_tx,
  2178. $line->localtax1_tx,
  2179. $line->localtax2_tx,
  2180. 'HT',
  2181. $line->info_bits,
  2182. $line->date_start,
  2183. $line->date_end,
  2184. $line->product_type,
  2185. $line->fk_parent_line,
  2186. $line->skip_update_total,
  2187. $line->fk_fournprice,
  2188. $line->pa_ht,
  2189. $line->label,
  2190. $line->special_code,
  2191. $line->array_options,
  2192. $line->fk_unit,
  2193. $line->multicurrency_subprice
  2194. );
  2195. break;
  2196. case 'facture':
  2197. $this->updateline(
  2198. $line->id,
  2199. ($line->description ? $line->description : $line->desc),
  2200. $line->subprice,
  2201. $line->qty,
  2202. $line->remise_percent,
  2203. $line->date_start,
  2204. $line->date_end,
  2205. $line->tva_tx,
  2206. $line->localtax1_tx,
  2207. $line->localtax2_tx,
  2208. 'HT',
  2209. $line->info_bits,
  2210. $line->product_type,
  2211. $line->fk_parent_line,
  2212. $line->skip_update_total,
  2213. $line->fk_fournprice,
  2214. $line->pa_ht,
  2215. $line->label,
  2216. $line->special_code,
  2217. $line->array_options,
  2218. $line->situation_percent,
  2219. $line->fk_unit,
  2220. $line->multicurrency_subprice
  2221. );
  2222. break;
  2223. case 'supplier_proposal':
  2224. $this->updateline(
  2225. $line->id,
  2226. $line->subprice,
  2227. $line->qty,
  2228. $line->remise_percent,
  2229. $line->tva_tx,
  2230. $line->localtax1_tx,
  2231. $line->localtax2_tx,
  2232. ($line->description ? $line->description : $line->desc),
  2233. 'HT',
  2234. $line->info_bits,
  2235. $line->special_code,
  2236. $line->fk_parent_line,
  2237. $line->skip_update_total,
  2238. $line->fk_fournprice,
  2239. $line->pa_ht,
  2240. $line->label,
  2241. $line->product_type,
  2242. $line->array_options,
  2243. $line->ref_fourn,
  2244. $line->multicurrency_subprice
  2245. );
  2246. break;
  2247. case 'order_supplier':
  2248. $this->updateline(
  2249. $line->id,
  2250. ($line->description ? $line->description : $line->desc),
  2251. $line->subprice,
  2252. $line->qty,
  2253. $line->remise_percent,
  2254. $line->tva_tx,
  2255. $line->localtax1_tx,
  2256. $line->localtax2_tx,
  2257. 'HT',
  2258. $line->info_bits,
  2259. $line->product_type,
  2260. false,
  2261. $line->date_start,
  2262. $line->date_end,
  2263. $line->array_options,
  2264. $line->fk_unit,
  2265. $line->multicurrency_subprice,
  2266. $line->ref_supplier
  2267. );
  2268. break;
  2269. case 'invoice_supplier':
  2270. $this->updateline(
  2271. $line->id,
  2272. ($line->description ? $line->description : $line->desc),
  2273. $line->subprice,
  2274. $line->tva_tx,
  2275. $line->localtax1_tx,
  2276. $line->localtax2_tx,
  2277. $line->qty,
  2278. 0,
  2279. 'HT',
  2280. $line->info_bits,
  2281. $line->product_type,
  2282. $line->remise_percent,
  2283. false,
  2284. $line->date_start,
  2285. $line->date_end,
  2286. $line->array_options,
  2287. $line->fk_unit,
  2288. $line->multicurrency_subprice,
  2289. $line->ref_supplier
  2290. );
  2291. break;
  2292. default:
  2293. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  2294. break;
  2295. }
  2296. }
  2297. }
  2298. return 1;
  2299. } else {
  2300. dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
  2301. $this->error = $this->db->error();
  2302. return -1;
  2303. }
  2304. } else {
  2305. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  2306. $this->error = 'Status of the object is incompatible '.$this->statut;
  2307. return -2;
  2308. }
  2309. }
  2310. /**
  2311. * Change the payments terms
  2312. *
  2313. * @param int $id Id of new payment terms
  2314. * @return int >0 if OK, <0 if KO
  2315. */
  2316. public function setPaymentTerms($id)
  2317. {
  2318. dol_syslog(get_class($this).'::setPaymentTerms('.$id.')');
  2319. if ($this->statut >= 0 || $this->element == 'societe') {
  2320. // TODO uniformize field name
  2321. $fieldname = 'fk_cond_reglement';
  2322. if ($this->element == 'societe') {
  2323. $fieldname = 'cond_reglement';
  2324. }
  2325. if (get_class($this) == 'Fournisseur') {
  2326. $fieldname = 'cond_reglement_supplier';
  2327. }
  2328. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2329. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2330. $sql .= ' WHERE rowid='.((int) $this->id);
  2331. if ($this->db->query($sql)) {
  2332. $this->cond_reglement_id = $id;
  2333. // for supplier
  2334. if (get_class($this) == 'Fournisseur') {
  2335. $this->cond_reglement_supplier_id = $id;
  2336. }
  2337. $this->cond_reglement = $id; // for compatibility
  2338. return 1;
  2339. } else {
  2340. dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
  2341. $this->error = $this->db->error();
  2342. return -1;
  2343. }
  2344. } else {
  2345. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  2346. $this->error = 'Status of the object is incompatible '.$this->statut;
  2347. return -2;
  2348. }
  2349. }
  2350. /**
  2351. * Change the transport mode methods
  2352. *
  2353. * @param int $id Id of transport mode
  2354. * @return int >0 if OK, <0 if KO
  2355. */
  2356. public function setTransportMode($id)
  2357. {
  2358. dol_syslog(get_class($this).'::setTransportMode('.$id.')');
  2359. if ($this->statut >= 0 || $this->element == 'societe') {
  2360. $fieldname = 'fk_transport_mode';
  2361. if ($this->element == 'societe') {
  2362. $fieldname = 'transport_mode';
  2363. }
  2364. if (get_class($this) == 'Fournisseur') {
  2365. $fieldname = 'transport_mode_supplier';
  2366. }
  2367. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2368. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2369. $sql .= ' WHERE rowid='.((int) $this->id);
  2370. if ($this->db->query($sql)) {
  2371. $this->transport_mode_id = $id;
  2372. // for supplier
  2373. if (get_class($this) == 'Fournisseur') {
  2374. $this->transport_mode_supplier_id = $id;
  2375. }
  2376. return 1;
  2377. } else {
  2378. dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
  2379. $this->error = $this->db->error();
  2380. return -1;
  2381. }
  2382. } else {
  2383. dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
  2384. $this->error = 'Status of the object is incompatible '.$this->statut;
  2385. return -2;
  2386. }
  2387. }
  2388. /**
  2389. * Change the retained warranty payments terms
  2390. *
  2391. * @param int $id Id of new payment terms
  2392. * @return int >0 if OK, <0 if KO
  2393. */
  2394. public function setRetainedWarrantyPaymentTerms($id)
  2395. {
  2396. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
  2397. if ($this->statut >= 0 || $this->element == 'societe') {
  2398. $fieldname = 'retained_warranty_fk_cond_reglement';
  2399. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2400. $sql .= " SET ".$fieldname." = ".((int) $id);
  2401. $sql .= ' WHERE rowid='.((int) $this->id);
  2402. if ($this->db->query($sql)) {
  2403. $this->retained_warranty_fk_cond_reglement = $id;
  2404. return 1;
  2405. } else {
  2406. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
  2407. $this->error = $this->db->error();
  2408. return -1;
  2409. }
  2410. } else {
  2411. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  2412. $this->error = 'Status of the object is incompatible '.$this->statut;
  2413. return -2;
  2414. }
  2415. }
  2416. /**
  2417. * Define delivery address
  2418. * @deprecated
  2419. *
  2420. * @param int $id Address id
  2421. * @return int <0 si ko, >0 si ok
  2422. */
  2423. public function setDeliveryAddress($id)
  2424. {
  2425. $fieldname = 'fk_delivery_address';
  2426. if ($this->element == 'delivery' || $this->element == 'shipping') {
  2427. $fieldname = 'fk_address';
  2428. }
  2429. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$fieldname." = ".((int) $id);
  2430. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
  2431. if ($this->db->query($sql)) {
  2432. $this->fk_delivery_address = $id;
  2433. return 1;
  2434. } else {
  2435. $this->error = $this->db->error();
  2436. dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
  2437. return -1;
  2438. }
  2439. }
  2440. /**
  2441. * Change the shipping method
  2442. *
  2443. * @param int $shipping_method_id Id of shipping method
  2444. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2445. * @param User $userused Object user
  2446. *
  2447. * @return int 1 if OK, 0 if KO
  2448. */
  2449. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  2450. {
  2451. global $user;
  2452. if (empty($userused)) {
  2453. $userused = $user;
  2454. }
  2455. $error = 0;
  2456. if (!$this->table_element) {
  2457. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2458. return -1;
  2459. }
  2460. $this->db->begin();
  2461. if ($shipping_method_id < 0) {
  2462. $shipping_method_id = 'NULL';
  2463. }
  2464. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  2465. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2466. $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
  2467. $sql .= " WHERE rowid=".((int) $this->id);
  2468. $resql = $this->db->query($sql);
  2469. if (!$resql) {
  2470. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  2471. $this->error = $this->db->lasterror();
  2472. $error++;
  2473. } else {
  2474. if (!$notrigger) {
  2475. // Call trigger
  2476. $this->context = array('shippingmethodupdate'=>1);
  2477. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2478. if ($result < 0) {
  2479. $error++;
  2480. }
  2481. // End call trigger
  2482. }
  2483. }
  2484. if ($error) {
  2485. $this->db->rollback();
  2486. return -1;
  2487. } else {
  2488. $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
  2489. $this->db->commit();
  2490. return 1;
  2491. }
  2492. }
  2493. /**
  2494. * Change the warehouse
  2495. *
  2496. * @param int $warehouse_id Id of warehouse
  2497. * @return int 1 if OK, 0 if KO
  2498. */
  2499. public function setWarehouse($warehouse_id)
  2500. {
  2501. if (!$this->table_element) {
  2502. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2503. return -1;
  2504. }
  2505. if ($warehouse_id < 0) {
  2506. $warehouse_id = 'NULL';
  2507. }
  2508. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  2509. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2510. $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
  2511. $sql .= " WHERE rowid=".((int) $this->id);
  2512. if ($this->db->query($sql)) {
  2513. $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
  2514. return 1;
  2515. } else {
  2516. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  2517. $this->error = $this->db->error();
  2518. return 0;
  2519. }
  2520. }
  2521. /**
  2522. * Set last model used by doc generator
  2523. *
  2524. * @param User $user User object that make change
  2525. * @param string $modelpdf Modele name
  2526. * @return int <0 if KO, >0 if OK
  2527. */
  2528. public function setDocModel($user, $modelpdf)
  2529. {
  2530. if (!$this->table_element) {
  2531. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2532. return -1;
  2533. }
  2534. $newmodelpdf = dol_trunc($modelpdf, 255);
  2535. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2536. $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  2537. $sql .= " WHERE rowid = ".((int) $this->id);
  2538. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  2539. $resql = $this->db->query($sql);
  2540. if ($resql) {
  2541. $this->model_pdf = $modelpdf;
  2542. $this->modelpdf = $modelpdf; // For bakward compatibility
  2543. return 1;
  2544. } else {
  2545. dol_print_error($this->db);
  2546. return 0;
  2547. }
  2548. }
  2549. /**
  2550. * Change the bank account
  2551. *
  2552. * @param int $fk_account Id of bank account
  2553. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2554. * @param User $userused Object user
  2555. * @return int 1 if OK, 0 if KO
  2556. */
  2557. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2558. {
  2559. global $user;
  2560. if (empty($userused)) {
  2561. $userused = $user;
  2562. }
  2563. $error = 0;
  2564. if (!$this->table_element) {
  2565. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2566. return -1;
  2567. }
  2568. $this->db->begin();
  2569. if ($fk_account < 0) {
  2570. $fk_account = 'NULL';
  2571. }
  2572. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  2573. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2574. $sql .= " SET fk_account = ".((int) $fk_account);
  2575. $sql .= " WHERE rowid=".((int) $this->id);
  2576. $resql = $this->db->query($sql);
  2577. if (!$resql) {
  2578. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  2579. $this->error = $this->db->lasterror();
  2580. $error++;
  2581. } else {
  2582. if (!$notrigger) {
  2583. // Call trigger
  2584. $this->context = array('bankaccountupdate'=>1);
  2585. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2586. if ($result < 0) {
  2587. $error++;
  2588. }
  2589. // End call trigger
  2590. }
  2591. }
  2592. if ($error) {
  2593. $this->db->rollback();
  2594. return -1;
  2595. } else {
  2596. $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
  2597. $this->db->commit();
  2598. return 1;
  2599. }
  2600. }
  2601. // TODO: Move line related operations to CommonObjectLine?
  2602. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2603. /**
  2604. * Save a new position (field rang) for details lines.
  2605. * You can choose to set position for lines with already a position or lines without any position defined.
  2606. *
  2607. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2608. * @param string $rowidorder ASC or DESC
  2609. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2610. * @return int <0 if KO, >0 if OK
  2611. */
  2612. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2613. {
  2614. // phpcs:enable
  2615. if (!$this->table_element_line) {
  2616. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2617. return -1;
  2618. }
  2619. if (!$this->fk_element) {
  2620. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2621. return -1;
  2622. }
  2623. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2624. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2625. $fieldposition = 'position';
  2626. }
  2627. // Count number of lines to reorder (according to choice $renum)
  2628. $nl = 0;
  2629. $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
  2630. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2631. if (!$renum) {
  2632. $sql .= " AND " . $fieldposition . " = 0";
  2633. }
  2634. if ($renum) {
  2635. $sql .= " AND " . $fieldposition . " <> 0";
  2636. }
  2637. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  2638. $resql = $this->db->query($sql);
  2639. if ($resql) {
  2640. $row = $this->db->fetch_row($resql);
  2641. $nl = $row[0];
  2642. } else {
  2643. dol_print_error($this->db);
  2644. }
  2645. if ($nl > 0) {
  2646. // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
  2647. $rows = array();
  2648. // We first search all lines that are parent lines (for multilevel details lines)
  2649. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2650. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2651. if ($fk_parent_line) {
  2652. $sql .= ' AND fk_parent_line IS NULL';
  2653. }
  2654. $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder;
  2655. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  2656. $resql = $this->db->query($sql);
  2657. if ($resql) {
  2658. $i = 0;
  2659. $num = $this->db->num_rows($resql);
  2660. while ($i < $num) {
  2661. $row = $this->db->fetch_row($resql);
  2662. $rows[] = $row[0]; // Add parent line into array rows
  2663. $childrens = $this->getChildrenOfLine($row[0]);
  2664. if (!empty($childrens)) {
  2665. foreach ($childrens as $child) {
  2666. array_push($rows, $child);
  2667. }
  2668. }
  2669. $i++;
  2670. }
  2671. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2672. if (!empty($rows)) {
  2673. foreach ($rows as $key => $row) {
  2674. $this->updateRangOfLine($row, ($key + 1));
  2675. }
  2676. }
  2677. } else {
  2678. dol_print_error($this->db);
  2679. }
  2680. }
  2681. return 1;
  2682. }
  2683. /**
  2684. * Get children of line
  2685. *
  2686. * @param int $id Id of parent line
  2687. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2688. * @return array Array with list of children lines id
  2689. */
  2690. public function getChildrenOfLine($id, $includealltree = 0)
  2691. {
  2692. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2693. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2694. $fieldposition = 'position';
  2695. }
  2696. $rows = array();
  2697. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2698. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2699. $sql .= ' AND fk_parent_line = '.((int) $id);
  2700. $sql .= " ORDER BY " . $fieldposition . " ASC";
  2701. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
  2702. $resql = $this->db->query($sql);
  2703. if ($resql) {
  2704. if ($this->db->num_rows($resql) > 0) {
  2705. while ($row = $this->db->fetch_row($resql)) {
  2706. $rows[] = $row[0];
  2707. if (!empty($includealltree)) {
  2708. $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2709. }
  2710. }
  2711. }
  2712. }
  2713. return $rows;
  2714. }
  2715. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2716. /**
  2717. * Update a line to have a lower rank
  2718. *
  2719. * @param int $rowid Id of line
  2720. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2721. * @return void
  2722. */
  2723. public function line_up($rowid, $fk_parent_line = true)
  2724. {
  2725. // phpcs:enable
  2726. $this->line_order(false, 'ASC', $fk_parent_line);
  2727. // Get rang of line
  2728. $rang = $this->getRangOfLine($rowid);
  2729. // Update position of line
  2730. $this->updateLineUp($rowid, $rang);
  2731. }
  2732. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2733. /**
  2734. * Update a line to have a higher rank
  2735. *
  2736. * @param int $rowid Id of line
  2737. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2738. * @return void
  2739. */
  2740. public function line_down($rowid, $fk_parent_line = true)
  2741. {
  2742. // phpcs:enable
  2743. $this->line_order(false, 'ASC', $fk_parent_line);
  2744. // Get rang of line
  2745. $rang = $this->getRangOfLine($rowid);
  2746. // Get max value for rang
  2747. $max = $this->line_max();
  2748. // Update position of line
  2749. $this->updateLineDown($rowid, $rang, $max);
  2750. }
  2751. /**
  2752. * Update position of line (rang)
  2753. *
  2754. * @param int $rowid Id of line
  2755. * @param int $rang Position
  2756. * @return int <0 if KO, >0 if OK
  2757. */
  2758. public function updateRangOfLine($rowid, $rang)
  2759. {
  2760. global $hookmanager;
  2761. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2762. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2763. $fieldposition = 'position';
  2764. }
  2765. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2766. $sql .= ' WHERE rowid = '.((int) $rowid);
  2767. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2768. if (!$this->db->query($sql)) {
  2769. dol_print_error($this->db);
  2770. return -1;
  2771. } else {
  2772. $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
  2773. $action='';
  2774. $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
  2775. return 1;
  2776. }
  2777. }
  2778. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2779. /**
  2780. * Update position of line with ajax (rang)
  2781. *
  2782. * @param array $rows Array of rows
  2783. * @return void
  2784. */
  2785. public function line_ajaxorder($rows)
  2786. {
  2787. // phpcs:enable
  2788. $num = count($rows);
  2789. for ($i = 0; $i < $num; $i++) {
  2790. $this->updateRangOfLine($rows[$i], ($i + 1));
  2791. }
  2792. }
  2793. /**
  2794. * Update position of line up (rang)
  2795. *
  2796. * @param int $rowid Id of line
  2797. * @param int $rang Position
  2798. * @return void
  2799. */
  2800. public function updateLineUp($rowid, $rang)
  2801. {
  2802. if ($rang > 1) {
  2803. $fieldposition = 'rang';
  2804. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2805. $fieldposition = 'position';
  2806. }
  2807. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2808. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2809. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1));
  2810. if ($this->db->query($sql)) {
  2811. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
  2812. $sql .= ' WHERE rowid = '.((int) $rowid);
  2813. if (!$this->db->query($sql)) {
  2814. dol_print_error($this->db);
  2815. }
  2816. } else {
  2817. dol_print_error($this->db);
  2818. }
  2819. }
  2820. }
  2821. /**
  2822. * Update position of line down (rang)
  2823. *
  2824. * @param int $rowid Id of line
  2825. * @param int $rang Position
  2826. * @param int $max Max
  2827. * @return void
  2828. */
  2829. public function updateLineDown($rowid, $rang, $max)
  2830. {
  2831. if ($rang < $max) {
  2832. $fieldposition = 'rang';
  2833. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2834. $fieldposition = 'position';
  2835. }
  2836. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2837. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2838. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1));
  2839. if ($this->db->query($sql)) {
  2840. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
  2841. $sql .= ' WHERE rowid = '.((int) $rowid);
  2842. if (!$this->db->query($sql)) {
  2843. dol_print_error($this->db);
  2844. }
  2845. } else {
  2846. dol_print_error($this->db);
  2847. }
  2848. }
  2849. }
  2850. /**
  2851. * Get position of line (rang)
  2852. *
  2853. * @param int $rowid Id of line
  2854. * @return int Value of rang in table of lines
  2855. */
  2856. public function getRangOfLine($rowid)
  2857. {
  2858. $fieldposition = 'rang';
  2859. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2860. $fieldposition = 'position';
  2861. }
  2862. $sql = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line;
  2863. $sql .= " WHERE rowid = ".((int) $rowid);
  2864. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  2865. $resql = $this->db->query($sql);
  2866. if ($resql) {
  2867. $row = $this->db->fetch_row($resql);
  2868. return $row[0];
  2869. }
  2870. }
  2871. /**
  2872. * Get rowid of the line relative to its position
  2873. *
  2874. * @param int $rang Rang value
  2875. * @return int Rowid of the line
  2876. */
  2877. public function getIdOfLine($rang)
  2878. {
  2879. $fieldposition = 'rang';
  2880. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2881. $fieldposition = 'position';
  2882. }
  2883. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2884. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2885. $sql .= " AND " . $fieldposition . " = ".((int) $rang);
  2886. $resql = $this->db->query($sql);
  2887. if ($resql) {
  2888. $row = $this->db->fetch_row($resql);
  2889. return $row[0];
  2890. }
  2891. }
  2892. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2893. /**
  2894. * Get max value used for position of line (rang)
  2895. *
  2896. * @param int $fk_parent_line Parent line id
  2897. * @return int Max value of rang in table of lines
  2898. */
  2899. public function line_max($fk_parent_line = 0)
  2900. {
  2901. // phpcs:enable
  2902. $positionfield = 'rang';
  2903. if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
  2904. $positionfield = 'position';
  2905. }
  2906. // Search the last rang with fk_parent_line
  2907. if ($fk_parent_line) {
  2908. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  2909. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2910. $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
  2911. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2912. $resql = $this->db->query($sql);
  2913. if ($resql) {
  2914. $row = $this->db->fetch_row($resql);
  2915. if (!empty($row[0])) {
  2916. return $row[0];
  2917. } else {
  2918. return $this->getRangOfLine($fk_parent_line);
  2919. }
  2920. }
  2921. } else {
  2922. // If not, search the last rang of element
  2923. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  2924. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2925. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2926. $resql = $this->db->query($sql);
  2927. if ($resql) {
  2928. $row = $this->db->fetch_row($resql);
  2929. return $row[0];
  2930. }
  2931. }
  2932. }
  2933. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2934. /**
  2935. * Update external ref of element
  2936. *
  2937. * @param string $ref_ext Update field ref_ext
  2938. * @return int <0 if KO, >0 if OK
  2939. */
  2940. public function update_ref_ext($ref_ext)
  2941. {
  2942. // phpcs:enable
  2943. if (!$this->table_element) {
  2944. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  2945. return -1;
  2946. }
  2947. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2948. $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  2949. $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
  2950. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  2951. if ($this->db->query($sql)) {
  2952. $this->ref_ext = $ref_ext;
  2953. return 1;
  2954. } else {
  2955. $this->error = $this->db->error();
  2956. return -1;
  2957. }
  2958. }
  2959. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2960. /**
  2961. * Update note of element
  2962. *
  2963. * @param string $note New value for note
  2964. * @param string $suffix '', '_public' or '_private'
  2965. * @return int <0 if KO, >0 if OK
  2966. */
  2967. public function update_note($note, $suffix = '')
  2968. {
  2969. // phpcs:enable
  2970. global $user;
  2971. if (!$this->table_element) {
  2972. $this->error = 'update_note was called on objet with property table_element not defined';
  2973. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  2974. return -1;
  2975. }
  2976. if (!in_array($suffix, array('', '_public', '_private'))) {
  2977. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  2978. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  2979. return -2;
  2980. }
  2981. $newsuffix = $suffix;
  2982. // Special cas
  2983. if ($this->table_element == 'product' && $newsuffix == '_private') {
  2984. $newsuffix = '';
  2985. }
  2986. if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  2987. $fieldusermod = "fk_user_mod";
  2988. } elseif ($this->table_element == 'ecm_files') {
  2989. $fieldusermod = "fk_user_m";
  2990. } else {
  2991. $fieldusermod = "fk_user_modif";
  2992. }
  2993. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2994. $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
  2995. $sql .= ", ".$fieldusermod." = ".((int) $user->id);
  2996. $sql .= " WHERE rowid = ".((int) $this->id);
  2997. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  2998. if ($this->db->query($sql)) {
  2999. if ($suffix == '_public') {
  3000. $this->note_public = $note;
  3001. } elseif ($suffix == '_private') {
  3002. $this->note_private = $note;
  3003. } else {
  3004. $this->note = $note; // deprecated
  3005. $this->note_private = $note;
  3006. }
  3007. return 1;
  3008. } else {
  3009. $this->error = $this->db->lasterror();
  3010. return -1;
  3011. }
  3012. }
  3013. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3014. /**
  3015. * Update public note (kept for backward compatibility)
  3016. *
  3017. * @param string $note New value for note
  3018. * @return int <0 if KO, >0 if OK
  3019. * @deprecated
  3020. * @see update_note()
  3021. */
  3022. public function update_note_public($note)
  3023. {
  3024. // phpcs:enable
  3025. return $this->update_note($note, '_public');
  3026. }
  3027. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3028. /**
  3029. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  3030. * Must be called at end of methods addline or updateline.
  3031. *
  3032. * @param int $exclspec >0 = Exclude special product (product_type=9)
  3033. * @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
  3034. * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object.
  3035. * @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.
  3036. * @return int <0 if KO, >0 if OK
  3037. */
  3038. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  3039. {
  3040. // phpcs:enable
  3041. global $conf, $hookmanager, $action;
  3042. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  3043. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3044. if ($reshook > 0) {
  3045. return 1; // replacement code
  3046. } elseif ($reshook < 0) {
  3047. return -1; // failure
  3048. } // reshook = 0 => execute normal code
  3049. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  3050. $MODULE = "";
  3051. if ($this->element == 'propal') {
  3052. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  3053. } elseif ($this->element == 'commande' || $this->element == 'order') {
  3054. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  3055. } elseif ($this->element == 'facture' || $this->element == 'invoice') {
  3056. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  3057. } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
  3058. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  3059. } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
  3060. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  3061. } elseif ($this->element == 'supplier_proposal') {
  3062. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  3063. }
  3064. if (!empty($MODULE)) {
  3065. if (!empty($conf->global->$MODULE)) {
  3066. $modsactivated = explode(',', $conf->global->$MODULE);
  3067. foreach ($modsactivated as $mod) {
  3068. if ($conf->$mod->enabled) {
  3069. return 1; // update was disabled by specific setup
  3070. }
  3071. }
  3072. }
  3073. }
  3074. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  3075. if ($roundingadjust == '-1') {
  3076. $roundingadjust = 'auto'; // For backward compatibility
  3077. }
  3078. $forcedroundingmode = $roundingadjust;
  3079. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
  3080. $forcedroundingmode = $conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
  3081. } elseif ($forcedroundingmode == 'auto') {
  3082. $forcedroundingmode = '0';
  3083. }
  3084. $error = 0;
  3085. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  3086. // Define constants to find lines to sum
  3087. $fieldtva = 'total_tva';
  3088. $fieldlocaltax1 = 'total_localtax1';
  3089. $fieldlocaltax2 = 'total_localtax2';
  3090. $fieldup = 'subprice';
  3091. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3092. $fieldtva = 'tva';
  3093. $fieldup = 'pu_ht';
  3094. }
  3095. if ($this->element == 'invoice_supplier_rec') {
  3096. $fieldup = 'pu_ht';
  3097. }
  3098. if ($this->element == 'expensereport') {
  3099. $fieldup = 'value_unit';
  3100. }
  3101. $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,";
  3102. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  3103. if ($this->table_element_line == 'facturedet') {
  3104. $sql .= ', situation_percent';
  3105. }
  3106. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3107. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  3108. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3109. if ($exclspec) {
  3110. $product_field = 'product_type';
  3111. if ($this->table_element_line == 'contratdet') {
  3112. $product_field = ''; // contratdet table has no product_type field
  3113. }
  3114. if ($product_field) {
  3115. $sql .= " AND ".$product_field." <> 9";
  3116. }
  3117. }
  3118. $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
  3119. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3120. $resql = $this->db->query($sql);
  3121. if ($resql) {
  3122. $this->total_ht = 0;
  3123. $this->total_tva = 0;
  3124. $this->total_localtax1 = 0;
  3125. $this->total_localtax2 = 0;
  3126. $this->total_ttc = 0;
  3127. $total_ht_by_vats = array();
  3128. $total_tva_by_vats = array();
  3129. $total_ttc_by_vats = array();
  3130. $this->multicurrency_total_ht = 0;
  3131. $this->multicurrency_total_tva = 0;
  3132. $this->multicurrency_total_ttc = 0;
  3133. $num = $this->db->num_rows($resql);
  3134. $i = 0;
  3135. while ($i < $num) {
  3136. $obj = $this->db->fetch_object($resql);
  3137. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  3138. $parameters = array('fk_element' => $obj->rowid);
  3139. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3140. 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'
  3141. // This part of code is to fix data. We should not call it too often.
  3142. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  3143. $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);
  3144. $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.
  3145. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  3146. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
  3147. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  3148. if ($diff_when_using_price_ht && $diff_on_current_total) {
  3149. $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2])." WHERE rowid = ".((int) $obj->rowid);
  3150. 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);
  3151. $resqlfix = $this->db->query($sqlfix);
  3152. if (!$resqlfix) {
  3153. dol_print_error($this->db, 'Failed to update line');
  3154. }
  3155. $obj->total_tva = $tmpcal[1];
  3156. $obj->total_ttc = $tmpcal[2];
  3157. }
  3158. }
  3159. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  3160. $this->total_tva += $obj->total_tva;
  3161. $this->total_localtax1 += $obj->total_localtax1;
  3162. $this->total_localtax2 += $obj->total_localtax2;
  3163. $this->total_ttc += $obj->total_ttc;
  3164. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  3165. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  3166. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  3167. if (!isset($total_ht_by_vats[$obj->vatrate])) {
  3168. $total_ht_by_vats[$obj->vatrate] = 0;
  3169. }
  3170. if (!isset($total_tva_by_vats[$obj->vatrate])) {
  3171. $total_tva_by_vats[$obj->vatrate] = 0;
  3172. }
  3173. if (!isset($total_ttc_by_vats[$obj->vatrate])) {
  3174. $total_ttc_by_vats[$obj->vatrate] = 0;
  3175. }
  3176. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  3177. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  3178. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  3179. if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  3180. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  3181. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  3182. //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";
  3183. if ($diff) {
  3184. if (abs($diff) > 0.1) {
  3185. $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.';
  3186. dol_syslog($errmsg, LOG_WARNING);
  3187. dol_print_error('', $errmsg);
  3188. exit;
  3189. }
  3190. $sqlfix = "UPDATE ".$this->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);
  3191. 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);
  3192. $resqlfix = $this->db->query($sqlfix);
  3193. if (!$resqlfix) {
  3194. dol_print_error($this->db, 'Failed to update line');
  3195. }
  3196. $this->total_tva -= $diff;
  3197. $this->total_ttc -= $diff;
  3198. $total_tva_by_vats[$obj->vatrate] -= $diff;
  3199. $total_ttc_by_vats[$obj->vatrate] -= $diff;
  3200. }
  3201. }
  3202. $i++;
  3203. }
  3204. // Add revenue stamp to total
  3205. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  3206. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  3207. // Situations totals
  3208. if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
  3209. $prev_sits = $this->get_prev_sits();
  3210. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  3211. $this->total_ht -= $sit->total_ht;
  3212. $this->total_tva -= $sit->total_tva;
  3213. $this->total_localtax1 -= $sit->total_localtax1;
  3214. $this->total_localtax2 -= $sit->total_localtax2;
  3215. $this->total_ttc -= $sit->total_ttc;
  3216. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  3217. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  3218. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  3219. }
  3220. }
  3221. $this->db->free($resql);
  3222. // Now update global field total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_*
  3223. $fieldht = 'total_ht';
  3224. $fieldtva = 'tva';
  3225. $fieldlocaltax1 = 'localtax1';
  3226. $fieldlocaltax2 = 'localtax2';
  3227. $fieldttc = 'total_ttc';
  3228. // Specific code for backward compatibility with old field names
  3229. if ($this->element == 'facture' || $this->element == 'facturerec') {
  3230. $fieldtva = 'total_tva';
  3231. }
  3232. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
  3233. $fieldtva = 'total_tva';
  3234. }
  3235. if ($this->element == 'propal') {
  3236. $fieldtva = 'total_tva';
  3237. }
  3238. if ($this->element == 'expensereport') {
  3239. $fieldtva = 'total_tva';
  3240. }
  3241. if ($this->element == 'supplier_proposal') {
  3242. $fieldtva = 'total_tva';
  3243. }
  3244. if ($this->element == 'commande') {
  3245. $fieldtva = 'total_tva';
  3246. }
  3247. if ($this->element == 'order_supplier') {
  3248. $fieldtva = 'total_tva';
  3249. }
  3250. if (empty($nodatabaseupdate)) {
  3251. $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
  3252. $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht)).",";
  3253. $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva)).",";
  3254. $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1)).",";
  3255. $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2)).",";
  3256. $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc));
  3257. $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
  3258. $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
  3259. $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
  3260. $sql .= " WHERE rowid = ".((int) $this->id);
  3261. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3262. $resql = $this->db->query($sql);
  3263. if (!$resql) {
  3264. $error++;
  3265. $this->error = $this->db->lasterror();
  3266. $this->errors[] = $this->db->lasterror();
  3267. }
  3268. }
  3269. if (!$error) {
  3270. return 1;
  3271. } else {
  3272. return -1;
  3273. }
  3274. } else {
  3275. dol_print_error($this->db, 'Bad request in update_price');
  3276. return -1;
  3277. }
  3278. }
  3279. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3280. /**
  3281. * Add objects linked in llx_element_element.
  3282. *
  3283. * @param string $origin Linked element type
  3284. * @param int $origin_id Linked element id
  3285. * @param User $f_user User that create
  3286. * @param int $notrigger 1=Does not execute triggers, 0=execute triggers
  3287. * @return int <=0 if KO, >0 if OK
  3288. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  3289. */
  3290. public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
  3291. {
  3292. // phpcs:enable
  3293. global $user, $hookmanager, $action;
  3294. $origin = (!empty($origin) ? $origin : $this->origin);
  3295. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  3296. $f_user = isset($f_user) ? $f_user : $user;
  3297. // Special case
  3298. if ($origin == 'order') {
  3299. $origin = 'commande';
  3300. }
  3301. if ($origin == 'invoice') {
  3302. $origin = 'facture';
  3303. }
  3304. if ($origin == 'invoice_template') {
  3305. $origin = 'facturerec';
  3306. }
  3307. if ($origin == 'supplierorder') {
  3308. $origin = 'order_supplier';
  3309. }
  3310. // 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.
  3311. // 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.
  3312. $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
  3313. // Add module part to target type if object has $module property and isn't in core modules.
  3314. $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
  3315. $parameters = array('targettype'=>$targettype);
  3316. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3317. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3318. if ($reshook > 0) {
  3319. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3320. }
  3321. $this->db->begin();
  3322. $error = 0;
  3323. $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
  3324. $sql .= "fk_source";
  3325. $sql .= ", sourcetype";
  3326. $sql .= ", fk_target";
  3327. $sql .= ", targettype";
  3328. $sql .= ") VALUES (";
  3329. $sql .= ((int) $origin_id);
  3330. $sql .= ", '" . $this->db->escape($origin) . "'";
  3331. $sql .= ", " . ((int) $this->id);
  3332. $sql .= ", '" . $this->db->escape($targettype) . "'";
  3333. $sql .= ")";
  3334. dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
  3335. if ($this->db->query($sql)) {
  3336. if (!$notrigger) {
  3337. // Call trigger
  3338. $this->context['link_origin'] = $origin;
  3339. $this->context['link_origin_id'] = $origin_id;
  3340. $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
  3341. if ($result < 0) {
  3342. $error++;
  3343. }
  3344. // End call triggers
  3345. }
  3346. } else {
  3347. $this->error = $this->db->lasterror();
  3348. $error++;
  3349. }
  3350. if (!$error) {
  3351. $this->db->commit();
  3352. return 1;
  3353. } else {
  3354. $this->db->rollback();
  3355. return 0;
  3356. }
  3357. }
  3358. /**
  3359. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  3360. * this->linkedObjectsIds array +
  3361. * this->linkedObjects array if $loadalsoobjects = 1 or $loadalsoobjects = type
  3362. * Possible usage for parameters:
  3363. * - all parameters empty -> we look all link to current object (current object can be source or target)
  3364. * - source id+type -> will get list of targets linked to source
  3365. * - target id+type -> will get list of sources linked to target
  3366. * - source id+type + target type -> will get list of targets of the type linked to source
  3367. * - target id+type + source type -> will get list of sources of the type linked to target
  3368. *
  3369. * @param int $sourceid Object source id (if not defined, id of object)
  3370. * @param string $sourcetype Object source type (if not defined, element name of object)
  3371. * @param int $targetid Object target id (if not defined, id of object)
  3372. * @param string $targettype Object target type (if not defined, element name of object)
  3373. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  3374. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  3375. * @param string $orderby SQL 'ORDER BY' clause
  3376. * @param int|string $loadalsoobjects Load also array this->linkedObjects. Use 0 to increase performances, Use 1 to load all, Use value of type ('facture', 'facturerec', ...) to load only a type of object.
  3377. * @return int <0 if KO, >0 if OK
  3378. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  3379. */
  3380. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  3381. {
  3382. global $conf, $hookmanager, $action;
  3383. // important for pdf generation time reduction
  3384. // this boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
  3385. if ($this->linkedObjectsFullLoaded) return 1;
  3386. $this->linkedObjectsIds = array();
  3387. $this->linkedObjects = array();
  3388. $justsource = false;
  3389. $justtarget = false;
  3390. $withtargettype = false;
  3391. $withsourcetype = false;
  3392. $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
  3393. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3394. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3395. if ($reshook > 0) {
  3396. if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
  3397. if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
  3398. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3399. if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
  3400. }
  3401. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
  3402. $justsource = true; // the source (id and type) is a search criteria
  3403. if (!empty($targettype)) {
  3404. $withtargettype = true;
  3405. }
  3406. }
  3407. if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
  3408. $justtarget = true; // the target (id and type) is a search criteria
  3409. if (!empty($sourcetype)) {
  3410. $withsourcetype = true;
  3411. }
  3412. }
  3413. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3414. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3415. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3416. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3417. /*if (empty($sourceid) && empty($targetid))
  3418. {
  3419. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  3420. return -1;
  3421. }*/
  3422. // Links between objects are stored in table element_element
  3423. $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
  3424. $sql .= " FROM ".$this->db->prefix()."element_element";
  3425. $sql .= " WHERE ";
  3426. if ($justsource || $justtarget) {
  3427. if ($justsource) {
  3428. $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3429. if ($withtargettype) {
  3430. $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
  3431. }
  3432. } elseif ($justtarget) {
  3433. $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
  3434. if ($withsourcetype) {
  3435. $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3436. }
  3437. }
  3438. } else {
  3439. $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
  3440. $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
  3441. if ($sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
  3442. $this->linkedObjectsFullLoaded = true;
  3443. }
  3444. }
  3445. $sql .= " ORDER BY ".$orderby;
  3446. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  3447. $resql = $this->db->query($sql);
  3448. if ($resql) {
  3449. $num = $this->db->num_rows($resql);
  3450. $i = 0;
  3451. while ($i < $num) {
  3452. $obj = $this->db->fetch_object($resql);
  3453. if ($justsource || $justtarget) {
  3454. if ($justsource) {
  3455. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3456. } elseif ($justtarget) {
  3457. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3458. }
  3459. } else {
  3460. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
  3461. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3462. }
  3463. if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
  3464. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3465. }
  3466. }
  3467. $i++;
  3468. }
  3469. if (!empty($this->linkedObjectsIds)) {
  3470. $tmparray = $this->linkedObjectsIds;
  3471. foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  3472. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  3473. $module = $element = $subelement = $objecttype;
  3474. $regs = array();
  3475. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  3476. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  3477. $module = $element = $regs[1];
  3478. $subelement = $regs[2];
  3479. }
  3480. $classpath = $element.'/class';
  3481. // To work with non standard classpath or module name
  3482. if ($objecttype == 'facture') {
  3483. $classpath = 'compta/facture/class';
  3484. } elseif ($objecttype == 'facturerec') {
  3485. $classpath = 'compta/facture/class';
  3486. $module = 'facture';
  3487. } elseif ($objecttype == 'propal') {
  3488. $classpath = 'comm/propal/class';
  3489. } elseif ($objecttype == 'supplier_proposal') {
  3490. $classpath = 'supplier_proposal/class';
  3491. } elseif ($objecttype == 'shipping') {
  3492. $classpath = 'expedition/class';
  3493. $subelement = 'expedition';
  3494. $module = 'expedition_bon';
  3495. } elseif ($objecttype == 'delivery') {
  3496. $classpath = 'delivery/class';
  3497. $subelement = 'delivery';
  3498. $module = 'delivery_note';
  3499. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  3500. $classpath = 'fourn/class';
  3501. $module = 'fournisseur';
  3502. } elseif ($objecttype == 'fichinter') {
  3503. $classpath = 'fichinter/class';
  3504. $subelement = 'fichinter';
  3505. $module = 'ficheinter';
  3506. } elseif ($objecttype == 'subscription') {
  3507. $classpath = 'adherents/class';
  3508. $module = 'adherent';
  3509. } elseif ($objecttype == 'contact') {
  3510. $module = 'societe';
  3511. }
  3512. // Set classfile
  3513. $classfile = strtolower($subelement);
  3514. $classname = ucfirst($subelement);
  3515. if ($objecttype == 'order') {
  3516. $classfile = 'commande';
  3517. $classname = 'Commande';
  3518. } elseif ($objecttype == 'invoice_supplier') {
  3519. $classfile = 'fournisseur.facture';
  3520. $classname = 'FactureFournisseur';
  3521. } elseif ($objecttype == 'order_supplier') {
  3522. $classfile = 'fournisseur.commande';
  3523. $classname = 'CommandeFournisseur';
  3524. } elseif ($objecttype == 'supplier_proposal') {
  3525. $classfile = 'supplier_proposal';
  3526. $classname = 'SupplierProposal';
  3527. } elseif ($objecttype == 'facturerec') {
  3528. $classfile = 'facture-rec';
  3529. $classname = 'FactureRec';
  3530. } elseif ($objecttype == 'subscription') {
  3531. $classfile = 'subscription';
  3532. $classname = 'Subscription';
  3533. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  3534. $classpath = 'projet/class';
  3535. $classfile = 'project';
  3536. $classname = 'Project';
  3537. } elseif ($objecttype == 'conferenceorboothattendee') {
  3538. $classpath = 'eventorganization/class';
  3539. $classfile = 'conferenceorboothattendee';
  3540. $classname = 'ConferenceOrBoothAttendee';
  3541. $module = 'eventorganization';
  3542. } elseif ($objecttype == 'conferenceorbooth') {
  3543. $classpath = 'eventorganization/class';
  3544. $classfile = 'conferenceorbooth';
  3545. $classname = 'ConferenceOrBooth';
  3546. $module = 'eventorganization';
  3547. } elseif ($objecttype == 'mo') {
  3548. $classpath = 'mrp/class';
  3549. $classfile = 'mo';
  3550. $classname = 'Mo';
  3551. $module = 'mrp';
  3552. }
  3553. // Here $module, $classfile and $classname are set, we can use them.
  3554. if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
  3555. if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
  3556. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  3557. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  3558. if (class_exists($classname)) {
  3559. foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
  3560. $object = new $classname($this->db);
  3561. $ret = $object->fetch($objectid);
  3562. if ($ret >= 0) {
  3563. $this->linkedObjects[$objecttype][$i] = $object;
  3564. }
  3565. }
  3566. }
  3567. }
  3568. } else {
  3569. unset($this->linkedObjectsIds[$objecttype]);
  3570. }
  3571. }
  3572. }
  3573. return 1;
  3574. } else {
  3575. dol_print_error($this->db);
  3576. return -1;
  3577. }
  3578. }
  3579. /**
  3580. * Update object linked of a current object
  3581. *
  3582. * @param int $sourceid Object source id
  3583. * @param string $sourcetype Object source type
  3584. * @param int $targetid Object target id
  3585. * @param string $targettype Object target type
  3586. * @param User $f_user User that create
  3587. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3588. * @return int >0 if OK, <0 if KO
  3589. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3590. */
  3591. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
  3592. {
  3593. global $user;
  3594. $updatesource = false;
  3595. $updatetarget = false;
  3596. $f_user = isset($f_user) ? $f_user : $user;
  3597. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3598. $updatesource = true;
  3599. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3600. $updatetarget = true;
  3601. }
  3602. $this->db->begin();
  3603. $error = 0;
  3604. $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
  3605. if ($updatesource) {
  3606. $sql .= "fk_source = " . ((int) $sourceid);
  3607. $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3608. $sql .= " WHERE fk_target = " . ((int) $this->id);
  3609. $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
  3610. } elseif ($updatetarget) {
  3611. $sql .= "fk_target = " . ((int) $targetid);
  3612. $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
  3613. $sql .= " WHERE fk_source = " . ((int) $this->id);
  3614. $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3615. }
  3616. dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
  3617. if ($this->db->query($sql)) {
  3618. if (!$notrigger) {
  3619. // Call trigger
  3620. $this->context['link_source_id'] = $sourceid;
  3621. $this->context['link_source_type'] = $sourcetype;
  3622. $this->context['link_target_id'] = $targetid;
  3623. $this->context['link_target_type'] = $targettype;
  3624. $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
  3625. if ($result < 0) {
  3626. $error++;
  3627. }
  3628. // End call triggers
  3629. }
  3630. } else {
  3631. $this->error = $this->db->lasterror();
  3632. $error++;
  3633. }
  3634. if (!$error) {
  3635. $this->db->commit();
  3636. return 1;
  3637. } else {
  3638. $this->db->rollback();
  3639. return -1;
  3640. }
  3641. }
  3642. /**
  3643. * Delete all links between an object $this
  3644. *
  3645. * @param int $sourceid Object source id
  3646. * @param string $sourcetype Object source type
  3647. * @param int $targetid Object target id
  3648. * @param string $targettype Object target type
  3649. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3650. * @param User $f_user User that create
  3651. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3652. * @return int >0 if OK, <0 if KO
  3653. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3654. */
  3655. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
  3656. {
  3657. global $user;
  3658. $deletesource = false;
  3659. $deletetarget = false;
  3660. $f_user = isset($f_user) ? $f_user : $user;
  3661. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3662. $deletesource = true;
  3663. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3664. $deletetarget = true;
  3665. }
  3666. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3667. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3668. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3669. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3670. $this->db->begin();
  3671. $error = 0;
  3672. if (!$notrigger) {
  3673. // Call trigger
  3674. $this->context['link_id'] = $rowid;
  3675. $this->context['link_source_id'] = $sourceid;
  3676. $this->context['link_source_type'] = $sourcetype;
  3677. $this->context['link_target_id'] = $targetid;
  3678. $this->context['link_target_type'] = $targettype;
  3679. $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
  3680. if ($result < 0) {
  3681. $error++;
  3682. }
  3683. // End call triggers
  3684. }
  3685. if (!$error) {
  3686. $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
  3687. $sql .= " WHERE";
  3688. if ($rowid > 0) {
  3689. $sql .= " rowid = " . ((int) $rowid);
  3690. } else {
  3691. if ($deletesource) {
  3692. $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3693. $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
  3694. } elseif ($deletetarget) {
  3695. $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
  3696. $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3697. } else {
  3698. $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
  3699. $sql .= " OR";
  3700. $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
  3701. }
  3702. }
  3703. dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
  3704. if (!$this->db->query($sql)) {
  3705. $this->error = $this->db->lasterror();
  3706. $this->errors[] = $this->error;
  3707. $error++;
  3708. }
  3709. }
  3710. if (!$error) {
  3711. $this->db->commit();
  3712. return 1;
  3713. } else {
  3714. $this->db->rollback();
  3715. return 0;
  3716. }
  3717. }
  3718. /**
  3719. * Function used to get an array with all items linked to an object id in association table
  3720. *
  3721. * @param int $fk_object_where id of object we need to get linked items
  3722. * @param string $field_select name of field we need to get a list
  3723. * @param string $field_where name of field of object we need to get linked items
  3724. * @param string $table_element name of association table
  3725. * @return array Array of record
  3726. */
  3727. public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
  3728. {
  3729. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3730. return -1;
  3731. }
  3732. global $db;
  3733. $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3734. $resql = $db->query($sql);
  3735. $TRes = array();
  3736. if (!empty($resql)) {
  3737. while ($res = $db->fetch_object($resql)) {
  3738. $TRes[] = $res->{$field_select};
  3739. }
  3740. }
  3741. return $TRes;
  3742. }
  3743. /**
  3744. * Function used to remove all items linked to an object id in association table
  3745. *
  3746. * @param int $fk_object_where id of object we need to remove linked items
  3747. * @param string $field_where name of field of object we need to delete linked items
  3748. * @param string $table_element name of association table
  3749. * @return int <0 if KO, 0 if nothing done, >0 if OK and something done
  3750. */
  3751. public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
  3752. {
  3753. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3754. return -1;
  3755. }
  3756. global $db;
  3757. $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3758. $resql = $db->query($sql);
  3759. if (empty($resql)) {
  3760. return 0;
  3761. }
  3762. return 1;
  3763. }
  3764. /**
  3765. * Set status of an object
  3766. *
  3767. * @param int $status Status to set
  3768. * @param int $elementId Id of element to force (use this->id by default if null)
  3769. * @param string $elementType Type of element to force (use this->table_element by default)
  3770. * @param string $trigkey Trigger key to use for trigger. Use '' means automatic but it not recommended and is deprecated.
  3771. * @param string $fieldstatus Name of status field in this->table_element
  3772. * @return int <0 if KO, >0 if OK
  3773. */
  3774. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
  3775. {
  3776. global $user, $langs, $conf;
  3777. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3778. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3779. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3780. $this->db->begin();
  3781. if ($elementTable == 'facture_rec') {
  3782. $fieldstatus = "suspended";
  3783. }
  3784. if ($elementTable == 'mailing') {
  3785. $fieldstatus = "statut";
  3786. }
  3787. if ($elementTable == 'cronjob') {
  3788. $fieldstatus = "status";
  3789. }
  3790. if ($elementTable == 'user') {
  3791. $fieldstatus = "statut";
  3792. }
  3793. if ($elementTable == 'expensereport') {
  3794. $fieldstatus = "fk_statut";
  3795. }
  3796. if ($elementTable == 'commande_fournisseur_dispatch') {
  3797. $fieldstatus = "status";
  3798. }
  3799. if (is_array($this->fields) && array_key_exists('status', $this->fields)) {
  3800. $fieldstatus = 'status';
  3801. }
  3802. $sql = "UPDATE ".$this->db->prefix().$elementTable;
  3803. $sql .= " SET ".$fieldstatus." = ".((int) $status);
  3804. // If status = 1 = validated, update also fk_user_valid
  3805. // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
  3806. if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
  3807. $sql .= ", fk_user_valid = ".((int) $user->id);
  3808. }
  3809. if ($status == 1 && in_array($elementTable, array('expensereport'))) {
  3810. $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
  3811. }
  3812. if ($status == 1 && in_array($elementTable, array('inventory'))) {
  3813. $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
  3814. }
  3815. $sql .= " WHERE rowid=".((int) $elementId);
  3816. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  3817. if ($this->db->query($sql)) {
  3818. $error = 0;
  3819. // Try autoset of trigkey
  3820. if (empty($trigkey)) {
  3821. if ($this->element == 'supplier_proposal' && $status == 2) {
  3822. $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3823. }
  3824. if ($this->element == 'supplier_proposal' && $status == 3) {
  3825. $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3826. }
  3827. if ($this->element == 'supplier_proposal' && $status == 4) {
  3828. $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3829. }
  3830. if ($this->element == 'fichinter' && $status == 3) {
  3831. $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3832. }
  3833. if ($this->element == 'fichinter' && $status == 2) {
  3834. $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3835. }
  3836. if ($this->element == 'fichinter' && $status == 1) {
  3837. $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3838. }
  3839. }
  3840. if ($trigkey) {
  3841. // Call trigger
  3842. $result = $this->call_trigger($trigkey, $user);
  3843. if ($result < 0) {
  3844. $error++;
  3845. }
  3846. // End call triggers
  3847. }
  3848. if (!$error) {
  3849. $this->db->commit();
  3850. if (empty($savElementId)) {
  3851. // If the element we update is $this (so $elementId was provided as null)
  3852. if ($fieldstatus == 'tosell') {
  3853. $this->status = $status;
  3854. } elseif ($fieldstatus == 'tobuy') {
  3855. $this->status_buy = $status;
  3856. } else {
  3857. $this->statut = $status;
  3858. $this->status = $status;
  3859. }
  3860. }
  3861. return 1;
  3862. } else {
  3863. $this->db->rollback();
  3864. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  3865. return -1;
  3866. }
  3867. } else {
  3868. $this->error = $this->db->lasterror();
  3869. $this->db->rollback();
  3870. return -1;
  3871. }
  3872. }
  3873. /**
  3874. * Load type of canvas of an object if it exists
  3875. *
  3876. * @param int $id Record id
  3877. * @param string $ref Record ref
  3878. * @return int <0 if KO, 0 if nothing done, >0 if OK
  3879. */
  3880. public function getCanvas($id = 0, $ref = '')
  3881. {
  3882. global $conf;
  3883. if (empty($id) && empty($ref)) {
  3884. return 0;
  3885. }
  3886. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
  3887. return 0; // To increase speed. Not enabled by default.
  3888. }
  3889. // Clean parameters
  3890. $ref = trim($ref);
  3891. $sql = "SELECT rowid, canvas";
  3892. $sql .= " FROM ".$this->db->prefix().$this->table_element;
  3893. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  3894. if (!empty($id)) {
  3895. $sql .= " AND rowid = ".((int) $id);
  3896. }
  3897. if (!empty($ref)) {
  3898. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  3899. }
  3900. $resql = $this->db->query($sql);
  3901. if ($resql) {
  3902. $obj = $this->db->fetch_object($resql);
  3903. if ($obj) {
  3904. $this->canvas = $obj->canvas;
  3905. return 1;
  3906. } else {
  3907. return 0;
  3908. }
  3909. } else {
  3910. dol_print_error($this->db);
  3911. return -1;
  3912. }
  3913. }
  3914. /**
  3915. * Get special code of a line
  3916. *
  3917. * @param int $lineid Id of line
  3918. * @return int Special code
  3919. */
  3920. public function getSpecialCode($lineid)
  3921. {
  3922. $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
  3923. $sql .= " WHERE rowid = ".((int) $lineid);
  3924. $resql = $this->db->query($sql);
  3925. if ($resql) {
  3926. $row = $this->db->fetch_row($resql);
  3927. return $row[0];
  3928. }
  3929. }
  3930. /**
  3931. * Function to check if an object is used by others.
  3932. * Check is done into this->childtables. There is no check into llx_element_element.
  3933. *
  3934. * @param int $id Force id of object
  3935. * @param int $entity Force entity to check
  3936. * @return int <0 if KO, 0 if not used, >0 if already used
  3937. */
  3938. public function isObjectUsed($id = 0, $entity = 0)
  3939. {
  3940. global $langs;
  3941. if (empty($id)) {
  3942. $id = $this->id;
  3943. }
  3944. // Check parameters
  3945. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
  3946. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  3947. return -1;
  3948. }
  3949. $arraytoscan = $this->childtables;
  3950. // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
  3951. $tmparray = array_keys($this->childtables);
  3952. if (is_numeric($tmparray[0])) {
  3953. $arraytoscan = array_flip($this->childtables);
  3954. }
  3955. // Test if child exists
  3956. $haschild = 0;
  3957. foreach ($arraytoscan as $table => $element) {
  3958. //print $id.'-'.$table.'-'.$elementname.'<br>';
  3959. // Check if element can be deleted
  3960. $sql = "SELECT COUNT(*) as nb";
  3961. $sql.= " FROM ".$this->db->prefix().$table." as c";
  3962. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  3963. $sql.= ", ".$this->db->prefix().$element['parent']." as p";
  3964. }
  3965. $sql.= " WHERE c.".$this->fk_element." = ".((int) $id);
  3966. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  3967. $sql.= " AND c.".$element['parentkey']." = p.rowid";
  3968. }
  3969. if (!empty($entity)) {
  3970. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  3971. $sql.= " AND p.entity = ".((int) $entity);
  3972. } else {
  3973. $sql.= " AND c.entity = ".((int) $entity);
  3974. }
  3975. }
  3976. $resql = $this->db->query($sql);
  3977. if ($resql) {
  3978. $obj = $this->db->fetch_object($resql);
  3979. if ($obj->nb > 0) {
  3980. $langs->load("errors");
  3981. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  3982. $haschild += $obj->nb;
  3983. if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
  3984. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
  3985. } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
  3986. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
  3987. } else { // new usage: $element['name']=Translation key
  3988. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
  3989. }
  3990. break; // We found at least one, we stop here
  3991. }
  3992. } else {
  3993. $this->errors[] = $this->db->lasterror();
  3994. return -1;
  3995. }
  3996. }
  3997. if ($haschild > 0) {
  3998. $this->errors[] = "ErrorRecordHasChildren";
  3999. return $haschild;
  4000. } else {
  4001. return 0;
  4002. }
  4003. }
  4004. /**
  4005. * Function to say how many lines object contains
  4006. *
  4007. * @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
  4008. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  4009. */
  4010. public function hasProductsOrServices($predefined = -1)
  4011. {
  4012. $nb = 0;
  4013. foreach ($this->lines as $key => $val) {
  4014. $qualified = 0;
  4015. if ($predefined == -1) {
  4016. $qualified = 1;
  4017. }
  4018. if ($predefined == 1 && $val->fk_product > 0) {
  4019. $qualified = 1;
  4020. }
  4021. if ($predefined == 0 && $val->fk_product <= 0) {
  4022. $qualified = 1;
  4023. }
  4024. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
  4025. $qualified = 1;
  4026. }
  4027. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
  4028. $qualified = 1;
  4029. }
  4030. if ($qualified) {
  4031. $nb++;
  4032. }
  4033. }
  4034. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  4035. return $nb;
  4036. }
  4037. /**
  4038. * Function that returns the total amount HT of discounts applied for all lines.
  4039. *
  4040. * @return float|string Total amout of discount
  4041. */
  4042. public function getTotalDiscount()
  4043. {
  4044. if (!empty($this->table_element_line) ) {
  4045. $total_discount = 0.00;
  4046. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  4047. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  4048. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  4049. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  4050. $resql = $this->db->query($sql);
  4051. if ($resql) {
  4052. $num = $this->db->num_rows($resql);
  4053. $i = 0;
  4054. while ($i < $num) {
  4055. $obj = $this->db->fetch_object($resql);
  4056. $pu_ht = $obj->pu_ht;
  4057. $qty = $obj->qty;
  4058. $total_ht = $obj->total_ht;
  4059. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  4060. $total_discount += $total_discount_line;
  4061. $i++;
  4062. }
  4063. }
  4064. //print $total_discount; exit;
  4065. return price2num($total_discount);
  4066. }
  4067. return null;
  4068. }
  4069. /**
  4070. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  4071. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  4072. *
  4073. * @return array array('weight'=>...,'volume'=>...)
  4074. */
  4075. public function getTotalWeightVolume()
  4076. {
  4077. $totalWeight = 0;
  4078. $totalVolume = 0;
  4079. // defined for shipment only
  4080. $totalOrdered = '';
  4081. // defined for shipment only
  4082. $totalToShip = '';
  4083. foreach ($this->lines as $line) {
  4084. if (isset($line->qty_asked)) {
  4085. if (empty($totalOrdered)) {
  4086. $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  4087. }
  4088. $totalOrdered += $line->qty_asked; // defined for shipment only
  4089. }
  4090. if (isset($line->qty_shipped)) {
  4091. if (empty($totalToShip)) {
  4092. $totalToShip = 0; // Avoid warning because $totalToShip is ''
  4093. }
  4094. $totalToShip += $line->qty_shipped; // defined for shipment only
  4095. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
  4096. if (empty($totalToShip)) {
  4097. $totalToShip = 0;
  4098. }
  4099. $totalToShip += $line->qty; // defined for reception only
  4100. }
  4101. // Define qty, weight, volume, weight_units, volume_units
  4102. if ($this->element == 'shipping') {
  4103. // for shipments
  4104. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  4105. } else {
  4106. $qty = $line->qty ? $line->qty : 0;
  4107. }
  4108. $weight = !empty($line->weight) ? $line->weight : 0;
  4109. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  4110. $volume = !empty($line->volume) ? $line->volume : 0;
  4111. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  4112. $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
  4113. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  4114. $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
  4115. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  4116. $weightUnit = 0;
  4117. $volumeUnit = 0;
  4118. if (!empty($weight_units)) {
  4119. $weightUnit = $weight_units;
  4120. }
  4121. if (!empty($volume_units)) {
  4122. $volumeUnit = $volume_units;
  4123. }
  4124. if (empty($totalWeight)) {
  4125. $totalWeight = 0; // Avoid warning because $totalWeight is ''
  4126. }
  4127. if (empty($totalVolume)) {
  4128. $totalVolume = 0; // Avoid warning because $totalVolume is ''
  4129. }
  4130. //var_dump($line->volume_units);
  4131. if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4132. $trueWeightUnit = pow(10, $weightUnit);
  4133. $totalWeight += $weight * $qty * $trueWeightUnit;
  4134. } else {
  4135. if ($weight_units == 99) {
  4136. // conversion 1 Pound = 0.45359237 KG
  4137. $trueWeightUnit = 0.45359237;
  4138. $totalWeight += $weight * $qty * $trueWeightUnit;
  4139. } elseif ($weight_units == 98) {
  4140. // conversion 1 Ounce = 0.0283495 KG
  4141. $trueWeightUnit = 0.0283495;
  4142. $totalWeight += $weight * $qty * $trueWeightUnit;
  4143. } else {
  4144. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  4145. }
  4146. }
  4147. if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4148. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  4149. $trueVolumeUnit = pow(10, $volumeUnit);
  4150. //print $line->volume;
  4151. $totalVolume += $volume * $qty * $trueVolumeUnit;
  4152. } else {
  4153. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  4154. }
  4155. }
  4156. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  4157. }
  4158. /**
  4159. * Set extra parameters
  4160. *
  4161. * @return int <0 if KO, >0 if OK
  4162. */
  4163. public function setExtraParameters()
  4164. {
  4165. $this->db->begin();
  4166. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  4167. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  4168. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  4169. $sql .= " WHERE rowid = ".((int) $this->id);
  4170. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  4171. $resql = $this->db->query($sql);
  4172. if (!$resql) {
  4173. $this->error = $this->db->lasterror();
  4174. $this->db->rollback();
  4175. return -1;
  4176. } else {
  4177. $this->db->commit();
  4178. return 1;
  4179. }
  4180. }
  4181. // --------------------
  4182. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  4183. // --------------------
  4184. /* This is to show add lines */
  4185. /**
  4186. * Show add free and predefined products/services form
  4187. *
  4188. * @param int $dateSelector 1=Show also date range input fields
  4189. * @param Societe $seller Object thirdparty who sell
  4190. * @param Societe $buyer Object thirdparty who buy
  4191. * @param string $defaulttpldir Directory where to find the template
  4192. * @return void
  4193. */
  4194. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  4195. {
  4196. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  4197. global $form;
  4198. // Line extrafield
  4199. if (!is_object($extrafields)) {
  4200. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4201. $extrafields = new ExtraFields($this->db);
  4202. }
  4203. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4204. // Output template part (modules that overwrite templates must declare this into descriptor)
  4205. // Use global variables + $dateSelector + $seller and $buyer
  4206. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  4207. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4208. foreach ($dirtpls as $module => $reldir) {
  4209. if (!empty($module)) {
  4210. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  4211. } else {
  4212. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  4213. }
  4214. if (empty($conf->file->strict_mode)) {
  4215. $res = @include $tpl;
  4216. } else {
  4217. $res = include $tpl; // for debug
  4218. }
  4219. if ($res) {
  4220. break;
  4221. }
  4222. }
  4223. }
  4224. /* This is to show array of line of details */
  4225. /**
  4226. * Return HTML table for object lines
  4227. * TODO Move this into an output class file (htmlline.class.php)
  4228. * If lines are into a template, title must also be into a template
  4229. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4230. *
  4231. * @param string $action Action code
  4232. * @param string $seller Object of seller third party
  4233. * @param string $buyer Object of buyer third party
  4234. * @param int $selected Object line selected
  4235. * @param int $dateSelector 1=Show also date range input fields
  4236. * @param string $defaulttpldir Directory where to find the template
  4237. * @return void
  4238. */
  4239. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  4240. {
  4241. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  4242. // TODO We should not use global var for this
  4243. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  4244. // Define usemargins
  4245. $usemargins = 0;
  4246. if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
  4247. $usemargins = 1;
  4248. }
  4249. $num = count($this->lines);
  4250. // Line extrafield
  4251. if (!is_object($extrafields)) {
  4252. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4253. $extrafields = new ExtraFields($this->db);
  4254. }
  4255. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4256. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  4257. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4258. if (empty($reshook)) {
  4259. // Output template part (modules that overwrite templates must declare this into descriptor)
  4260. // Use global variables + $dateSelector + $seller and $buyer
  4261. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  4262. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4263. foreach ($dirtpls as $module => $reldir) {
  4264. if (!empty($module)) {
  4265. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  4266. } else {
  4267. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  4268. }
  4269. if (empty($conf->file->strict_mode)) {
  4270. $res = @include $tpl;
  4271. } else {
  4272. $res = include $tpl; // for debug
  4273. }
  4274. if ($res) {
  4275. break;
  4276. }
  4277. }
  4278. }
  4279. $i = 0;
  4280. print "<!-- begin printObjectLines() --><tbody>\n";
  4281. foreach ($this->lines as $line) {
  4282. //Line extrafield
  4283. $line->fetch_optionals();
  4284. //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  4285. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4286. if (empty($line->fk_parent_line)) {
  4287. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  4288. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4289. } else {
  4290. $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);
  4291. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4292. }
  4293. }
  4294. if (empty($reshook)) {
  4295. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  4296. }
  4297. $i++;
  4298. }
  4299. print "</tbody><!-- end printObjectLines() -->\n";
  4300. }
  4301. /**
  4302. * Return HTML content of a detail line
  4303. * TODO Move this into an output class file (htmlline.class.php)
  4304. *
  4305. * @param string $action GET/POST action
  4306. * @param CommonObjectLine $line Selected object line to output
  4307. * @param string $var Is it a an odd line (true)
  4308. * @param int $num Number of line (0)
  4309. * @param int $i I
  4310. * @param int $dateSelector 1=Show also date range input fields
  4311. * @param string $seller Object of seller third party
  4312. * @param string $buyer Object of buyer third party
  4313. * @param int $selected Object line selected
  4314. * @param Extrafields $extrafields Object of extrafields
  4315. * @param string $defaulttpldir Directory where to find the template (deprecated)
  4316. * @return void
  4317. */
  4318. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  4319. {
  4320. global $conf, $langs, $user, $object, $hookmanager;
  4321. global $form;
  4322. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  4323. $object_rights = $this->getRights();
  4324. $element = $this->element;
  4325. $text = '';
  4326. $description = '';
  4327. // Line in view mode
  4328. if ($action != 'editline' || $selected != $line->id) {
  4329. // Product
  4330. if ($line->fk_product > 0) {
  4331. $product_static = new Product($this->db);
  4332. $product_static->fetch($line->fk_product);
  4333. $product_static->ref = $line->ref; //can change ref in hook
  4334. $product_static->label = $line->label; //can change label in hook
  4335. $text = $product_static->getNomUrl(1);
  4336. // Define output language and label
  4337. if (!empty($conf->global->MAIN_MULTILANGS)) {
  4338. if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
  4339. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  4340. return;
  4341. }
  4342. $prod = new Product($this->db);
  4343. $prod->fetch($line->fk_product);
  4344. $outputlangs = $langs;
  4345. $newlang = '';
  4346. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  4347. $newlang = GETPOST('lang_id', 'aZ09');
  4348. }
  4349. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
  4350. $newlang = $this->thirdparty->default_lang; // To use language of customer
  4351. }
  4352. if (!empty($newlang)) {
  4353. $outputlangs = new Translate("", $conf);
  4354. $outputlangs->setDefaultLang($newlang);
  4355. }
  4356. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  4357. } else {
  4358. $label = $line->product_label;
  4359. }
  4360. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  4361. $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.
  4362. }
  4363. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4364. // Output template part (modules that overwrite templates must declare this into descriptor)
  4365. // Use global variables + $dateSelector + $seller and $buyer
  4366. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4367. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4368. foreach ($dirtpls as $module => $reldir) {
  4369. if (!empty($module)) {
  4370. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  4371. } else {
  4372. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  4373. }
  4374. if (empty($conf->file->strict_mode)) {
  4375. $res = @include $tpl;
  4376. } else {
  4377. $res = include $tpl; // for debug
  4378. }
  4379. if ($res) {
  4380. break;
  4381. }
  4382. }
  4383. }
  4384. // Line in update mode
  4385. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
  4386. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  4387. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4388. // Output template part (modules that overwrite templates must declare this into descriptor)
  4389. // Use global variables + $dateSelector + $seller and $buyer
  4390. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4391. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4392. foreach ($dirtpls as $module => $reldir) {
  4393. if (!empty($module)) {
  4394. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  4395. } else {
  4396. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  4397. }
  4398. if (empty($conf->file->strict_mode)) {
  4399. $res = @include $tpl;
  4400. } else {
  4401. $res = include $tpl; // for debug
  4402. }
  4403. if ($res) {
  4404. break;
  4405. }
  4406. }
  4407. }
  4408. }
  4409. /* This is to show array of line of details of source object */
  4410. /**
  4411. * Return HTML table table of source object lines
  4412. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4413. * If lines are into a template, title must also be into a template
  4414. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  4415. *
  4416. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  4417. * @param array $selectedLines Array of lines id for selected lines
  4418. * @return void
  4419. */
  4420. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  4421. {
  4422. global $langs, $hookmanager, $conf, $form, $action;
  4423. print '<tr class="liste_titre">';
  4424. print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
  4425. print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
  4426. print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
  4427. print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
  4428. if (!empty($conf->multicurrency->enabled)) {
  4429. print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
  4430. }
  4431. print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
  4432. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4433. print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
  4434. }
  4435. print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
  4436. print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
  4437. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  4438. print '</tr>';
  4439. $i = 0;
  4440. if (!empty($this->lines)) {
  4441. foreach ($this->lines as $line) {
  4442. $reshook = 0;
  4443. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
  4444. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4445. $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
  4446. if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
  4447. $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4448. }
  4449. if (empty($reshook)) {
  4450. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  4451. }
  4452. $i++;
  4453. }
  4454. }
  4455. }
  4456. /**
  4457. * Return HTML with a line of table array of source object lines
  4458. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4459. * If lines are into a template, title must also be into a template
  4460. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4461. *
  4462. * @param CommonObjectLine $line Line
  4463. * @param string $var Var
  4464. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  4465. * @param string $defaulttpldir Directory where to find the template
  4466. * @param array $selectedLines Array of lines id for selected lines
  4467. * @return void
  4468. */
  4469. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  4470. {
  4471. global $langs, $conf;
  4472. //var_dump($line);
  4473. if (!empty($line->date_start)) {
  4474. $date_start = $line->date_start;
  4475. } else {
  4476. $date_start = $line->date_debut_prevue;
  4477. if ($line->date_debut_reel) {
  4478. $date_start = $line->date_debut_reel;
  4479. }
  4480. }
  4481. if (!empty($line->date_end)) {
  4482. $date_end = $line->date_end;
  4483. } else {
  4484. $date_end = $line->date_fin_prevue;
  4485. if ($line->date_fin_reel) {
  4486. $date_end = $line->date_fin_reel;
  4487. }
  4488. }
  4489. $this->tpl['id'] = $line->id;
  4490. $this->tpl['label'] = '';
  4491. if (!empty($line->fk_parent_line)) {
  4492. $this->tpl['label'] .= img_picto('', 'rightarrow');
  4493. }
  4494. if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
  4495. $discount = new DiscountAbsolute($this->db);
  4496. $discount->fk_soc = $this->socid;
  4497. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  4498. } elseif (!empty($line->fk_product)) {
  4499. $productstatic = new Product($this->db);
  4500. $productstatic->id = $line->fk_product;
  4501. $productstatic->ref = $line->ref;
  4502. $productstatic->type = $line->fk_product_type;
  4503. if (empty($productstatic->ref)) {
  4504. $line->fetch_product();
  4505. $productstatic = $line->product;
  4506. }
  4507. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  4508. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  4509. // Dates
  4510. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4511. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4512. }
  4513. } else {
  4514. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  4515. if (!empty($line->desc)) {
  4516. $this->tpl['label'] .= $line->desc;
  4517. } else {
  4518. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  4519. }
  4520. // Dates
  4521. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4522. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4523. }
  4524. }
  4525. if (!empty($line->desc)) {
  4526. if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
  4527. $discount = new DiscountAbsolute($this->db);
  4528. $discount->fetch($line->fk_remise_except);
  4529. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  4530. } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
  4531. $discount = new DiscountAbsolute($this->db);
  4532. $discount->fetch($line->fk_remise_except);
  4533. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  4534. } elseif ($line->desc == '(EXCESS RECEIVED)') {
  4535. $discount = new DiscountAbsolute($this->db);
  4536. $discount->fetch($line->fk_remise_except);
  4537. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  4538. } elseif ($line->desc == '(EXCESS PAID)') {
  4539. $discount = new DiscountAbsolute($this->db);
  4540. $discount->fetch($line->fk_remise_except);
  4541. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  4542. } else {
  4543. $this->tpl['description'] = dol_trunc($line->desc, 60);
  4544. }
  4545. } else {
  4546. $this->tpl['description'] = '&nbsp;';
  4547. }
  4548. // VAT Rate
  4549. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  4550. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  4551. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
  4552. $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  4553. }
  4554. $this->tpl['price'] = price($line->subprice);
  4555. $this->tpl['total_ht'] = price($line->total_ht);
  4556. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  4557. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  4558. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4559. $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  4560. }
  4561. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  4562. // Is the line strike or not
  4563. $this->tpl['strike'] = 0;
  4564. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
  4565. $this->tpl['strike'] = 1;
  4566. }
  4567. // Output template part (modules that overwrite templates must declare this into descriptor)
  4568. // Use global variables + $dateSelector + $seller and $buyer
  4569. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4570. foreach ($dirtpls as $module => $reldir) {
  4571. if (!empty($module)) {
  4572. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  4573. } else {
  4574. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  4575. }
  4576. if (empty($conf->file->strict_mode)) {
  4577. $res = @include $tpl;
  4578. } else {
  4579. $res = include $tpl; // for debug
  4580. }
  4581. if ($res) {
  4582. break;
  4583. }
  4584. }
  4585. }
  4586. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4587. /**
  4588. * Add resources to the current object : add entry into llx_element_resources
  4589. * Need $this->element & $this->id
  4590. *
  4591. * @param int $resource_id Resource id
  4592. * @param string $resource_type 'resource'
  4593. * @param int $busy Busy or not
  4594. * @param int $mandatory Mandatory or not
  4595. * @return int <=0 if KO, >0 if OK
  4596. */
  4597. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  4598. {
  4599. // phpcs:enable
  4600. $this->db->begin();
  4601. $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
  4602. $sql .= "resource_id";
  4603. $sql .= ", resource_type";
  4604. $sql .= ", element_id";
  4605. $sql .= ", element_type";
  4606. $sql .= ", busy";
  4607. $sql .= ", mandatory";
  4608. $sql .= ") VALUES (";
  4609. $sql .= $resource_id;
  4610. $sql .= ", '".$this->db->escape($resource_type)."'";
  4611. $sql .= ", '".$this->db->escape($this->id)."'";
  4612. $sql .= ", '".$this->db->escape($this->element)."'";
  4613. $sql .= ", '".$this->db->escape($busy)."'";
  4614. $sql .= ", '".$this->db->escape($mandatory)."'";
  4615. $sql .= ")";
  4616. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  4617. if ($this->db->query($sql)) {
  4618. $this->db->commit();
  4619. return 1;
  4620. } else {
  4621. $this->error = $this->db->lasterror();
  4622. $this->db->rollback();
  4623. return 0;
  4624. }
  4625. }
  4626. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4627. /**
  4628. * Delete a link to resource line
  4629. *
  4630. * @param int $rowid Id of resource line to delete
  4631. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  4632. * @param int $notrigger Disable all triggers
  4633. * @return int >0 if OK, <0 if KO
  4634. */
  4635. public function delete_resource($rowid, $element, $notrigger = 0)
  4636. {
  4637. // phpcs:enable
  4638. global $user;
  4639. $this->db->begin();
  4640. $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
  4641. $sql .= " WHERE rowid = ".((int) $rowid);
  4642. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  4643. $resql = $this->db->query($sql);
  4644. if (!$resql) {
  4645. $this->error = $this->db->lasterror();
  4646. $this->db->rollback();
  4647. return -1;
  4648. } else {
  4649. if (!$notrigger) {
  4650. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  4651. if ($result < 0) {
  4652. $this->db->rollback();
  4653. return -1;
  4654. }
  4655. }
  4656. $this->db->commit();
  4657. return 1;
  4658. }
  4659. }
  4660. /**
  4661. * Overwrite magic function to solve problem of cloning object that are kept as references
  4662. *
  4663. * @return void
  4664. */
  4665. public function __clone()
  4666. {
  4667. // Force a copy of this->lines, otherwise it will point to same object.
  4668. if (isset($this->lines) && is_array($this->lines)) {
  4669. $nboflines = count($this->lines);
  4670. for ($i = 0; $i < $nboflines; $i++) {
  4671. $this->lines[$i] = clone $this->lines[$i];
  4672. }
  4673. }
  4674. }
  4675. /**
  4676. * Common function for all objects extending CommonObject for generating documents
  4677. *
  4678. * @param string $modelspath Relative folder where generators are placed
  4679. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4680. * @param Translate $outputlangs Output language to use
  4681. * @param int $hidedetails 1 to hide details. 0 by default
  4682. * @param int $hidedesc 1 to hide product description. 0 by default
  4683. * @param int $hideref 1 to hide product reference. 0 by default
  4684. * @param null|array $moreparams Array to provide more information
  4685. * @return int >0 if OK, <0 if KO
  4686. * @see addFileIntoDatabaseIndex()
  4687. */
  4688. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4689. {
  4690. global $conf, $langs, $user, $hookmanager, $action;
  4691. $srctemplatepath = '';
  4692. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  4693. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4694. if (empty($reshook)) {
  4695. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4696. if (empty($modele)) {
  4697. $this->error = 'BadValueForParameterModele';
  4698. return -1;
  4699. }
  4700. // Increase limit for PDF build
  4701. $err = error_reporting();
  4702. error_reporting(0);
  4703. @set_time_limit(120);
  4704. error_reporting($err);
  4705. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4706. $tmp = explode(':', $modele, 2);
  4707. if (!empty($tmp[1])) {
  4708. $modele = $tmp[0];
  4709. $srctemplatepath = $tmp[1];
  4710. }
  4711. // Search template files
  4712. $file = '';
  4713. $classname = '';
  4714. $filefound = '';
  4715. $dirmodels = array('/');
  4716. if (is_array($conf->modules_parts['models'])) {
  4717. $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4718. }
  4719. foreach ($dirmodels as $reldir) {
  4720. foreach (array('doc', 'pdf') as $prefix) {
  4721. if (in_array(get_class($this), array('Adherent'))) {
  4722. // Member module use prefix_modele.class.php
  4723. $file = $prefix."_".$modele.".class.php";
  4724. } else {
  4725. // Other module use prefix_modele.modules.php
  4726. $file = $prefix."_".$modele.".modules.php";
  4727. }
  4728. // On verifie l'emplacement du modele
  4729. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  4730. if (file_exists($file)) {
  4731. $filefound = $file;
  4732. $classname = $prefix.'_'.$modele;
  4733. break;
  4734. }
  4735. }
  4736. if ($filefound) {
  4737. break;
  4738. }
  4739. }
  4740. // If generator was found
  4741. if ($filefound) {
  4742. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4743. require_once $file;
  4744. $obj = new $classname($this->db);
  4745. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4746. if ($obj->type == 'odt' && empty($srctemplatepath)) {
  4747. $varfortemplatedir = $obj->scandir;
  4748. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
  4749. $dirtoscan = $conf->global->$varfortemplatedir;
  4750. $listoffiles = array();
  4751. // Now we add first model found in directories scanned
  4752. $listofdir = explode(',', $dirtoscan);
  4753. foreach ($listofdir as $key => $tmpdir) {
  4754. $tmpdir = trim($tmpdir);
  4755. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4756. if (!$tmpdir) {
  4757. unset($listofdir[$key]);
  4758. continue;
  4759. }
  4760. if (is_dir($tmpdir)) {
  4761. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4762. if (count($tmpfiles)) {
  4763. $listoffiles = array_merge($listoffiles, $tmpfiles);
  4764. }
  4765. }
  4766. }
  4767. if (count($listoffiles)) {
  4768. foreach ($listoffiles as $record) {
  4769. $srctemplatepath = $record['fullname'];
  4770. break;
  4771. }
  4772. }
  4773. }
  4774. if (empty($srctemplatepath)) {
  4775. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4776. return -1;
  4777. }
  4778. }
  4779. if ($obj->type == 'odt' && !empty($srctemplatepath)) {
  4780. if (!dol_is_file($srctemplatepath)) {
  4781. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  4782. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4783. return -1;
  4784. }
  4785. }
  4786. // We save charset_output to restore it because write_file can change it if needed for
  4787. // output format that does not support UTF8.
  4788. $sav_charset_output = $outputlangs->charset_output;
  4789. if (in_array(get_class($this), array('Adherent'))) {
  4790. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
  4791. } else {
  4792. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4793. }
  4794. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4795. if ($resultwritefile > 0) {
  4796. $outputlangs->charset_output = $sav_charset_output;
  4797. // We delete old preview
  4798. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4799. dol_delete_preview($this);
  4800. // Index file in database
  4801. if (!empty($obj->result['fullpath'])) {
  4802. $destfull = $obj->result['fullpath'];
  4803. // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
  4804. $update_main_doc_field = 0;
  4805. if (!empty($obj->update_main_doc_field)) {
  4806. $update_main_doc_field = 1;
  4807. }
  4808. $this->indexFile($destfull, $update_main_doc_field);
  4809. } else {
  4810. 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);
  4811. }
  4812. // Success in building document. We build meta file.
  4813. dol_meta_create($this);
  4814. return 1;
  4815. } else {
  4816. $outputlangs->charset_output = $sav_charset_output;
  4817. $this->error = $obj->error;
  4818. $this->errors = $obj->errors;
  4819. dol_syslog("Error generating document for ".__CLASS__.". Error: ".$obj->error, LOG_ERR);
  4820. return -1;
  4821. }
  4822. } else {
  4823. if (!$filefound) {
  4824. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4825. $this->errors[] = $this->error;
  4826. dol_syslog($this->error, LOG_ERR);
  4827. } else {
  4828. $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
  4829. $this->errors[] = $this->error;
  4830. dol_syslog($this->error, LOG_ERR);
  4831. }
  4832. return -1;
  4833. }
  4834. } else {
  4835. return $reshook;
  4836. }
  4837. }
  4838. /**
  4839. * Index a file into the ECM database
  4840. *
  4841. * @param string $destfull Full path of file to index
  4842. * @param int $update_main_doc_field Update field main_doc file into table of object
  4843. * @return int <0 if KO, >0 if OK
  4844. */
  4845. public function indexFile($destfull, $update_main_doc_field)
  4846. {
  4847. global $conf, $user;
  4848. $upload_dir = dirname($destfull);
  4849. $destfile = basename($destfull);
  4850. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  4851. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  4852. $filename = basename($destfile);
  4853. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4854. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4855. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4856. $ecmfile = new EcmFiles($this->db);
  4857. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  4858. // Set the public "share" key
  4859. $setsharekey = false;
  4860. if ($this->element == 'propal' || $this->element == 'proposal') {
  4861. if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
  4862. $setsharekey = true; // feature to make online signature is not set or set to on (default)
  4863. }
  4864. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4865. $setsharekey = true;
  4866. }
  4867. }
  4868. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  4869. $setsharekey = true;
  4870. }
  4871. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  4872. $setsharekey = true;
  4873. }
  4874. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4875. $setsharekey = true;
  4876. }
  4877. if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4878. $setsharekey = true;
  4879. }
  4880. if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4881. $setsharekey = true;
  4882. }
  4883. if ($setsharekey) {
  4884. if (empty($ecmfile->share)) { // Because object not found or share not set yet
  4885. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  4886. $ecmfile->share = getRandomPassword(true);
  4887. }
  4888. }
  4889. if ($result > 0) {
  4890. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4891. $ecmfile->fullpath_orig = '';
  4892. $ecmfile->gen_or_uploaded = 'generated';
  4893. $ecmfile->description = ''; // indexed content
  4894. $ecmfile->keywords = ''; // keyword content
  4895. $result = $ecmfile->update($user);
  4896. if ($result < 0) {
  4897. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4898. return -1;
  4899. }
  4900. } else {
  4901. $ecmfile->entity = $conf->entity;
  4902. $ecmfile->filepath = $rel_dir;
  4903. $ecmfile->filename = $filename;
  4904. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4905. $ecmfile->fullpath_orig = '';
  4906. $ecmfile->gen_or_uploaded = 'generated';
  4907. $ecmfile->description = ''; // indexed content
  4908. $ecmfile->keywords = ''; // keyword content
  4909. $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
  4910. $ecmfile->src_object_id = $this->id;
  4911. $result = $ecmfile->create($user);
  4912. if ($result < 0) {
  4913. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4914. return -1;
  4915. }
  4916. }
  4917. /*$this->result['fullname']=$destfull;
  4918. $this->result['filepath']=$ecmfile->filepath;
  4919. $this->result['filename']=$ecmfile->filename;*/
  4920. //var_dump($obj->update_main_doc_field);exit;
  4921. if ($update_main_doc_field && !empty($this->table_element)) {
  4922. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
  4923. $sql .= " WHERE rowid = ".((int) $this->id);
  4924. $resql = $this->db->query($sql);
  4925. if (!$resql) {
  4926. dol_print_error($this->db);
  4927. return -1;
  4928. } else {
  4929. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  4930. }
  4931. }
  4932. }
  4933. return 1;
  4934. }
  4935. /**
  4936. * Build thumb
  4937. * @todo Move this into files.lib.php
  4938. *
  4939. * @param string $file Path file in UTF8 to original file to create thumbs from.
  4940. * @return void
  4941. */
  4942. public function addThumbs($file)
  4943. {
  4944. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  4945. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  4946. $file_osencoded = dol_osencode($file);
  4947. if (file_exists($file_osencoded)) {
  4948. // Create small thumbs for company (Ratio is near 16/9)
  4949. // Used on logon for example
  4950. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  4951. // Create mini thumbs for company (Ratio is near 16/9)
  4952. // Used on menu or for setup page for example
  4953. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  4954. }
  4955. }
  4956. /* Functions common to commonobject and commonobjectline */
  4957. /* For default values */
  4958. /**
  4959. * Return the default value to use for a field when showing the create form of object.
  4960. * Return values in this order:
  4961. * 1) If parameter is available into POST, we return it first.
  4962. * 2) If not but an alternate value was provided as parameter of function, we return it.
  4963. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  4964. * 4) Return value found into database (TODO No yet implemented)
  4965. *
  4966. * @param string $fieldname Name of field
  4967. * @param string $alternatevalue Alternate value to use
  4968. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  4969. **/
  4970. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
  4971. {
  4972. global $conf, $_POST;
  4973. // If param here has been posted, we use this value first.
  4974. if (GETPOSTISSET($fieldname)) {
  4975. return GETPOST($fieldname, 'alphanohtml', 3);
  4976. }
  4977. if (isset($alternatevalue)) {
  4978. return $alternatevalue;
  4979. }
  4980. $newelement = $this->element;
  4981. if ($newelement == 'facture') {
  4982. $newelement = 'invoice';
  4983. }
  4984. if ($newelement == 'commande') {
  4985. $newelement = 'order';
  4986. }
  4987. if (empty($newelement)) {
  4988. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  4989. return '';
  4990. }
  4991. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  4992. //var_dump($keyforfieldname);
  4993. if (isset($conf->global->$keyforfieldname)) {
  4994. return $conf->global->$keyforfieldname;
  4995. }
  4996. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  4997. }
  4998. /* For triggers */
  4999. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5000. /**
  5001. * Call trigger based on this instance.
  5002. * Some context information may also be provided into array property this->context.
  5003. * NB: Error from trigger are stacked in interface->errors
  5004. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  5005. *
  5006. * @param string $triggerName trigger's name to execute
  5007. * @param User $user Object user
  5008. * @return int Result of run_triggers
  5009. */
  5010. public function call_trigger($triggerName, $user)
  5011. {
  5012. // phpcs:enable
  5013. global $langs, $conf;
  5014. if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
  5015. dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.');
  5016. exit;
  5017. }
  5018. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  5019. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  5020. $langs = new Translate('', $conf);
  5021. }
  5022. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  5023. $interface = new Interfaces($this->db);
  5024. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  5025. if ($result < 0) {
  5026. if (!empty($this->errors)) {
  5027. $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.
  5028. } else {
  5029. $this->errors = $interface->errors;
  5030. }
  5031. }
  5032. return $result;
  5033. }
  5034. /* Functions for data in other language */
  5035. /**
  5036. * Function to get alternative languages of a data into $this->array_languages
  5037. * This method is NOT called by method fetch of objects but must be called separately.
  5038. *
  5039. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  5040. * @see fetch_optionnals()
  5041. */
  5042. public function fetchValuesForExtraLanguages()
  5043. {
  5044. // To avoid SQL errors. Probably not the better solution though
  5045. if (!$this->element) {
  5046. return 0;
  5047. }
  5048. if (!($this->id > 0)) {
  5049. return 0;
  5050. }
  5051. if (is_array($this->array_languages)) {
  5052. return 1;
  5053. }
  5054. $this->array_languages = array();
  5055. $element = $this->element;
  5056. if ($element == 'categorie') {
  5057. $element = 'categories'; // For compatibility
  5058. }
  5059. // Request to get translation values for object
  5060. $sql = "SELECT rowid, property, lang , value";
  5061. $sql .= " FROM ".$this->db->prefix()."object_lang";
  5062. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  5063. $sql .= " AND fk_object = ".((int) $this->id);
  5064. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5065. $resql = $this->db->query($sql);
  5066. if ($resql) {
  5067. $numrows = $this->db->num_rows($resql);
  5068. if ($numrows) {
  5069. $i = 0;
  5070. while ($i < $numrows) {
  5071. $obj = $this->db->fetch_object($resql);
  5072. $key = $obj->property;
  5073. $value = $obj->value;
  5074. $codelang = $obj->lang;
  5075. $type = $this->fields[$key]['type'];
  5076. // we can add this attribute to object
  5077. if (preg_match('/date/', $type)) {
  5078. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  5079. } else {
  5080. $this->array_languages[$key][$codelang] = $value;
  5081. }
  5082. $i++;
  5083. }
  5084. }
  5085. $this->db->free($resql);
  5086. if ($numrows) {
  5087. return $numrows;
  5088. } else {
  5089. return 0;
  5090. }
  5091. } else {
  5092. dol_print_error($this->db);
  5093. return -1;
  5094. }
  5095. }
  5096. /**
  5097. * Fill array_options property of object by extrafields value (using for data sent by forms)
  5098. *
  5099. * @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.
  5100. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  5101. */
  5102. public function setValuesForExtraLanguages($onlykey = '')
  5103. {
  5104. global $_POST, $langs;
  5105. // Get extra fields
  5106. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  5107. $tmparray = explode('-', $postfieldkey);
  5108. if ($tmparray[0] != 'field') {
  5109. continue;
  5110. }
  5111. $element = $tmparray[1];
  5112. $key = $tmparray[2];
  5113. $codelang = $tmparray[3];
  5114. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  5115. if (!empty($onlykey) && $key != $onlykey) {
  5116. continue;
  5117. }
  5118. if ($element != $this->element) {
  5119. continue;
  5120. }
  5121. $key_type = $this->fields[$key]['type'];
  5122. $enabled = 1;
  5123. if (isset($this->fields[$key]['enabled'])) {
  5124. $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
  5125. }
  5126. /*$perms = 1;
  5127. if (isset($this->fields[$key]['perms']))
  5128. {
  5129. $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
  5130. }*/
  5131. if (empty($enabled)) {
  5132. continue;
  5133. }
  5134. //if (empty($perms)) continue;
  5135. if (in_array($key_type, array('date'))) {
  5136. // Clean parameters
  5137. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5138. $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
  5139. } elseif (in_array($key_type, array('datetime'))) {
  5140. // Clean parameters
  5141. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5142. $value_key = dol_mktime(GETPOST($postfieldkey."hour", 'int'), GETPOST($postfieldkey."min", 'int'), 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
  5143. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  5144. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  5145. if (!empty($value_arr)) {
  5146. $value_key = implode(',', $value_arr);
  5147. } else {
  5148. $value_key = '';
  5149. }
  5150. } elseif (in_array($key_type, array('price', 'double'))) {
  5151. $value_arr = GETPOST($postfieldkey, 'alpha');
  5152. $value_key = price2num($value_arr);
  5153. } else {
  5154. $value_key = GETPOST($postfieldkey);
  5155. if (in_array($key_type, array('link')) && $value_key == '-1') {
  5156. $value_key = '';
  5157. }
  5158. }
  5159. $this->array_languages[$key][$codelang] = $value_key;
  5160. /*if ($nofillrequired) {
  5161. $langs->load('errors');
  5162. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  5163. return -1;
  5164. }*/
  5165. }
  5166. return 1;
  5167. }
  5168. /* Functions for extrafields */
  5169. /**
  5170. * Function to make a fetch but set environment to avoid to load computed values before.
  5171. *
  5172. * @param int $id ID of object
  5173. * @return int >0 if OK, 0 if not found, <0 if KO
  5174. */
  5175. public function fetchNoCompute($id)
  5176. {
  5177. global $conf;
  5178. $savDisableCompute = $conf->disable_compute;
  5179. $conf->disable_compute = 1;
  5180. $ret = $this->fetch($id);
  5181. $conf->disable_compute = $savDisableCompute;
  5182. return $ret;
  5183. }
  5184. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5185. /**
  5186. * Function to get extra fields of an object into $this->array_options
  5187. * This method is in most cases called by method fetch of objects but you can call it separately.
  5188. *
  5189. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  5190. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  5191. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  5192. * @see fetchValuesForExtraLanguages()
  5193. */
  5194. public function fetch_optionals($rowid = null, $optionsArray = null)
  5195. {
  5196. // phpcs:enable
  5197. global $conf, $extrafields;
  5198. if (empty($rowid)) {
  5199. $rowid = $this->id;
  5200. }
  5201. if (empty($rowid) && isset($this->rowid)) {
  5202. $rowid = $this->rowid; // deprecated
  5203. }
  5204. // To avoid SQL errors. Probably not the better solution though
  5205. if (!$this->table_element) {
  5206. return 0;
  5207. }
  5208. $this->array_options = array();
  5209. if (!is_array($optionsArray)) {
  5210. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  5211. if (!isset($extrafields) || !is_object($extrafields)) {
  5212. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5213. $extrafields = new ExtraFields($this->db);
  5214. }
  5215. // Load array of extrafields for elementype = $this->table_element
  5216. if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
  5217. $extrafields->fetch_name_optionals_label($this->table_element);
  5218. }
  5219. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  5220. } else {
  5221. global $extrafields;
  5222. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  5223. }
  5224. $table_element = $this->table_element;
  5225. if ($table_element == 'categorie') {
  5226. $table_element = 'categories'; // For compatibility
  5227. }
  5228. // Request to get complementary values
  5229. if (is_array($optionsArray) && count($optionsArray) > 0) {
  5230. $sql = "SELECT rowid";
  5231. foreach ($optionsArray as $name => $label) {
  5232. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
  5233. $sql .= ", ".$name;
  5234. }
  5235. }
  5236. $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
  5237. $sql .= " WHERE fk_object = ".((int) $rowid);
  5238. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5239. $resql = $this->db->query($sql);
  5240. if ($resql) {
  5241. $numrows = $this->db->num_rows($resql);
  5242. if ($numrows) {
  5243. $tab = $this->db->fetch_array($resql);
  5244. foreach ($tab as $key => $value) {
  5245. // 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)
  5246. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
  5247. // we can add this attribute to object
  5248. if (!empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
  5249. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  5250. $this->array_options["options_".$key] = $this->db->jdate($value);
  5251. } else {
  5252. $this->array_options["options_".$key] = $value;
  5253. }
  5254. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  5255. }
  5256. }
  5257. // If field is a computed field, value must become result of compute
  5258. foreach ($tab as $key => $value) {
  5259. if (!empty($extrafields) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
  5260. //var_dump($conf->disable_compute);
  5261. if (empty($conf->disable_compute)) {
  5262. $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
  5263. }
  5264. }
  5265. }
  5266. }
  5267. $this->db->free($resql);
  5268. if ($numrows) {
  5269. return $numrows;
  5270. } else {
  5271. return 0;
  5272. }
  5273. } else {
  5274. $this->errors[]=$this->db->lasterror;
  5275. return -1;
  5276. }
  5277. }
  5278. return 0;
  5279. }
  5280. /**
  5281. * Delete all extra fields values for the current object.
  5282. *
  5283. * @return int <0 if KO, >0 if OK
  5284. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  5285. */
  5286. public function deleteExtraFields()
  5287. {
  5288. global $conf;
  5289. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5290. return 0;
  5291. }
  5292. $this->db->begin();
  5293. $table_element = $this->table_element;
  5294. if ($table_element == 'categorie') {
  5295. $table_element = 'categories'; // For compatibility
  5296. }
  5297. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  5298. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5299. $resql = $this->db->query($sql_del);
  5300. if (!$resql) {
  5301. $this->error = $this->db->lasterror();
  5302. $this->db->rollback();
  5303. return -1;
  5304. } else {
  5305. $this->db->commit();
  5306. return 1;
  5307. }
  5308. }
  5309. /**
  5310. * Add/Update all extra fields values for the current object.
  5311. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5312. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5313. *
  5314. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5315. * @param User $userused Object user
  5316. * @return int -1=error, O=did nothing, 1=OK
  5317. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  5318. */
  5319. public function insertExtraFields($trigger = '', $userused = null)
  5320. {
  5321. global $conf, $langs, $user;
  5322. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5323. return 0;
  5324. }
  5325. if (empty($userused)) {
  5326. $userused = $user;
  5327. }
  5328. $error = 0;
  5329. if (!empty($this->array_options)) {
  5330. // Check parameters
  5331. $langs->load('admin');
  5332. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5333. $extrafields = new ExtraFields($this->db);
  5334. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  5335. // Eliminate copied source object extra fields that do not exist in target object
  5336. $new_array_options = array();
  5337. foreach ($this->array_options as $key => $value) {
  5338. if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
  5339. $new_array_options[$key] = $value;
  5340. } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
  5341. $new_array_options['options_'.$key] = $value;
  5342. }
  5343. }
  5344. foreach ($new_array_options as $key => $value) {
  5345. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5346. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  5347. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  5348. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  5349. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  5350. $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
  5351. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  5352. // If we clone, we have to clean unique extrafields to prevent duplicates.
  5353. // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
  5354. if (! empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && ! empty($attributeUnique)) {
  5355. $new_array_options[$key] = null;
  5356. }
  5357. // Similar code than into insertExtraFields
  5358. if ($attributeRequired) {
  5359. $mandatorypb = false;
  5360. if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
  5361. $mandatorypb = true;
  5362. }
  5363. if ($this->array_options[$key] === '') {
  5364. $mandatorypb = true;
  5365. }
  5366. if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
  5367. $mandatorypb = true;
  5368. }
  5369. if ($mandatorypb) {
  5370. $langs->load("errors");
  5371. dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
  5372. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5373. return -1;
  5374. }
  5375. }
  5376. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5377. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5378. if (!empty($attrfieldcomputed)) {
  5379. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5380. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5381. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5382. $new_array_options[$key] = $value;
  5383. } else {
  5384. $new_array_options[$key] = null;
  5385. }
  5386. }
  5387. switch ($attributeType) {
  5388. case 'int':
  5389. if (!is_numeric($value) && $value != '') {
  5390. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5391. return -1;
  5392. } elseif ($value == '') {
  5393. $new_array_options[$key] = null;
  5394. }
  5395. break;
  5396. case 'price':
  5397. case 'double':
  5398. $value = price2num($value);
  5399. if (!is_numeric($value) && $value != '') {
  5400. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5401. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5402. return -1;
  5403. } elseif ($value == '') {
  5404. $new_array_options[$key] = null;
  5405. }
  5406. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5407. $new_array_options[$key] = $value;
  5408. break;
  5409. /*case 'select': // Not required, we chosed value='0' for undefined values
  5410. if ($value=='-1')
  5411. {
  5412. $this->array_options[$key] = null;
  5413. }
  5414. break;*/
  5415. case 'password':
  5416. $algo = '';
  5417. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
  5418. // If there is an encryption choice, we use it to crypt data before insert
  5419. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  5420. $algo = reset($tmparrays);
  5421. if ($algo != '') {
  5422. //global $action; // $action may be 'create', 'update', 'update_extras'...
  5423. //var_dump($action);
  5424. //var_dump($this->oldcopy);exit;
  5425. 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
  5426. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  5427. 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.
  5428. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5429. } else {
  5430. // var_dump($algo);
  5431. $newvalue = dol_hash($this->array_options[$key], $algo);
  5432. $new_array_options[$key] = $newvalue;
  5433. }
  5434. } else {
  5435. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5436. }
  5437. }
  5438. } else // Common usage
  5439. {
  5440. $new_array_options[$key] = $this->array_options[$key];
  5441. }
  5442. break;
  5443. case 'date':
  5444. case 'datetime':
  5445. // If data is a string instead of a timestamp, we convert it
  5446. if (!is_int($this->array_options[$key])) {
  5447. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5448. }
  5449. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  5450. break;
  5451. case 'link':
  5452. $param_list = array_keys($attributeParam['options']);
  5453. // 0 : ObjectName
  5454. // 1 : classPath
  5455. $InfoFieldList = explode(":", $param_list[0]);
  5456. dol_include_once($InfoFieldList[1]);
  5457. if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
  5458. if ($value == '-1') { // -1 is key for no defined in combo list of objects
  5459. $new_array_options[$key] = '';
  5460. } elseif ($value) {
  5461. $object = new $InfoFieldList[0]($this->db);
  5462. if (is_numeric($value)) {
  5463. $res = $object->fetch($value); // Common case
  5464. } else {
  5465. $res = $object->fetch('', $value); // For compatibility
  5466. }
  5467. if ($res > 0) {
  5468. $new_array_options[$key] = $object->id;
  5469. } else {
  5470. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5471. $this->db->rollback();
  5472. return -1;
  5473. }
  5474. }
  5475. } else {
  5476. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5477. }
  5478. break;
  5479. }
  5480. }
  5481. $this->db->begin();
  5482. $table_element = $this->table_element;
  5483. if ($table_element == 'categorie') {
  5484. $table_element = 'categories'; // For compatibility
  5485. }
  5486. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  5487. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5488. $this->db->query($sql_del);
  5489. $sql = "INSERT INTO ".$this->db->prefix().$table_element."_extrafields (fk_object";
  5490. foreach ($new_array_options as $key => $value) {
  5491. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5492. // Add field of attribut
  5493. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
  5494. $sql .= ",".$attributeKey;
  5495. }
  5496. }
  5497. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5498. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5499. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5500. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5501. $sql .= ",".$tmpkey;
  5502. }
  5503. }
  5504. }
  5505. $sql .= ") VALUES (".$this->id;
  5506. foreach ($new_array_options as $key => $value) {
  5507. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5508. // Add field of attribute
  5509. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
  5510. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
  5511. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  5512. } else {
  5513. $sql .= ",null";
  5514. }
  5515. }
  5516. }
  5517. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5518. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5519. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5520. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5521. if (in_array($tmpval, array('int', 'double', 'price'))) {
  5522. $sql .= ", 0";
  5523. } else {
  5524. $sql .= ", ''";
  5525. }
  5526. }
  5527. }
  5528. }
  5529. $sql .= ")";
  5530. $resql = $this->db->query($sql);
  5531. if (!$resql) {
  5532. $this->error = $this->db->lasterror();
  5533. $error++;
  5534. }
  5535. if (!$error && $trigger) {
  5536. // Call trigger
  5537. $this->context = array('extrafieldaddupdate'=>1);
  5538. $result = $this->call_trigger($trigger, $userused);
  5539. if ($result < 0) {
  5540. $error++;
  5541. }
  5542. // End call trigger
  5543. }
  5544. if ($error) {
  5545. $this->db->rollback();
  5546. return -1;
  5547. } else {
  5548. $this->db->commit();
  5549. return 1;
  5550. }
  5551. } else {
  5552. return 0;
  5553. }
  5554. }
  5555. /**
  5556. * Add/Update all extra fields values for the current object.
  5557. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5558. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5559. *
  5560. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5561. * @param User $userused Object user
  5562. * @return int -1=error, O=did nothing, 1=OK
  5563. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  5564. */
  5565. public function insertExtraLanguages($trigger = '', $userused = null)
  5566. {
  5567. global $conf, $langs, $user;
  5568. if (empty($userused)) {
  5569. $userused = $user;
  5570. }
  5571. $error = 0;
  5572. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5573. return 0; // For avoid conflicts if trigger used
  5574. }
  5575. if (is_array($this->array_languages)) {
  5576. $new_array_languages = $this->array_languages;
  5577. foreach ($new_array_languages as $key => $value) {
  5578. $attributeKey = $key;
  5579. $attributeType = $this->fields[$attributeKey]['type'];
  5580. $attributeLabel = $this->fields[$attributeKey]['label'];
  5581. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5582. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5583. switch ($attributeType) {
  5584. case 'int':
  5585. if (!is_numeric($value) && $value != '') {
  5586. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5587. return -1;
  5588. } elseif ($value == '') {
  5589. $new_array_languages[$key] = null;
  5590. }
  5591. break;
  5592. case 'double':
  5593. $value = price2num($value);
  5594. if (!is_numeric($value) && $value != '') {
  5595. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5596. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5597. return -1;
  5598. } elseif ($value == '') {
  5599. $new_array_languages[$key] = null;
  5600. }
  5601. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5602. $new_array_languages[$key] = $value;
  5603. break;
  5604. /*case 'select': // Not required, we chosed value='0' for undefined values
  5605. if ($value=='-1')
  5606. {
  5607. $this->array_options[$key] = null;
  5608. }
  5609. break;*/
  5610. }
  5611. }
  5612. $this->db->begin();
  5613. $table_element = $this->table_element;
  5614. if ($table_element == 'categorie') {
  5615. $table_element = 'categories'; // For compatibility
  5616. }
  5617. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  5618. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  5619. foreach ($langcodearray as $langcode => $value) {
  5620. $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
  5621. $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  5622. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  5623. $this->db->query($sql_del);
  5624. if ($value !== '') {
  5625. $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
  5626. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  5627. $sql .= ")";
  5628. $resql = $this->db->query($sql);
  5629. if (!$resql) {
  5630. $this->error = $this->db->lasterror();
  5631. $error++;
  5632. break;
  5633. }
  5634. }
  5635. }
  5636. }
  5637. if (!$error && $trigger) {
  5638. // Call trigger
  5639. $this->context = array('extralanguagesaddupdate'=>1);
  5640. $result = $this->call_trigger($trigger, $userused);
  5641. if ($result < 0) {
  5642. $error++;
  5643. }
  5644. // End call trigger
  5645. }
  5646. if ($error) {
  5647. $this->db->rollback();
  5648. return -1;
  5649. } else {
  5650. $this->db->commit();
  5651. return 1;
  5652. }
  5653. } else {
  5654. return 0;
  5655. }
  5656. }
  5657. /**
  5658. * Update 1 extra field value for the current object. Keep other fields unchanged.
  5659. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5660. *
  5661. * @param string $key Key of the extrafield to update (without starting 'options_')
  5662. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5663. * @param User $userused Object user
  5664. * @return int -1=error, O=did nothing, 1=OK
  5665. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  5666. */
  5667. public function updateExtraField($key, $trigger = null, $userused = null)
  5668. {
  5669. global $conf, $langs, $user;
  5670. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5671. return 0;
  5672. }
  5673. if (empty($userused)) {
  5674. $userused = $user;
  5675. }
  5676. $error = 0;
  5677. if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
  5678. // Check parameters
  5679. $langs->load('admin');
  5680. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5681. $extrafields = new ExtraFields($this->db);
  5682. $extrafields->fetch_name_optionals_label($this->table_element);
  5683. $value = $this->array_options["options_".$key];
  5684. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  5685. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  5686. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  5687. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  5688. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  5689. // Similar code than into insertExtraFields
  5690. if ($attributeRequired) {
  5691. $mandatorypb = false;
  5692. if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
  5693. $mandatorypb = true;
  5694. }
  5695. if ($this->array_options["options_".$key] === '') {
  5696. $mandatorypb = true;
  5697. }
  5698. if ($mandatorypb) {
  5699. $langs->load("errors");
  5700. dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
  5701. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5702. return -1;
  5703. }
  5704. }
  5705. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5706. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5707. if (!empty($attrfieldcomputed)) {
  5708. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5709. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5710. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5711. $this->array_options["options_".$key] = $value;
  5712. } else {
  5713. $this->array_options["options_".$key] = null;
  5714. }
  5715. }
  5716. switch ($attributeType) {
  5717. case 'int':
  5718. if (!is_numeric($value) && $value != '') {
  5719. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5720. return -1;
  5721. } elseif ($value === '') {
  5722. $this->array_options["options_".$key] = null;
  5723. }
  5724. break;
  5725. case 'double':
  5726. $value = price2num($value);
  5727. if (!is_numeric($value) && $value != '') {
  5728. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5729. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5730. return -1;
  5731. } elseif ($value === '') {
  5732. $this->array_options["options_".$key] = null;
  5733. }
  5734. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5735. $this->array_options["options_".$key] = $value;
  5736. break;
  5737. /*case 'select': // Not required, we chosed value='0' for undefined values
  5738. if ($value=='-1')
  5739. {
  5740. $this->array_options[$key] = null;
  5741. }
  5742. break;*/
  5743. case 'price':
  5744. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  5745. break;
  5746. case 'date':
  5747. case 'datetime':
  5748. if (empty($this->array_options["options_".$key])) {
  5749. $this->array_options["options_".$key] = null;
  5750. } else {
  5751. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5752. }
  5753. break;
  5754. case 'boolean':
  5755. if (empty($this->array_options["options_".$key])) {
  5756. $this->array_options["options_".$key] = null;
  5757. }
  5758. break;
  5759. /*
  5760. case 'link':
  5761. $param_list = array_keys($attributeParam['options']);
  5762. // 0 : ObjectName
  5763. // 1 : classPath
  5764. $InfoFieldList = explode(":", $param_list[0]);
  5765. dol_include_once($InfoFieldList[1]);
  5766. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  5767. {
  5768. if ($value == '-1') // -1 is key for no defined in combo list of objects
  5769. {
  5770. $new_array_options[$key] = '';
  5771. } elseif ($value) {
  5772. $object = new $InfoFieldList[0]($this->db);
  5773. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  5774. else $res = $object->fetch('', $value); // For compatibility
  5775. if ($res > 0) $new_array_options[$key] = $object->id;
  5776. else {
  5777. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5778. $this->db->rollback();
  5779. return -1;
  5780. }
  5781. }
  5782. } else {
  5783. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5784. }
  5785. break;
  5786. */
  5787. }
  5788. $this->db->begin();
  5789. $linealreadyfound = 0;
  5790. // 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)
  5791. $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5792. $resql = $this->db->query($sql);
  5793. if ($resql) {
  5794. $tmpobj = $this->db->fetch_object($resql);
  5795. if ($tmpobj) {
  5796. $linealreadyfound = $tmpobj->nb;
  5797. }
  5798. }
  5799. if ($linealreadyfound) {
  5800. if ($this->array_options["options_".$key] === null) {
  5801. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = null";
  5802. } else {
  5803. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
  5804. }
  5805. $sql .= " WHERE fk_object = ".((int) $this->id);
  5806. } else {
  5807. $result = $this->insertExtraFields('', $user);
  5808. if ($result < 0) {
  5809. $error++;
  5810. }
  5811. }
  5812. $resql = $this->db->query($sql);
  5813. if (!$resql) {
  5814. $error++;
  5815. $this->error = $this->db->lasterror();
  5816. }
  5817. if (!$error && $trigger) {
  5818. // Call trigger
  5819. $this->context = array('extrafieldupdate'=>1);
  5820. $result = $this->call_trigger($trigger, $userused);
  5821. if ($result < 0) {
  5822. $error++;
  5823. }
  5824. // End call trigger
  5825. }
  5826. if ($error) {
  5827. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  5828. $this->db->rollback();
  5829. return -1;
  5830. } else {
  5831. $this->db->commit();
  5832. return 1;
  5833. }
  5834. } else {
  5835. return 0;
  5836. }
  5837. }
  5838. /**
  5839. * Update an extra language value for the current object.
  5840. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5841. *
  5842. * @param string $key Key of the extrafield (without starting 'options_')
  5843. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5844. * @param User $userused Object user
  5845. * @return int -1=error, O=did nothing, 1=OK
  5846. * @see updateExtraFields(), insertExtraLanguages()
  5847. */
  5848. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  5849. {
  5850. global $conf, $langs, $user;
  5851. if (empty($userused)) {
  5852. $userused = $user;
  5853. }
  5854. $error = 0;
  5855. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5856. return 0; // For avoid conflicts if trigger used
  5857. }
  5858. return 0;
  5859. }
  5860. /**
  5861. * Return HTML string to put an input field into a page
  5862. * Code very similar with showInputField of extra fields
  5863. *
  5864. * @param array $val Array of properties for field to show (used only if ->fields not defined)
  5865. * @param string $key Key of attribute
  5866. * @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)
  5867. * @param string $moreparam To add more parameters on html input tag
  5868. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5869. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5870. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  5871. * @param int $nonewbutton Force to not show the new button on field that are links to object
  5872. * @return string
  5873. */
  5874. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  5875. {
  5876. global $conf, $langs, $form;
  5877. if (!is_object($form)) {
  5878. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  5879. $form = new Form($this->db);
  5880. }
  5881. if (!empty($this->fields)) {
  5882. $val = $this->fields[$key];
  5883. }
  5884. // Validation tests and output
  5885. $fieldValidationErrorMsg = '';
  5886. $validationClass = '';
  5887. $fieldValidationErrorMsg = $this->getFieldError($key);
  5888. if (!empty($fieldValidationErrorMsg)) {
  5889. $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
  5890. } else {
  5891. $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
  5892. }
  5893. $out = '';
  5894. $type = '';
  5895. $isDependList = 0;
  5896. $param = array();
  5897. $param['options'] = array();
  5898. $reg = array();
  5899. $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
  5900. // Because we work on extrafields
  5901. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5902. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5903. $type = 'link';
  5904. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5905. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5906. $type = 'link';
  5907. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  5908. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5909. $type = 'link';
  5910. } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5911. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5912. $type = 'sellist';
  5913. } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5914. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5915. $type = 'sellist';
  5916. } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
  5917. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5918. $type = 'sellist';
  5919. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  5920. $param['options'] = array();
  5921. $type = 'varchar';
  5922. $size = $reg[1];
  5923. } elseif (preg_match('/varchar/', $val['type'])) {
  5924. $param['options'] = array();
  5925. $type = 'varchar';
  5926. } else {
  5927. $param['options'] = array();
  5928. $type = $this->fields[$key]['type'];
  5929. }
  5930. // Special case that force options and type ($type can be integer, varchar, ...)
  5931. if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
  5932. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  5933. $type = 'select';
  5934. }
  5935. $label = $this->fields[$key]['label'];
  5936. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  5937. $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
  5938. $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
  5939. $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
  5940. $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
  5941. $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
  5942. $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
  5943. $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
  5944. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  5945. $objectid = $this->id;
  5946. if ($computed) {
  5947. if (!preg_match('/^search_/', $keyprefix)) {
  5948. return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  5949. } else {
  5950. return '';
  5951. }
  5952. }
  5953. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  5954. if (empty($morecss) && !empty($val['css'])) {
  5955. $morecss = $val['css'];
  5956. } elseif (empty($morecss)) {
  5957. if ($type == 'date') {
  5958. $morecss = 'minwidth100imp';
  5959. } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
  5960. $morecss = 'minwidth200imp';
  5961. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  5962. $morecss = 'maxwidth75';
  5963. } elseif ($type == 'url') {
  5964. $morecss = 'minwidth400';
  5965. } elseif ($type == 'boolean') {
  5966. $morecss = '';
  5967. } else {
  5968. if (round($size) < 12) {
  5969. $morecss = 'minwidth100';
  5970. } elseif (round($size) <= 48) {
  5971. $morecss = 'minwidth200';
  5972. } else {
  5973. $morecss = 'minwidth400';
  5974. }
  5975. }
  5976. }
  5977. // Add validation state class
  5978. if (!empty($validationClass)) {
  5979. $morecss.= $validationClass;
  5980. }
  5981. if (in_array($type, array('date'))) {
  5982. $tmp = explode(',', $size);
  5983. $newsize = $tmp[0];
  5984. $showtime = 0;
  5985. // Do not show current date when field not required (see selectDate() method)
  5986. if (!$required && $value == '') {
  5987. $value = '-1';
  5988. }
  5989. // TODO Must also support $moreparam
  5990. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  5991. } elseif (in_array($type, array('datetime'))) {
  5992. $tmp = explode(',', $size);
  5993. $newsize = $tmp[0];
  5994. $showtime = 1;
  5995. // Do not show current date when field not required (see selectDate() method)
  5996. if (!$required && $value == '') $value = '-1';
  5997. // TODO Must also support $moreparam
  5998. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
  5999. } elseif (in_array($type, array('duration'))) {
  6000. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  6001. } elseif (in_array($type, array('int', 'integer'))) {
  6002. $tmp = explode(',', $size);
  6003. $newsize = $tmp[0];
  6004. $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' : '').'>';
  6005. } elseif (in_array($type, array('real'))) {
  6006. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6007. } elseif (preg_match('/varchar/', $type)) {
  6008. $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' : '').'>';
  6009. } elseif (in_array($type, array('mail', 'phone', 'url'))) {
  6010. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6011. } elseif (preg_match('/^text/', $type)) {
  6012. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6013. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  6014. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  6015. $out = $doleditor->Create(1);
  6016. } else {
  6017. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  6018. }
  6019. } elseif (preg_match('/^html/', $type)) {
  6020. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6021. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  6022. $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%');
  6023. $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
  6024. } else {
  6025. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  6026. }
  6027. } elseif ($type == 'boolean') {
  6028. $checked = '';
  6029. if (!empty($value)) {
  6030. $checked = ' checked value="1" ';
  6031. } else {
  6032. $checked = ' value="1" ';
  6033. }
  6034. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  6035. } elseif ($type == 'price') {
  6036. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6037. $value = price($value);
  6038. }
  6039. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  6040. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  6041. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6042. $value = price($value);
  6043. }
  6044. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  6045. } elseif ($type == 'select') {
  6046. $out = '';
  6047. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6048. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6049. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6050. }
  6051. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6052. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
  6053. $out .= '<option value="0">&nbsp;</option>';
  6054. }
  6055. foreach ($param['options'] as $key => $val) {
  6056. if ((string) $key == '') {
  6057. continue;
  6058. }
  6059. list($val, $parent) = explode('|', $val);
  6060. $out .= '<option value="'.$key.'"';
  6061. $out .= (((string) $value == (string) $key) ? ' selected' : '');
  6062. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6063. $out .= '>'.$val.'</option>';
  6064. }
  6065. $out .= '</select>';
  6066. } elseif ($type == 'sellist') {
  6067. $out = '';
  6068. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6069. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6070. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6071. }
  6072. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6073. if (is_array($param['options'])) {
  6074. $param_list = array_keys($param['options']);
  6075. $InfoFieldList = explode(":", $param_list[0]);
  6076. $parentName = '';
  6077. $parentField = '';
  6078. // 0 : tableName
  6079. // 1 : label field name
  6080. // 2 : key fields name (if differ of rowid)
  6081. // 3 : key field parent (for dependent lists)
  6082. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6083. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6084. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6085. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6086. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6087. } else {
  6088. $keyList = $InfoFieldList[2].' as rowid';
  6089. }
  6090. }
  6091. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6092. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6093. $keyList .= ', '.$parentField;
  6094. }
  6095. $fields_label = explode('|', $InfoFieldList[1]);
  6096. if (is_array($fields_label)) {
  6097. $keyList .= ', ';
  6098. $keyList .= implode(', ', $fields_label);
  6099. }
  6100. $sqlwhere = '';
  6101. $sql = "SELECT ".$keyList;
  6102. $sql .= " FROM ".$this->db->prefix().$InfoFieldList[0];
  6103. if (!empty($InfoFieldList[4])) {
  6104. // can use SELECT request
  6105. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6106. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6107. }
  6108. // current object id can be use into filter
  6109. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6110. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6111. } else {
  6112. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6113. }
  6114. //We have to join on extrafield table
  6115. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6116. $sql .= " as main, ".$this->db->prefix().$InfoFieldList[0]."_extrafields as extra";
  6117. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  6118. } else {
  6119. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  6120. }
  6121. } else {
  6122. $sqlwhere .= ' WHERE 1=1';
  6123. }
  6124. // Some tables may have field, some other not. For the moment we disable it.
  6125. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6126. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  6127. }
  6128. $sql .= $sqlwhere;
  6129. //print $sql;
  6130. $sql .= ' ORDER BY '.implode(', ', $fields_label);
  6131. dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
  6132. $resql = $this->db->query($sql);
  6133. if ($resql) {
  6134. $out .= '<option value="0">&nbsp;</option>';
  6135. $num = $this->db->num_rows($resql);
  6136. $i = 0;
  6137. while ($i < $num) {
  6138. $labeltoshow = '';
  6139. $obj = $this->db->fetch_object($resql);
  6140. // Several field into label (eq table:code|libelle:rowid)
  6141. $notrans = false;
  6142. $fields_label = explode('|', $InfoFieldList[1]);
  6143. if (count($fields_label) > 1) {
  6144. $notrans = true;
  6145. foreach ($fields_label as $field_toshow) {
  6146. $labeltoshow .= $obj->$field_toshow.' ';
  6147. }
  6148. } else {
  6149. $labeltoshow = $obj->{$InfoFieldList[1]};
  6150. }
  6151. $labeltoshow = dol_trunc($labeltoshow, 45);
  6152. if ($value == $obj->rowid) {
  6153. foreach ($fields_label as $field_toshow) {
  6154. $translabel = $langs->trans($obj->$field_toshow);
  6155. if ($translabel != $obj->$field_toshow) {
  6156. $labeltoshow = dol_trunc($translabel).' ';
  6157. } else {
  6158. $labeltoshow = dol_trunc($obj->$field_toshow).' ';
  6159. }
  6160. }
  6161. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6162. } else {
  6163. if (!$notrans) {
  6164. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6165. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6166. $labeltoshow = dol_trunc($translabel, 18);
  6167. } else {
  6168. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
  6169. }
  6170. }
  6171. if (empty($labeltoshow)) {
  6172. $labeltoshow = '(not defined)';
  6173. }
  6174. if ($value == $obj->rowid) {
  6175. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6176. }
  6177. if (!empty($InfoFieldList[3]) && $parentField) {
  6178. $parent = $parentName.':'.$obj->{$parentField};
  6179. $isDependList = 1;
  6180. }
  6181. $out .= '<option value="'.$obj->rowid.'"';
  6182. $out .= ($value == $obj->rowid ? ' selected' : '');
  6183. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6184. $out .= '>'.$labeltoshow.'</option>';
  6185. }
  6186. $i++;
  6187. }
  6188. $this->db->free($resql);
  6189. } else {
  6190. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6191. }
  6192. }
  6193. $out .= '</select>';
  6194. } elseif ($type == 'checkbox') {
  6195. $value_arr = explode(',', $value);
  6196. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
  6197. } elseif ($type == 'radio') {
  6198. $out = '';
  6199. foreach ($param['options'] as $keyopt => $val) {
  6200. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  6201. $out .= ' value="'.$keyopt.'"';
  6202. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  6203. $out .= ($value == $keyopt ? 'checked' : '');
  6204. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
  6205. }
  6206. } elseif ($type == 'chkbxlst') {
  6207. if (is_array($value)) {
  6208. $value_arr = $value;
  6209. } else {
  6210. $value_arr = explode(',', $value);
  6211. }
  6212. if (is_array($param['options'])) {
  6213. $param_list = array_keys($param['options']);
  6214. $InfoFieldList = explode(":", $param_list[0]);
  6215. $parentName = '';
  6216. $parentField = '';
  6217. // 0 : tableName
  6218. // 1 : label field name
  6219. // 2 : key fields name (if differ of rowid)
  6220. // 3 : key field parent (for dependent lists)
  6221. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6222. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6223. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6224. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6225. $keyList .= ', '.$parentField;
  6226. }
  6227. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6228. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6229. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6230. } else {
  6231. $keyList = $InfoFieldList[2].' as rowid';
  6232. }
  6233. }
  6234. $fields_label = explode('|', $InfoFieldList[1]);
  6235. if (is_array($fields_label)) {
  6236. $keyList .= ', ';
  6237. $keyList .= implode(', ', $fields_label);
  6238. }
  6239. $sqlwhere = '';
  6240. $sql = "SELECT ".$keyList;
  6241. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6242. if (!empty($InfoFieldList[4])) {
  6243. // can use SELECT request
  6244. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6245. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6246. }
  6247. // current object id can be use into filter
  6248. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6249. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6250. } else {
  6251. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6252. }
  6253. // We have to join on extrafield table
  6254. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6255. $sql .= ' as main, '.$this->db->prefix().$InfoFieldList[0].'_extrafields as extra';
  6256. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  6257. } else {
  6258. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  6259. }
  6260. } else {
  6261. $sqlwhere .= ' WHERE 1=1';
  6262. }
  6263. // Some tables may have field, some other not. For the moment we disable it.
  6264. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6265. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  6266. }
  6267. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  6268. // print $sql;
  6269. $sql .= $sqlwhere;
  6270. dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
  6271. $resql = $this->db->query($sql);
  6272. if ($resql) {
  6273. $num = $this->db->num_rows($resql);
  6274. $i = 0;
  6275. $data = array();
  6276. while ($i < $num) {
  6277. $labeltoshow = '';
  6278. $obj = $this->db->fetch_object($resql);
  6279. $notrans = false;
  6280. // Several field into label (eq table:code|libelle:rowid)
  6281. $fields_label = explode('|', $InfoFieldList[1]);
  6282. if (count($fields_label) > 1) {
  6283. $notrans = true;
  6284. foreach ($fields_label as $field_toshow) {
  6285. $labeltoshow .= $obj->$field_toshow.' ';
  6286. }
  6287. } else {
  6288. $labeltoshow = $obj->{$InfoFieldList[1]};
  6289. }
  6290. $labeltoshow = dol_trunc($labeltoshow, 45);
  6291. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6292. foreach ($fields_label as $field_toshow) {
  6293. $translabel = $langs->trans($obj->$field_toshow);
  6294. if ($translabel != $obj->$field_toshow) {
  6295. $labeltoshow = dol_trunc($translabel, 18).' ';
  6296. } else {
  6297. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  6298. }
  6299. }
  6300. $data[$obj->rowid] = $labeltoshow;
  6301. } else {
  6302. if (!$notrans) {
  6303. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6304. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6305. $labeltoshow = dol_trunc($translabel, 18);
  6306. } else {
  6307. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  6308. }
  6309. }
  6310. if (empty($labeltoshow)) {
  6311. $labeltoshow = '(not defined)';
  6312. }
  6313. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6314. $data[$obj->rowid] = $labeltoshow;
  6315. }
  6316. if (!empty($InfoFieldList[3]) && $parentField) {
  6317. $parent = $parentName.':'.$obj->{$parentField};
  6318. $isDependList = 1;
  6319. }
  6320. $data[$obj->rowid] = $labeltoshow;
  6321. }
  6322. $i++;
  6323. }
  6324. $this->db->free($resql);
  6325. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
  6326. } else {
  6327. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6328. }
  6329. }
  6330. } elseif ($type == 'link') {
  6331. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
  6332. $param_list_array = explode(':', $param_list[0]);
  6333. $showempty = (($required && $default != '') ? 0 : 1);
  6334. if (!preg_match('/search_/', $keyprefix)) {
  6335. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6336. if (!empty($this->fields[$key]['picto'])) {
  6337. $morecss .= ' widthcentpercentminusxx';
  6338. } else {
  6339. $morecss .= ' widthcentpercentminusx';
  6340. }
  6341. } else {
  6342. if (!empty($this->fields[$key]['picto'])) {
  6343. $morecss .= ' widthcentpercentminusx';
  6344. }
  6345. }
  6346. }
  6347. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  6348. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6349. 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".
  6350. list($class, $classfile) = explode(':', $param_list[0]);
  6351. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
  6352. $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  6353. } else {
  6354. $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  6355. }
  6356. $paramforthenewlink = '';
  6357. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  6358. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  6359. $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin='.GETPOST('origin', 'aZ09') : '');
  6360. $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid='.GETPOST('originid', 'int') : '');
  6361. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  6362. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  6363. $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>';
  6364. }
  6365. }
  6366. } elseif ($type == 'password') {
  6367. // If prefix is 'search_', field is used as a filter, we use a common text field.
  6368. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  6369. } elseif ($type == 'array') {
  6370. $newval = $val;
  6371. $newval['type'] = 'varchar(256)';
  6372. $out = '';
  6373. if (!empty($value)) {
  6374. foreach ($value as $option) {
  6375. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6376. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  6377. }
  6378. }
  6379. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6380. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6381. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  6382. if (!empty($conf->use_javascript_ajax)) {
  6383. $out .= '
  6384. <script>
  6385. $(document).ready(function() {
  6386. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  6387. $("'.dol_escape_js($newInput).'").insertBefore(this);
  6388. });
  6389. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  6390. $(this).parent().remove();
  6391. });
  6392. });
  6393. </script>';
  6394. }
  6395. }
  6396. if (!empty($hidden)) {
  6397. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  6398. }
  6399. if ($isDependList==1) {
  6400. $out .= $this->getJSListDependancies('_common');
  6401. }
  6402. /* Add comments
  6403. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  6404. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  6405. */
  6406. // Display error message for field
  6407. if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
  6408. $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
  6409. }
  6410. return $out;
  6411. }
  6412. /**
  6413. * Return HTML string to show a field into a page
  6414. * Code very similar with showOutputField of extra fields
  6415. *
  6416. * @param array $val Array of properties of field to show
  6417. * @param string $key Key of attribute
  6418. * @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)
  6419. * @param string $moreparam To add more parametes on html input tag
  6420. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6421. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6422. * @param mixed $morecss Value for css to define size. May also be a numeric.
  6423. * @return string
  6424. */
  6425. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  6426. {
  6427. global $conf, $langs, $form;
  6428. if (!is_object($form)) {
  6429. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6430. $form = new Form($this->db);
  6431. }
  6432. $objectid = $this->id; // Not used ???
  6433. $label = empty($val['label']) ? '' : $val['label'];
  6434. $type = empty($val['type']) ? '' : $val['type'];
  6435. $size = empty($val['css']) ? '' : $val['css'];
  6436. $reg = array();
  6437. // Convert var to be able to share same code than showOutputField of extrafields
  6438. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6439. $type = 'varchar'; // convert varchar(xx) int varchar
  6440. $size = $reg[1];
  6441. } elseif (preg_match('/varchar/', $type)) {
  6442. $type = 'varchar'; // convert varchar(xx) int varchar
  6443. }
  6444. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6445. $type = 'select';
  6446. }
  6447. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6448. $type = 'link';
  6449. }
  6450. $default = empty($val['default']) ? '' : $val['default'];
  6451. $computed = empty($val['computed']) ? '' : $val['computed'];
  6452. $unique = empty($val['unique']) ? '' : $val['unique'];
  6453. $required = empty($val['required']) ? '' : $val['required'];
  6454. $param = array();
  6455. $param['options'] = array();
  6456. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6457. $param['options'] = $val['arrayofkeyval'];
  6458. }
  6459. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6460. $type = 'link';
  6461. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6462. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6463. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6464. $type = 'sellist';
  6465. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6466. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6467. $type = 'sellist';
  6468. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6469. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6470. $type = 'sellist';
  6471. }
  6472. $langfile = empty($val['langfile']) ? '' : $val['langfile'];
  6473. $list = (empty($val['list']) ? '' : $val['list']);
  6474. $help = (empty($val['help']) ? '' : $val['help']);
  6475. $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)
  6476. if ($hidden) {
  6477. return '';
  6478. }
  6479. // If field is a computed field, value must become result of compute
  6480. if ($computed) {
  6481. // Make the eval of compute string
  6482. //var_dump($computed);
  6483. $value = dol_eval($computed, 1, 0, '');
  6484. }
  6485. if (empty($morecss)) {
  6486. if ($type == 'date') {
  6487. $morecss = 'minwidth100imp';
  6488. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6489. $morecss = 'minwidth200imp';
  6490. } elseif (in_array($type, array('int', 'double', 'price'))) {
  6491. $morecss = 'maxwidth75';
  6492. } elseif ($type == 'url') {
  6493. $morecss = 'minwidth400';
  6494. } elseif ($type == 'boolean') {
  6495. $morecss = '';
  6496. } else {
  6497. if (is_numeric($size) && round($size) < 12) {
  6498. $morecss = 'minwidth100';
  6499. } elseif (is_numeric($size) && round($size) <= 48) {
  6500. $morecss = 'minwidth200';
  6501. } else {
  6502. $morecss = 'minwidth400';
  6503. }
  6504. }
  6505. }
  6506. // Format output value differently according to properties of field
  6507. if ($key == 'ref' && method_exists($this, 'getNomUrl')) {
  6508. $value = $this->getNomUrl(1, '', 0, '', 1);
  6509. } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
  6510. $value = $this->getLibStatut(3);
  6511. } elseif ($type == 'date') {
  6512. if (!empty($value)) {
  6513. $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
  6514. } else {
  6515. $value = '';
  6516. }
  6517. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6518. if (!empty($value)) {
  6519. $value = dol_print_date($value, 'dayhour', 'tzuserrel');
  6520. } else {
  6521. $value = '';
  6522. }
  6523. } elseif ($type == 'duration') {
  6524. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6525. if (!is_null($value) && $value !== '') {
  6526. $value = convertSecondToTime($value, 'allhourmin');
  6527. }
  6528. } elseif ($type == 'double' || $type == 'real') {
  6529. if (!is_null($value) && $value !== '') {
  6530. $value = price($value);
  6531. }
  6532. } elseif ($type == 'boolean') {
  6533. $checked = '';
  6534. if (!empty($value)) {
  6535. $checked = ' checked ';
  6536. }
  6537. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  6538. } elseif ($type == 'mail') {
  6539. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  6540. } elseif ($type == 'url') {
  6541. $value = dol_print_url($value, '_blank', 32, 1);
  6542. } elseif ($type == 'phone') {
  6543. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
  6544. } elseif ($type == 'price') {
  6545. if (!is_null($value) && $value !== '') {
  6546. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  6547. }
  6548. } elseif ($type == 'select') {
  6549. $value = $param['options'][$value];
  6550. } elseif ($type == 'sellist') {
  6551. $param_list = array_keys($param['options']);
  6552. $InfoFieldList = explode(":", $param_list[0]);
  6553. $selectkey = "rowid";
  6554. $keyList = 'rowid';
  6555. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6556. $selectkey = $InfoFieldList[2];
  6557. $keyList = $InfoFieldList[2].' as rowid';
  6558. }
  6559. $fields_label = explode('|', $InfoFieldList[1]);
  6560. if (is_array($fields_label)) {
  6561. $keyList .= ', ';
  6562. $keyList .= implode(', ', $fields_label);
  6563. }
  6564. $sql = "SELECT ".$keyList;
  6565. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6566. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6567. $sql .= ' as main';
  6568. }
  6569. if ($selectkey == 'rowid' && empty($value)) {
  6570. $sql .= " WHERE ".$selectkey." = 0";
  6571. } elseif ($selectkey == 'rowid') {
  6572. $sql .= " WHERE ".$selectkey." = ".((int) $value);
  6573. } else {
  6574. $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
  6575. }
  6576. //$sql.= ' AND entity = '.$conf->entity;
  6577. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  6578. $resql = $this->db->query($sql);
  6579. if ($resql) {
  6580. $value = ''; // value was used, so now we reste it to use it to build final output
  6581. $obj = $this->db->fetch_object($resql);
  6582. // Several field into label (eq table:code|libelle:rowid)
  6583. $fields_label = explode('|', $InfoFieldList[1]);
  6584. if (is_array($fields_label) && count($fields_label) > 1) {
  6585. foreach ($fields_label as $field_toshow) {
  6586. $translabel = '';
  6587. if (!empty($obj->$field_toshow)) {
  6588. $translabel = $langs->trans($obj->$field_toshow);
  6589. }
  6590. if ($translabel != $field_toshow) {
  6591. $value .= dol_trunc($translabel, 18).' ';
  6592. } else {
  6593. $value .= $obj->$field_toshow.' ';
  6594. }
  6595. }
  6596. } else {
  6597. $translabel = '';
  6598. if (!empty($obj->{$InfoFieldList[1]})) {
  6599. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6600. }
  6601. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6602. $value = dol_trunc($translabel, 18);
  6603. } else {
  6604. $value = $obj->{$InfoFieldList[1]};
  6605. }
  6606. }
  6607. } else {
  6608. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6609. }
  6610. } elseif ($type == 'radio') {
  6611. $value = $param['options'][$value];
  6612. } elseif ($type == 'checkbox') {
  6613. $value_arr = explode(',', $value);
  6614. $value = '';
  6615. if (is_array($value_arr) && count($value_arr) > 0) {
  6616. $toprint = array();
  6617. foreach ($value_arr as $keyval => $valueval) {
  6618. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  6619. }
  6620. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6621. }
  6622. } elseif ($type == 'chkbxlst') {
  6623. $value_arr = explode(',', $value);
  6624. $param_list = array_keys($param['options']);
  6625. $InfoFieldList = explode(":", $param_list[0]);
  6626. $selectkey = "rowid";
  6627. $keyList = 'rowid';
  6628. if (count($InfoFieldList) >= 3) {
  6629. $selectkey = $InfoFieldList[2];
  6630. $keyList = $InfoFieldList[2].' as rowid';
  6631. }
  6632. $fields_label = explode('|', $InfoFieldList[1]);
  6633. if (is_array($fields_label)) {
  6634. $keyList .= ', ';
  6635. $keyList .= implode(', ', $fields_label);
  6636. }
  6637. $sql = "SELECT ".$keyList;
  6638. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6639. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6640. $sql .= ' as main';
  6641. }
  6642. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  6643. // $sql.= ' AND entity = '.$conf->entity;
  6644. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  6645. $resql = $this->db->query($sql);
  6646. if ($resql) {
  6647. $value = ''; // value was used, so now we reste it to use it to build final output
  6648. $toprint = array();
  6649. while ($obj = $this->db->fetch_object($resql)) {
  6650. // Several field into label (eq table:code|libelle:rowid)
  6651. $fields_label = explode('|', $InfoFieldList[1]);
  6652. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6653. if (is_array($fields_label) && count($fields_label) > 1) {
  6654. foreach ($fields_label as $field_toshow) {
  6655. $translabel = '';
  6656. if (!empty($obj->$field_toshow)) {
  6657. $translabel = $langs->trans($obj->$field_toshow);
  6658. }
  6659. if ($translabel != $field_toshow) {
  6660. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6661. } else {
  6662. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->$field_toshow.'</li>';
  6663. }
  6664. }
  6665. } else {
  6666. $translabel = '';
  6667. if (!empty($obj->{$InfoFieldList[1]})) {
  6668. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6669. }
  6670. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6671. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6672. } else {
  6673. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->{$InfoFieldList[1]}.'</li>';
  6674. }
  6675. }
  6676. }
  6677. }
  6678. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6679. } else {
  6680. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6681. }
  6682. } elseif ($type == 'link') {
  6683. $out = '';
  6684. // only if something to display (perf)
  6685. if ($value) {
  6686. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6687. $InfoFieldList = explode(":", $param_list[0]);
  6688. $classname = $InfoFieldList[0];
  6689. $classpath = $InfoFieldList[1];
  6690. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  6691. $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
  6692. if (!empty($classpath)) {
  6693. dol_include_once($InfoFieldList[1]);
  6694. if ($classname && class_exists($classname)) {
  6695. $object = new $classname($this->db);
  6696. if ($object->element === 'product') { // Special cas for product because default valut of fetch are wrong
  6697. $object->fetch($value, '', '', '', 0, 1, 1);
  6698. } else {
  6699. $object->fetch($value);
  6700. }
  6701. $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
  6702. }
  6703. } else {
  6704. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  6705. return 'Error bad setup of extrafield';
  6706. }
  6707. } else {
  6708. $value = '';
  6709. }
  6710. } elseif (preg_match('/^(text|html)/', $type)) {
  6711. $value = dol_htmlentitiesbr($value);
  6712. } elseif ($type == 'password') {
  6713. $value = preg_replace('/./i', '*', $value);
  6714. } elseif ($type == 'array') {
  6715. $value = implode('<br>', $value);
  6716. }
  6717. //print $type.'-'.$size.'-'.$value;
  6718. $out = $value;
  6719. return $out;
  6720. }
  6721. /**
  6722. * clear validation message result for a field
  6723. *
  6724. * @param string $fieldKey Key of attribute to clear
  6725. * @return null
  6726. */
  6727. public function clearFieldError($fieldKey)
  6728. {
  6729. $this->error = '';
  6730. unset($this->validateFieldsErrors[$fieldKey]);
  6731. }
  6732. /**
  6733. * set validation error message a field
  6734. *
  6735. * @param string $fieldKey Key of attribute
  6736. * @param string $msg the field error message
  6737. * @return null
  6738. */
  6739. public function setFieldError($fieldKey, $msg = '')
  6740. {
  6741. global $langs;
  6742. if (empty($msg)) { $msg = $langs->trans("UnknowError"); }
  6743. $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
  6744. }
  6745. /**
  6746. * get field error message
  6747. *
  6748. * @param string $fieldKey Key of attribute
  6749. * @return string
  6750. */
  6751. public function getFieldError($fieldKey)
  6752. {
  6753. if (!empty($this->validateFieldsErrors[$fieldKey])) {
  6754. return $this->validateFieldsErrors[$fieldKey];
  6755. }
  6756. return '';
  6757. }
  6758. /**
  6759. * Return validation test result for a field
  6760. *
  6761. * @param array $val Array of properties of field to show
  6762. * @param string $fieldKey Key of attribute
  6763. * @param string $fieldValue value of attribute
  6764. * @return bool return false if fail true on success, see $this->error for error message
  6765. */
  6766. public function validateField($val, $fieldKey, $fieldValue)
  6767. {
  6768. global $langs;
  6769. if (!class_exists('Validate')) { require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php'; }
  6770. $this->clearFieldError($fieldKey);
  6771. if (!isset($val[$fieldKey])) {
  6772. $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
  6773. return false;
  6774. }
  6775. $param = array();
  6776. $param['options'] = array();
  6777. $type = $val[$fieldKey]['type'];
  6778. $required = false;
  6779. if (isset($val[$fieldKey]['notnull']) && $val[$fieldKey]['notnull'] === 1) {
  6780. // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  6781. $required = true;
  6782. }
  6783. $maxSize = 0;
  6784. $minSize = 0;
  6785. //
  6786. // PREPARE Elements
  6787. //
  6788. // Convert var to be able to share same code than showOutputField of extrafields
  6789. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6790. $type = 'varchar'; // convert varchar(xx) int varchar
  6791. $maxSize = $reg[1];
  6792. } elseif (preg_match('/varchar/', $type)) {
  6793. $type = 'varchar'; // convert varchar(xx) int varchar
  6794. }
  6795. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6796. $type = 'select';
  6797. }
  6798. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6799. $type = 'link';
  6800. }
  6801. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6802. $param['options'] = $val['arrayofkeyval'];
  6803. }
  6804. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6805. $type = 'link';
  6806. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6807. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6808. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6809. $type = 'sellist';
  6810. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6811. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6812. $type = 'sellist';
  6813. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6814. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6815. $type = 'sellist';
  6816. }
  6817. //
  6818. // TEST Value
  6819. //
  6820. // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
  6821. $validate = new Validate($this->db, $langs);
  6822. // little trick : to perform tests with good performances sort tests by quick to low
  6823. //
  6824. // COMMON TESTS
  6825. //
  6826. // Required test and empty value
  6827. if ($required && !$validate->isNotEmptyString($fieldValue)) {
  6828. $this->setFieldError($fieldKey, $validate->error);
  6829. return false;
  6830. } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
  6831. // if no value sent and the field is not mandatory, no need to perform tests
  6832. return true;
  6833. }
  6834. // MAX Size test
  6835. if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
  6836. $this->setFieldError($fieldKey, $validate->error);
  6837. return false;
  6838. }
  6839. // MIN Size test
  6840. if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
  6841. $this->setFieldError($fieldKey, $validate->error);
  6842. return false;
  6843. }
  6844. //
  6845. // TESTS for TYPE
  6846. //
  6847. if (in_array($type, array('date', 'datetime', 'timestamp'))) {
  6848. if (!$validate->isTimestamp($fieldValue)) {
  6849. $this->setFieldError($fieldKey, $validate->error);
  6850. return false;
  6851. } else { return true; }
  6852. } elseif ($type == 'duration') {
  6853. if (!$validate->isDuration($fieldValue)) {
  6854. $this->setFieldError($fieldKey, $validate->error);
  6855. return false;
  6856. } else { return true; }
  6857. } elseif (in_array($type, array('double', 'real', 'price'))) {
  6858. // is numeric
  6859. if (!$validate->isNumeric($fieldValue)) {
  6860. $this->setFieldError($fieldKey, $validate->error);
  6861. return false;
  6862. } else { return true; }
  6863. } elseif ($type == 'boolean') {
  6864. if (!$validate->isBool($fieldValue)) {
  6865. $this->setFieldError($fieldKey, $validate->error);
  6866. return false;
  6867. } else { return true; }
  6868. } elseif ($type == 'mail') {
  6869. if (!$validate->isEmail($fieldValue)) {
  6870. $this->setFieldError($fieldKey, $validate->error);
  6871. return false;
  6872. }
  6873. } elseif ($type == 'url') {
  6874. if (!$validate->isUrl($fieldValue)) {
  6875. $this->setFieldError($fieldKey, $validate->error);
  6876. return false;
  6877. } else { return true; }
  6878. } elseif ($type == 'phone') {
  6879. if (!$validate->isPhone($fieldValue)) {
  6880. $this->setFieldError($fieldKey, $validate->error);
  6881. return false;
  6882. } else { return true; }
  6883. } elseif ($type == 'select' || $type == 'radio') {
  6884. if (!isset($param['options'][$fieldValue])) {
  6885. $this->error = $langs->trans('RequireValidValue');
  6886. return false;
  6887. } else { return true; }
  6888. } elseif ($type == 'sellist' || $type == 'chkbxlst') {
  6889. $param_list = array_keys($param['options']);
  6890. $InfoFieldList = explode(":", $param_list[0]);
  6891. $value_arr = explode(',', $fieldValue);
  6892. $value_arr = array_map(array($this->db, 'escape'), $value_arr);
  6893. $selectkey = "rowid";
  6894. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6895. $selectkey = $InfoFieldList[2];
  6896. }
  6897. if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
  6898. $this->setFieldError($fieldKey, $validate->error);
  6899. return false;
  6900. } else { return true; }
  6901. } elseif ($type == 'link') {
  6902. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6903. $InfoFieldList = explode(":", $param_list[0]);
  6904. $classname = $InfoFieldList[0];
  6905. $classpath = $InfoFieldList[1];
  6906. if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
  6907. $this->setFieldError($fieldKey, $validate->error);
  6908. return false;
  6909. } else { return true; }
  6910. }
  6911. // if no test failled all is ok
  6912. return true;
  6913. }
  6914. /**
  6915. * Function to show lines of extrafields with output datas.
  6916. * 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
  6917. *
  6918. * @param Extrafields $extrafields Extrafield Object
  6919. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  6920. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  6921. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  6922. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  6923. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  6924. * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...)
  6925. * @return string
  6926. */
  6927. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
  6928. {
  6929. global $db, $conf, $langs, $action, $form, $hookmanager;
  6930. if (!is_object($form)) {
  6931. $form = new Form($db);
  6932. }
  6933. $out = '';
  6934. $parameters = array();
  6935. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  6936. if (empty($reshook)) {
  6937. 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) {
  6938. $out .= "\n";
  6939. $out .= '<!-- commonobject:showOptionals --> ';
  6940. $out .= "\n";
  6941. $extrafields_collapse_num = '';
  6942. $e = 0;
  6943. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
  6944. // Show only the key field in params
  6945. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
  6946. continue;
  6947. }
  6948. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  6949. $enabled = 1;
  6950. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  6951. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '1');
  6952. }
  6953. if (empty($enabled)) {
  6954. continue;
  6955. }
  6956. $visibility = 1;
  6957. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  6958. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '1');
  6959. }
  6960. $perms = 1;
  6961. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  6962. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '1');
  6963. }
  6964. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
  6965. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  6966. } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
  6967. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  6968. } elseif ($mode == 'view' && empty($visibility)) {
  6969. continue;
  6970. }
  6971. if (empty($perms)) {
  6972. continue;
  6973. }
  6974. // Load language if required
  6975. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  6976. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  6977. }
  6978. $colspan = 0;
  6979. if (is_array($params) && count($params) > 0 && $display_type=='card') {
  6980. if (array_key_exists('cols', $params)) {
  6981. $colspan = $params['cols'];
  6982. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  6983. $reg = array();
  6984. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  6985. $colspan = $reg[1];
  6986. } else {
  6987. $colspan = $params['colspan'];
  6988. }
  6989. }
  6990. }
  6991. $colspan = intval($colspan);
  6992. switch ($mode) {
  6993. case "view":
  6994. $value = $this->array_options["options_".$key.$keysuffix]; // Value may be clean or formated later
  6995. break;
  6996. case "create":
  6997. case "edit":
  6998. // We get the value of property found with GETPOST so it takes into account:
  6999. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  7000. $check = 'alphanohtml';
  7001. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  7002. $check = 'restricthtml';
  7003. }
  7004. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  7005. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  7006. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
  7007. if (is_array($getposttemp)) {
  7008. // $getposttemp is an array but following code expects a comma separated string
  7009. $value = implode(",", $getposttemp);
  7010. } else {
  7011. $value = $getposttemp;
  7012. }
  7013. } else {
  7014. $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.
  7015. }
  7016. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  7017. break;
  7018. }
  7019. // Output value of the current field
  7020. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  7021. $extrafields_collapse_num = '';
  7022. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  7023. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  7024. $extrafield_param_list = array_keys($extrafield_param['options']);
  7025. if (count($extrafield_param_list) > 0) {
  7026. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  7027. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  7028. $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  7029. }
  7030. }
  7031. }
  7032. // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
  7033. $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
  7034. } else {
  7035. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  7036. $csstyle = '';
  7037. if (is_array($params) && count($params) > 0) {
  7038. if (array_key_exists('class', $params)) {
  7039. $class .= $params['class'].' ';
  7040. }
  7041. if (array_key_exists('style', $params)) {
  7042. $csstyle = $params['style'];
  7043. }
  7044. }
  7045. // add html5 elements
  7046. $domData = ' data-element="extrafield"';
  7047. $domData .= ' data-targetelement="'.$this->element.'"';
  7048. $domData .= ' data-targetid="'.$this->id.'"';
  7049. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  7050. if ($display_type=='card') {
  7051. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
  7052. $colspan = 0;
  7053. }
  7054. if ($action == 'selectlines') {
  7055. $colspan++;
  7056. }
  7057. }
  7058. // Convert date into timestamp format (value in memory must be a timestamp)
  7059. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
  7060. $datenotinstring = $this->array_options['options_'.$key];
  7061. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7062. $datenotinstring = $this->db->jdate($datenotinstring);
  7063. }
  7064. $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;
  7065. }
  7066. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
  7067. $datenotinstring = $this->array_options['options_'.$key];
  7068. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7069. $datenotinstring = $this->db->jdate($datenotinstring);
  7070. }
  7071. $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;
  7072. }
  7073. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  7074. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
  7075. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? price2num($value) : $this->array_options['options_'.$key];
  7076. }
  7077. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  7078. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int'))) {
  7079. if ($action == 'create') {
  7080. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  7081. }
  7082. }
  7083. $labeltoshow = $langs->trans($label);
  7084. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  7085. if ($display_type == 'card') {
  7086. $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.' >';
  7087. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action == 'view' || $action == 'valid' || $action == 'editline')) {
  7088. $out .= '<td></td>';
  7089. }
  7090. $out .= '<td class="wordbreak';
  7091. } elseif ($display_type == 'line') {
  7092. $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.' >';
  7093. $out .= '<div style="display: inline-block; padding-right:4px" class="wordbreak';
  7094. }
  7095. //$out .= "titlefield";
  7096. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  7097. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  7098. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  7099. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  7100. $out .= '">';
  7101. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7102. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7103. } else {
  7104. $out .= $labeltoshow;
  7105. }
  7106. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7107. $out .= '&nbsp;<span style="color: red">*</span>';
  7108. }
  7109. } else {
  7110. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7111. $out .= ' fieldrequired';
  7112. }
  7113. $out .= '">';
  7114. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7115. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7116. } else {
  7117. $out .= $labeltoshow;
  7118. }
  7119. }
  7120. $out .= ($display_type == 'card' ? '</td>' : '</div>');
  7121. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  7122. if ($display_type == 'card') {
  7123. // 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
  7124. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="'.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  7125. } elseif ($display_type == 'line') {
  7126. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').' style="display: inline-block" class="'.$this->element.'_extras_'.$key.'">';
  7127. }
  7128. switch ($mode) {
  7129. case "view":
  7130. $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
  7131. break;
  7132. case "create":
  7133. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7134. break;
  7135. case "edit":
  7136. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7137. break;
  7138. }
  7139. $out .= ($display_type=='card' ? '</td>' : '</div>');
  7140. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
  7141. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7142. } else {
  7143. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7144. }
  7145. $e++;
  7146. }
  7147. }
  7148. $out .= "\n";
  7149. // Add code to manage list depending on others
  7150. if (!empty($conf->use_javascript_ajax)) {
  7151. $out .= $this->getJSListDependancies();
  7152. }
  7153. $out .= '<!-- commonobject:showOptionals end --> '."\n";
  7154. }
  7155. }
  7156. $out .= $hookmanager->resPrint;
  7157. return $out;
  7158. }
  7159. /**
  7160. * @param string $type Type for prefix
  7161. * @return string Javacript code to manage dependency
  7162. */
  7163. public function getJSListDependancies($type = '_extra')
  7164. {
  7165. $out = '
  7166. <script>
  7167. jQuery(document).ready(function() {
  7168. function showOptions'.$type.'(child_list, parent_list, orig_select)
  7169. {
  7170. var val = $("select[name=\""+parent_list+"\"]").val();
  7171. var parentVal = parent_list + ":" + val;
  7172. if(typeof val == "string"){
  7173. if(val != "") {
  7174. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7175. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7176. $("select[name=\""+child_list+"\"]").append(options);
  7177. } else {
  7178. var options = orig_select.find("option[parent]").clone();
  7179. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7180. $("select[name=\""+child_list+"\"]").append(options);
  7181. }
  7182. } else if(val > 0) {
  7183. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7184. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7185. $("select[name=\""+child_list+"\"]").append(options);
  7186. } else {
  7187. var options = orig_select.find("option[parent]").clone();
  7188. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7189. $("select[name=\""+child_list+"\"]").append(options);
  7190. }
  7191. }
  7192. function setListDependencies'.$type.'() {
  7193. jQuery("select option[parent]").parent().each(function() {
  7194. var orig_select = {};
  7195. var child_list = $(this).attr("name");
  7196. orig_select[child_list] = $(this).clone();
  7197. var parent = $(this).find("option[parent]:first").attr("parent");
  7198. var infos = parent.split(":");
  7199. var parent_list = infos[0];
  7200. //Hide daughters lists
  7201. if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
  7202. $("#"+child_list).hide();
  7203. //Show mother lists
  7204. } else if ($("#"+parent_list).val() != 0){
  7205. $("#"+parent_list).show();
  7206. }
  7207. //Show the child list if the parent list value is selected
  7208. $("select[name=\""+parent_list+"\"]").click(function() {
  7209. if ($(this).val() != 0){
  7210. $("#"+child_list).show()
  7211. }
  7212. });
  7213. //When we change parent list
  7214. $("select[name=\""+parent_list+"\"]").change(function() {
  7215. showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
  7216. //Select the value 0 on child list after a change on the parent list
  7217. $("#"+child_list).val(0).trigger("change");
  7218. //Hide child lists if the parent value is set to 0
  7219. if ($(this).val() == 0){
  7220. $("#"+child_list).hide();
  7221. }
  7222. });
  7223. });
  7224. }
  7225. setListDependencies'.$type.'();
  7226. });
  7227. </script>'."\n";
  7228. return $out;
  7229. }
  7230. /**
  7231. * Returns the rights used for this class
  7232. * @return stdClass
  7233. */
  7234. public function getRights()
  7235. {
  7236. global $user;
  7237. $element = $this->element;
  7238. if ($element == 'facturerec') {
  7239. $element = 'facture';
  7240. } elseif ($element == 'invoice_supplier_rec') {
  7241. return $user->rights->fournisseur->facture;
  7242. }
  7243. return $user->rights->{$element};
  7244. }
  7245. /**
  7246. * Function used to replace a thirdparty id with another one.
  7247. * This function is meant to be called from replaceThirdparty with the appropriate tables
  7248. * Column name fk_soc MUST be used to identify thirdparties
  7249. *
  7250. * @param DoliDB $db Database handler
  7251. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  7252. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  7253. * @param string[] $tables Tables that need to be changed
  7254. * @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)
  7255. * @return bool True if success, False if error
  7256. */
  7257. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7258. {
  7259. foreach ($tables as $table) {
  7260. $sql = 'UPDATE '.$db->prefix().$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
  7261. if (!$db->query($sql)) {
  7262. if ($ignoreerrors) {
  7263. return true; // TODO Not enough. If there is A-B on kept thirdparty and B-C on old one, we must get A-B-C after merge. Not A-B.
  7264. }
  7265. //$this->errors = $db->lasterror();
  7266. return false;
  7267. }
  7268. }
  7269. return true;
  7270. }
  7271. /**
  7272. * Function used to replace a product id with another one.
  7273. * This function is meant to be called from replaceProduct with the appropriate tables
  7274. * Column name fk_product MUST be used to identify products
  7275. *
  7276. * @param DoliDB $db Database handler
  7277. * @param int $origin_id Old product id (the product to delete)
  7278. * @param int $dest_id New product id (the product that will received element of the other)
  7279. * @param string[] $tables Tables that need to be changed
  7280. * @param int $ignoreerrors Ignore errors. Return true even if errors. We need this when replacement can fails like for categories (categorie of old product may already exists on new one)
  7281. * @return bool True if success, False if error
  7282. */
  7283. public static function commonReplaceProduct(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7284. {
  7285. foreach ($tables as $table) {
  7286. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_product = '.((int) $dest_id).' WHERE fk_product = '.((int) $origin_id);
  7287. if (!$db->query($sql)) {
  7288. if ($ignoreerrors) {
  7289. return true; // TODO Not enough. If there is A-B on kept product and B-C on old one, we must get A-B-C after merge. Not A-B.
  7290. }
  7291. //$this->errors = $db->lasterror();
  7292. return false;
  7293. }
  7294. }
  7295. return true;
  7296. }
  7297. /**
  7298. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  7299. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  7300. * else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  7301. * else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  7302. * else set min buy price as buy price
  7303. *
  7304. * @param float $unitPrice Product unit price
  7305. * @param float $discountPercent Line discount percent
  7306. * @param int $fk_product Product id
  7307. * @return float <0 if KO, buyprice if OK
  7308. */
  7309. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  7310. {
  7311. global $conf;
  7312. $buyPrice = 0;
  7313. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
  7314. // When ForceBuyingPriceIfNull is set
  7315. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  7316. } else {
  7317. // Get cost price for margin calculation
  7318. if (!empty($fk_product) && $fk_product > 0) {
  7319. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
  7320. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7321. $product = new Product($this->db);
  7322. $result = $product->fetch($fk_product);
  7323. if ($result <= 0) {
  7324. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7325. return -1;
  7326. }
  7327. if ($product->cost_price > 0) {
  7328. $buyPrice = $product->cost_price;
  7329. } elseif ($product->pmp > 0) {
  7330. $buyPrice = $product->pmp;
  7331. }
  7332. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
  7333. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7334. $product = new Product($this->db);
  7335. $result = $product->fetch($fk_product);
  7336. if ($result <= 0) {
  7337. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7338. return -1;
  7339. }
  7340. if ($product->pmp > 0) {
  7341. $buyPrice = $product->pmp;
  7342. }
  7343. }
  7344. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
  7345. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  7346. $productFournisseur = new ProductFournisseur($this->db);
  7347. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
  7348. $buyPrice = $productFournisseur->fourn_unitprice;
  7349. } elseif ($result < 0) {
  7350. $this->errors[] = $productFournisseur->error;
  7351. return -2;
  7352. }
  7353. }
  7354. }
  7355. }
  7356. return $buyPrice;
  7357. }
  7358. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7359. /**
  7360. * Show photos of an object (nbmax maximum), into several columns
  7361. *
  7362. * @param string $modulepart 'product', 'ticket', ...
  7363. * @param string $sdir Directory to scan (full absolute path)
  7364. * @param int $size 0=original size, 1='small' use thumbnail if possible
  7365. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  7366. * @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'.
  7367. * @param int $showfilename 1=Show filename
  7368. * @param int $showaction 1=Show icon with action links (resize, delete)
  7369. * @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.
  7370. * @param int $maxWidth Max width of original image when size='small'
  7371. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  7372. * @param int $notitle Do not add title tag on image
  7373. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  7374. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  7375. */
  7376. 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)
  7377. {
  7378. // phpcs:enable
  7379. global $conf, $user, $langs;
  7380. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7381. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  7382. $sortfield = 'position_name';
  7383. $sortorder = 'asc';
  7384. $dir = $sdir.'/';
  7385. $pdir = '/';
  7386. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7387. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7388. // For backward compatibility
  7389. if ($modulepart == 'product') {
  7390. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  7391. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7392. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7393. }
  7394. }
  7395. // Defined relative dir to DOL_DATA_ROOT
  7396. $relativedir = '';
  7397. if ($dir) {
  7398. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  7399. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  7400. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  7401. }
  7402. $dirthumb = $dir.'thumbs/';
  7403. $pdirthumb = $pdir.'thumbs/';
  7404. $return = '<!-- Photo -->'."\n";
  7405. $nbphoto = 0;
  7406. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  7407. /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
  7408. {
  7409. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  7410. $filearray=array_merge($filearray, $filearrayold);
  7411. }*/
  7412. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  7413. if (count($filearray)) {
  7414. if ($sortfield && $sortorder) {
  7415. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  7416. }
  7417. foreach ($filearray as $key => $val) {
  7418. $photo = '';
  7419. $file = $val['name'];
  7420. //if (! utf8_check($file)) $file=utf8_encode($file); // To be sure file is stored in UTF8 in memory
  7421. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  7422. if (image_format_supported($file) >= 0) {
  7423. $nbphoto++;
  7424. $photo = $file;
  7425. $viewfilename = $file;
  7426. if ($size == 1 || $size == 'small') { // Format vignette
  7427. // Find name of thumb file
  7428. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  7429. if (!dol_is_file($dirthumb.$photo_vignette)) {
  7430. $photo_vignette = '';
  7431. }
  7432. // Get filesize of original file
  7433. $imgarray = dol_getImageSize($dir.$photo);
  7434. if ($nbbyrow > 0) {
  7435. if ($nbphoto == 1) {
  7436. $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  7437. }
  7438. if ($nbphoto % $nbbyrow == 1) {
  7439. $return .= '<tr class="center valignmiddle" style="border: 1px">';
  7440. }
  7441. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
  7442. } elseif ($nbbyrow < 0) {
  7443. $return .= '<div class="inline-block">';
  7444. }
  7445. $return .= "\n";
  7446. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  7447. if (empty($nolink)) {
  7448. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  7449. if ($urladvanced) {
  7450. $return .= '<a href="'.$urladvanced.'">';
  7451. } else {
  7452. $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
  7453. }
  7454. }
  7455. // Show image (width height=$maxHeight)
  7456. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  7457. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  7458. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  7459. if ($notitle) {
  7460. $alt = '';
  7461. }
  7462. $addphotorefcss = 1;
  7463. if ($usesharelink) {
  7464. if ($val['share']) {
  7465. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7466. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  7467. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7468. } else {
  7469. $return .= '<!-- Show original file -->';
  7470. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7471. }
  7472. } else {
  7473. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  7474. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  7475. }
  7476. } else {
  7477. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7478. $return .= '<!-- Show thumb -->';
  7479. $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).'">';
  7480. } else {
  7481. $return .= '<!-- Show original file -->';
  7482. $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).'">';
  7483. }
  7484. }
  7485. if (empty($nolink)) {
  7486. $return .= '</a>';
  7487. }
  7488. $return .= "\n";
  7489. if ($showfilename) {
  7490. $return .= '<br>'.$viewfilename;
  7491. }
  7492. if ($showaction) {
  7493. $return .= '<br>';
  7494. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  7495. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
  7496. $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>';
  7497. }
  7498. // Special cas for product
  7499. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7500. // Link to resize
  7501. $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; ';
  7502. // Link to delete
  7503. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7504. $return .= img_delete().'</a>';
  7505. }
  7506. }
  7507. $return .= "\n";
  7508. if ($nbbyrow > 0) {
  7509. $return .= '</td>';
  7510. if (($nbphoto % $nbbyrow) == 0) {
  7511. $return .= '</tr>';
  7512. }
  7513. } elseif ($nbbyrow < 0) {
  7514. $return .= '</div>';
  7515. }
  7516. }
  7517. if (empty($size)) { // Format origine
  7518. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  7519. if ($showfilename) {
  7520. $return .= '<br>'.$viewfilename;
  7521. }
  7522. if ($showaction) {
  7523. // Special case for product
  7524. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7525. // Link to resize
  7526. $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; ';
  7527. // Link to delete
  7528. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7529. $return .= img_delete().'</a>';
  7530. }
  7531. }
  7532. }
  7533. // On continue ou on arrete de boucler ?
  7534. if ($nbmax && $nbphoto >= $nbmax) {
  7535. break;
  7536. }
  7537. }
  7538. }
  7539. if ($size == 1 || $size == 'small') {
  7540. if ($nbbyrow > 0) {
  7541. // Ferme tableau
  7542. while ($nbphoto % $nbbyrow) {
  7543. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  7544. $nbphoto++;
  7545. }
  7546. if ($nbphoto) {
  7547. $return .= '</table>';
  7548. }
  7549. }
  7550. }
  7551. }
  7552. $this->nbphoto = $nbphoto;
  7553. return $return;
  7554. }
  7555. /**
  7556. * Function test if type is array
  7557. *
  7558. * @param array $info content informations of field
  7559. * @return bool true if array
  7560. */
  7561. protected function isArray($info)
  7562. {
  7563. if (is_array($info)) {
  7564. if (isset($info['type']) && $info['type'] == 'array') {
  7565. return true;
  7566. } else {
  7567. return false;
  7568. }
  7569. }
  7570. return false;
  7571. }
  7572. /**
  7573. * Function test if type is date
  7574. *
  7575. * @param array $info content informations of field
  7576. * @return bool true if date
  7577. */
  7578. public function isDate($info)
  7579. {
  7580. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
  7581. return true;
  7582. }
  7583. return false;
  7584. }
  7585. /**
  7586. * Function test if type is duration
  7587. *
  7588. * @param array $info content informations of field
  7589. * @return bool true if field of type duration
  7590. */
  7591. public function isDuration($info)
  7592. {
  7593. if (is_array($info)) {
  7594. if (isset($info['type']) && ($info['type'] == 'duration')) {
  7595. return true;
  7596. } else {
  7597. return false;
  7598. }
  7599. } else {
  7600. return false;
  7601. }
  7602. }
  7603. /**
  7604. * Function test if type is integer
  7605. *
  7606. * @param array $info content informations of field
  7607. * @return bool true if integer
  7608. */
  7609. public function isInt($info)
  7610. {
  7611. if (is_array($info)) {
  7612. if (isset($info['type']) && ($info['type'] == 'int' || preg_match('/^integer/i', $info['type']))) {
  7613. return true;
  7614. } else {
  7615. return false;
  7616. }
  7617. } else {
  7618. return false;
  7619. }
  7620. }
  7621. /**
  7622. * Function test if type is float
  7623. *
  7624. * @param array $info content informations of field
  7625. * @return bool true if float
  7626. */
  7627. public function isFloat($info)
  7628. {
  7629. if (is_array($info)) {
  7630. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
  7631. return true;
  7632. } else {
  7633. return false;
  7634. }
  7635. }
  7636. return false;
  7637. }
  7638. /**
  7639. * Function test if type is text
  7640. *
  7641. * @param array $info content informations of field
  7642. * @return bool true if type text
  7643. */
  7644. public function isText($info)
  7645. {
  7646. if (is_array($info)) {
  7647. if (isset($info['type']) && $info['type'] == 'text') {
  7648. return true;
  7649. } else {
  7650. return false;
  7651. }
  7652. }
  7653. return false;
  7654. }
  7655. /**
  7656. * Function test if field can be null
  7657. *
  7658. * @param array $info content informations of field
  7659. * @return bool true if it can be null
  7660. */
  7661. protected function canBeNull($info)
  7662. {
  7663. if (is_array($info)) {
  7664. if (isset($info['notnull']) && $info['notnull'] != '1') {
  7665. return true;
  7666. } else {
  7667. return false;
  7668. }
  7669. }
  7670. return true;
  7671. }
  7672. /**
  7673. * Function test if field is forced to null if zero or empty
  7674. *
  7675. * @param array $info content informations of field
  7676. * @return bool true if forced to null
  7677. */
  7678. protected function isForcedToNullIfZero($info)
  7679. {
  7680. if (is_array($info)) {
  7681. if (isset($info['notnull']) && $info['notnull'] == '-1') {
  7682. return true;
  7683. } else {
  7684. return false;
  7685. }
  7686. }
  7687. return false;
  7688. }
  7689. /**
  7690. * Function test if is indexed
  7691. *
  7692. * @param array $info content informations of field
  7693. * @return bool
  7694. */
  7695. protected function isIndex($info)
  7696. {
  7697. if (is_array($info)) {
  7698. if (isset($info['index']) && $info['index'] == true) {
  7699. return true;
  7700. } else {
  7701. return false;
  7702. }
  7703. }
  7704. return false;
  7705. }
  7706. /**
  7707. * Function to prepare a part of the query for insert.
  7708. * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
  7709. * $this->${field} should be a clean value. The page can run
  7710. *
  7711. * @return array
  7712. */
  7713. protected function setSaveQuery()
  7714. {
  7715. global $conf;
  7716. $queryarray = array();
  7717. foreach ($this->fields as $field => $info) { // Loop on definition of fields
  7718. // Depending on field type ('datetime', ...)
  7719. if ($this->isDate($info)) {
  7720. if (empty($this->{$field})) {
  7721. $queryarray[$field] = null;
  7722. } else {
  7723. $queryarray[$field] = $this->db->idate($this->{$field});
  7724. }
  7725. } elseif ($this->isDuration($info)) {
  7726. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7727. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7728. if (!isset($this->{$field})) {
  7729. $queryarray[$field] = 0;
  7730. } else {
  7731. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7732. }
  7733. } else {
  7734. $queryarray[$field] = null;
  7735. }
  7736. } elseif ($this->isInt($info) || $this->isFloat($info)) {
  7737. if ($field == 'entity' && is_null($this->{$field})) {
  7738. $queryarray[$field] = $conf->entity;
  7739. } else {
  7740. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7741. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7742. if (!isset($this->{$field})) {
  7743. $queryarray[$field] = 0;
  7744. } elseif ($this->isInt($info)) {
  7745. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7746. } elseif ($this->isFloat($info)) {
  7747. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7748. }
  7749. } else {
  7750. $queryarray[$field] = null;
  7751. }
  7752. }
  7753. } else {
  7754. // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
  7755. // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
  7756. $queryarray[$field] = $this->{$field};
  7757. }
  7758. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
  7759. unset($queryarray[$field]);
  7760. }
  7761. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
  7762. $queryarray[$field] = null; // May force 0 to null
  7763. }
  7764. }
  7765. return $queryarray;
  7766. }
  7767. /**
  7768. * Function to load data from a SQL pointer into properties of current object $this
  7769. *
  7770. * @param stdClass $obj Contain data of object from database
  7771. * @return void
  7772. */
  7773. public function setVarsFromFetchObj(&$obj)
  7774. {
  7775. global $db;
  7776. foreach ($this->fields as $field => $info) {
  7777. if ($this->isDate($info)) {
  7778. if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
  7779. $this->{$field} = '';
  7780. } else {
  7781. $this->{$field} = $db->jdate($obj->{$field});
  7782. }
  7783. } elseif ($this->isInt($info)) {
  7784. if ($field == 'rowid') {
  7785. $this->id = (int) $obj->{$field};
  7786. } else {
  7787. if ($this->isForcedToNullIfZero($info)) {
  7788. if (empty($obj->{$field})) {
  7789. $this->{$field} = null;
  7790. } else {
  7791. $this->{$field} = (double) $obj->{$field};
  7792. }
  7793. } else {
  7794. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7795. $this->{$field} = (int) $obj->{$field};
  7796. } else {
  7797. $this->{$field} = null;
  7798. }
  7799. }
  7800. }
  7801. } elseif ($this->isFloat($info)) {
  7802. if ($this->isForcedToNullIfZero($info)) {
  7803. if (empty($obj->{$field})) {
  7804. $this->{$field} = null;
  7805. } else {
  7806. $this->{$field} = (double) $obj->{$field};
  7807. }
  7808. } else {
  7809. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7810. $this->{$field} = (double) $obj->{$field};
  7811. } else {
  7812. $this->{$field} = null;
  7813. }
  7814. }
  7815. } else {
  7816. $this->{$field} = $obj->{$field};
  7817. }
  7818. }
  7819. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  7820. if (!isset($this->fields['ref']) && isset($this->id)) {
  7821. $this->ref = $this->id;
  7822. }
  7823. }
  7824. /**
  7825. * Function to concat keys of fields
  7826. *
  7827. * @param string $alias String of alias of table for fields. For example 't'.
  7828. * @return string list of alias fields
  7829. */
  7830. public function getFieldList($alias = '')
  7831. {
  7832. $keys = array_keys($this->fields);
  7833. if (!empty($alias)) {
  7834. $keys_with_alias = array();
  7835. foreach ($keys as $fieldname) {
  7836. $keys_with_alias[] = $alias . '.' . $fieldname;
  7837. }
  7838. return implode(',', $keys_with_alias);
  7839. } else {
  7840. return implode(',', $keys);
  7841. }
  7842. }
  7843. /**
  7844. * Add quote to field value if necessary
  7845. *
  7846. * @param string|int $value Value to protect
  7847. * @param array $fieldsentry Properties of field
  7848. * @return string
  7849. */
  7850. protected function quote($value, $fieldsentry)
  7851. {
  7852. if (is_null($value)) {
  7853. return 'NULL';
  7854. } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
  7855. return price2num("$value");
  7856. } elseif ($fieldsentry['type'] == 'boolean') {
  7857. if ($value) {
  7858. return 'true';
  7859. } else {
  7860. return 'false';
  7861. }
  7862. } else {
  7863. return "'".$this->db->escape($value)."'";
  7864. }
  7865. }
  7866. /**
  7867. * Create object into database
  7868. *
  7869. * @param User $user User that creates
  7870. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7871. * @return int <0 if KO, Id of created object if OK
  7872. */
  7873. public function createCommon(User $user, $notrigger = false)
  7874. {
  7875. global $langs;
  7876. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  7877. $error = 0;
  7878. $now = dol_now();
  7879. $fieldvalues = $this->setSaveQuery();
  7880. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
  7881. $fieldvalues['date_creation'] = $this->db->idate($now);
  7882. }
  7883. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
  7884. $fieldvalues['fk_user_creat'] = $user->id;
  7885. }
  7886. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  7887. if (array_key_exists('ref', $fieldvalues)) {
  7888. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  7889. }
  7890. $keys = array();
  7891. $values = array(); // Array to store string forged for SQL syntax
  7892. foreach ($fieldvalues as $k => $v) {
  7893. $keys[$k] = $k;
  7894. $value = $this->fields[$k];
  7895. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  7896. }
  7897. // Clean and check mandatory
  7898. foreach ($keys as $key) {
  7899. // If field is an implicit foreign key field
  7900. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  7901. $values[$key] = '';
  7902. }
  7903. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  7904. $values[$key] = '';
  7905. }
  7906. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
  7907. $error++;
  7908. $langs->load("errors");
  7909. dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
  7910. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  7911. }
  7912. // If value is null and there is a default value for field
  7913. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
  7914. $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
  7915. }
  7916. // If field is an implicit foreign key field
  7917. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  7918. if (isset($this->fields[$key]['default'])) {
  7919. $values[$key] = ((int) $this->fields[$key]['default']);
  7920. } else {
  7921. $values[$key] = 'null';
  7922. }
  7923. }
  7924. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
  7925. $values[$key] = 'null';
  7926. }
  7927. }
  7928. if ($error) {
  7929. return -1;
  7930. }
  7931. $this->db->begin();
  7932. if (!$error) {
  7933. $sql = "INSERT INTO ".$this->db->prefix().$this->table_element;
  7934. $sql .= " (".implode(", ", $keys).')';
  7935. $sql .= " VALUES (".implode(", ", $values).")"; // $values can contains 'abc' or 123
  7936. $res = $this->db->query($sql);
  7937. if (!$res) {
  7938. $error++;
  7939. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  7940. $this->errors[] = "ErrorRefAlreadyExists";
  7941. } else {
  7942. $this->errors[] = $this->db->lasterror();
  7943. }
  7944. }
  7945. }
  7946. if (!$error) {
  7947. $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
  7948. }
  7949. // If we have a field ref with a default value of (PROV)
  7950. if (!$error) {
  7951. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
  7952. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
  7953. $resqlupdate = $this->db->query($sql);
  7954. if ($resqlupdate === false) {
  7955. $error++;
  7956. $this->errors[] = $this->db->lasterror();
  7957. } else {
  7958. $this->ref = '(PROV'.$this->id.')';
  7959. }
  7960. }
  7961. }
  7962. // Create extrafields
  7963. if (!$error) {
  7964. $result = $this->insertExtraFields();
  7965. if ($result < 0) {
  7966. $error++;
  7967. }
  7968. }
  7969. // Create lines
  7970. if (!empty($this->table_element_line) && !empty($this->fk_element)) {
  7971. $num = (is_array($this->lines) ? count($this->lines) : 0);
  7972. for ($i = 0; $i < $num; $i++) {
  7973. $line = $this->lines[$i];
  7974. $keyforparent = $this->fk_element;
  7975. $line->$keyforparent = $this->id;
  7976. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  7977. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  7978. if (!is_object($line)) {
  7979. $line = (object) $line;
  7980. }
  7981. $result = $line->create($user, 1);
  7982. if ($result < 0) {
  7983. $this->error = $line->error;
  7984. $this->db->rollback();
  7985. return -1;
  7986. }
  7987. }
  7988. }
  7989. // Triggers
  7990. if (!$error && !$notrigger) {
  7991. // Call triggers
  7992. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  7993. if ($result < 0) {
  7994. $error++;
  7995. }
  7996. // End call triggers
  7997. }
  7998. // Commit or rollback
  7999. if ($error) {
  8000. $this->db->rollback();
  8001. return -1;
  8002. } else {
  8003. $this->db->commit();
  8004. return $this->id;
  8005. }
  8006. }
  8007. /**
  8008. * Load object in memory from the database
  8009. *
  8010. * @param int $id Id object
  8011. * @param string $ref Ref
  8012. * @param string $morewhere More SQL filters (' AND ...')
  8013. * @return int <0 if KO, 0 if not found, >0 if OK
  8014. */
  8015. public function fetchCommon($id, $ref = null, $morewhere = '')
  8016. {
  8017. if (empty($id) && empty($ref) && empty($morewhere)) {
  8018. return -1;
  8019. }
  8020. $fieldlist = $this->getFieldList('t');
  8021. if (empty($fieldlist)) {
  8022. return 0;
  8023. }
  8024. $sql = "SELECT ".$fieldlist;
  8025. $sql .= " FROM ".$this->db->prefix().$this->table_element.' as t';
  8026. if (!empty($id)) {
  8027. $sql .= ' WHERE t.rowid = '.((int) $id);
  8028. } elseif (!empty($ref)) {
  8029. $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
  8030. } else {
  8031. $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  8032. }
  8033. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  8034. $sql .= ' AND t.entity IN ('.getEntity($this->table_element).')';
  8035. }
  8036. if ($morewhere) {
  8037. $sql .= $morewhere;
  8038. }
  8039. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  8040. $res = $this->db->query($sql);
  8041. if ($res) {
  8042. $obj = $this->db->fetch_object($res);
  8043. if ($obj) {
  8044. $this->setVarsFromFetchObj($obj);
  8045. // Retrieve all extrafield
  8046. // fetch optionals attributes and labels
  8047. $this->fetch_optionals();
  8048. return $this->id;
  8049. } else {
  8050. return 0;
  8051. }
  8052. } else {
  8053. $this->error = $this->db->lasterror();
  8054. $this->errors[] = $this->error;
  8055. return -1;
  8056. }
  8057. }
  8058. /**
  8059. * Load object in memory from the database
  8060. *
  8061. * @param string $morewhere More SQL filters (' AND ...')
  8062. * @return int <0 if KO, 0 if not found, >0 if OK
  8063. */
  8064. public function fetchLinesCommon($morewhere = '')
  8065. {
  8066. $objectlineclassname = get_class($this).'Line';
  8067. if (!class_exists($objectlineclassname)) {
  8068. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  8069. return -1;
  8070. }
  8071. $objectline = new $objectlineclassname($this->db);
  8072. $sql = "SELECT ".$objectline->getFieldList('l');
  8073. $sql .= " FROM ".$this->db->prefix().$objectline->table_element." as l";
  8074. $sql .= " WHERE l.fk_".$this->db->escape($this->element)." = ".((int) $this->id);
  8075. if ($morewhere) {
  8076. $sql .= $morewhere;
  8077. }
  8078. if (isset($objectline->fields['position'])) {
  8079. $sql .= $this->db->order('position', 'ASC');
  8080. }
  8081. $resql = $this->db->query($sql);
  8082. if ($resql) {
  8083. $num_rows = $this->db->num_rows($resql);
  8084. $i = 0;
  8085. while ($i < $num_rows) {
  8086. $obj = $this->db->fetch_object($resql);
  8087. if ($obj) {
  8088. $newline = new $objectlineclassname($this->db);
  8089. $newline->setVarsFromFetchObj($obj);
  8090. $this->lines[] = $newline;
  8091. }
  8092. $i++;
  8093. }
  8094. return 1;
  8095. } else {
  8096. $this->error = $this->db->lasterror();
  8097. $this->errors[] = $this->error;
  8098. return -1;
  8099. }
  8100. }
  8101. /**
  8102. * Update object into database
  8103. *
  8104. * @param User $user User that modifies
  8105. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8106. * @return int <0 if KO, >0 if OK
  8107. */
  8108. public function updateCommon(User $user, $notrigger = false)
  8109. {
  8110. global $conf, $langs;
  8111. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  8112. $error = 0;
  8113. $now = dol_now();
  8114. $fieldvalues = $this->setSaveQuery();
  8115. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
  8116. $fieldvalues['date_modification'] = $this->db->idate($now);
  8117. }
  8118. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
  8119. $fieldvalues['fk_user_modif'] = $user->id;
  8120. }
  8121. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  8122. if (array_key_exists('ref', $fieldvalues)) {
  8123. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8124. }
  8125. // Add quotes and escape on fields with type string
  8126. $keys = array();
  8127. $values = array();
  8128. $tmp = array();
  8129. foreach ($fieldvalues as $k => $v) {
  8130. $keys[$k] = $k;
  8131. $value = $this->fields[$k];
  8132. $values[$k] = $this->quote($v, $value);
  8133. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  8134. }
  8135. // Clean and check mandatory fields
  8136. foreach ($keys as $key) {
  8137. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8138. $values[$key] = ''; // This is an implicit foreign key field
  8139. }
  8140. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8141. $values[$key] = ''; // This is an explicit foreign key field
  8142. }
  8143. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  8144. /*
  8145. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  8146. {
  8147. $error++;
  8148. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8149. }*/
  8150. }
  8151. $sql = 'UPDATE '.$this->db->prefix().$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
  8152. $this->db->begin();
  8153. if (!$error) {
  8154. $res = $this->db->query($sql);
  8155. if (!$res) {
  8156. $error++;
  8157. $this->errors[] = $this->db->lasterror();
  8158. }
  8159. }
  8160. // Update extrafield
  8161. if (!$error) {
  8162. $result = $this->insertExtraFields();
  8163. if ($result < 0) {
  8164. $error++;
  8165. }
  8166. }
  8167. // Triggers
  8168. if (!$error && !$notrigger) {
  8169. // Call triggers
  8170. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  8171. if ($result < 0) {
  8172. $error++;
  8173. } //Do also here what you must do to rollback action if trigger fail
  8174. // End call triggers
  8175. }
  8176. // Commit or rollback
  8177. if ($error) {
  8178. $this->db->rollback();
  8179. return -1;
  8180. } else {
  8181. $this->db->commit();
  8182. return $this->id;
  8183. }
  8184. }
  8185. /**
  8186. * Delete object in database
  8187. *
  8188. * @param User $user User that deletes
  8189. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8190. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  8191. * @return int <=0 if KO, 0=Nothing done because object has child, >0 if OK
  8192. */
  8193. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  8194. {
  8195. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  8196. $error = 0;
  8197. $this->db->begin();
  8198. if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
  8199. foreach ($this->childtables as $table) {
  8200. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8201. $resql = $this->db->query($sql);
  8202. if (!$resql) {
  8203. $this->error = $this->db->lasterror();
  8204. $this->errors[] = $this->error;
  8205. $this->db->rollback();
  8206. return -1;
  8207. }
  8208. }
  8209. } elseif (!empty($this->fk_element) && !empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
  8210. $objectisused = $this->isObjectUsed($this->id);
  8211. if (!empty($objectisused)) {
  8212. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  8213. $this->error = 'ErrorRecordHasChildren';
  8214. $this->errors[] = $this->error;
  8215. $this->db->rollback();
  8216. return 0;
  8217. }
  8218. }
  8219. // Delete cascade first
  8220. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  8221. foreach ($this->childtablesoncascade as $table) {
  8222. $deleteFromObject = explode(':', $table);
  8223. if (count($deleteFromObject) >= 2) {
  8224. $className = str_replace('@', '', $deleteFromObject[0]);
  8225. $filePath = $deleteFromObject[1];
  8226. $columnName = $deleteFromObject[2];
  8227. $TMoreSQL = array();
  8228. $more_sql = $deleteFromObject[3];
  8229. if (!empty($more_sql)) {
  8230. $TMoreSQL['customsql'] = $more_sql;
  8231. }
  8232. if (dol_include_once($filePath)) {
  8233. $childObject = new $className($this->db);
  8234. if (method_exists($childObject, 'deleteByParentField')) {
  8235. $result = $childObject->deleteByParentField($this->id, $columnName, $TMoreSQL);
  8236. if ($result < 0) {
  8237. $error++;
  8238. $this->errors[] = $childObject->error;
  8239. break;
  8240. }
  8241. } else {
  8242. $error++;
  8243. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  8244. break;
  8245. }
  8246. } else {
  8247. $error++;
  8248. $this->errors[] = 'Cannot include child class file '.$filePath;
  8249. break;
  8250. }
  8251. } else {
  8252. // Delete record in child table
  8253. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8254. $resql = $this->db->query($sql);
  8255. if (!$resql) {
  8256. $error++;
  8257. $this->error = $this->db->lasterror();
  8258. $this->errors[] = $this->error;
  8259. break;
  8260. }
  8261. }
  8262. }
  8263. }
  8264. if (!$error) {
  8265. if (!$notrigger) {
  8266. // Call triggers
  8267. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  8268. if ($result < 0) {
  8269. $error++;
  8270. } // Do also here what you must do to rollback action if trigger fail
  8271. // End call triggers
  8272. }
  8273. }
  8274. // Delete llx_ecm_files
  8275. if (!$error) {
  8276. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  8277. if (!$res) {
  8278. $error++;
  8279. }
  8280. }
  8281. if (!$error && !empty($this->isextrafieldmanaged)) {
  8282. $result = $this->deleteExtraFields();
  8283. if ($result < 0) {
  8284. $error++;
  8285. }
  8286. }
  8287. if (!$error) {
  8288. $sql = 'DELETE FROM '.$this->db->prefix().$this->table_element.' WHERE rowid='.((int) $this->id);
  8289. $resql = $this->db->query($sql);
  8290. if (!$resql) {
  8291. $error++;
  8292. $this->errors[] = $this->db->lasterror();
  8293. }
  8294. }
  8295. // Commit or rollback
  8296. if ($error) {
  8297. $this->db->rollback();
  8298. return -1;
  8299. } else {
  8300. $this->db->commit();
  8301. return 1;
  8302. }
  8303. }
  8304. /**
  8305. * Delete all child object from a parent ID
  8306. *
  8307. * @param int $parentId Parent Id
  8308. * @param string $parentField Name of Foreign key parent column
  8309. * @param array $filter an array filter
  8310. * @param string $filtermode AND or OR
  8311. * @return int <0 if KO, >0 if OK
  8312. * @throws Exception
  8313. */
  8314. public function deleteByParentField($parentId = 0, $parentField = '', $filter = array(), $filtermode = "AND")
  8315. {
  8316. global $user;
  8317. $error = 0;
  8318. $deleted = 0;
  8319. if (!empty($parentId) && !empty($parentField)) {
  8320. $this->db->begin();
  8321. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
  8322. $sql .= " WHERE ".$parentField." = ".(int) $parentId;
  8323. // Manage filters
  8324. $sqlwhere = array();
  8325. if (count($filter) > 0) {
  8326. foreach ($filter as $key => $value) {
  8327. if ($key == 'customsql') {
  8328. $sqlwhere[] = $value;
  8329. } elseif (strpos($value, '%') === false) {
  8330. $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
  8331. } else {
  8332. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  8333. }
  8334. }
  8335. }
  8336. if (count($sqlwhere) > 0) {
  8337. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  8338. }
  8339. $resql = $this->db->query($sql);
  8340. if (!$resql) {
  8341. $this->errors[] = $this->db->lasterror();
  8342. $error++;
  8343. } else {
  8344. while ($obj = $this->db->fetch_object($resql)) {
  8345. $result = $this->fetch($obj->rowid);
  8346. if ($result < 0) {
  8347. $error++;
  8348. $this->errors[] = $this->error;
  8349. } else {
  8350. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  8351. $result = $this->delete();
  8352. } else {
  8353. $result = $this->delete($user);
  8354. }
  8355. if ($result < 0) {
  8356. $error++;
  8357. $this->errors[] = $this->error;
  8358. } else {
  8359. $deleted++;
  8360. }
  8361. }
  8362. }
  8363. }
  8364. if (empty($error)) {
  8365. $this->db->commit();
  8366. return $deleted;
  8367. } else {
  8368. $this->error = implode(', ', $this->errors);
  8369. $this->db->rollback();
  8370. return $error * -1;
  8371. }
  8372. }
  8373. return $deleted;
  8374. }
  8375. /**
  8376. * Delete a line of object in database
  8377. *
  8378. * @param User $user User that delete
  8379. * @param int $idline Id of line to delete
  8380. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8381. * @return int >0 if OK, <0 if KO
  8382. */
  8383. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  8384. {
  8385. global $conf;
  8386. $error = 0;
  8387. $tmpforobjectclass = get_class($this);
  8388. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  8389. // Call trigger
  8390. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  8391. if ($result < 0) {
  8392. return -1;
  8393. }
  8394. // End call triggers
  8395. $this->db->begin();
  8396. $sql = "DELETE FROM ".$this->db->prefix().$this->table_element_line;
  8397. $sql .= " WHERE rowid = ".((int) $idline);
  8398. dol_syslog(get_class($this)."::deleteLineCommon", LOG_DEBUG);
  8399. $resql = $this->db->query($sql);
  8400. if (!$resql) {
  8401. $this->error = "Error ".$this->db->lasterror();
  8402. $error++;
  8403. }
  8404. if (empty($error)) {
  8405. // Remove extrafields
  8406. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  8407. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  8408. $tmpobjectline->id = $idline;
  8409. $result = $tmpobjectline->deleteExtraFields();
  8410. if ($result < 0) {
  8411. $error++;
  8412. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  8413. }
  8414. }
  8415. }
  8416. if (empty($error)) {
  8417. $this->db->commit();
  8418. return 1;
  8419. } else {
  8420. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  8421. $this->db->rollback();
  8422. return -1;
  8423. }
  8424. }
  8425. /**
  8426. * Set to a status
  8427. *
  8428. * @param User $user Object user that modify
  8429. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  8430. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  8431. * @param string $triggercode Trigger code to use
  8432. * @return int <0 if KO, >0 if OK
  8433. */
  8434. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  8435. {
  8436. $error = 0;
  8437. $this->db->begin();
  8438. $statusfield = 'status';
  8439. if ($this->element == 'don' || $this->element == 'donation') {
  8440. $statusfield = 'fk_statut';
  8441. }
  8442. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  8443. $sql .= " SET ".$statusfield." = ".((int) $status);
  8444. $sql .= " WHERE rowid = ".((int) $this->id);
  8445. if ($this->db->query($sql)) {
  8446. if (!$error) {
  8447. $this->oldcopy = clone $this;
  8448. }
  8449. if (!$error && !$notrigger) {
  8450. // Call trigger
  8451. $result = $this->call_trigger($triggercode, $user);
  8452. if ($result < 0) {
  8453. $error++;
  8454. }
  8455. }
  8456. if (!$error) {
  8457. $this->status = $status;
  8458. $this->db->commit();
  8459. return 1;
  8460. } else {
  8461. $this->db->rollback();
  8462. return -1;
  8463. }
  8464. } else {
  8465. $this->error = $this->db->error();
  8466. $this->db->rollback();
  8467. return -1;
  8468. }
  8469. }
  8470. /**
  8471. * Initialise object with example values
  8472. * Id must be 0 if object instance is a specimen
  8473. *
  8474. * @return int
  8475. */
  8476. public function initAsSpecimenCommon()
  8477. {
  8478. global $user;
  8479. $this->id = 0;
  8480. $this->specimen = 1;
  8481. $fields = array(
  8482. 'label' => 'This is label',
  8483. 'ref' => 'ABCD1234',
  8484. 'description' => 'This is a description',
  8485. 'qty' => 123.12,
  8486. 'note_public' => 'Public note',
  8487. 'note_private' => 'Private note',
  8488. 'date_creation' => (dol_now() - 3600 * 48),
  8489. 'date_modification' => (dol_now() - 3600 * 24),
  8490. 'fk_user_creat' => $user->id,
  8491. 'fk_user_modif' => $user->id,
  8492. 'date' => dol_now(),
  8493. );
  8494. foreach ($fields as $key => $value) {
  8495. if (array_key_exists($key, $this->fields)) {
  8496. $this->{$key} = $value;
  8497. }
  8498. }
  8499. return 1;
  8500. }
  8501. /* Part for comments */
  8502. /**
  8503. * Load comments linked with current task
  8504. * @return boolean 1 if ok
  8505. */
  8506. public function fetchComments()
  8507. {
  8508. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  8509. $comment = new Comment($this->db);
  8510. $result = $comment->fetchAllFor($this->element, $this->id);
  8511. if ($result < 0) {
  8512. $this->errors = array_merge($this->errors, $comment->errors);
  8513. return -1;
  8514. } else {
  8515. $this->comments = $comment->comments;
  8516. }
  8517. return count($this->comments);
  8518. }
  8519. /**
  8520. * Return nb comments already posted
  8521. *
  8522. * @return int
  8523. */
  8524. public function getNbComments()
  8525. {
  8526. return count($this->comments);
  8527. }
  8528. /**
  8529. * Trim object parameters
  8530. *
  8531. * @param string[] $parameters array of parameters to trim
  8532. * @return void
  8533. */
  8534. public function trimParameters($parameters)
  8535. {
  8536. if (!is_array($parameters)) {
  8537. return;
  8538. }
  8539. foreach ($parameters as $parameter) {
  8540. if (isset($this->$parameter)) {
  8541. $this->$parameter = trim($this->$parameter);
  8542. }
  8543. }
  8544. }
  8545. /* Part for categories/tags */
  8546. /**
  8547. * Sets object to given categories.
  8548. *
  8549. * Deletes object from existing categories not supplied.
  8550. * Adds it to non existing supplied categories.
  8551. * Existing categories are left untouch.
  8552. *
  8553. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  8554. * @return int Array of category objects or < 0 if KO
  8555. */
  8556. public function getCategoriesCommon($type_categ)
  8557. {
  8558. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8559. // Get current categories
  8560. $c = new Categorie($this->db);
  8561. $existing = $c->containing($this->id, $type_categ, 'id');
  8562. return $existing;
  8563. }
  8564. /**
  8565. * Sets object to given categories.
  8566. *
  8567. * Adds it to non existing supplied categories.
  8568. * Deletes object from existing categories not supplied (if remove_existing==true).
  8569. * Existing categories are left untouch.
  8570. *
  8571. * @param int[]|int $categories Category ID or array of Categories IDs
  8572. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) definied into const class Categorie type
  8573. * @param boolean $remove_existing True: Remove existings categories from Object if not supplies by $categories, False: let them
  8574. * @return int <0 if KO, >0 if OK
  8575. */
  8576. public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
  8577. {
  8578. // Handle single category
  8579. if (!is_array($categories)) {
  8580. $categories = array($categories);
  8581. }
  8582. dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
  8583. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8584. if (empty($type_categ)) {
  8585. dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
  8586. return -1;
  8587. }
  8588. // Get current categories
  8589. $c = new Categorie($this->db);
  8590. $existing = $c->containing($this->id, $type_categ, 'id');
  8591. if ($remove_existing) {
  8592. // Diff
  8593. if (is_array($existing)) {
  8594. $to_del = array_diff($existing, $categories);
  8595. $to_add = array_diff($categories, $existing);
  8596. } else {
  8597. $to_del = array(); // Nothing to delete
  8598. $to_add = $categories;
  8599. }
  8600. } else {
  8601. $to_del = array(); // Nothing to delete
  8602. $to_add = array_diff($categories, $existing);
  8603. }
  8604. $error = 0;
  8605. $ok = 0;
  8606. // Process
  8607. foreach ($to_del as $del) {
  8608. if ($c->fetch($del) > 0) {
  8609. $result=$c->del_type($this, $type_categ);
  8610. if ($result < 0) {
  8611. $error++;
  8612. $this->error = $c->error;
  8613. $this->errors = $c->errors;
  8614. break;
  8615. } else {
  8616. $ok += $result;
  8617. }
  8618. }
  8619. }
  8620. foreach ($to_add as $add) {
  8621. if ($c->fetch($add) > 0) {
  8622. $result = $c->add_type($this, $type_categ);
  8623. if ($result < 0) {
  8624. $error++;
  8625. $this->error = $c->error;
  8626. $this->errors = $c->errors;
  8627. break;
  8628. } else {
  8629. $ok += $result;
  8630. }
  8631. }
  8632. }
  8633. return $error ? -1 * $error : $ok;
  8634. }
  8635. /**
  8636. * Copy related categories to another object
  8637. *
  8638. * @param int $fromId Id object source
  8639. * @param int $toId Id object cible
  8640. * @param string $type Type of category ('product', ...)
  8641. * @return int < 0 if error, > 0 if ok
  8642. */
  8643. public function cloneCategories($fromId, $toId, $type = '')
  8644. {
  8645. $this->db->begin();
  8646. if (empty($type)) {
  8647. $type = $this->table_element;
  8648. }
  8649. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8650. $categorystatic = new Categorie($this->db);
  8651. $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  8652. $sql .= " SELECT fk_categorie, $toId FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  8653. $sql .= " WHERE fk_product = ".((int) $fromId);
  8654. if (!$this->db->query($sql)) {
  8655. $this->error = $this->db->lasterror();
  8656. $this->db->rollback();
  8657. return -1;
  8658. }
  8659. $this->db->commit();
  8660. return 1;
  8661. }
  8662. /**
  8663. * Delete related files of object in database
  8664. *
  8665. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  8666. * @return bool True if OK, False if KO
  8667. */
  8668. public function deleteEcmFiles($mode = 0)
  8669. {
  8670. global $conf;
  8671. $this->db->begin();
  8672. // Delete in database with mode 0
  8673. if ($mode == 0) {
  8674. switch ($this->element) {
  8675. case 'propal':
  8676. $element = 'propale';
  8677. break;
  8678. case 'product':
  8679. $element = 'produit';
  8680. break;
  8681. case 'order_supplier':
  8682. $element = 'fournisseur/commande';
  8683. break;
  8684. case 'invoice_supplier':
  8685. $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  8686. break;
  8687. case 'shipping':
  8688. $element = 'expedition/sending';
  8689. break;
  8690. default:
  8691. $element = $this->element;
  8692. }
  8693. // Delete ecm_files extrafields
  8694. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files_extrafields WHERE fk_object IN (";
  8695. $sql .= " SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8696. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  8697. $sql .= ")";
  8698. if (!$this->db->query($sql)) {
  8699. $this->error = $this->db->lasterror();
  8700. $this->db->rollback();
  8701. return false;
  8702. }
  8703. // Delete ecm_files
  8704. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files";
  8705. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8706. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  8707. if (!$this->db->query($sql)) {
  8708. $this->error = $this->db->lasterror();
  8709. $this->db->rollback();
  8710. return false;
  8711. }
  8712. }
  8713. // Delete in database with mode 1
  8714. if ($mode == 1) {
  8715. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files_extrafields";
  8716. $sql .= " WHERE fk_object IN (SELECT rowid FROM ".$this->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).")";
  8717. $resql = $this->db->query($sql);
  8718. if (!$resql) {
  8719. $this->error = $this->db->lasterror();
  8720. $this->db->rollback();
  8721. return false;
  8722. }
  8723. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files";
  8724. $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
  8725. $resql = $this->db->query($sql);
  8726. if (!$resql) {
  8727. $this->error = $this->db->lasterror();
  8728. $this->db->rollback();
  8729. return false;
  8730. }
  8731. }
  8732. $this->db->commit();
  8733. return true;
  8734. }
  8735. }