commonobject.class.php 344 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973
  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 array To store result of ->liste_contact()
  103. */
  104. public $contacts_ids;
  105. /**
  106. * @var mixed Array of linked objects, set and used when calling ->create() to be able to create links during the creation of object
  107. */
  108. public $linked_objects;
  109. /**
  110. * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked
  111. */
  112. public $linkedObjectsIds;
  113. /**
  114. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  115. */
  116. public $linkedObjects;
  117. /**
  118. * @var boolean Array of boolean with object id as key and value as true if linkedObjects full loaded. Loaded by ->fetchObjectLinked. Important for pdf generation time reduction.
  119. */
  120. public $linkedObjectsFullLoaded = array();
  121. /**
  122. * @var Object To store a cloned copy of object before to edit it and keep track of old properties
  123. */
  124. public $oldcopy;
  125. /**
  126. * @var string Column name of the ref field.
  127. */
  128. protected $table_ref_field = '';
  129. /**
  130. * @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
  131. */
  132. public $restrictiononfksoc = 0;
  133. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  134. /**
  135. * @var array<string,mixed> Can be used to pass information when only object is provided to method
  136. */
  137. public $context = array();
  138. /**
  139. * @var string Contains canvas name if record is an alternative canvas record
  140. */
  141. public $canvas;
  142. /**
  143. * @var Project The related project object
  144. * @see fetch_projet()
  145. */
  146. public $project;
  147. /**
  148. * @var int The related project ID
  149. * @see setProject(), project
  150. */
  151. public $fk_project;
  152. /**
  153. * @deprecated
  154. * @see project
  155. */
  156. public $projet;
  157. /**
  158. * @deprecated
  159. * @see $fk_project
  160. */
  161. public $fk_projet;
  162. /**
  163. * @var Contact A related contact object
  164. * @see fetch_contact()
  165. */
  166. public $contact;
  167. /**
  168. * @var int The related contact ID
  169. * @see fetch_contact()
  170. */
  171. public $contact_id;
  172. /**
  173. * @var Societe A related thirdparty object
  174. * @see fetch_thirdparty()
  175. */
  176. public $thirdparty;
  177. /**
  178. * @var User A related user
  179. * @see fetch_user()
  180. */
  181. public $user;
  182. /**
  183. * @var string The type of originating object ('commande', 'facture', ...). Note: on some object this field is called $origin_type
  184. * @see fetch_origin()
  185. */
  186. public $origin;
  187. /**
  188. * @var int The id of originating object
  189. * @see fetch_origin()
  190. */
  191. public $origin_id;
  192. /**
  193. * @var string The object's reference
  194. */
  195. public $ref;
  196. /**
  197. * @var string An external reference for the object
  198. */
  199. public $ref_ext;
  200. /**
  201. * @var string The object's previous reference
  202. */
  203. public $ref_previous;
  204. /**
  205. * @var string The object's next reference
  206. */
  207. public $ref_next;
  208. /**
  209. * @var string Ref to store on object to save the new ref to use for example when making a validate() of an object
  210. */
  211. public $newref;
  212. /**
  213. * @var int The object's status. Prefer use of status.
  214. * @see setStatut()
  215. */
  216. public $statut;
  217. /**
  218. * @var int The object's status
  219. * @see setStatut()
  220. */
  221. public $status;
  222. /**
  223. * @var string
  224. * @see getFullAddress()
  225. */
  226. public $country;
  227. /**
  228. * @var int
  229. * @see getFullAddress(), country
  230. */
  231. public $country_id;
  232. /**
  233. * @var string The ISO country code on 2 chars.
  234. * @see getFullAddress(), isInEEC(), country
  235. */
  236. public $country_code;
  237. /**
  238. * @var string
  239. * @see getFullAddress()
  240. */
  241. public $state;
  242. /**
  243. * @var int
  244. * @see getFullAddress(), state
  245. */
  246. public $state_id;
  247. /**
  248. * @var string
  249. * @see getFullAddress(), $state
  250. */
  251. public $state_code;
  252. /**
  253. * @var int
  254. * @see getFullAddress(), $region_code, $region
  255. */
  256. public $region_id;
  257. /**
  258. * @var string
  259. * @see getFullAddress(), $region_id, $region
  260. */
  261. public $region_code;
  262. /**
  263. * @var string
  264. * @see getFullAddress(), $region_id, $region_code
  265. */
  266. public $region;
  267. /**
  268. * @var int
  269. * @see fetch_barcode()
  270. */
  271. public $barcode_type;
  272. /**
  273. * @var string
  274. * @see fetch_barcode(), barcode_type
  275. */
  276. public $barcode_type_code;
  277. /**
  278. * @var string
  279. * @see fetch_barcode(), barcode_type
  280. */
  281. public $barcode_type_label;
  282. /**
  283. * @var string
  284. * @see fetch_barcode(), barcode_type
  285. */
  286. public $barcode_type_coder;
  287. /**
  288. * @var int Payment method ID (cheque, cash, ...)
  289. * @see setPaymentMethods()
  290. */
  291. public $mode_reglement_id;
  292. /**
  293. * @var int Payment terms ID
  294. * @see setPaymentTerms()
  295. */
  296. public $cond_reglement_id;
  297. /**
  298. * @var int Demand reason ID
  299. */
  300. public $demand_reason_id;
  301. /**
  302. * @var int Transport mode ID (For module intracomm report)
  303. * @see setTransportMode()
  304. */
  305. public $transport_mode_id;
  306. /**
  307. * @var int Payment terms ID
  308. * @deprecated Kept for compatibility
  309. * @see cond_reglement_id;
  310. */
  311. public $cond_reglement;
  312. /**
  313. * @var int Delivery address ID
  314. * @see setDeliveryAddress()
  315. * @deprecated
  316. */
  317. public $fk_delivery_address;
  318. /**
  319. * @var int Shipping method ID
  320. * @see setShippingMethod()
  321. */
  322. public $shipping_method_id;
  323. /**
  324. * @var string
  325. * @see SetDocModel()
  326. */
  327. public $model_pdf;
  328. /**
  329. * @var string
  330. * @deprecated
  331. * @see $model_pdf
  332. */
  333. public $modelpdf;
  334. /**
  335. * @var string
  336. * Contains relative path of last generated main file
  337. */
  338. public $last_main_doc;
  339. /**
  340. * @var int Bank account ID sometimes, ID of record into llx_bank sometimes
  341. * @deprecated
  342. * @see $fk_account
  343. */
  344. public $fk_bank;
  345. /**
  346. * @var int Bank account ID
  347. * @see SetBankAccount()
  348. */
  349. public $fk_account;
  350. /**
  351. * @var string Open ID
  352. */
  353. public $openid;
  354. /**
  355. * @var string Public note
  356. * @see update_note()
  357. */
  358. public $note_public;
  359. /**
  360. * @var string Private note
  361. * @see update_note()
  362. */
  363. public $note_private;
  364. /**
  365. * @deprecated
  366. * @see $note_private
  367. */
  368. public $note;
  369. /**
  370. * @var float Total amount before taxes
  371. * @see update_price()
  372. */
  373. public $total_ht;
  374. /**
  375. * @var float Total VAT amount
  376. * @see update_price()
  377. */
  378. public $total_tva;
  379. /**
  380. * @var float Total local tax 1 amount
  381. * @see update_price()
  382. */
  383. public $total_localtax1;
  384. /**
  385. * @var float Total local tax 2 amount
  386. * @see update_price()
  387. */
  388. public $total_localtax2;
  389. /**
  390. * @var float Total amount with taxes
  391. * @see update_price()
  392. */
  393. public $total_ttc;
  394. /**
  395. * @var CommonObjectLine[]
  396. */
  397. public $lines;
  398. /**
  399. * @var mixed Contains comments
  400. * @see fetchComments()
  401. */
  402. public $comments = array();
  403. /**
  404. * @var string The name
  405. */
  406. public $name;
  407. /**
  408. * @var string The lastname
  409. */
  410. public $lastname;
  411. /**
  412. * @var string The firstname
  413. */
  414. public $firstname;
  415. /**
  416. * @var string The civility code, not an integer
  417. */
  418. public $civility_id;
  419. // Dates
  420. /**
  421. * @var integer|string date_creation
  422. */
  423. public $date_creation;
  424. /**
  425. * @var integer|string $date_validation;
  426. */
  427. public $date_validation; // Date validation
  428. /**
  429. * @var integer|string $date_modification;
  430. */
  431. public $date_modification; // Date last change (tms field)
  432. /**
  433. * @var integer|string $date_cloture;
  434. */
  435. public $date_cloture; // Date closing (tms field)
  436. /**
  437. * @var User|int User author/creation
  438. * @TODO Merge with user_creation
  439. */
  440. public $user_author;
  441. /**
  442. * @var User|int User author/creation
  443. * @TODO Remove type id
  444. */
  445. public $user_creation;
  446. /**
  447. * @var int User id author/creation
  448. */
  449. public $user_creation_id;
  450. /**
  451. * @var User|int User of validation
  452. * @TODO Merge with user_validation
  453. */
  454. public $user_valid;
  455. /**
  456. * @var User|int User of validation
  457. * @TODO Remove type id
  458. */
  459. public $user_validation;
  460. /**
  461. * @var int User id of validation
  462. */
  463. public $user_validation_id;
  464. /**
  465. * @var int User id closing object
  466. */
  467. public $user_closing_id;
  468. /**
  469. * @var User|int User last modifier
  470. * @TODO Remove type id
  471. */
  472. public $user_modification;
  473. /**
  474. * @var int User id last modifier
  475. */
  476. public $user_modification_id;
  477. public $next_prev_filter;
  478. /**
  479. * @var int 1 if object is specimen
  480. */
  481. public $specimen = 0;
  482. /**
  483. * @var int Id of contact to send object (used by the trigger of module Agenda)
  484. */
  485. public $sendtoid;
  486. /**
  487. * @var float Amount already paid (used to show correct status)
  488. */
  489. public $alreadypaid;
  490. /**
  491. * @var array List of child tables. To test if we can delete object.
  492. */
  493. protected $childtables = array();
  494. /**
  495. * @var array List of child tables. To know object to delete on cascade.
  496. * If name is like '@ClassName:FilePathClass:ParentFkFieldName', it will
  497. * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object.
  498. */
  499. protected $childtablesoncascade = array();
  500. // No constructor as it is an abstract class
  501. /**
  502. * Check an object id/ref exists
  503. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  504. *
  505. * @param string $element String of element ('product', 'facture', ...)
  506. * @param int $id Id of object
  507. * @param string $ref Ref of object to check
  508. * @param string $ref_ext Ref ext of object to check
  509. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  510. */
  511. public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
  512. {
  513. global $db, $conf;
  514. $sql = "SELECT rowid, ref, ref_ext";
  515. $sql .= " FROM ".$db->prefix().$element;
  516. $sql .= " WHERE entity IN (".getEntity($element).")";
  517. if ($id > 0) {
  518. $sql .= " AND rowid = ".((int) $id);
  519. } elseif ($ref) {
  520. $sql .= " AND ref = '".$db->escape($ref)."'";
  521. } elseif ($ref_ext) {
  522. $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
  523. } else {
  524. $error = 'ErrorWrongParameters';
  525. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  526. return -1;
  527. }
  528. if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
  529. $sql .= " AND entity = ".((int) $conf->entity);
  530. }
  531. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  532. $resql = $db->query($sql);
  533. if ($resql) {
  534. $num = $db->num_rows($resql);
  535. if ($num > 0) {
  536. return 1;
  537. } else {
  538. return 0;
  539. }
  540. }
  541. return -1;
  542. }
  543. /**
  544. * Method to output saved errors
  545. *
  546. * @return string String with errors
  547. */
  548. public function errorsToString()
  549. {
  550. return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
  551. }
  552. /**
  553. * Return customer ref for screen output.
  554. *
  555. * @param string $objref Customer ref
  556. * @return string Customer ref formated
  557. */
  558. public function getFormatedCustomerRef($objref)
  559. {
  560. global $hookmanager;
  561. $parameters = array('objref'=>$objref);
  562. $action = '';
  563. $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  564. if ($reshook > 0) {
  565. return $hookmanager->resArray['objref'];
  566. }
  567. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  568. }
  569. /**
  570. * Return supplier ref for screen output.
  571. *
  572. * @param string $objref Supplier ref
  573. * @return string Supplier ref formated
  574. */
  575. public function getFormatedSupplierRef($objref)
  576. {
  577. global $hookmanager;
  578. $parameters = array('objref'=>$objref);
  579. $action = '';
  580. $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  581. if ($reshook > 0) {
  582. return $hookmanager->resArray['objref'];
  583. }
  584. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  585. }
  586. /**
  587. * Return full name (civility+' '+name+' '+lastname)
  588. *
  589. * @param Translate $langs Language object for translation of civility (used only if option is 1)
  590. * @param int $option 0=No option, 1=Add civility
  591. * @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
  592. * @param int $maxlen Maximum length
  593. * @return string String with full name
  594. */
  595. public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
  596. {
  597. //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
  598. $lastname = $this->lastname;
  599. $firstname = $this->firstname;
  600. if (empty($lastname)) {
  601. $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 : '')))));
  602. }
  603. $ret = '';
  604. if (!empty($option) && !empty($this->civility_code)) {
  605. if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) {
  606. $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
  607. } else {
  608. $ret .= $this->civility_code.' ';
  609. }
  610. }
  611. $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
  612. return dol_trunc($ret, $maxlen);
  613. }
  614. /**
  615. * Set to upper or ucwords/lower if needed
  616. *
  617. * @return void;
  618. */
  619. public function setUpperOrLowerCase()
  620. {
  621. global $conf;
  622. if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
  623. $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
  624. $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
  625. $this->name = dol_ucwords(dol_strtolower($this->name));
  626. $this->name_alias = dol_ucwords(dol_strtolower($this->name_alias));
  627. }
  628. if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
  629. $this->lastname = dol_strtoupper($this->lastname);
  630. $this->name = dol_strtoupper($this->name);
  631. $this->name_alias = dol_strtoupper($this->name_alias);
  632. }
  633. if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
  634. $this->address = dol_strtoupper($this->address);
  635. $this->town = dol_strtoupper($this->town);
  636. }
  637. }
  638. /**
  639. * Return clicable link of object (with eventually picto)
  640. *
  641. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  642. * @return string HTML Code for Kanban thumb.
  643. */
  644. public function getKanbanView($option = '')
  645. {
  646. $return = '<div class="box-flex-item box-flex-grow-zero">';
  647. $return .= '<div class="info-box info-box-sm">';
  648. $return .= '<span class="info-box-icon bg-infobox-action">';
  649. $return .= img_picto('', $this->picto);
  650. //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
  651. $return .= '</span>';
  652. $return .= '<div class="info-box-content">';
  653. $return .= '<span class="info-box-ref">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  654. if (property_exists($this, 'label')) {
  655. $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
  656. }
  657. if (method_exists($this, 'getLibStatut')) {
  658. $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(5).'</div>';
  659. }
  660. $return .= '</div>';
  661. $return .= '</div>';
  662. $return .= '</div>';
  663. return $return;
  664. }
  665. /**
  666. * Return full address of contact
  667. *
  668. * @param int $withcountry 1=Add country into address string
  669. * @param string $sep Separator to use to build string
  670. * @param int $withregion 1=Add region into address string
  671. * @param string $extralangcode User extralanguages as value
  672. * @return string Full address string
  673. */
  674. public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
  675. {
  676. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
  677. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  678. $tmparray = getCountry($this->country_id, 'all');
  679. $this->country_code = $tmparray['code'];
  680. $this->country = $tmparray['label'];
  681. }
  682. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
  683. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  684. $tmparray = getState($this->state_id, 'all', 0, 1);
  685. $this->state_code = $tmparray['code'];
  686. $this->state = $tmparray['label'];
  687. $this->region_code = $tmparray['region_code'];
  688. $this->region = $tmparray['region'];
  689. }
  690. return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
  691. }
  692. /**
  693. * Return full address for banner
  694. *
  695. * @param string $htmlkey HTML id to make banner content unique
  696. * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member)
  697. * @return string Full address string
  698. */
  699. public function getBannerAddress($htmlkey, $object)
  700. {
  701. global $conf, $langs, $form, $extralanguages;
  702. $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
  703. $contactid = 0;
  704. $thirdpartyid = 0;
  705. $elementforaltlanguage = $this->element;
  706. if ($this->element == 'societe') {
  707. $thirdpartyid = $this->id;
  708. }
  709. if ($this->element == 'contact') {
  710. $contactid = $this->id;
  711. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  712. }
  713. if ($this->element == 'user') {
  714. $contactid = $this->contact_id;
  715. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  716. }
  717. $out = '';
  718. $outdone = 0;
  719. $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
  720. if ($coords) {
  721. if (!empty($conf->use_javascript_ajax)) {
  722. // Add picto with tooltip on map
  723. $namecoords = '';
  724. if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
  725. $namecoords .= $object->name.'<br>';
  726. }
  727. $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
  728. // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
  729. $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
  730. $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
  731. $out .= '</a> ';
  732. }
  733. $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  734. $outdone++;
  735. $outdone++;
  736. // List of extra languages
  737. $arrayoflangcode = array();
  738. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  739. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  740. }
  741. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  742. if (!is_object($extralanguages)) {
  743. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  744. $extralanguages = new ExtraLanguages($this->db);
  745. }
  746. $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
  747. if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
  748. $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
  749. $this->fetchValuesForExtraLanguages();
  750. if (!is_object($form)) {
  751. $form = new Form($this->db);
  752. }
  753. $htmltext = '';
  754. // If there is extra languages
  755. foreach ($arrayoflangcode as $extralangcode) {
  756. $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  757. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
  758. $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  759. }
  760. $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  761. }
  762. }
  763. }
  764. 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
  765. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
  766. if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
  767. $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
  768. } else {
  769. $out .= ($outdone ? ' - ' : '').$this->state;
  770. }
  771. $outdone++;
  772. }
  773. 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)) {
  774. $out .= ($outdone ? '<br>' : '');
  775. }
  776. if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  777. $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  778. $outdone++;
  779. }
  780. if (!empty($this->phone_pro)) {
  781. $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  782. $outdone++;
  783. }
  784. if (!empty($this->phone_mobile)) {
  785. $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  786. $outdone++;
  787. }
  788. if (!empty($this->phone_perso)) {
  789. $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
  790. $outdone++;
  791. }
  792. if (!empty($this->office_phone)) {
  793. $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  794. $outdone++;
  795. }
  796. if (!empty($this->user_mobile)) {
  797. $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  798. $outdone++;
  799. }
  800. if (!empty($this->fax)) {
  801. $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  802. $outdone++;
  803. }
  804. if (!empty($this->office_fax)) {
  805. $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  806. $outdone++;
  807. }
  808. if ($out) {
  809. $out .= '<div style="clear: both;"></div>';
  810. }
  811. $outdone = 0;
  812. if (!empty($this->email)) {
  813. $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
  814. $outdone++;
  815. }
  816. if (!empty($this->url)) {
  817. //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
  818. $out .= dol_print_url($this->url, '_blank', 0, 1);
  819. $outdone++;
  820. }
  821. if (!empty($conf->socialnetworks->enabled)) {
  822. $outsocialnetwork = '';
  823. if (!empty($this->socialnetworks) && is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
  824. $socialnetworksdict = getArrayOfSocialNetworks();
  825. foreach ($this->socialnetworks as $key => $value) {
  826. if ($value) {
  827. $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
  828. }
  829. $outdone++;
  830. }
  831. } else { // Old code to remove
  832. if (!empty($this->skype)) {
  833. $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
  834. }
  835. $outdone++;
  836. if (!empty($this->jabberid)) {
  837. $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
  838. }
  839. $outdone++;
  840. if (!empty($this->twitter)) {
  841. $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
  842. }
  843. $outdone++;
  844. if (!empty($this->facebook)) {
  845. $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
  846. }
  847. $outdone++;
  848. if (!empty($this->linkedin)) {
  849. $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
  850. }
  851. $outdone++;
  852. }
  853. if ($outsocialnetwork) {
  854. $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
  855. }
  856. }
  857. if ($out) {
  858. return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
  859. } else {
  860. return '';
  861. }
  862. }
  863. /**
  864. * Return the link of last main doc file for direct public download.
  865. *
  866. * @param string $modulepart Module related to document
  867. * @param int $initsharekey Init the share key if it was not yet defined
  868. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  869. * @return string Link or empty string if there is no download link
  870. */
  871. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  872. {
  873. global $user, $dolibarr_main_url_root;
  874. if (empty($this->last_main_doc)) {
  875. return ''; // No way to known which document name to use
  876. }
  877. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  878. $ecmfile = new EcmFiles($this->db);
  879. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  880. if ($result < 0) {
  881. $this->error = $ecmfile->error;
  882. $this->errors = $ecmfile->errors;
  883. return -1;
  884. }
  885. if (empty($ecmfile->id)) {
  886. // Add entry into index
  887. if ($initsharekey) {
  888. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  889. // TODO We can't, we dont' have full path of file, only last_main_doc and ->element, so we must first rebuild full path $destfull
  890. /*
  891. $ecmfile->filepath = $rel_dir;
  892. $ecmfile->filename = $filename;
  893. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  894. $ecmfile->fullpath_orig = '';
  895. $ecmfile->gen_or_uploaded = 'generated';
  896. $ecmfile->description = ''; // indexed content
  897. $ecmfile->keywords = ''; // keyword content
  898. $ecmfile->share = getRandomPassword(true);
  899. $result = $ecmfile->create($user);
  900. if ($result < 0)
  901. {
  902. $this->error = $ecmfile->error;
  903. $this->errors = $ecmfile->errors;
  904. }
  905. */
  906. } else {
  907. return '';
  908. }
  909. } elseif (empty($ecmfile->share)) {
  910. // Add entry into index
  911. if ($initsharekey) {
  912. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  913. $ecmfile->share = getRandomPassword(true);
  914. $ecmfile->update($user);
  915. } else {
  916. return '';
  917. }
  918. }
  919. // Define $urlwithroot
  920. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  921. // This is to use external domain name found into config file
  922. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  923. //else
  924. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  925. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  926. $forcedownload = 0;
  927. $paramlink = '';
  928. //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  929. //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  930. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  931. if (!empty($ecmfile->share)) {
  932. $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
  933. }
  934. if ($forcedownload) {
  935. $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  936. }
  937. if ($relativelink) {
  938. $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
  939. } else {
  940. $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  941. }
  942. // Here $ecmfile->share is defined
  943. return $linktoreturn;
  944. }
  945. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  946. /**
  947. * Add a link between element $this->element and a contact
  948. *
  949. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  950. * @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
  951. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  952. * @param int $notrigger Disable all triggers
  953. * @return int <0 if KO, 0 if already added, >0 if OK
  954. */
  955. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  956. {
  957. // phpcs:enable
  958. global $user, $langs;
  959. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  960. // Check parameters
  961. if ($fk_socpeople <= 0) {
  962. $langs->load("errors");
  963. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  964. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  965. return -1;
  966. }
  967. if (!$type_contact) {
  968. $langs->load("errors");
  969. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  970. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  971. return -2;
  972. }
  973. $id_type_contact = 0;
  974. if (is_numeric($type_contact)) {
  975. $id_type_contact = $type_contact;
  976. } else {
  977. // We look for id type_contact
  978. $sql = "SELECT tc.rowid";
  979. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  980. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  981. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  982. $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  983. //print $sql;
  984. $resql = $this->db->query($sql);
  985. if ($resql) {
  986. $obj = $this->db->fetch_object($resql);
  987. if ($obj) {
  988. $id_type_contact = $obj->rowid;
  989. }
  990. }
  991. }
  992. if ($id_type_contact == 0) {
  993. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  994. 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");
  995. return -3;
  996. }
  997. $datecreate = dol_now();
  998. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  999. $TListeContacts = $this->liste_contact(-1, $source);
  1000. $already_added = false;
  1001. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  1002. foreach ($TListeContacts as $array_contact) {
  1003. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  1004. $already_added = true;
  1005. break;
  1006. }
  1007. }
  1008. }
  1009. if (!$already_added) {
  1010. $this->db->begin();
  1011. // Insert into database
  1012. $sql = "INSERT INTO ".$this->db->prefix()."element_contact";
  1013. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  1014. $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
  1015. $sql .= "'".$this->db->idate($datecreate)."'";
  1016. $sql .= ", 4, ".((int) $id_type_contact);
  1017. $sql .= ")";
  1018. $resql = $this->db->query($sql);
  1019. if ($resql) {
  1020. if (!$notrigger) {
  1021. $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  1022. if ($result < 0) {
  1023. $this->db->rollback();
  1024. return -1;
  1025. }
  1026. }
  1027. $this->db->commit();
  1028. return 1;
  1029. } else {
  1030. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1031. $this->error = $this->db->errno();
  1032. $this->db->rollback();
  1033. return -2;
  1034. } else {
  1035. $this->error = $this->db->lasterror();
  1036. $this->db->rollback();
  1037. return -1;
  1038. }
  1039. }
  1040. } else {
  1041. return 0;
  1042. }
  1043. }
  1044. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1045. /**
  1046. * Copy contact from one element to current
  1047. *
  1048. * @param CommonObject $objFrom Source element
  1049. * @param string $source Nature of contact ('internal' or 'external')
  1050. * @return int >0 if OK, <0 if KO
  1051. */
  1052. public function copy_linked_contact($objFrom, $source = 'internal')
  1053. {
  1054. // phpcs:enable
  1055. $contacts = $objFrom->liste_contact(-1, $source);
  1056. foreach ($contacts as $contact) {
  1057. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
  1058. return -1;
  1059. }
  1060. }
  1061. return 1;
  1062. }
  1063. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1064. /**
  1065. * Update a link to contact line
  1066. *
  1067. * @param int $rowid Id of line contact-element
  1068. * @param int $statut New status of link
  1069. * @param int $type_contact_id Id of contact type (not modified if 0)
  1070. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  1071. * @return int <0 if KO, >= 0 if OK
  1072. */
  1073. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  1074. {
  1075. // phpcs:enable
  1076. // Insert into database
  1077. $sql = "UPDATE ".$this->db->prefix()."element_contact set";
  1078. $sql .= " statut = ".$statut;
  1079. if ($type_contact_id) {
  1080. $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
  1081. }
  1082. if ($fk_socpeople) {
  1083. $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
  1084. }
  1085. $sql .= " where rowid = ".((int) $rowid);
  1086. $resql = $this->db->query($sql);
  1087. if ($resql) {
  1088. return 0;
  1089. } else {
  1090. $this->error = $this->db->lasterror();
  1091. return -1;
  1092. }
  1093. }
  1094. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1095. /**
  1096. * Delete a link to contact line
  1097. *
  1098. * @param int $rowid Id of contact link line to delete
  1099. * @param int $notrigger Disable all triggers
  1100. * @return int >0 if OK, <0 if KO
  1101. */
  1102. public function delete_contact($rowid, $notrigger = 0)
  1103. {
  1104. // phpcs:enable
  1105. global $user;
  1106. $this->db->begin();
  1107. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1108. $sql .= " WHERE rowid = ".((int) $rowid);
  1109. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  1110. if ($this->db->query($sql)) {
  1111. if (!$notrigger) {
  1112. $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  1113. if ($result < 0) {
  1114. $this->db->rollback();
  1115. return -1;
  1116. }
  1117. }
  1118. $this->db->commit();
  1119. return 1;
  1120. } else {
  1121. $this->error = $this->db->lasterror();
  1122. $this->db->rollback();
  1123. return -1;
  1124. }
  1125. }
  1126. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1127. /**
  1128. * Delete all links between an object $this and all its contacts
  1129. *
  1130. * @param string $source '' or 'internal' or 'external'
  1131. * @param string $code Type of contact (code or id)
  1132. * @return int >0 if OK, <0 if KO
  1133. */
  1134. public function delete_linked_contact($source = '', $code = '')
  1135. {
  1136. // phpcs:enable
  1137. $listId = '';
  1138. $temp = array();
  1139. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  1140. if (!empty($typeContact)) {
  1141. foreach ($typeContact as $key => $value) {
  1142. array_push($temp, $key);
  1143. }
  1144. $listId = implode(",", $temp);
  1145. }
  1146. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1147. $sql .= " WHERE element_id = ".((int) $this->id);
  1148. if (!empty($listId)) {
  1149. $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
  1150. }
  1151. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  1152. if ($this->db->query($sql)) {
  1153. return 1;
  1154. } else {
  1155. $this->error = $this->db->lasterror();
  1156. return -1;
  1157. }
  1158. }
  1159. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1160. /**
  1161. * Get array of all contacts for an object
  1162. *
  1163. * @param int $status Status of links to get (-1=all)
  1164. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  1165. * @param int $list 0:Return array contains all properties, 1:Return array contains just id
  1166. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1167. * @return array|int Array of contacts, -1 if error
  1168. */
  1169. public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
  1170. {
  1171. // phpcs:enable
  1172. global $langs;
  1173. $tab = array();
  1174. $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
  1175. if ($source == 'internal') {
  1176. $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  1177. }
  1178. if ($source == 'external' || $source == 'thirdparty') {
  1179. $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1180. }
  1181. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  1182. $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
  1183. $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
  1184. $sql .= ", ".$this->db->prefix()."element_contact ec";
  1185. if ($source == 'internal') {
  1186. $sql .= " LEFT JOIN ".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid";
  1187. }
  1188. if ($source == 'external' || $source == 'thirdparty') {
  1189. $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid";
  1190. }
  1191. $sql .= " WHERE ec.element_id = ".((int) $this->id);
  1192. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1193. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1194. if ($code) {
  1195. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1196. }
  1197. if ($source == 'internal') {
  1198. $sql .= " AND tc.source = 'internal'";
  1199. }
  1200. if ($source == 'external' || $source == 'thirdparty') {
  1201. $sql .= " AND tc.source = 'external'";
  1202. }
  1203. $sql .= " AND tc.active=1";
  1204. if ($status >= 0) {
  1205. $sql .= " AND ec.statut = ".((int) $status);
  1206. }
  1207. $sql .= " ORDER BY t.lastname ASC";
  1208. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  1209. $resql = $this->db->query($sql);
  1210. if ($resql) {
  1211. $num = $this->db->num_rows($resql);
  1212. $i = 0;
  1213. while ($i < $num) {
  1214. $obj = $this->db->fetch_object($resql);
  1215. if (!$list) {
  1216. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1217. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1218. $tab[$i] = array(
  1219. 'source' => $obj->source,
  1220. 'socid' => $obj->socid,
  1221. 'id' => $obj->id,
  1222. 'nom' => $obj->lastname, // For backward compatibility
  1223. 'civility' => $obj->civility,
  1224. 'lastname' => $obj->lastname,
  1225. 'firstname' => $obj->firstname,
  1226. 'email'=>$obj->email,
  1227. 'login'=> (empty($obj->login) ? '' : $obj->login),
  1228. 'photo' => (empty($obj->photo) ? '' : $obj->photo),
  1229. 'statuscontact' => $obj->statuscontact,
  1230. 'rowid' => $obj->rowid,
  1231. 'code' => $obj->code,
  1232. 'libelle' => $libelle_type,
  1233. 'status' => $obj->statuslink,
  1234. 'fk_c_type_contact' => $obj->fk_c_type_contact
  1235. );
  1236. } else {
  1237. $tab[$i] = $obj->id;
  1238. }
  1239. $i++;
  1240. }
  1241. return $tab;
  1242. } else {
  1243. $this->error = $this->db->lasterror();
  1244. dol_print_error($this->db);
  1245. return -1;
  1246. }
  1247. }
  1248. /**
  1249. * Update status of a contact linked to object
  1250. *
  1251. * @param int $rowid Id of link between object and contact
  1252. * @return int <0 if KO, >=0 if OK
  1253. */
  1254. public function swapContactStatus($rowid)
  1255. {
  1256. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1257. $sql .= " tc.code, tc.libelle";
  1258. $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
  1259. $sql .= " WHERE ec.rowid =".((int) $rowid);
  1260. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1261. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1262. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  1263. $resql = $this->db->query($sql);
  1264. if ($resql) {
  1265. $obj = $this->db->fetch_object($resql);
  1266. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1267. $result = $this->update_contact($rowid, $newstatut);
  1268. $this->db->free($resql);
  1269. return $result;
  1270. } else {
  1271. $this->error = $this->db->error();
  1272. dol_print_error($this->db);
  1273. return -1;
  1274. }
  1275. }
  1276. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1277. /**
  1278. * Return array with list of possible values for type of contacts
  1279. *
  1280. * @param string $source 'internal', 'external' or 'all'
  1281. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  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. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1286. */
  1287. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1288. {
  1289. // phpcs:enable
  1290. global $langs;
  1291. if (empty($order)) {
  1292. $order = 'position';
  1293. }
  1294. if ($order == 'position') {
  1295. $order .= ',code';
  1296. }
  1297. $tab = array();
  1298. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  1299. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1300. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1301. if ($activeonly == 1) {
  1302. $sql .= " AND tc.active=1"; // only the active types
  1303. }
  1304. if (!empty($source) && $source != 'all') {
  1305. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1306. }
  1307. if (!empty($code)) {
  1308. $sql .= " AND tc.code='".$this->db->escape($code)."'";
  1309. }
  1310. $sql .= $this->db->order($order, 'ASC');
  1311. //print "sql=".$sql;
  1312. $resql = $this->db->query($sql);
  1313. if ($resql) {
  1314. $num = $this->db->num_rows($resql);
  1315. $i = 0;
  1316. while ($i < $num) {
  1317. $obj = $this->db->fetch_object($resql);
  1318. $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
  1319. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1320. if (empty($option)) {
  1321. $tab[$obj->rowid] = $libelle_type;
  1322. } else {
  1323. $tab[$obj->code] = $libelle_type;
  1324. }
  1325. $i++;
  1326. }
  1327. return $tab;
  1328. } else {
  1329. $this->error = $this->db->lasterror();
  1330. //dol_print_error($this->db);
  1331. return null;
  1332. }
  1333. }
  1334. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1335. /**
  1336. * Return array with list of possible values for type of contacts
  1337. *
  1338. * @param string $source 'internal', 'external' or 'all'
  1339. * @param int $option 0=Return array id->label, 1=Return array code->label
  1340. * @param int $activeonly 0=all status of contact, 1=only the active
  1341. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1342. * @param string $element Filter on 1 element type
  1343. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1344. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1345. */
  1346. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1347. {
  1348. // phpcs:enable
  1349. global $langs, $conf;
  1350. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1351. $tab = array();
  1352. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
  1353. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1354. $sqlWhere = array();
  1355. if (!empty($element)) {
  1356. $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
  1357. }
  1358. if (!empty($excludeelement)) {
  1359. $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
  1360. }
  1361. if ($activeonly == 1) {
  1362. $sqlWhere[] = " tc.active=1"; // only the active types
  1363. }
  1364. if (!empty($source) && $source != 'all') {
  1365. $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
  1366. }
  1367. if (!empty($code)) {
  1368. $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
  1369. }
  1370. if (count($sqlWhere) > 0) {
  1371. $sql .= " WHERE ".implode(' AND ', $sqlWhere);
  1372. }
  1373. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1374. dol_syslog(__METHOD__, LOG_DEBUG);
  1375. $resql = $this->db->query($sql);
  1376. if ($resql) {
  1377. $num = $this->db->num_rows($resql);
  1378. if ($num > 0) {
  1379. $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
  1380. while ($obj = $this->db->fetch_object($resql)) {
  1381. $modulename = $obj->element;
  1382. if (strpos($obj->element, 'project') !== false) {
  1383. $modulename = 'projet';
  1384. } elseif ($obj->element == 'contrat') {
  1385. $element = 'contract';
  1386. } elseif ($obj->element == 'action') {
  1387. $modulename = 'agenda';
  1388. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1389. $modulename = 'fournisseur';
  1390. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1391. $modulename = 'fournisseur';
  1392. }
  1393. if (!empty($conf->{$modulename}->enabled)) {
  1394. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1395. $tmpelement = $obj->element;
  1396. $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
  1397. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1398. if (empty($option)) {
  1399. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1400. } else {
  1401. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1402. }
  1403. }
  1404. }
  1405. }
  1406. return $tab;
  1407. } else {
  1408. $this->error = $this->db->lasterror();
  1409. return null;
  1410. }
  1411. }
  1412. /**
  1413. * Return id of contacts for a source and a contact code.
  1414. * Example: contact client de facturation ('external', 'BILLING')
  1415. * Example: contact client de livraison ('external', 'SHIPPING')
  1416. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1417. *
  1418. * @param string $source 'external' or 'internal'
  1419. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1420. * @param int $status limited to a certain status
  1421. * @return array List of id for such contacts
  1422. */
  1423. public function getIdContact($source, $code, $status = 0)
  1424. {
  1425. global $conf;
  1426. $result = array();
  1427. $i = 0;
  1428. //cas particulier pour les expeditions
  1429. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1430. $id = $this->origin_id;
  1431. $element = 'commande';
  1432. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1433. $id = $this->origin_id;
  1434. $element = 'order_supplier';
  1435. } else {
  1436. $id = $this->id;
  1437. $element = $this->element;
  1438. }
  1439. $sql = "SELECT ec.fk_socpeople";
  1440. $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
  1441. if ($source == 'internal') {
  1442. $sql .= " ".$this->db->prefix()."user as c,";
  1443. }
  1444. if ($source == 'external') {
  1445. $sql .= " ".$this->db->prefix()."socpeople as c,";
  1446. }
  1447. $sql .= " ".$this->db->prefix()."c_type_contact as tc";
  1448. $sql .= " WHERE ec.element_id = ".((int) $id);
  1449. $sql .= " AND ec.fk_socpeople = c.rowid";
  1450. if ($source == 'internal') {
  1451. $sql .= " AND c.entity IN (".getEntity('user').")";
  1452. }
  1453. if ($source == 'external') {
  1454. $sql .= " AND c.entity IN (".getEntity('societe').")";
  1455. }
  1456. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1457. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1458. $sql .= " AND tc.source = '".$this->db->escape($source)."'";
  1459. if ($code) {
  1460. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1461. }
  1462. $sql .= " AND tc.active = 1";
  1463. if ($status) {
  1464. $sql .= " AND ec.statut = ".((int) $status);
  1465. }
  1466. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1467. $resql = $this->db->query($sql);
  1468. if ($resql) {
  1469. while ($obj = $this->db->fetch_object($resql)) {
  1470. $result[$i] = $obj->fk_socpeople;
  1471. $i++;
  1472. }
  1473. } else {
  1474. $this->error = $this->db->error();
  1475. return null;
  1476. }
  1477. return $result;
  1478. }
  1479. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1480. /**
  1481. * Load object contact with id=$this->contact_id into $this->contact
  1482. *
  1483. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1484. * @return int <0 if KO, >0 if OK
  1485. */
  1486. public function fetch_contact($contactid = null)
  1487. {
  1488. // phpcs:enable
  1489. if (empty($contactid)) {
  1490. $contactid = $this->contact_id;
  1491. }
  1492. if (empty($contactid)) {
  1493. return 0;
  1494. }
  1495. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1496. $contact = new Contact($this->db);
  1497. $result = $contact->fetch($contactid);
  1498. $this->contact = $contact;
  1499. return $result;
  1500. }
  1501. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1502. /**
  1503. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1504. *
  1505. * @param int $force_thirdparty_id Force thirdparty id
  1506. * @return int <0 if KO, >0 if OK
  1507. */
  1508. public function fetch_thirdparty($force_thirdparty_id = 0)
  1509. {
  1510. // phpcs:enable
  1511. global $conf;
  1512. if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
  1513. return 0;
  1514. }
  1515. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1516. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
  1517. if ($force_thirdparty_id) {
  1518. $idtofetch = $force_thirdparty_id;
  1519. }
  1520. if ($idtofetch) {
  1521. $thirdparty = new Societe($this->db);
  1522. $result = $thirdparty->fetch($idtofetch);
  1523. if ($result<0) {
  1524. $this->errors=array_merge($this->errors, $thirdparty->errors);
  1525. }
  1526. $this->thirdparty = $thirdparty;
  1527. // Use first price level if level not defined for third party
  1528. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1529. $this->thirdparty->price_level = 1;
  1530. }
  1531. return $result;
  1532. } else {
  1533. return -1;
  1534. }
  1535. }
  1536. /**
  1537. * Looks for an object with ref matching the wildcard provided
  1538. * It does only work when $this->table_ref_field is set
  1539. *
  1540. * @param string $ref Wildcard
  1541. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1542. */
  1543. public function fetchOneLike($ref)
  1544. {
  1545. if (!$this->table_ref_field) {
  1546. return 0;
  1547. }
  1548. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element." WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."' LIMIT 1";
  1549. $query = $this->db->query($sql);
  1550. if (!$this->db->num_rows($query)) {
  1551. return 0;
  1552. }
  1553. $result = $this->db->fetch_object($query);
  1554. return $this->fetch($result->rowid);
  1555. }
  1556. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1557. /**
  1558. * Load data for barcode into properties ->barcode_type*
  1559. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1560. * if it is not defined, ->element must be defined to know default barcode type.
  1561. *
  1562. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1563. */
  1564. public function fetch_barcode()
  1565. {
  1566. // phpcs:enable
  1567. global $conf;
  1568. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1569. $idtype = $this->barcode_type;
  1570. 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
  1571. if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
  1572. $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1573. } elseif ($this->element == 'societe') {
  1574. $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1575. } else {
  1576. dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1577. }
  1578. }
  1579. if ($idtype > 0) {
  1580. 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
  1581. $sql = "SELECT rowid, code, libelle as label, coder";
  1582. $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
  1583. $sql .= " WHERE rowid = ".((int) $idtype);
  1584. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1585. $resql = $this->db->query($sql);
  1586. if ($resql) {
  1587. $obj = $this->db->fetch_object($resql);
  1588. $this->barcode_type = $obj->rowid;
  1589. $this->barcode_type_code = $obj->code;
  1590. $this->barcode_type_label = $obj->label;
  1591. $this->barcode_type_coder = $obj->coder;
  1592. return 1;
  1593. } else {
  1594. dol_print_error($this->db);
  1595. return -1;
  1596. }
  1597. }
  1598. }
  1599. return 0;
  1600. }
  1601. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1602. /**
  1603. * Load the project with id $this->fk_project into this->project
  1604. *
  1605. * @return int <0 if KO, >=0 if OK
  1606. */
  1607. public function fetch_project()
  1608. {
  1609. // phpcs:enable
  1610. return $this->fetch_projet();
  1611. }
  1612. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1613. /**
  1614. * Load the project with id $this->fk_project into this->project
  1615. *
  1616. * @return int <0 if KO, >=0 if OK
  1617. */
  1618. public function fetch_projet()
  1619. {
  1620. // phpcs:enable
  1621. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1622. if (empty($this->fk_project) && !empty($this->fk_projet)) {
  1623. $this->fk_project = $this->fk_projet; // For backward compatibility
  1624. }
  1625. if (empty($this->fk_project)) {
  1626. return 0;
  1627. }
  1628. $project = new Project($this->db);
  1629. $result = $project->fetch($this->fk_project);
  1630. $this->projet = $project; // deprecated
  1631. $this->project = $project;
  1632. return $result;
  1633. }
  1634. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1635. /**
  1636. * Load the product with id $this->fk_product into this->product
  1637. *
  1638. * @return int <0 if KO, >=0 if OK
  1639. */
  1640. public function fetch_product()
  1641. {
  1642. // phpcs:enable
  1643. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1644. if (empty($this->fk_product)) {
  1645. return 0;
  1646. }
  1647. $product = new Product($this->db);
  1648. $result = $product->fetch($this->fk_product);
  1649. $this->product = $product;
  1650. return $result;
  1651. }
  1652. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1653. /**
  1654. * Load the user with id $userid into this->user
  1655. *
  1656. * @param int $userid Id du contact
  1657. * @return int <0 if KO, >0 if OK
  1658. */
  1659. public function fetch_user($userid)
  1660. {
  1661. // phpcs:enable
  1662. $user = new User($this->db);
  1663. $result = $user->fetch($userid);
  1664. $this->user = $user;
  1665. return $result;
  1666. }
  1667. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1668. /**
  1669. * Read linked origin object
  1670. *
  1671. * @return void
  1672. */
  1673. public function fetch_origin()
  1674. {
  1675. // phpcs:enable
  1676. if ($this->origin == 'shipping') {
  1677. $this->origin = 'expedition';
  1678. }
  1679. if ($this->origin == 'delivery') {
  1680. $this->origin = 'livraison';
  1681. }
  1682. if ($this->origin == 'order_supplier') {
  1683. $this->origin = 'commandeFournisseur';
  1684. }
  1685. $origin = $this->origin;
  1686. $classname = ucfirst($origin);
  1687. $this->$origin = new $classname($this->db);
  1688. $this->$origin->fetch($this->origin_id);
  1689. }
  1690. /**
  1691. * Load object from specific field
  1692. *
  1693. * @param string $table Table element or element line
  1694. * @param string $field Field selected
  1695. * @param string $key Import key
  1696. * @param string $element Element name
  1697. * @return int <0 if KO, >0 if OK
  1698. */
  1699. public function fetchObjectFrom($table, $field, $key, $element = null)
  1700. {
  1701. global $conf;
  1702. $result = false;
  1703. $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
  1704. $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
  1705. if (!empty($element)) {
  1706. $sql .= " AND entity IN (".getEntity($element).")";
  1707. } else {
  1708. $sql .= " AND entity = ".((int) $conf->entity);
  1709. }
  1710. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1711. $resql = $this->db->query($sql);
  1712. if ($resql) {
  1713. $row = $this->db->fetch_row($resql);
  1714. // Test for avoid error -1
  1715. if ($row[0] > 0) {
  1716. $result = $this->fetch($row[0]);
  1717. }
  1718. }
  1719. return $result;
  1720. }
  1721. /**
  1722. * Getter generic. Load value from a specific field
  1723. *
  1724. * @param string $table Table of element or element line
  1725. * @param int $id Element id
  1726. * @param string $field Field selected
  1727. * @return int <0 if KO, >0 if OK
  1728. */
  1729. public function getValueFrom($table, $id, $field)
  1730. {
  1731. $result = false;
  1732. if (!empty($id) && !empty($field) && !empty($table)) {
  1733. $sql = "SELECT ".$field." FROM ".$this->db->prefix().$table;
  1734. $sql .= " WHERE rowid = ".((int) $id);
  1735. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1736. $resql = $this->db->query($sql);
  1737. if ($resql) {
  1738. $row = $this->db->fetch_row($resql);
  1739. $result = $row[0];
  1740. }
  1741. }
  1742. return $result;
  1743. }
  1744. /**
  1745. * Setter generic. Update a specific field into database.
  1746. * Warning: Trigger is run only if param trigkey is provided.
  1747. *
  1748. * @param string $field Field to update
  1749. * @param mixed $value New value
  1750. * @param string $table To force other table element or element line (should not be used)
  1751. * @param int $id To force other object id (should not be used)
  1752. * @param string $format Data format ('text', 'date'). 'text' is used if not defined
  1753. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1754. * @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'
  1755. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1756. * @param string $fk_user_field Name of field to save user id making change
  1757. * @return int <0 if KO, >0 if OK
  1758. * @see updateExtraField()
  1759. */
  1760. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1761. {
  1762. global $user, $langs, $conf;
  1763. if (empty($table)) {
  1764. $table = $this->table_element;
  1765. }
  1766. if (empty($id)) {
  1767. $id = $this->id;
  1768. }
  1769. if (empty($format)) {
  1770. $format = 'text';
  1771. }
  1772. if (empty($id_field)) {
  1773. $id_field = 'rowid';
  1774. }
  1775. $error = 0;
  1776. $this->db->begin();
  1777. // Special case
  1778. if ($table == 'product' && $field == 'note_private') {
  1779. $field = 'note';
  1780. }
  1781. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  1782. $fk_user_field = 'fk_user_mod';
  1783. }
  1784. $sql = "UPDATE ".$this->db->prefix().$table." SET ";
  1785. if ($format == 'text') {
  1786. $sql .= $field." = '".$this->db->escape($value)."'";
  1787. } elseif ($format == 'int') {
  1788. $sql .= $field." = ".((int) $value);
  1789. } elseif ($format == 'date') {
  1790. $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1791. }
  1792. if ($fk_user_field) {
  1793. if (!empty($fuser) && is_object($fuser)) {
  1794. $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
  1795. } elseif (empty($fuser) || $fuser != 'none') {
  1796. $sql .= ", ".$fk_user_field." = ".((int) $user->id);
  1797. }
  1798. }
  1799. $sql .= " WHERE ".$id_field." = ".((int) $id);
  1800. dol_syslog(__METHOD__."", LOG_DEBUG);
  1801. $resql = $this->db->query($sql);
  1802. if ($resql) {
  1803. if ($trigkey) {
  1804. // call trigger with updated object values
  1805. if (empty($this->fields) && method_exists($this, 'fetch')) {
  1806. $result = $this->fetch($id);
  1807. } else {
  1808. $result = $this->fetchCommon($id);
  1809. }
  1810. if ($result >= 0) {
  1811. $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1812. }
  1813. if ($result < 0) {
  1814. $error++;
  1815. }
  1816. }
  1817. if (!$error) {
  1818. if (property_exists($this, $field)) {
  1819. $this->$field = $value;
  1820. }
  1821. $this->db->commit();
  1822. return 1;
  1823. } else {
  1824. $this->db->rollback();
  1825. return -2;
  1826. }
  1827. } else {
  1828. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1829. $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
  1830. } else {
  1831. $this->error = $this->db->lasterror();
  1832. }
  1833. $this->db->rollback();
  1834. return -1;
  1835. }
  1836. }
  1837. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1838. /**
  1839. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1840. *
  1841. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')". Do not allow user input data here.
  1842. * @param string $fieldid Name of field to use for the select MAX and MIN
  1843. * @param int $nodbprefix Do not include DB prefix to forge table name
  1844. * @return int <0 if KO, >0 if OK
  1845. */
  1846. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1847. {
  1848. // phpcs:enable
  1849. global $conf, $user;
  1850. if (!$this->table_element) {
  1851. dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1852. return -1;
  1853. }
  1854. if ($fieldid == 'none') {
  1855. return 1;
  1856. }
  1857. // For backward compatibility
  1858. if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
  1859. $fieldid = 'titre';
  1860. }
  1861. // Security on socid
  1862. $socid = 0;
  1863. if ($user->socid > 0) {
  1864. $socid = $user->socid;
  1865. }
  1866. // this->ismultientitymanaged contains
  1867. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1868. $aliastablesociete = 's';
  1869. if ($this->element == 'societe') {
  1870. $aliastablesociete = 'te'; // te as table_element
  1871. }
  1872. $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
  1873. $sql = "SELECT MAX(te.".$fieldid.")";
  1874. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1875. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1876. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1877. }
  1878. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1879. $tmparray = explode('@', $this->ismultientitymanaged);
  1880. $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
  1881. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1882. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1883. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1884. $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
  1885. }
  1886. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1887. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1888. }
  1889. $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)
  1890. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1891. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1892. }
  1893. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1894. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1895. }
  1896. if (!empty($filter)) {
  1897. if (!preg_match('/^\s*AND/i', $filter)) {
  1898. $sql .= " AND "; // For backward compatibility
  1899. }
  1900. $sql .= $filter;
  1901. }
  1902. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1903. $tmparray = explode('@', $this->ismultientitymanaged);
  1904. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1905. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1906. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1907. }
  1908. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1909. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1910. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1911. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1912. } else {
  1913. $sql .= " AND ug.fk_user = te.rowid";
  1914. $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
  1915. }
  1916. } else {
  1917. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1918. }
  1919. }
  1920. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1921. $tmparray = explode('@', $this->ismultientitymanaged);
  1922. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1923. }
  1924. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1925. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1926. }
  1927. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1928. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1929. }
  1930. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1931. $sql .= ' AND te.rowid = '.((int) $socid);
  1932. }
  1933. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1934. $result = $this->db->query($sql);
  1935. if (!$result) {
  1936. $this->error = $this->db->lasterror();
  1937. return -1;
  1938. }
  1939. $row = $this->db->fetch_row($result);
  1940. $this->ref_previous = $row[0];
  1941. $sql = "SELECT MIN(te.".$fieldid.")";
  1942. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1943. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1944. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1945. }
  1946. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1947. $tmparray = explode('@', $this->ismultientitymanaged);
  1948. $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
  1949. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1950. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1951. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1952. $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
  1953. }
  1954. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1955. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1956. }
  1957. $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)
  1958. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1959. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1960. }
  1961. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1962. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1963. }
  1964. if (!empty($filter)) {
  1965. if (!preg_match('/^\s*AND/i', $filter)) {
  1966. $sql .= " AND "; // For backward compatibility
  1967. }
  1968. $sql .= $filter;
  1969. }
  1970. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1971. $tmparray = explode('@', $this->ismultientitymanaged);
  1972. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1973. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1974. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1975. }
  1976. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1977. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1978. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1979. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1980. } else {
  1981. $sql .= " AND ug.fk_user = te.rowid";
  1982. $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
  1983. }
  1984. } else {
  1985. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1986. }
  1987. }
  1988. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1989. $tmparray = explode('@', $this->ismultientitymanaged);
  1990. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1991. }
  1992. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1993. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1994. }
  1995. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1996. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1997. }
  1998. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1999. $sql .= ' AND te.rowid = '.((int) $socid);
  2000. }
  2001. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  2002. // 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
  2003. $result = $this->db->query($sql);
  2004. if (!$result) {
  2005. $this->error = $this->db->lasterror();
  2006. return -2;
  2007. }
  2008. $row = $this->db->fetch_row($result);
  2009. $this->ref_next = $row[0];
  2010. return 1;
  2011. }
  2012. /**
  2013. * Return list of id of contacts of object
  2014. *
  2015. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  2016. * @return array Array of id of contacts (if source=external or internal)
  2017. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  2018. */
  2019. public function getListContactId($source = 'external')
  2020. {
  2021. $contactAlreadySelected = array();
  2022. $tab = $this->liste_contact(-1, $source);
  2023. $num = count($tab);
  2024. $i = 0;
  2025. while ($i < $num) {
  2026. if ($source == 'thirdparty') {
  2027. $contactAlreadySelected[$i] = $tab[$i]['socid'];
  2028. } else {
  2029. $contactAlreadySelected[$i] = $tab[$i]['id'];
  2030. }
  2031. $i++;
  2032. }
  2033. return $contactAlreadySelected;
  2034. }
  2035. /**
  2036. * Link element with a project
  2037. *
  2038. * @param int $projectid Project id to link element to
  2039. * @param int $notrigger Disable the trigger
  2040. * @return int <0 if KO, >0 if OK
  2041. */
  2042. public function setProject($projectid, $notrigger = 0)
  2043. {
  2044. global $user;
  2045. $error = 0;
  2046. if (!$this->table_element) {
  2047. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  2048. return -1;
  2049. }
  2050. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2051. if (!empty($this->fields['fk_project'])) { // Common case
  2052. if ($projectid) {
  2053. $sql .= " SET fk_project = ".((int) $projectid);
  2054. } else {
  2055. $sql .= " SET fk_project = NULL";
  2056. }
  2057. $sql .= ' WHERE rowid = '.((int) $this->id);
  2058. } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
  2059. if ($projectid) {
  2060. $sql .= " SET fk_project = ".((int) $projectid);
  2061. } else {
  2062. $sql .= " SET fk_project = NULL";
  2063. }
  2064. $sql .= ' WHERE id = '.((int) $this->id);
  2065. } else // Special case for old architecture objects
  2066. {
  2067. if ($projectid) {
  2068. $sql .= ' SET fk_projet = '.((int) $projectid);
  2069. } else {
  2070. $sql .= ' SET fk_projet = NULL';
  2071. }
  2072. $sql .= " WHERE rowid = ".((int) $this->id);
  2073. }
  2074. $this->db->begin();
  2075. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  2076. if ($this->db->query($sql)) {
  2077. $this->fk_project = ((int) $projectid);
  2078. } else {
  2079. dol_print_error($this->db);
  2080. $error++;
  2081. }
  2082. // Triggers
  2083. if (!$error && !$notrigger) {
  2084. // Call triggers
  2085. $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
  2086. if ($result < 0) {
  2087. $error++;
  2088. } //Do also here what you must do to rollback action if trigger fail
  2089. // End call triggers
  2090. }
  2091. // Commit or rollback
  2092. if ($error) {
  2093. $this->db->rollback();
  2094. return -1;
  2095. } else {
  2096. $this->db->commit();
  2097. return 1;
  2098. }
  2099. }
  2100. /**
  2101. * Change the payments methods
  2102. *
  2103. * @param int $id Id of new payment method
  2104. * @return int >0 if OK, <0 if KO
  2105. */
  2106. public function setPaymentMethods($id)
  2107. {
  2108. global $user;
  2109. $error = 0; $notrigger = 0;
  2110. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  2111. if ($this->statut >= 0 || $this->element == 'societe') {
  2112. // TODO uniformize field name
  2113. $fieldname = 'fk_mode_reglement';
  2114. if ($this->element == 'societe') {
  2115. $fieldname = 'mode_reglement';
  2116. }
  2117. if (get_class($this) == 'Fournisseur') {
  2118. $fieldname = 'mode_reglement_supplier';
  2119. }
  2120. if (get_class($this) == 'Tva') {
  2121. $fieldname = 'fk_typepayment';
  2122. }
  2123. if (get_class($this) == 'Salary') {
  2124. $fieldname = 'fk_typepayment';
  2125. }
  2126. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2127. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2128. $sql .= ' WHERE rowid='.((int) $this->id);
  2129. if ($this->db->query($sql)) {
  2130. $this->mode_reglement_id = $id;
  2131. // for supplier
  2132. if (get_class($this) == 'Fournisseur') {
  2133. $this->mode_reglement_supplier_id = $id;
  2134. }
  2135. // Triggers
  2136. if (!$error && !$notrigger) {
  2137. // Call triggers
  2138. if (get_class($this) == 'Commande') {
  2139. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2140. } else {
  2141. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  2142. }
  2143. if ($result < 0) {
  2144. $error++;
  2145. }
  2146. // End call triggers
  2147. }
  2148. return 1;
  2149. } else {
  2150. dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
  2151. $this->error = $this->db->error();
  2152. return -1;
  2153. }
  2154. } else {
  2155. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  2156. $this->error = 'Status of the object is incompatible '.$this->statut;
  2157. return -2;
  2158. }
  2159. }
  2160. /**
  2161. * Change the multicurrency code
  2162. *
  2163. * @param string $code multicurrency code
  2164. * @return int >0 if OK, <0 if KO
  2165. */
  2166. public function setMulticurrencyCode($code)
  2167. {
  2168. dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
  2169. if ($this->statut >= 0 || $this->element == 'societe') {
  2170. $fieldname = 'multicurrency_code';
  2171. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2172. $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
  2173. $sql .= ' WHERE rowid='.((int) $this->id);
  2174. if ($this->db->query($sql)) {
  2175. $this->multicurrency_code = $code;
  2176. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  2177. if ($rate) {
  2178. $this->setMulticurrencyRate($rate, 2);
  2179. }
  2180. return 1;
  2181. } else {
  2182. dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
  2183. $this->error = $this->db->error();
  2184. return -1;
  2185. }
  2186. } else {
  2187. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  2188. $this->error = 'Status of the object is incompatible '.$this->statut;
  2189. return -2;
  2190. }
  2191. }
  2192. /**
  2193. * Change the multicurrency rate
  2194. *
  2195. * @param double $rate multicurrency rate
  2196. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  2197. * @return int >0 if OK, <0 if KO
  2198. */
  2199. public function setMulticurrencyRate($rate, $mode = 1)
  2200. {
  2201. dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
  2202. if ($this->statut >= 0 || $this->element == 'societe') {
  2203. $fieldname = 'multicurrency_tx';
  2204. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2205. $sql .= " SET ".$fieldname." = ".((float) $rate);
  2206. $sql .= ' WHERE rowid='.((int) $this->id);
  2207. if ($this->db->query($sql)) {
  2208. $this->multicurrency_tx = $rate;
  2209. // Update line price
  2210. if (!empty($this->lines)) {
  2211. foreach ($this->lines as &$line) {
  2212. // Amounts in company currency will be recalculated
  2213. if ($mode == 1) {
  2214. $line->subprice = 0;
  2215. }
  2216. // Amounts in foreign currency will be recalculated
  2217. if ($mode == 2) {
  2218. $line->multicurrency_subprice = 0;
  2219. }
  2220. switch ($this->element) {
  2221. case 'propal':
  2222. $this->updateline(
  2223. $line->id,
  2224. $line->subprice,
  2225. $line->qty,
  2226. $line->remise_percent,
  2227. $line->tva_tx,
  2228. $line->localtax1_tx,
  2229. $line->localtax2_tx,
  2230. ($line->description ? $line->description : $line->desc),
  2231. 'HT',
  2232. $line->info_bits,
  2233. $line->special_code,
  2234. $line->fk_parent_line,
  2235. $line->skip_update_total,
  2236. $line->fk_fournprice,
  2237. $line->pa_ht,
  2238. $line->label,
  2239. $line->product_type,
  2240. $line->date_start,
  2241. $line->date_end,
  2242. $line->array_options,
  2243. $line->fk_unit,
  2244. $line->multicurrency_subprice
  2245. );
  2246. break;
  2247. case 'commande':
  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->date_start,
  2260. $line->date_end,
  2261. $line->product_type,
  2262. $line->fk_parent_line,
  2263. $line->skip_update_total,
  2264. $line->fk_fournprice,
  2265. $line->pa_ht,
  2266. $line->label,
  2267. $line->special_code,
  2268. $line->array_options,
  2269. $line->fk_unit,
  2270. $line->multicurrency_subprice
  2271. );
  2272. break;
  2273. case 'facture':
  2274. $this->updateline(
  2275. $line->id,
  2276. ($line->description ? $line->description : $line->desc),
  2277. $line->subprice,
  2278. $line->qty,
  2279. $line->remise_percent,
  2280. $line->date_start,
  2281. $line->date_end,
  2282. $line->tva_tx,
  2283. $line->localtax1_tx,
  2284. $line->localtax2_tx,
  2285. 'HT',
  2286. $line->info_bits,
  2287. $line->product_type,
  2288. $line->fk_parent_line,
  2289. $line->skip_update_total,
  2290. $line->fk_fournprice,
  2291. $line->pa_ht,
  2292. $line->label,
  2293. $line->special_code,
  2294. $line->array_options,
  2295. $line->situation_percent,
  2296. $line->fk_unit,
  2297. $line->multicurrency_subprice
  2298. );
  2299. break;
  2300. case 'supplier_proposal':
  2301. $this->updateline(
  2302. $line->id,
  2303. $line->subprice,
  2304. $line->qty,
  2305. $line->remise_percent,
  2306. $line->tva_tx,
  2307. $line->localtax1_tx,
  2308. $line->localtax2_tx,
  2309. ($line->description ? $line->description : $line->desc),
  2310. 'HT',
  2311. $line->info_bits,
  2312. $line->special_code,
  2313. $line->fk_parent_line,
  2314. $line->skip_update_total,
  2315. $line->fk_fournprice,
  2316. $line->pa_ht,
  2317. $line->label,
  2318. $line->product_type,
  2319. $line->array_options,
  2320. $line->ref_fourn,
  2321. $line->multicurrency_subprice
  2322. );
  2323. break;
  2324. case 'order_supplier':
  2325. $this->updateline(
  2326. $line->id,
  2327. ($line->description ? $line->description : $line->desc),
  2328. $line->subprice,
  2329. $line->qty,
  2330. $line->remise_percent,
  2331. $line->tva_tx,
  2332. $line->localtax1_tx,
  2333. $line->localtax2_tx,
  2334. 'HT',
  2335. $line->info_bits,
  2336. $line->product_type,
  2337. false,
  2338. $line->date_start,
  2339. $line->date_end,
  2340. $line->array_options,
  2341. $line->fk_unit,
  2342. $line->multicurrency_subprice,
  2343. $line->ref_supplier
  2344. );
  2345. break;
  2346. case 'invoice_supplier':
  2347. $this->updateline(
  2348. $line->id,
  2349. ($line->description ? $line->description : $line->desc),
  2350. $line->subprice,
  2351. $line->tva_tx,
  2352. $line->localtax1_tx,
  2353. $line->localtax2_tx,
  2354. $line->qty,
  2355. 0,
  2356. 'HT',
  2357. $line->info_bits,
  2358. $line->product_type,
  2359. $line->remise_percent,
  2360. false,
  2361. $line->date_start,
  2362. $line->date_end,
  2363. $line->array_options,
  2364. $line->fk_unit,
  2365. $line->multicurrency_subprice,
  2366. $line->ref_supplier
  2367. );
  2368. break;
  2369. default:
  2370. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  2371. break;
  2372. }
  2373. }
  2374. }
  2375. return 1;
  2376. } else {
  2377. dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
  2378. $this->error = $this->db->error();
  2379. return -1;
  2380. }
  2381. } else {
  2382. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  2383. $this->error = 'Status of the object is incompatible '.$this->statut;
  2384. return -2;
  2385. }
  2386. }
  2387. /**
  2388. * Change the payments terms
  2389. *
  2390. * @param int $id Id of new payment terms
  2391. * @param string $deposit_percent % of deposit if needed by payment terms
  2392. * @return int >0 if OK, <0 if KO
  2393. */
  2394. public function setPaymentTerms($id, $deposit_percent = null)
  2395. {
  2396. dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
  2397. if ($this->statut >= 0 || $this->element == 'societe') {
  2398. // TODO uniformize field name
  2399. $fieldname = 'fk_cond_reglement';
  2400. if ($this->element == 'societe') {
  2401. $fieldname = 'cond_reglement';
  2402. }
  2403. if (get_class($this) == 'Fournisseur') {
  2404. $fieldname = 'cond_reglement_supplier';
  2405. }
  2406. if (empty($deposit_percent) || $deposit_percent < 0) {
  2407. $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id);
  2408. }
  2409. if ($deposit_percent > 100) {
  2410. $deposit_percent = 100;
  2411. }
  2412. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2413. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2414. if (in_array($this->table_element, array('propal', 'commande'))) {
  2415. $sql .= " , deposit_percent = " . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'");
  2416. }
  2417. $sql .= ' WHERE rowid='.((int) $this->id);
  2418. if ($this->db->query($sql)) {
  2419. $this->cond_reglement_id = $id;
  2420. // for supplier
  2421. if (get_class($this) == 'Fournisseur') {
  2422. $this->cond_reglement_supplier_id = $id;
  2423. }
  2424. $this->cond_reglement = $id; // for compatibility
  2425. $this->deposit_percent = $deposit_percent;
  2426. return 1;
  2427. } else {
  2428. dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
  2429. $this->error = $this->db->error();
  2430. return -1;
  2431. }
  2432. } else {
  2433. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  2434. $this->error = 'Status of the object is incompatible '.$this->statut;
  2435. return -2;
  2436. }
  2437. }
  2438. /**
  2439. * Change the transport mode methods
  2440. *
  2441. * @param int $id Id of transport mode
  2442. * @return int >0 if OK, <0 if KO
  2443. */
  2444. public function setTransportMode($id)
  2445. {
  2446. dol_syslog(get_class($this).'::setTransportMode('.$id.')');
  2447. if ($this->statut >= 0 || $this->element == 'societe') {
  2448. $fieldname = 'fk_transport_mode';
  2449. if ($this->element == 'societe') {
  2450. $fieldname = 'transport_mode';
  2451. }
  2452. if (get_class($this) == 'Fournisseur') {
  2453. $fieldname = 'transport_mode_supplier';
  2454. }
  2455. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2456. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2457. $sql .= ' WHERE rowid='.((int) $this->id);
  2458. if ($this->db->query($sql)) {
  2459. $this->transport_mode_id = $id;
  2460. // for supplier
  2461. if (get_class($this) == 'Fournisseur') {
  2462. $this->transport_mode_supplier_id = $id;
  2463. }
  2464. return 1;
  2465. } else {
  2466. dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
  2467. $this->error = $this->db->error();
  2468. return -1;
  2469. }
  2470. } else {
  2471. dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
  2472. $this->error = 'Status of the object is incompatible '.$this->statut;
  2473. return -2;
  2474. }
  2475. }
  2476. /**
  2477. * Change the retained warranty payments terms
  2478. *
  2479. * @param int $id Id of new payment terms
  2480. * @return int >0 if OK, <0 if KO
  2481. */
  2482. public function setRetainedWarrantyPaymentTerms($id)
  2483. {
  2484. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
  2485. if ($this->statut >= 0 || $this->element == 'societe') {
  2486. $fieldname = 'retained_warranty_fk_cond_reglement';
  2487. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2488. $sql .= " SET ".$fieldname." = ".((int) $id);
  2489. $sql .= ' WHERE rowid='.((int) $this->id);
  2490. if ($this->db->query($sql)) {
  2491. $this->retained_warranty_fk_cond_reglement = $id;
  2492. return 1;
  2493. } else {
  2494. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
  2495. $this->error = $this->db->error();
  2496. return -1;
  2497. }
  2498. } else {
  2499. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  2500. $this->error = 'Status of the object is incompatible '.$this->statut;
  2501. return -2;
  2502. }
  2503. }
  2504. /**
  2505. * Define delivery address
  2506. * @deprecated
  2507. *
  2508. * @param int $id Address id
  2509. * @return int <0 si ko, >0 si ok
  2510. */
  2511. public function setDeliveryAddress($id)
  2512. {
  2513. $fieldname = 'fk_delivery_address';
  2514. if ($this->element == 'delivery' || $this->element == 'shipping') {
  2515. $fieldname = 'fk_address';
  2516. }
  2517. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$fieldname." = ".((int) $id);
  2518. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
  2519. if ($this->db->query($sql)) {
  2520. $this->fk_delivery_address = $id;
  2521. return 1;
  2522. } else {
  2523. $this->error = $this->db->error();
  2524. dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
  2525. return -1;
  2526. }
  2527. }
  2528. /**
  2529. * Change the shipping method
  2530. *
  2531. * @param int $shipping_method_id Id of shipping method
  2532. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2533. * @param User $userused Object user
  2534. *
  2535. * @return int 1 if OK, 0 if KO
  2536. */
  2537. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  2538. {
  2539. global $user;
  2540. if (empty($userused)) {
  2541. $userused = $user;
  2542. }
  2543. $error = 0;
  2544. if (!$this->table_element) {
  2545. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2546. return -1;
  2547. }
  2548. $this->db->begin();
  2549. if ($shipping_method_id < 0) {
  2550. $shipping_method_id = 'NULL';
  2551. }
  2552. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  2553. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2554. $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
  2555. $sql .= " WHERE rowid=".((int) $this->id);
  2556. $resql = $this->db->query($sql);
  2557. if (!$resql) {
  2558. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  2559. $this->error = $this->db->lasterror();
  2560. $error++;
  2561. } else {
  2562. if (!$notrigger) {
  2563. // Call trigger
  2564. $this->context = array('shippingmethodupdate'=>1);
  2565. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2566. if ($result < 0) {
  2567. $error++;
  2568. }
  2569. // End call trigger
  2570. }
  2571. }
  2572. if ($error) {
  2573. $this->db->rollback();
  2574. return -1;
  2575. } else {
  2576. $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
  2577. $this->db->commit();
  2578. return 1;
  2579. }
  2580. }
  2581. /**
  2582. * Change the warehouse
  2583. *
  2584. * @param int $warehouse_id Id of warehouse
  2585. * @return int 1 if OK, 0 if KO
  2586. */
  2587. public function setWarehouse($warehouse_id)
  2588. {
  2589. if (!$this->table_element) {
  2590. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2591. return -1;
  2592. }
  2593. if ($warehouse_id < 0) {
  2594. $warehouse_id = 'NULL';
  2595. }
  2596. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  2597. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2598. $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
  2599. $sql .= " WHERE rowid=".((int) $this->id);
  2600. if ($this->db->query($sql)) {
  2601. $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
  2602. return 1;
  2603. } else {
  2604. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  2605. $this->error = $this->db->error();
  2606. return 0;
  2607. }
  2608. }
  2609. /**
  2610. * Set last model used by doc generator
  2611. *
  2612. * @param User $user User object that make change
  2613. * @param string $modelpdf Modele name
  2614. * @return int <0 if KO, >0 if OK
  2615. */
  2616. public function setDocModel($user, $modelpdf)
  2617. {
  2618. if (!$this->table_element) {
  2619. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2620. return -1;
  2621. }
  2622. $newmodelpdf = dol_trunc($modelpdf, 255);
  2623. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2624. $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  2625. $sql .= " WHERE rowid = ".((int) $this->id);
  2626. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  2627. $resql = $this->db->query($sql);
  2628. if ($resql) {
  2629. $this->model_pdf = $modelpdf;
  2630. $this->modelpdf = $modelpdf; // For bakward compatibility
  2631. return 1;
  2632. } else {
  2633. dol_print_error($this->db);
  2634. return 0;
  2635. }
  2636. }
  2637. /**
  2638. * Change the bank account
  2639. *
  2640. * @param int $fk_account Id of bank account
  2641. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2642. * @param User $userused Object user
  2643. * @return int 1 if OK, 0 if KO
  2644. */
  2645. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2646. {
  2647. global $user;
  2648. if (empty($userused)) {
  2649. $userused = $user;
  2650. }
  2651. $error = 0;
  2652. if (!$this->table_element) {
  2653. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2654. return -1;
  2655. }
  2656. $this->db->begin();
  2657. if ($fk_account < 0) {
  2658. $fk_account = 'NULL';
  2659. }
  2660. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  2661. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2662. $sql .= " SET fk_account = ".((int) $fk_account);
  2663. $sql .= " WHERE rowid=".((int) $this->id);
  2664. $resql = $this->db->query($sql);
  2665. if (!$resql) {
  2666. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  2667. $this->error = $this->db->lasterror();
  2668. $error++;
  2669. } else {
  2670. if (!$notrigger) {
  2671. // Call trigger
  2672. $this->context = array('bankaccountupdate'=>1);
  2673. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2674. if ($result < 0) {
  2675. $error++;
  2676. }
  2677. // End call trigger
  2678. }
  2679. }
  2680. if ($error) {
  2681. $this->db->rollback();
  2682. return -1;
  2683. } else {
  2684. $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
  2685. $this->db->commit();
  2686. return 1;
  2687. }
  2688. }
  2689. // TODO: Move line related operations to CommonObjectLine?
  2690. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2691. /**
  2692. * Save a new position (field rang) for details lines.
  2693. * You can choose to set position for lines with already a position or lines without any position defined.
  2694. *
  2695. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2696. * @param string $rowidorder ASC or DESC
  2697. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2698. * @return int <0 if KO, >0 if OK
  2699. */
  2700. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2701. {
  2702. // phpcs:enable
  2703. if (!$this->table_element_line) {
  2704. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2705. return -1;
  2706. }
  2707. if (!$this->fk_element) {
  2708. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2709. return -1;
  2710. }
  2711. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2712. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2713. $fieldposition = 'position';
  2714. }
  2715. // Count number of lines to reorder (according to choice $renum)
  2716. $nl = 0;
  2717. $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
  2718. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2719. if (!$renum) {
  2720. $sql .= " AND " . $fieldposition . " = 0";
  2721. }
  2722. if ($renum) {
  2723. $sql .= " AND " . $fieldposition . " <> 0";
  2724. }
  2725. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  2726. $resql = $this->db->query($sql);
  2727. if ($resql) {
  2728. $row = $this->db->fetch_row($resql);
  2729. $nl = $row[0];
  2730. } else {
  2731. dol_print_error($this->db);
  2732. }
  2733. if ($nl > 0) {
  2734. // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
  2735. $rows = array();
  2736. // We first search all lines that are parent lines (for multilevel details lines)
  2737. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2738. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2739. if ($fk_parent_line) {
  2740. $sql .= ' AND fk_parent_line IS NULL';
  2741. }
  2742. $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder;
  2743. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  2744. $resql = $this->db->query($sql);
  2745. if ($resql) {
  2746. $i = 0;
  2747. $num = $this->db->num_rows($resql);
  2748. while ($i < $num) {
  2749. $row = $this->db->fetch_row($resql);
  2750. $rows[] = $row[0]; // Add parent line into array rows
  2751. $childrens = $this->getChildrenOfLine($row[0]);
  2752. if (!empty($childrens)) {
  2753. foreach ($childrens as $child) {
  2754. array_push($rows, $child);
  2755. }
  2756. }
  2757. $i++;
  2758. }
  2759. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2760. if (!empty($rows)) {
  2761. foreach ($rows as $key => $row) {
  2762. $this->updateRangOfLine($row, ($key + 1));
  2763. }
  2764. }
  2765. } else {
  2766. dol_print_error($this->db);
  2767. }
  2768. }
  2769. return 1;
  2770. }
  2771. /**
  2772. * Get children of line
  2773. *
  2774. * @param int $id Id of parent line
  2775. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2776. * @return array Array with list of children lines id
  2777. */
  2778. public function getChildrenOfLine($id, $includealltree = 0)
  2779. {
  2780. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2781. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2782. $fieldposition = 'position';
  2783. }
  2784. $rows = array();
  2785. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2786. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2787. $sql .= ' AND fk_parent_line = '.((int) $id);
  2788. $sql .= " ORDER BY " . $fieldposition . " ASC";
  2789. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
  2790. $resql = $this->db->query($sql);
  2791. if ($resql) {
  2792. if ($this->db->num_rows($resql) > 0) {
  2793. while ($row = $this->db->fetch_row($resql)) {
  2794. $rows[] = $row[0];
  2795. if (!empty($includealltree)) {
  2796. $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2797. }
  2798. }
  2799. }
  2800. }
  2801. return $rows;
  2802. }
  2803. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2804. /**
  2805. * Update a line to have a lower rank
  2806. *
  2807. * @param int $rowid Id of line
  2808. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2809. * @return void
  2810. */
  2811. public function line_up($rowid, $fk_parent_line = true)
  2812. {
  2813. // phpcs:enable
  2814. $this->line_order(false, 'ASC', $fk_parent_line);
  2815. // Get rang of line
  2816. $rang = $this->getRangOfLine($rowid);
  2817. // Update position of line
  2818. $this->updateLineUp($rowid, $rang);
  2819. }
  2820. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2821. /**
  2822. * Update a line to have a higher rank
  2823. *
  2824. * @param int $rowid Id of line
  2825. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2826. * @return void
  2827. */
  2828. public function line_down($rowid, $fk_parent_line = true)
  2829. {
  2830. // phpcs:enable
  2831. $this->line_order(false, 'ASC', $fk_parent_line);
  2832. // Get rang of line
  2833. $rang = $this->getRangOfLine($rowid);
  2834. // Get max value for rang
  2835. $max = $this->line_max();
  2836. // Update position of line
  2837. $this->updateLineDown($rowid, $rang, $max);
  2838. }
  2839. /**
  2840. * Update position of line (rang)
  2841. *
  2842. * @param int $rowid Id of line
  2843. * @param int $rang Position
  2844. * @return int <0 if KO, >0 if OK
  2845. */
  2846. public function updateRangOfLine($rowid, $rang)
  2847. {
  2848. global $hookmanager;
  2849. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2850. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2851. $fieldposition = 'position';
  2852. }
  2853. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2854. $sql .= ' WHERE rowid = '.((int) $rowid);
  2855. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2856. if (!$this->db->query($sql)) {
  2857. dol_print_error($this->db);
  2858. return -1;
  2859. } else {
  2860. $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
  2861. $action='';
  2862. $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
  2863. return 1;
  2864. }
  2865. }
  2866. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2867. /**
  2868. * Update position of line with ajax (rang)
  2869. *
  2870. * @param array $rows Array of rows
  2871. * @return void
  2872. */
  2873. public function line_ajaxorder($rows)
  2874. {
  2875. // phpcs:enable
  2876. $num = count($rows);
  2877. for ($i = 0; $i < $num; $i++) {
  2878. $this->updateRangOfLine($rows[$i], ($i + 1));
  2879. }
  2880. }
  2881. /**
  2882. * Update position of line up (rang)
  2883. *
  2884. * @param int $rowid Id of line
  2885. * @param int $rang Position
  2886. * @return void
  2887. */
  2888. public function updateLineUp($rowid, $rang)
  2889. {
  2890. if ($rang > 1) {
  2891. $fieldposition = 'rang';
  2892. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2893. $fieldposition = 'position';
  2894. }
  2895. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2896. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2897. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1));
  2898. if ($this->db->query($sql)) {
  2899. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
  2900. $sql .= ' WHERE rowid = '.((int) $rowid);
  2901. if (!$this->db->query($sql)) {
  2902. dol_print_error($this->db);
  2903. }
  2904. } else {
  2905. dol_print_error($this->db);
  2906. }
  2907. }
  2908. }
  2909. /**
  2910. * Update position of line down (rang)
  2911. *
  2912. * @param int $rowid Id of line
  2913. * @param int $rang Position
  2914. * @param int $max Max
  2915. * @return void
  2916. */
  2917. public function updateLineDown($rowid, $rang, $max)
  2918. {
  2919. if ($rang < $max) {
  2920. $fieldposition = 'rang';
  2921. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2922. $fieldposition = 'position';
  2923. }
  2924. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2925. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2926. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1));
  2927. if ($this->db->query($sql)) {
  2928. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
  2929. $sql .= ' WHERE rowid = '.((int) $rowid);
  2930. if (!$this->db->query($sql)) {
  2931. dol_print_error($this->db);
  2932. }
  2933. } else {
  2934. dol_print_error($this->db);
  2935. }
  2936. }
  2937. }
  2938. /**
  2939. * Get position of line (rang)
  2940. *
  2941. * @param int $rowid Id of line
  2942. * @return int Value of rang in table of lines
  2943. */
  2944. public function getRangOfLine($rowid)
  2945. {
  2946. $fieldposition = 'rang';
  2947. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2948. $fieldposition = 'position';
  2949. }
  2950. $sql = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line;
  2951. $sql .= " WHERE rowid = ".((int) $rowid);
  2952. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  2953. $resql = $this->db->query($sql);
  2954. if ($resql) {
  2955. $row = $this->db->fetch_row($resql);
  2956. return $row[0];
  2957. }
  2958. }
  2959. /**
  2960. * Get rowid of the line relative to its position
  2961. *
  2962. * @param int $rang Rang value
  2963. * @return int Rowid of the line
  2964. */
  2965. public function getIdOfLine($rang)
  2966. {
  2967. $fieldposition = 'rang';
  2968. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2969. $fieldposition = 'position';
  2970. }
  2971. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2972. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2973. $sql .= " AND " . $fieldposition . " = ".((int) $rang);
  2974. $resql = $this->db->query($sql);
  2975. if ($resql) {
  2976. $row = $this->db->fetch_row($resql);
  2977. return $row[0];
  2978. }
  2979. }
  2980. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2981. /**
  2982. * Get max value used for position of line (rang)
  2983. *
  2984. * @param int $fk_parent_line Parent line id
  2985. * @return int Max value of rang in table of lines
  2986. */
  2987. public function line_max($fk_parent_line = 0)
  2988. {
  2989. // phpcs:enable
  2990. $positionfield = 'rang';
  2991. if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
  2992. $positionfield = 'position';
  2993. }
  2994. // Search the last rang with fk_parent_line
  2995. if ($fk_parent_line) {
  2996. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  2997. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2998. $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
  2999. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  3000. $resql = $this->db->query($sql);
  3001. if ($resql) {
  3002. $row = $this->db->fetch_row($resql);
  3003. if (!empty($row[0])) {
  3004. return $row[0];
  3005. } else {
  3006. return $this->getRangOfLine($fk_parent_line);
  3007. }
  3008. }
  3009. } else {
  3010. // If not, search the last rang of element
  3011. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  3012. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3013. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  3014. $resql = $this->db->query($sql);
  3015. if ($resql) {
  3016. $row = $this->db->fetch_row($resql);
  3017. return $row[0];
  3018. }
  3019. }
  3020. }
  3021. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3022. /**
  3023. * Update external ref of element
  3024. *
  3025. * @param string $ref_ext Update field ref_ext
  3026. * @return int <0 if KO, >0 if OK
  3027. */
  3028. public function update_ref_ext($ref_ext)
  3029. {
  3030. // phpcs:enable
  3031. if (!$this->table_element) {
  3032. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  3033. return -1;
  3034. }
  3035. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  3036. $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  3037. $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
  3038. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  3039. if ($this->db->query($sql)) {
  3040. $this->ref_ext = $ref_ext;
  3041. return 1;
  3042. } else {
  3043. $this->error = $this->db->error();
  3044. return -1;
  3045. }
  3046. }
  3047. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3048. /**
  3049. * Update note of element
  3050. *
  3051. * @param string $note New value for note
  3052. * @param string $suffix '', '_public' or '_private'
  3053. * @return int <0 if KO, >0 if OK
  3054. */
  3055. public function update_note($note, $suffix = '')
  3056. {
  3057. // phpcs:enable
  3058. global $user;
  3059. if (!$this->table_element) {
  3060. $this->error = 'update_note was called on objet with property table_element not defined';
  3061. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  3062. return -1;
  3063. }
  3064. if (!in_array($suffix, array('', '_public', '_private'))) {
  3065. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  3066. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  3067. return -2;
  3068. }
  3069. $newsuffix = $suffix;
  3070. // Special cas
  3071. if ($this->table_element == 'product' && $newsuffix == '_private') {
  3072. $newsuffix = '';
  3073. }
  3074. if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  3075. $fieldusermod = "fk_user_mod";
  3076. } elseif ($this->table_element == 'ecm_files') {
  3077. $fieldusermod = "fk_user_m";
  3078. } else {
  3079. $fieldusermod = "fk_user_modif";
  3080. }
  3081. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  3082. $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
  3083. $sql .= ", ".$fieldusermod." = ".((int) $user->id);
  3084. $sql .= " WHERE rowid = ".((int) $this->id);
  3085. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  3086. if ($this->db->query($sql)) {
  3087. if ($suffix == '_public') {
  3088. $this->note_public = $note;
  3089. } elseif ($suffix == '_private') {
  3090. $this->note_private = $note;
  3091. } else {
  3092. $this->note = $note; // deprecated
  3093. $this->note_private = $note;
  3094. }
  3095. return 1;
  3096. } else {
  3097. $this->error = $this->db->lasterror();
  3098. return -1;
  3099. }
  3100. }
  3101. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3102. /**
  3103. * Update public note (kept for backward compatibility)
  3104. *
  3105. * @param string $note New value for note
  3106. * @return int <0 if KO, >0 if OK
  3107. * @deprecated
  3108. * @see update_note()
  3109. */
  3110. public function update_note_public($note)
  3111. {
  3112. // phpcs:enable
  3113. return $this->update_note($note, '_public');
  3114. }
  3115. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3116. /**
  3117. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  3118. * Must be called at end of methods addline or updateline.
  3119. *
  3120. * @param int $exclspec >0 = Exclude special product (product_type=9)
  3121. * @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
  3122. * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object.
  3123. * @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 (used to analyze lines to check corrupted data).
  3124. * @return int <0 if KO, >0 if OK
  3125. */
  3126. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  3127. {
  3128. // phpcs:enable
  3129. global $conf, $hookmanager, $action;
  3130. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  3131. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3132. if ($reshook > 0) {
  3133. return 1; // replacement code
  3134. } elseif ($reshook < 0) {
  3135. return -1; // failure
  3136. } // reshook = 0 => execute normal code
  3137. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  3138. $MODULE = "";
  3139. if ($this->element == 'propal') {
  3140. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  3141. } elseif ($this->element == 'commande' || $this->element == 'order') {
  3142. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  3143. } elseif ($this->element == 'facture' || $this->element == 'invoice') {
  3144. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  3145. } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
  3146. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  3147. } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
  3148. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  3149. } elseif ($this->element == 'supplier_proposal') {
  3150. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  3151. }
  3152. if (!empty($MODULE)) {
  3153. if (!empty($conf->global->$MODULE)) {
  3154. $modsactivated = explode(',', $conf->global->$MODULE);
  3155. foreach ($modsactivated as $mod) {
  3156. if ($conf->$mod->enabled) {
  3157. return 1; // update was disabled by specific setup
  3158. }
  3159. }
  3160. }
  3161. }
  3162. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  3163. if ($roundingadjust == '-1') {
  3164. $roundingadjust = 'auto'; // For backward compatibility
  3165. }
  3166. $forcedroundingmode = $roundingadjust;
  3167. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
  3168. $forcedroundingmode = getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND');
  3169. } elseif ($forcedroundingmode == 'auto') {
  3170. $forcedroundingmode = '0';
  3171. }
  3172. $error = 0;
  3173. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  3174. // Define constants to find lines to sum
  3175. $fieldtva = 'total_tva';
  3176. $fieldlocaltax1 = 'total_localtax1';
  3177. $fieldlocaltax2 = 'total_localtax2';
  3178. $fieldup = 'subprice';
  3179. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3180. $fieldtva = 'tva';
  3181. $fieldup = 'pu_ht';
  3182. }
  3183. if ($this->element == 'invoice_supplier_rec') {
  3184. $fieldup = 'pu_ht';
  3185. }
  3186. if ($this->element == 'expensereport') {
  3187. $fieldup = 'value_unit';
  3188. }
  3189. $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,";
  3190. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  3191. if ($this->table_element_line == 'facturedet') {
  3192. $sql .= ', situation_percent';
  3193. }
  3194. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3195. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  3196. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3197. if ($exclspec) {
  3198. $product_field = 'product_type';
  3199. if ($this->table_element_line == 'contratdet') {
  3200. $product_field = ''; // contratdet table has no product_type field
  3201. }
  3202. if ($product_field) {
  3203. $sql .= " AND ".$product_field." <> 9";
  3204. }
  3205. }
  3206. $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
  3207. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3208. $resql = $this->db->query($sql);
  3209. if ($resql) {
  3210. $this->total_ht = 0;
  3211. $this->total_tva = 0;
  3212. $this->total_localtax1 = 0;
  3213. $this->total_localtax2 = 0;
  3214. $this->total_ttc = 0;
  3215. $total_ht_by_vats = array();
  3216. $total_tva_by_vats = array();
  3217. $total_ttc_by_vats = array();
  3218. $this->multicurrency_total_ht = 0;
  3219. $this->multicurrency_total_tva = 0;
  3220. $this->multicurrency_total_ttc = 0;
  3221. $num = $this->db->num_rows($resql);
  3222. $i = 0;
  3223. while ($i < $num) {
  3224. $obj = $this->db->fetch_object($resql);
  3225. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  3226. $parameters = array('fk_element' => $obj->rowid);
  3227. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3228. 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'
  3229. // This part of code is to fix data. We should not call it too often.
  3230. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  3231. $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);
  3232. $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.
  3233. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  3234. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
  3235. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  3236. if ($diff_when_using_price_ht && $diff_on_current_total) {
  3237. $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);
  3238. 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);
  3239. $resqlfix = $this->db->query($sqlfix);
  3240. if (!$resqlfix) {
  3241. dol_print_error($this->db, 'Failed to update line');
  3242. }
  3243. $obj->total_tva = $tmpcal[1];
  3244. $obj->total_ttc = $tmpcal[2];
  3245. }
  3246. }
  3247. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  3248. $this->total_tva += $obj->total_tva;
  3249. $this->total_localtax1 += $obj->total_localtax1;
  3250. $this->total_localtax2 += $obj->total_localtax2;
  3251. $this->total_ttc += $obj->total_ttc;
  3252. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  3253. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  3254. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  3255. if (!isset($total_ht_by_vats[$obj->vatrate])) {
  3256. $total_ht_by_vats[$obj->vatrate] = 0;
  3257. }
  3258. if (!isset($total_tva_by_vats[$obj->vatrate])) {
  3259. $total_tva_by_vats[$obj->vatrate] = 0;
  3260. }
  3261. if (!isset($total_ttc_by_vats[$obj->vatrate])) {
  3262. $total_ttc_by_vats[$obj->vatrate] = 0;
  3263. }
  3264. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  3265. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  3266. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  3267. if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  3268. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  3269. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  3270. //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";
  3271. if ($diff) {
  3272. if (abs($diff) > 0.1) {
  3273. $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.';
  3274. dol_syslog($errmsg, LOG_WARNING);
  3275. dol_print_error('', $errmsg);
  3276. exit;
  3277. }
  3278. $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);
  3279. 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);
  3280. $resqlfix = $this->db->query($sqlfix);
  3281. if (!$resqlfix) {
  3282. dol_print_error($this->db, 'Failed to update line');
  3283. }
  3284. $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1);
  3285. $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1);
  3286. $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1);
  3287. $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1);
  3288. }
  3289. }
  3290. $i++;
  3291. }
  3292. // Add revenue stamp to total
  3293. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  3294. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  3295. // Situations totals
  3296. if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
  3297. $prev_sits = $this->get_prev_sits();
  3298. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  3299. $this->total_ht -= $sit->total_ht;
  3300. $this->total_tva -= $sit->total_tva;
  3301. $this->total_localtax1 -= $sit->total_localtax1;
  3302. $this->total_localtax2 -= $sit->total_localtax2;
  3303. $this->total_ttc -= $sit->total_ttc;
  3304. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  3305. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  3306. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  3307. }
  3308. }
  3309. // Clean total
  3310. $this->total_ht = (float) price2num($this->total_ht);
  3311. $this->total_tva = (float) price2num($this->total_tva);
  3312. $this->total_localtax1 = (float) price2num($this->total_localtax1);
  3313. $this->total_localtax2 = (float) price2num($this->total_localtax2);
  3314. $this->total_ttc = (float) price2num($this->total_ttc);
  3315. $this->db->free($resql);
  3316. // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_*
  3317. $fieldht = 'total_ht';
  3318. $fieldtva = 'tva';
  3319. $fieldlocaltax1 = 'localtax1';
  3320. $fieldlocaltax2 = 'localtax2';
  3321. $fieldttc = 'total_ttc';
  3322. // Specific code for backward compatibility with old field names
  3323. if ($this->element == 'facture' || $this->element == 'facturerec') {
  3324. $fieldtva = 'total_tva';
  3325. }
  3326. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
  3327. $fieldtva = 'total_tva';
  3328. }
  3329. if ($this->element == 'propal') {
  3330. $fieldtva = 'total_tva';
  3331. }
  3332. if ($this->element == 'expensereport') {
  3333. $fieldtva = 'total_tva';
  3334. }
  3335. if ($this->element == 'supplier_proposal') {
  3336. $fieldtva = 'total_tva';
  3337. }
  3338. if ($this->element == 'commande') {
  3339. $fieldtva = 'total_tva';
  3340. }
  3341. if ($this->element == 'order_supplier') {
  3342. $fieldtva = 'total_tva';
  3343. }
  3344. if (empty($nodatabaseupdate)) {
  3345. $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
  3346. $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht, 'MT', 1)).",";
  3347. $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva, 'MT', 1)).",";
  3348. $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1, 'MT', 1)).",";
  3349. $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2, 'MT', 1)).",";
  3350. $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc, 'MT', 1));
  3351. $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
  3352. $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
  3353. $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
  3354. $sql .= " WHERE rowid = ".((int) $this->id);
  3355. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3356. $resql = $this->db->query($sql);
  3357. if (!$resql) {
  3358. $error++;
  3359. $this->error = $this->db->lasterror();
  3360. $this->errors[] = $this->db->lasterror();
  3361. }
  3362. }
  3363. if (!$error) {
  3364. return 1;
  3365. } else {
  3366. return -1;
  3367. }
  3368. } else {
  3369. dol_print_error($this->db, 'Bad request in update_price');
  3370. return -1;
  3371. }
  3372. }
  3373. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3374. /**
  3375. * Add objects linked in llx_element_element.
  3376. *
  3377. * @param string $origin Linked element type
  3378. * @param int $origin_id Linked element id
  3379. * @param User $f_user User that create
  3380. * @param int $notrigger 1=Does not execute triggers, 0=execute triggers
  3381. * @return int <=0 if KO, >0 if OK
  3382. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  3383. */
  3384. public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
  3385. {
  3386. // phpcs:enable
  3387. global $user, $hookmanager, $action;
  3388. $origin = (!empty($origin) ? $origin : $this->origin);
  3389. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  3390. $f_user = isset($f_user) ? $f_user : $user;
  3391. // Special case
  3392. if ($origin == 'order') {
  3393. $origin = 'commande';
  3394. }
  3395. if ($origin == 'invoice') {
  3396. $origin = 'facture';
  3397. }
  3398. if ($origin == 'invoice_template') {
  3399. $origin = 'facturerec';
  3400. }
  3401. if ($origin == 'supplierorder') {
  3402. $origin = 'order_supplier';
  3403. }
  3404. // 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.
  3405. // 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.
  3406. $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
  3407. // Add module part to target type if object has $module property and isn't in core modules.
  3408. $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
  3409. $parameters = array('targettype'=>$targettype);
  3410. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3411. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3412. if ($reshook > 0) {
  3413. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3414. }
  3415. $this->db->begin();
  3416. $error = 0;
  3417. $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
  3418. $sql .= "fk_source";
  3419. $sql .= ", sourcetype";
  3420. $sql .= ", fk_target";
  3421. $sql .= ", targettype";
  3422. $sql .= ") VALUES (";
  3423. $sql .= ((int) $origin_id);
  3424. $sql .= ", '" . $this->db->escape($origin) . "'";
  3425. $sql .= ", " . ((int) $this->id);
  3426. $sql .= ", '" . $this->db->escape($targettype) . "'";
  3427. $sql .= ")";
  3428. dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
  3429. if ($this->db->query($sql)) {
  3430. if (!$notrigger) {
  3431. // Call trigger
  3432. $this->context['link_origin'] = $origin;
  3433. $this->context['link_origin_id'] = $origin_id;
  3434. $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
  3435. if ($result < 0) {
  3436. $error++;
  3437. }
  3438. // End call triggers
  3439. }
  3440. } else {
  3441. $this->error = $this->db->lasterror();
  3442. $error++;
  3443. }
  3444. if (!$error) {
  3445. $this->db->commit();
  3446. return 1;
  3447. } else {
  3448. $this->db->rollback();
  3449. return 0;
  3450. }
  3451. }
  3452. /**
  3453. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  3454. * this->linkedObjectsIds array +
  3455. * this->linkedObjects array if $loadalsoobjects = 1 or $loadalsoobjects = type
  3456. * Possible usage for parameters:
  3457. * - all parameters empty -> we look all link to current object (current object can be source or target)
  3458. * - source id+type -> will get list of targets linked to source
  3459. * - target id+type -> will get list of sources linked to target
  3460. * - source id+type + target type -> will get list of targets of the type linked to source
  3461. * - target id+type + source type -> will get list of sources of the type linked to target
  3462. *
  3463. * @param int $sourceid Object source id (if not defined, id of object)
  3464. * @param string $sourcetype Object source type (if not defined, element name of object)
  3465. * @param int $targetid Object target id (if not defined, id of object)
  3466. * @param string $targettype Object target type (if not defined, element name of object)
  3467. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  3468. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  3469. * @param string $orderby SQL 'ORDER BY' clause
  3470. * @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.
  3471. * @return int <0 if KO, >0 if OK
  3472. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  3473. */
  3474. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  3475. {
  3476. global $conf, $hookmanager, $action;
  3477. // Important for pdf generation time reduction
  3478. // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
  3479. if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
  3480. return 1;
  3481. }
  3482. $this->linkedObjectsIds = array();
  3483. $this->linkedObjects = array();
  3484. $justsource = false;
  3485. $justtarget = false;
  3486. $withtargettype = false;
  3487. $withsourcetype = false;
  3488. $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
  3489. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3490. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3491. if ($reshook > 0) {
  3492. if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
  3493. if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
  3494. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3495. if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
  3496. }
  3497. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
  3498. $justsource = true; // the source (id and type) is a search criteria
  3499. if (!empty($targettype)) {
  3500. $withtargettype = true;
  3501. }
  3502. }
  3503. if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
  3504. $justtarget = true; // the target (id and type) is a search criteria
  3505. if (!empty($sourcetype)) {
  3506. $withsourcetype = true;
  3507. }
  3508. }
  3509. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3510. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3511. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3512. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3513. /*if (empty($sourceid) && empty($targetid))
  3514. {
  3515. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  3516. return -1;
  3517. }*/
  3518. // Links between objects are stored in table element_element
  3519. $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
  3520. $sql .= " FROM ".$this->db->prefix()."element_element";
  3521. $sql .= " WHERE ";
  3522. if ($justsource || $justtarget) {
  3523. if ($justsource) {
  3524. $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3525. if ($withtargettype) {
  3526. $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
  3527. }
  3528. } elseif ($justtarget) {
  3529. $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
  3530. if ($withsourcetype) {
  3531. $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3532. }
  3533. }
  3534. } else {
  3535. $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
  3536. $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
  3537. if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
  3538. $this->linkedObjectsFullLoaded[$this->id] = true;
  3539. }
  3540. }
  3541. $sql .= " ORDER BY ".$orderby;
  3542. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  3543. $resql = $this->db->query($sql);
  3544. if ($resql) {
  3545. $num = $this->db->num_rows($resql);
  3546. $i = 0;
  3547. while ($i < $num) {
  3548. $obj = $this->db->fetch_object($resql);
  3549. if ($justsource || $justtarget) {
  3550. if ($justsource) {
  3551. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3552. } elseif ($justtarget) {
  3553. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3554. }
  3555. } else {
  3556. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
  3557. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3558. }
  3559. if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
  3560. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3561. }
  3562. }
  3563. $i++;
  3564. }
  3565. if (!empty($this->linkedObjectsIds)) {
  3566. $tmparray = $this->linkedObjectsIds;
  3567. foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  3568. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  3569. $module = $element = $subelement = $objecttype;
  3570. $regs = array();
  3571. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  3572. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  3573. $module = $element = $regs[1];
  3574. $subelement = $regs[2];
  3575. }
  3576. $classpath = $element.'/class';
  3577. // To work with non standard classpath or module name
  3578. if ($objecttype == 'facture') {
  3579. $classpath = 'compta/facture/class';
  3580. } elseif ($objecttype == 'facturerec') {
  3581. $classpath = 'compta/facture/class';
  3582. $module = 'facture';
  3583. } elseif ($objecttype == 'propal') {
  3584. $classpath = 'comm/propal/class';
  3585. } elseif ($objecttype == 'supplier_proposal') {
  3586. $classpath = 'supplier_proposal/class';
  3587. } elseif ($objecttype == 'shipping') {
  3588. $classpath = 'expedition/class';
  3589. $subelement = 'expedition';
  3590. $module = 'expedition_bon';
  3591. } elseif ($objecttype == 'delivery') {
  3592. $classpath = 'delivery/class';
  3593. $subelement = 'delivery';
  3594. $module = 'delivery_note';
  3595. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  3596. $classpath = 'fourn/class';
  3597. $module = 'fournisseur';
  3598. } elseif ($objecttype == 'fichinter') {
  3599. $classpath = 'fichinter/class';
  3600. $subelement = 'fichinter';
  3601. $module = 'ficheinter';
  3602. } elseif ($objecttype == 'subscription') {
  3603. $classpath = 'adherents/class';
  3604. $module = 'adherent';
  3605. } elseif ($objecttype == 'contact') {
  3606. $module = 'societe';
  3607. }
  3608. // Set classfile
  3609. $classfile = strtolower($subelement);
  3610. $classname = ucfirst($subelement);
  3611. if ($objecttype == 'order') {
  3612. $classfile = 'commande';
  3613. $classname = 'Commande';
  3614. } elseif ($objecttype == 'invoice_supplier') {
  3615. $classfile = 'fournisseur.facture';
  3616. $classname = 'FactureFournisseur';
  3617. } elseif ($objecttype == 'order_supplier') {
  3618. $classfile = 'fournisseur.commande';
  3619. $classname = 'CommandeFournisseur';
  3620. } elseif ($objecttype == 'supplier_proposal') {
  3621. $classfile = 'supplier_proposal';
  3622. $classname = 'SupplierProposal';
  3623. } elseif ($objecttype == 'facturerec') {
  3624. $classfile = 'facture-rec';
  3625. $classname = 'FactureRec';
  3626. } elseif ($objecttype == 'subscription') {
  3627. $classfile = 'subscription';
  3628. $classname = 'Subscription';
  3629. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  3630. $classpath = 'projet/class';
  3631. $classfile = 'project';
  3632. $classname = 'Project';
  3633. } elseif ($objecttype == 'conferenceorboothattendee') {
  3634. $classpath = 'eventorganization/class';
  3635. $classfile = 'conferenceorboothattendee';
  3636. $classname = 'ConferenceOrBoothAttendee';
  3637. $module = 'eventorganization';
  3638. } elseif ($objecttype == 'conferenceorbooth') {
  3639. $classpath = 'eventorganization/class';
  3640. $classfile = 'conferenceorbooth';
  3641. $classname = 'ConferenceOrBooth';
  3642. $module = 'eventorganization';
  3643. } elseif ($objecttype == 'mo') {
  3644. $classpath = 'mrp/class';
  3645. $classfile = 'mo';
  3646. $classname = 'Mo';
  3647. $module = 'mrp';
  3648. }
  3649. // Here $module, $classfile and $classname are set, we can use them.
  3650. if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
  3651. if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
  3652. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  3653. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  3654. if (class_exists($classname)) {
  3655. foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
  3656. $object = new $classname($this->db);
  3657. $ret = $object->fetch($objectid);
  3658. if ($ret >= 0) {
  3659. $this->linkedObjects[$objecttype][$i] = $object;
  3660. }
  3661. }
  3662. }
  3663. }
  3664. } else {
  3665. unset($this->linkedObjectsIds[$objecttype]);
  3666. }
  3667. }
  3668. }
  3669. return 1;
  3670. } else {
  3671. dol_print_error($this->db);
  3672. return -1;
  3673. }
  3674. }
  3675. /**
  3676. * Update object linked of a current object
  3677. *
  3678. * @param int $sourceid Object source id
  3679. * @param string $sourcetype Object source type
  3680. * @param int $targetid Object target id
  3681. * @param string $targettype Object target type
  3682. * @param User $f_user User that create
  3683. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3684. * @return int >0 if OK, <0 if KO
  3685. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3686. */
  3687. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
  3688. {
  3689. global $user;
  3690. $updatesource = false;
  3691. $updatetarget = false;
  3692. $f_user = isset($f_user) ? $f_user : $user;
  3693. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3694. $updatesource = true;
  3695. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3696. $updatetarget = true;
  3697. }
  3698. $this->db->begin();
  3699. $error = 0;
  3700. $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
  3701. if ($updatesource) {
  3702. $sql .= "fk_source = " . ((int) $sourceid);
  3703. $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3704. $sql .= " WHERE fk_target = " . ((int) $this->id);
  3705. $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
  3706. } elseif ($updatetarget) {
  3707. $sql .= "fk_target = " . ((int) $targetid);
  3708. $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
  3709. $sql .= " WHERE fk_source = " . ((int) $this->id);
  3710. $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3711. }
  3712. dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
  3713. if ($this->db->query($sql)) {
  3714. if (!$notrigger) {
  3715. // Call trigger
  3716. $this->context['link_source_id'] = $sourceid;
  3717. $this->context['link_source_type'] = $sourcetype;
  3718. $this->context['link_target_id'] = $targetid;
  3719. $this->context['link_target_type'] = $targettype;
  3720. $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
  3721. if ($result < 0) {
  3722. $error++;
  3723. }
  3724. // End call triggers
  3725. }
  3726. } else {
  3727. $this->error = $this->db->lasterror();
  3728. $error++;
  3729. }
  3730. if (!$error) {
  3731. $this->db->commit();
  3732. return 1;
  3733. } else {
  3734. $this->db->rollback();
  3735. return -1;
  3736. }
  3737. }
  3738. /**
  3739. * Delete all links between an object $this
  3740. *
  3741. * @param int $sourceid Object source id
  3742. * @param string $sourcetype Object source type
  3743. * @param int $targetid Object target id
  3744. * @param string $targettype Object target type
  3745. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3746. * @param User $f_user User that create
  3747. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3748. * @return int >0 if OK, <0 if KO
  3749. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3750. */
  3751. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
  3752. {
  3753. global $user;
  3754. $deletesource = false;
  3755. $deletetarget = false;
  3756. $f_user = isset($f_user) ? $f_user : $user;
  3757. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3758. $deletesource = true;
  3759. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3760. $deletetarget = true;
  3761. }
  3762. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3763. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3764. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3765. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3766. $this->db->begin();
  3767. $error = 0;
  3768. if (!$notrigger) {
  3769. // Call trigger
  3770. $this->context['link_id'] = $rowid;
  3771. $this->context['link_source_id'] = $sourceid;
  3772. $this->context['link_source_type'] = $sourcetype;
  3773. $this->context['link_target_id'] = $targetid;
  3774. $this->context['link_target_type'] = $targettype;
  3775. $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
  3776. if ($result < 0) {
  3777. $error++;
  3778. }
  3779. // End call triggers
  3780. }
  3781. if (!$error) {
  3782. $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
  3783. $sql .= " WHERE";
  3784. if ($rowid > 0) {
  3785. $sql .= " rowid = " . ((int) $rowid);
  3786. } else {
  3787. if ($deletesource) {
  3788. $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3789. $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
  3790. } elseif ($deletetarget) {
  3791. $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
  3792. $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3793. } else {
  3794. $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
  3795. $sql .= " OR";
  3796. $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
  3797. }
  3798. }
  3799. dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
  3800. if (!$this->db->query($sql)) {
  3801. $this->error = $this->db->lasterror();
  3802. $this->errors[] = $this->error;
  3803. $error++;
  3804. }
  3805. }
  3806. if (!$error) {
  3807. $this->db->commit();
  3808. return 1;
  3809. } else {
  3810. $this->db->rollback();
  3811. return 0;
  3812. }
  3813. }
  3814. /**
  3815. * Function used to get an array with all items linked to an object id in association table
  3816. *
  3817. * @param int $fk_object_where id of object we need to get linked items
  3818. * @param string $field_select name of field we need to get a list
  3819. * @param string $field_where name of field of object we need to get linked items
  3820. * @param string $table_element name of association table
  3821. * @return array Array of record
  3822. */
  3823. public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
  3824. {
  3825. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3826. return -1;
  3827. }
  3828. global $db;
  3829. $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3830. $resql = $db->query($sql);
  3831. $TRes = array();
  3832. if (!empty($resql)) {
  3833. while ($res = $db->fetch_object($resql)) {
  3834. $TRes[] = $res->{$field_select};
  3835. }
  3836. }
  3837. return $TRes;
  3838. }
  3839. /**
  3840. * Function used to remove all items linked to an object id in association table
  3841. *
  3842. * @param int $fk_object_where id of object we need to remove linked items
  3843. * @param string $field_where name of field of object we need to delete linked items
  3844. * @param string $table_element name of association table
  3845. * @return int <0 if KO, 0 if nothing done, >0 if OK and something done
  3846. */
  3847. public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
  3848. {
  3849. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3850. return -1;
  3851. }
  3852. global $db;
  3853. $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3854. $resql = $db->query($sql);
  3855. if (empty($resql)) {
  3856. return 0;
  3857. }
  3858. return 1;
  3859. }
  3860. /**
  3861. * Set status of an object
  3862. *
  3863. * @param int $status Status to set
  3864. * @param int $elementId Id of element to force (use this->id by default if null)
  3865. * @param string $elementType Type of element to force (use this->table_element by default)
  3866. * @param string $trigkey Trigger key to use for trigger. Use '' means automatic but it is not recommended and is deprecated.
  3867. * @param string $fieldstatus Name of status field in this->table_element
  3868. * @return int <0 if KO, >0 if OK
  3869. */
  3870. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
  3871. {
  3872. global $user, $langs, $conf;
  3873. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3874. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3875. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3876. $this->db->begin();
  3877. if ($elementTable == 'facture_rec') {
  3878. $fieldstatus = "suspended";
  3879. }
  3880. if ($elementTable == 'mailing') {
  3881. $fieldstatus = "statut";
  3882. }
  3883. if ($elementTable == 'cronjob') {
  3884. $fieldstatus = "status";
  3885. }
  3886. if ($elementTable == 'user') {
  3887. $fieldstatus = "statut";
  3888. }
  3889. if ($elementTable == 'expensereport') {
  3890. $fieldstatus = "fk_statut";
  3891. }
  3892. if ($elementTable == 'commande_fournisseur_dispatch') {
  3893. $fieldstatus = "status";
  3894. }
  3895. if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
  3896. $fieldstatus = 'status';
  3897. }
  3898. $sql = "UPDATE ".$this->db->prefix().$elementTable;
  3899. $sql .= " SET ".$fieldstatus." = ".((int) $status);
  3900. // If status = 1 = validated, update also fk_user_valid
  3901. // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
  3902. if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
  3903. $sql .= ", fk_user_valid = ".((int) $user->id);
  3904. }
  3905. if ($status == 1 && in_array($elementTable, array('expensereport'))) {
  3906. $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
  3907. }
  3908. if ($status == 1 && in_array($elementTable, array('inventory'))) {
  3909. $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
  3910. }
  3911. $sql .= " WHERE rowid = ".((int) $elementId);
  3912. $sql .= " AND ".$fieldstatus." <> ".((int) $status); // We avoid update if status already correct
  3913. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  3914. $resql = $this->db->query($sql);
  3915. if ($resql) {
  3916. $error = 0;
  3917. $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
  3918. if ($nb_rows_affected > 0) {
  3919. if (empty($trigkey)) {
  3920. // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
  3921. if ($this->element == 'supplier_proposal' && $status == 2) {
  3922. $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3923. }
  3924. if ($this->element == 'supplier_proposal' && $status == 3) {
  3925. $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3926. }
  3927. if ($this->element == 'supplier_proposal' && $status == 4) {
  3928. $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3929. }
  3930. if ($this->element == 'fichinter' && $status == 3) {
  3931. $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3932. }
  3933. if ($this->element == 'fichinter' && $status == 2) {
  3934. $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3935. }
  3936. if ($this->element == 'fichinter' && $status == 1) {
  3937. $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3938. }
  3939. }
  3940. if ($trigkey) {
  3941. // Call trigger
  3942. $result = $this->call_trigger($trigkey, $user);
  3943. if ($result < 0) {
  3944. $error++;
  3945. }
  3946. // End call triggers
  3947. }
  3948. } else {
  3949. // The status was probably already good. We do nothing more, no triggers.
  3950. }
  3951. if (!$error) {
  3952. $this->db->commit();
  3953. if (empty($savElementId)) {
  3954. // If the element we update is $this (so $elementId was provided as null)
  3955. if ($fieldstatus == 'tosell') {
  3956. $this->status = $status;
  3957. } elseif ($fieldstatus == 'tobuy') {
  3958. $this->status_buy = $status;
  3959. } else {
  3960. $this->statut = $status;
  3961. $this->status = $status;
  3962. }
  3963. }
  3964. return 1;
  3965. } else {
  3966. $this->db->rollback();
  3967. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  3968. return -1;
  3969. }
  3970. } else {
  3971. $this->error = $this->db->lasterror();
  3972. $this->db->rollback();
  3973. return -1;
  3974. }
  3975. }
  3976. /**
  3977. * Load type of canvas of an object if it exists
  3978. *
  3979. * @param int $id Record id
  3980. * @param string $ref Record ref
  3981. * @return int <0 if KO, 0 if nothing done, >0 if OK
  3982. */
  3983. public function getCanvas($id = 0, $ref = '')
  3984. {
  3985. global $conf;
  3986. if (empty($id) && empty($ref)) {
  3987. return 0;
  3988. }
  3989. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
  3990. return 0; // To increase speed. Not enabled by default.
  3991. }
  3992. // Clean parameters
  3993. $ref = trim($ref);
  3994. $sql = "SELECT rowid, canvas";
  3995. $sql .= " FROM ".$this->db->prefix().$this->table_element;
  3996. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  3997. if (!empty($id)) {
  3998. $sql .= " AND rowid = ".((int) $id);
  3999. }
  4000. if (!empty($ref)) {
  4001. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  4002. }
  4003. $resql = $this->db->query($sql);
  4004. if ($resql) {
  4005. $obj = $this->db->fetch_object($resql);
  4006. if ($obj) {
  4007. $this->canvas = $obj->canvas;
  4008. return 1;
  4009. } else {
  4010. return 0;
  4011. }
  4012. } else {
  4013. dol_print_error($this->db);
  4014. return -1;
  4015. }
  4016. }
  4017. /**
  4018. * Get special code of a line
  4019. *
  4020. * @param int $lineid Id of line
  4021. * @return int Special code
  4022. */
  4023. public function getSpecialCode($lineid)
  4024. {
  4025. $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
  4026. $sql .= " WHERE rowid = ".((int) $lineid);
  4027. $resql = $this->db->query($sql);
  4028. if ($resql) {
  4029. $row = $this->db->fetch_row($resql);
  4030. return $row[0];
  4031. }
  4032. }
  4033. /**
  4034. * Function to check if an object is used by others.
  4035. * Check is done into this->childtables. There is no check into llx_element_element.
  4036. *
  4037. * @param int $id Force id of object
  4038. * @param int $entity Force entity to check
  4039. * @return int <0 if KO, 0 if not used, >0 if already used
  4040. */
  4041. public function isObjectUsed($id = 0, $entity = 0)
  4042. {
  4043. global $langs;
  4044. if (empty($id)) {
  4045. $id = $this->id;
  4046. }
  4047. // Check parameters
  4048. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
  4049. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  4050. return -1;
  4051. }
  4052. $arraytoscan = $this->childtables;
  4053. // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
  4054. $tmparray = array_keys($this->childtables);
  4055. if (is_numeric($tmparray[0])) {
  4056. $arraytoscan = array_flip($this->childtables);
  4057. }
  4058. // Test if child exists
  4059. $haschild = 0;
  4060. foreach ($arraytoscan as $table => $element) {
  4061. //print $id.'-'.$table.'-'.$elementname.'<br>';
  4062. // Check if element can be deleted
  4063. $sql = "SELECT COUNT(*) as nb";
  4064. $sql.= " FROM ".$this->db->prefix().$table." as c";
  4065. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4066. $sql.= ", ".$this->db->prefix().$element['parent']." as p";
  4067. }
  4068. $sql.= " WHERE c.".$this->fk_element." = ".((int) $id);
  4069. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4070. $sql.= " AND c.".$element['parentkey']." = p.rowid";
  4071. }
  4072. if (!empty($entity)) {
  4073. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4074. $sql.= " AND p.entity = ".((int) $entity);
  4075. } else {
  4076. $sql.= " AND c.entity = ".((int) $entity);
  4077. }
  4078. }
  4079. $resql = $this->db->query($sql);
  4080. if ($resql) {
  4081. $obj = $this->db->fetch_object($resql);
  4082. if ($obj->nb > 0) {
  4083. $langs->load("errors");
  4084. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  4085. $haschild += $obj->nb;
  4086. if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
  4087. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
  4088. } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
  4089. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
  4090. } else { // new usage: $element['name']=Translation key
  4091. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
  4092. }
  4093. break; // We found at least one, we stop here
  4094. }
  4095. } else {
  4096. $this->errors[] = $this->db->lasterror();
  4097. return -1;
  4098. }
  4099. }
  4100. if ($haschild > 0) {
  4101. $this->errors[] = "ErrorRecordHasChildren";
  4102. return $haschild;
  4103. } else {
  4104. return 0;
  4105. }
  4106. }
  4107. /**
  4108. * Function to say how many lines object contains
  4109. *
  4110. * @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
  4111. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  4112. */
  4113. public function hasProductsOrServices($predefined = -1)
  4114. {
  4115. $nb = 0;
  4116. foreach ($this->lines as $key => $val) {
  4117. $qualified = 0;
  4118. if ($predefined == -1) {
  4119. $qualified = 1;
  4120. }
  4121. if ($predefined == 1 && $val->fk_product > 0) {
  4122. $qualified = 1;
  4123. }
  4124. if ($predefined == 0 && $val->fk_product <= 0) {
  4125. $qualified = 1;
  4126. }
  4127. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
  4128. $qualified = 1;
  4129. }
  4130. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
  4131. $qualified = 1;
  4132. }
  4133. if ($qualified) {
  4134. $nb++;
  4135. }
  4136. }
  4137. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  4138. return $nb;
  4139. }
  4140. /**
  4141. * Function that returns the total amount HT of discounts applied for all lines.
  4142. *
  4143. * @return float|string Total amout of discount
  4144. */
  4145. public function getTotalDiscount()
  4146. {
  4147. if (!empty($this->table_element_line) ) {
  4148. $total_discount = 0.00;
  4149. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  4150. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  4151. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  4152. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  4153. $resql = $this->db->query($sql);
  4154. if ($resql) {
  4155. $num = $this->db->num_rows($resql);
  4156. $i = 0;
  4157. while ($i < $num) {
  4158. $obj = $this->db->fetch_object($resql);
  4159. $pu_ht = $obj->pu_ht;
  4160. $qty = $obj->qty;
  4161. $total_ht = $obj->total_ht;
  4162. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  4163. $total_discount += $total_discount_line;
  4164. $i++;
  4165. }
  4166. }
  4167. //print $total_discount; exit;
  4168. return price2num($total_discount);
  4169. }
  4170. return null;
  4171. }
  4172. /**
  4173. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  4174. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  4175. *
  4176. * @return array array('weight'=>...,'volume'=>...)
  4177. */
  4178. public function getTotalWeightVolume()
  4179. {
  4180. $totalWeight = 0;
  4181. $totalVolume = 0;
  4182. // defined for shipment only
  4183. $totalOrdered = '';
  4184. // defined for shipment only
  4185. $totalToShip = '';
  4186. foreach ($this->lines as $line) {
  4187. if (isset($line->qty_asked)) {
  4188. if (empty($totalOrdered)) {
  4189. $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  4190. }
  4191. $totalOrdered += $line->qty_asked; // defined for shipment only
  4192. }
  4193. if (isset($line->qty_shipped)) {
  4194. if (empty($totalToShip)) {
  4195. $totalToShip = 0; // Avoid warning because $totalToShip is ''
  4196. }
  4197. $totalToShip += $line->qty_shipped; // defined for shipment only
  4198. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
  4199. if (empty($totalToShip)) {
  4200. $totalToShip = 0;
  4201. }
  4202. $totalToShip += $line->qty; // defined for reception only
  4203. }
  4204. // Define qty, weight, volume, weight_units, volume_units
  4205. if ($this->element == 'shipping') {
  4206. // for shipments
  4207. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  4208. } else {
  4209. $qty = $line->qty ? $line->qty : 0;
  4210. }
  4211. $weight = !empty($line->weight) ? $line->weight : 0;
  4212. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  4213. $volume = !empty($line->volume) ? $line->volume : 0;
  4214. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  4215. $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
  4216. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  4217. $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
  4218. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  4219. $weightUnit = 0;
  4220. $volumeUnit = 0;
  4221. if (!empty($weight_units)) {
  4222. $weightUnit = $weight_units;
  4223. }
  4224. if (!empty($volume_units)) {
  4225. $volumeUnit = $volume_units;
  4226. }
  4227. if (empty($totalWeight)) {
  4228. $totalWeight = 0; // Avoid warning because $totalWeight is ''
  4229. }
  4230. if (empty($totalVolume)) {
  4231. $totalVolume = 0; // Avoid warning because $totalVolume is ''
  4232. }
  4233. //var_dump($line->volume_units);
  4234. if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4235. $trueWeightUnit = pow(10, $weightUnit);
  4236. $totalWeight += $weight * $qty * $trueWeightUnit;
  4237. } else {
  4238. if ($weight_units == 99) {
  4239. // conversion 1 Pound = 0.45359237 KG
  4240. $trueWeightUnit = 0.45359237;
  4241. $totalWeight += $weight * $qty * $trueWeightUnit;
  4242. } elseif ($weight_units == 98) {
  4243. // conversion 1 Ounce = 0.0283495 KG
  4244. $trueWeightUnit = 0.0283495;
  4245. $totalWeight += $weight * $qty * $trueWeightUnit;
  4246. } else {
  4247. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  4248. }
  4249. }
  4250. if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4251. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  4252. $trueVolumeUnit = pow(10, $volumeUnit);
  4253. //print $line->volume;
  4254. $totalVolume += $volume * $qty * $trueVolumeUnit;
  4255. } else {
  4256. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  4257. }
  4258. }
  4259. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  4260. }
  4261. /**
  4262. * Set extra parameters
  4263. *
  4264. * @return int <0 if KO, >0 if OK
  4265. */
  4266. public function setExtraParameters()
  4267. {
  4268. $this->db->begin();
  4269. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  4270. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  4271. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  4272. $sql .= " WHERE rowid = ".((int) $this->id);
  4273. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  4274. $resql = $this->db->query($sql);
  4275. if (!$resql) {
  4276. $this->error = $this->db->lasterror();
  4277. $this->db->rollback();
  4278. return -1;
  4279. } else {
  4280. $this->db->commit();
  4281. return 1;
  4282. }
  4283. }
  4284. // --------------------
  4285. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  4286. // --------------------
  4287. /* This is to show add lines */
  4288. /**
  4289. * Show add free and predefined products/services form
  4290. *
  4291. * @param int $dateSelector 1=Show also date range input fields
  4292. * @param Societe $seller Object thirdparty who sell
  4293. * @param Societe $buyer Object thirdparty who buy
  4294. * @param string $defaulttpldir Directory where to find the template
  4295. * @return void
  4296. */
  4297. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  4298. {
  4299. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  4300. global $form;
  4301. // Line extrafield
  4302. if (!is_object($extrafields)) {
  4303. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4304. $extrafields = new ExtraFields($this->db);
  4305. }
  4306. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4307. // Output template part (modules that overwrite templates must declare this into descriptor)
  4308. // Use global variables + $dateSelector + $seller and $buyer
  4309. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  4310. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4311. foreach ($dirtpls as $module => $reldir) {
  4312. if (!empty($module)) {
  4313. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  4314. } else {
  4315. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  4316. }
  4317. if (empty($conf->file->strict_mode)) {
  4318. $res = @include $tpl;
  4319. } else {
  4320. $res = include $tpl; // for debug
  4321. }
  4322. if ($res) {
  4323. break;
  4324. }
  4325. }
  4326. }
  4327. /* This is to show array of line of details */
  4328. /**
  4329. * Return HTML table for object lines
  4330. * TODO Move this into an output class file (htmlline.class.php)
  4331. * If lines are into a template, title must also be into a template
  4332. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4333. *
  4334. * @param string $action Action code
  4335. * @param string $seller Object of seller third party
  4336. * @param string $buyer Object of buyer third party
  4337. * @param int $selected Object line selected
  4338. * @param int $dateSelector 1=Show also date range input fields
  4339. * @param string $defaulttpldir Directory where to find the template
  4340. * @return void
  4341. */
  4342. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  4343. {
  4344. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  4345. // TODO We should not use global var for this
  4346. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  4347. // Define usemargins
  4348. $usemargins = 0;
  4349. if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
  4350. $usemargins = 1;
  4351. }
  4352. $num = count($this->lines);
  4353. // Line extrafield
  4354. if (!is_object($extrafields)) {
  4355. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4356. $extrafields = new ExtraFields($this->db);
  4357. }
  4358. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4359. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  4360. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4361. if (empty($reshook)) {
  4362. // Output template part (modules that overwrite templates must declare this into descriptor)
  4363. // Use global variables + $dateSelector + $seller and $buyer
  4364. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  4365. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4366. foreach ($dirtpls as $module => $reldir) {
  4367. if (!empty($module)) {
  4368. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  4369. } else {
  4370. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  4371. }
  4372. if (empty($conf->file->strict_mode)) {
  4373. $res = @include $tpl;
  4374. } else {
  4375. $res = include $tpl; // for debug
  4376. }
  4377. if ($res) {
  4378. break;
  4379. }
  4380. }
  4381. }
  4382. $i = 0;
  4383. print "<!-- begin printObjectLines() --><tbody>\n";
  4384. foreach ($this->lines as $line) {
  4385. //Line extrafield
  4386. $line->fetch_optionals();
  4387. //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  4388. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4389. if (empty($line->fk_parent_line)) {
  4390. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  4391. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4392. } else {
  4393. $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);
  4394. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4395. }
  4396. }
  4397. if (empty($reshook)) {
  4398. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  4399. }
  4400. $i++;
  4401. }
  4402. print "</tbody><!-- end printObjectLines() -->\n";
  4403. }
  4404. /**
  4405. * Return HTML content of a detail line
  4406. * TODO Move this into an output class file (htmlline.class.php)
  4407. *
  4408. * @param string $action GET/POST action
  4409. * @param CommonObjectLine $line Selected object line to output
  4410. * @param string $var Is it a an odd line (true)
  4411. * @param int $num Number of line (0)
  4412. * @param int $i I
  4413. * @param int $dateSelector 1=Show also date range input fields
  4414. * @param string $seller Object of seller third party
  4415. * @param string $buyer Object of buyer third party
  4416. * @param int $selected Object line selected
  4417. * @param Extrafields $extrafields Object of extrafields
  4418. * @param string $defaulttpldir Directory where to find the template (deprecated)
  4419. * @return void
  4420. */
  4421. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  4422. {
  4423. global $conf, $langs, $user, $object, $hookmanager;
  4424. global $form;
  4425. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  4426. $object_rights = $this->getRights();
  4427. $element = $this->element;
  4428. $text = '';
  4429. $description = '';
  4430. // Line in view mode
  4431. if ($action != 'editline' || $selected != $line->id) {
  4432. // Product
  4433. if ($line->fk_product > 0) {
  4434. $product_static = new Product($this->db);
  4435. $product_static->fetch($line->fk_product);
  4436. $product_static->ref = $line->ref; //can change ref in hook
  4437. $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
  4438. $text = $product_static->getNomUrl(1);
  4439. // Define output language and label
  4440. if (!empty($conf->global->MAIN_MULTILANGS)) {
  4441. if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
  4442. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  4443. return;
  4444. }
  4445. $prod = new Product($this->db);
  4446. $prod->fetch($line->fk_product);
  4447. $outputlangs = $langs;
  4448. $newlang = '';
  4449. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  4450. $newlang = GETPOST('lang_id', 'aZ09');
  4451. }
  4452. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
  4453. $newlang = $this->thirdparty->default_lang; // To use language of customer
  4454. }
  4455. if (!empty($newlang)) {
  4456. $outputlangs = new Translate("", $conf);
  4457. $outputlangs->setDefaultLang($newlang);
  4458. }
  4459. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  4460. } else {
  4461. $label = $line->product_label;
  4462. }
  4463. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  4464. $description .= (!empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : (!empty($line->description) ? dol_htmlentitiesbr($line->description) : '')); // Description is what to show on popup. We shown nothing if already into desc.
  4465. }
  4466. $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
  4467. // Output template part (modules that overwrite templates must declare this into descriptor)
  4468. // Use global variables + $dateSelector + $seller and $buyer
  4469. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4470. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4471. foreach ($dirtpls as $module => $reldir) {
  4472. if (!empty($module)) {
  4473. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  4474. } else {
  4475. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  4476. }
  4477. if (empty($conf->file->strict_mode)) {
  4478. $res = @include $tpl;
  4479. } else {
  4480. $res = include $tpl; // for debug
  4481. }
  4482. if ($res) {
  4483. break;
  4484. }
  4485. }
  4486. }
  4487. // Line in update mode
  4488. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
  4489. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  4490. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4491. // Output template part (modules that overwrite templates must declare this into descriptor)
  4492. // Use global variables + $dateSelector + $seller and $buyer
  4493. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4494. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4495. foreach ($dirtpls as $module => $reldir) {
  4496. if (!empty($module)) {
  4497. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  4498. } else {
  4499. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  4500. }
  4501. if (empty($conf->file->strict_mode)) {
  4502. $res = @include $tpl;
  4503. } else {
  4504. $res = include $tpl; // for debug
  4505. }
  4506. if ($res) {
  4507. break;
  4508. }
  4509. }
  4510. }
  4511. }
  4512. /* This is to show array of line of details of source object */
  4513. /**
  4514. * Return HTML table table of source object lines
  4515. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4516. * If lines are into a template, title must also be into a template
  4517. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  4518. *
  4519. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  4520. * @param array $selectedLines Array of lines id for selected lines
  4521. * @return void
  4522. */
  4523. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  4524. {
  4525. global $langs, $hookmanager, $conf, $form, $action;
  4526. print '<tr class="liste_titre">';
  4527. print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
  4528. print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
  4529. print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
  4530. print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
  4531. if (!empty($conf->multicurrency->enabled)) {
  4532. print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
  4533. }
  4534. print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
  4535. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4536. print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
  4537. }
  4538. print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
  4539. print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
  4540. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  4541. print '</tr>';
  4542. $i = 0;
  4543. if (!empty($this->lines)) {
  4544. foreach ($this->lines as $line) {
  4545. $reshook = 0;
  4546. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
  4547. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4548. $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
  4549. if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
  4550. $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4551. }
  4552. if (empty($reshook)) {
  4553. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  4554. }
  4555. $i++;
  4556. }
  4557. }
  4558. }
  4559. /**
  4560. * Return HTML with a line of table array of source object lines
  4561. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4562. * If lines are into a template, title must also be into a template
  4563. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4564. *
  4565. * @param CommonObjectLine $line Line
  4566. * @param string $var Var
  4567. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  4568. * @param string $defaulttpldir Directory where to find the template
  4569. * @param array $selectedLines Array of lines id for selected lines
  4570. * @return void
  4571. */
  4572. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  4573. {
  4574. global $langs, $conf;
  4575. //var_dump($line);
  4576. if (!empty($line->date_start)) {
  4577. $date_start = $line->date_start;
  4578. } else {
  4579. $date_start = $line->date_debut_prevue;
  4580. if ($line->date_debut_reel) {
  4581. $date_start = $line->date_debut_reel;
  4582. }
  4583. }
  4584. if (!empty($line->date_end)) {
  4585. $date_end = $line->date_end;
  4586. } else {
  4587. $date_end = $line->date_fin_prevue;
  4588. if ($line->date_fin_reel) {
  4589. $date_end = $line->date_fin_reel;
  4590. }
  4591. }
  4592. $this->tpl['id'] = $line->id;
  4593. $this->tpl['label'] = '';
  4594. if (!empty($line->fk_parent_line)) {
  4595. $this->tpl['label'] .= img_picto('', 'rightarrow');
  4596. }
  4597. if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
  4598. $discount = new DiscountAbsolute($this->db);
  4599. $discount->fk_soc = $this->socid;
  4600. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  4601. } elseif (!empty($line->fk_product)) {
  4602. $productstatic = new Product($this->db);
  4603. $productstatic->id = $line->fk_product;
  4604. $productstatic->ref = $line->ref;
  4605. $productstatic->type = $line->fk_product_type;
  4606. if (empty($productstatic->ref)) {
  4607. $line->fetch_product();
  4608. $productstatic = $line->product;
  4609. }
  4610. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  4611. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  4612. // Dates
  4613. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4614. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4615. }
  4616. } else {
  4617. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  4618. if (!empty($line->desc)) {
  4619. $this->tpl['label'] .= $line->desc;
  4620. } else {
  4621. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  4622. }
  4623. // Dates
  4624. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4625. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4626. }
  4627. }
  4628. if (!empty($line->desc)) {
  4629. if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
  4630. $discount = new DiscountAbsolute($this->db);
  4631. $discount->fetch($line->fk_remise_except);
  4632. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  4633. } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
  4634. $discount = new DiscountAbsolute($this->db);
  4635. $discount->fetch($line->fk_remise_except);
  4636. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  4637. } elseif ($line->desc == '(EXCESS RECEIVED)') {
  4638. $discount = new DiscountAbsolute($this->db);
  4639. $discount->fetch($line->fk_remise_except);
  4640. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  4641. } elseif ($line->desc == '(EXCESS PAID)') {
  4642. $discount = new DiscountAbsolute($this->db);
  4643. $discount->fetch($line->fk_remise_except);
  4644. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  4645. } else {
  4646. $this->tpl['description'] = dol_trunc($line->desc, 60);
  4647. }
  4648. } else {
  4649. $this->tpl['description'] = '&nbsp;';
  4650. }
  4651. // VAT Rate
  4652. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  4653. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  4654. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
  4655. $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  4656. }
  4657. $this->tpl['price'] = price($line->subprice);
  4658. $this->tpl['total_ht'] = price($line->total_ht);
  4659. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  4660. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  4661. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4662. $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  4663. }
  4664. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  4665. // Is the line strike or not
  4666. $this->tpl['strike'] = 0;
  4667. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
  4668. $this->tpl['strike'] = 1;
  4669. }
  4670. // Output template part (modules that overwrite templates must declare this into descriptor)
  4671. // Use global variables + $dateSelector + $seller and $buyer
  4672. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4673. foreach ($dirtpls as $module => $reldir) {
  4674. if (!empty($module)) {
  4675. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  4676. } else {
  4677. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  4678. }
  4679. if (empty($conf->file->strict_mode)) {
  4680. $res = @include $tpl;
  4681. } else {
  4682. $res = include $tpl; // for debug
  4683. }
  4684. if ($res) {
  4685. break;
  4686. }
  4687. }
  4688. }
  4689. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4690. /**
  4691. * Add resources to the current object : add entry into llx_element_resources
  4692. * Need $this->element & $this->id
  4693. *
  4694. * @param int $resource_id Resource id
  4695. * @param string $resource_type 'resource'
  4696. * @param int $busy Busy or not
  4697. * @param int $mandatory Mandatory or not
  4698. * @return int <=0 if KO, >0 if OK
  4699. */
  4700. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  4701. {
  4702. // phpcs:enable
  4703. $this->db->begin();
  4704. $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
  4705. $sql .= "resource_id";
  4706. $sql .= ", resource_type";
  4707. $sql .= ", element_id";
  4708. $sql .= ", element_type";
  4709. $sql .= ", busy";
  4710. $sql .= ", mandatory";
  4711. $sql .= ") VALUES (";
  4712. $sql .= $resource_id;
  4713. $sql .= ", '".$this->db->escape($resource_type)."'";
  4714. $sql .= ", '".$this->db->escape($this->id)."'";
  4715. $sql .= ", '".$this->db->escape($this->element)."'";
  4716. $sql .= ", '".$this->db->escape($busy)."'";
  4717. $sql .= ", '".$this->db->escape($mandatory)."'";
  4718. $sql .= ")";
  4719. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  4720. if ($this->db->query($sql)) {
  4721. $this->db->commit();
  4722. return 1;
  4723. } else {
  4724. $this->error = $this->db->lasterror();
  4725. $this->db->rollback();
  4726. return 0;
  4727. }
  4728. }
  4729. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4730. /**
  4731. * Delete a link to resource line
  4732. *
  4733. * @param int $rowid Id of resource line to delete
  4734. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  4735. * @param int $notrigger Disable all triggers
  4736. * @return int >0 if OK, <0 if KO
  4737. */
  4738. public function delete_resource($rowid, $element, $notrigger = 0)
  4739. {
  4740. // phpcs:enable
  4741. global $user;
  4742. $this->db->begin();
  4743. $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
  4744. $sql .= " WHERE rowid = ".((int) $rowid);
  4745. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  4746. $resql = $this->db->query($sql);
  4747. if (!$resql) {
  4748. $this->error = $this->db->lasterror();
  4749. $this->db->rollback();
  4750. return -1;
  4751. } else {
  4752. if (!$notrigger) {
  4753. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  4754. if ($result < 0) {
  4755. $this->db->rollback();
  4756. return -1;
  4757. }
  4758. }
  4759. $this->db->commit();
  4760. return 1;
  4761. }
  4762. }
  4763. /**
  4764. * Overwrite magic function to solve problem of cloning object that are kept as references
  4765. *
  4766. * @return void
  4767. */
  4768. public function __clone()
  4769. {
  4770. // Force a copy of this->lines, otherwise it will point to same object.
  4771. if (isset($this->lines) && is_array($this->lines)) {
  4772. $nboflines = count($this->lines);
  4773. for ($i = 0; $i < $nboflines; $i++) {
  4774. $this->lines[$i] = clone $this->lines[$i];
  4775. }
  4776. }
  4777. }
  4778. /**
  4779. * Common function for all objects extending CommonObject for generating documents
  4780. *
  4781. * @param string $modelspath Relative folder where generators are placed
  4782. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4783. * @param Translate $outputlangs Output language to use
  4784. * @param int $hidedetails 1 to hide details. 0 by default
  4785. * @param int $hidedesc 1 to hide product description. 0 by default
  4786. * @param int $hideref 1 to hide product reference. 0 by default
  4787. * @param null|array $moreparams Array to provide more information
  4788. * @return int >0 if OK, <0 if KO
  4789. * @see addFileIntoDatabaseIndex()
  4790. */
  4791. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4792. {
  4793. global $conf, $langs, $user, $hookmanager, $action;
  4794. $srctemplatepath = '';
  4795. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  4796. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4797. if (empty($reshook)) {
  4798. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4799. if (empty($modele)) {
  4800. $this->error = 'BadValueForParameterModele';
  4801. return -1;
  4802. }
  4803. // Increase limit for PDF build
  4804. $err = error_reporting();
  4805. error_reporting(0);
  4806. @set_time_limit(120);
  4807. error_reporting($err);
  4808. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4809. $tmp = explode(':', $modele, 2);
  4810. if (!empty($tmp[1])) {
  4811. $modele = $tmp[0];
  4812. $srctemplatepath = $tmp[1];
  4813. }
  4814. // Search template files
  4815. $file = '';
  4816. $classname = '';
  4817. $filefound = '';
  4818. $dirmodels = array('/');
  4819. if (is_array($conf->modules_parts['models'])) {
  4820. $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4821. }
  4822. foreach ($dirmodels as $reldir) {
  4823. foreach (array('doc', 'pdf') as $prefix) {
  4824. if (in_array(get_class($this), array('Adherent'))) {
  4825. // Member module use prefix_modele.class.php
  4826. $file = $prefix."_".$modele.".class.php";
  4827. } else {
  4828. // Other module use prefix_modele.modules.php
  4829. $file = $prefix."_".$modele.".modules.php";
  4830. }
  4831. // On verifie l'emplacement du modele
  4832. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  4833. if (file_exists($file)) {
  4834. $filefound = $file;
  4835. $classname = $prefix.'_'.$modele;
  4836. break;
  4837. }
  4838. }
  4839. if ($filefound) {
  4840. break;
  4841. }
  4842. }
  4843. // If generator was found
  4844. if ($filefound) {
  4845. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4846. require_once $file;
  4847. $obj = new $classname($this->db);
  4848. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4849. if ($obj->type == 'odt' && empty($srctemplatepath)) {
  4850. $varfortemplatedir = $obj->scandir;
  4851. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
  4852. $dirtoscan = $conf->global->$varfortemplatedir;
  4853. $listoffiles = array();
  4854. // Now we add first model found in directories scanned
  4855. $listofdir = explode(',', $dirtoscan);
  4856. foreach ($listofdir as $key => $tmpdir) {
  4857. $tmpdir = trim($tmpdir);
  4858. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4859. if (!$tmpdir) {
  4860. unset($listofdir[$key]);
  4861. continue;
  4862. }
  4863. if (is_dir($tmpdir)) {
  4864. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4865. if (count($tmpfiles)) {
  4866. $listoffiles = array_merge($listoffiles, $tmpfiles);
  4867. }
  4868. }
  4869. }
  4870. if (count($listoffiles)) {
  4871. foreach ($listoffiles as $record) {
  4872. $srctemplatepath = $record['fullname'];
  4873. break;
  4874. }
  4875. }
  4876. }
  4877. if (empty($srctemplatepath)) {
  4878. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4879. return -1;
  4880. }
  4881. }
  4882. if ($obj->type == 'odt' && !empty($srctemplatepath)) {
  4883. if (!dol_is_file($srctemplatepath)) {
  4884. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  4885. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4886. return -1;
  4887. }
  4888. }
  4889. // We save charset_output to restore it because write_file can change it if needed for
  4890. // output format that does not support UTF8.
  4891. $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
  4892. if (in_array(get_class($this), array('Adherent'))) {
  4893. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
  4894. } else {
  4895. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4896. }
  4897. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4898. if ($resultwritefile > 0) {
  4899. $outputlangs->charset_output = $sav_charset_output;
  4900. // We delete old preview
  4901. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4902. dol_delete_preview($this);
  4903. // Index file in database
  4904. if (!empty($obj->result['fullpath'])) {
  4905. $destfull = $obj->result['fullpath'];
  4906. // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
  4907. $update_main_doc_field = 0;
  4908. if (!empty($obj->update_main_doc_field)) {
  4909. $update_main_doc_field = 1;
  4910. }
  4911. $this->indexFile($destfull, $update_main_doc_field);
  4912. } else {
  4913. 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);
  4914. }
  4915. // Success in building document. We build meta file.
  4916. dol_meta_create($this);
  4917. return 1;
  4918. } else {
  4919. $outputlangs->charset_output = $sav_charset_output;
  4920. $this->error = $obj->error;
  4921. $this->errors = $obj->errors;
  4922. dol_syslog("Error generating document for ".__CLASS__.". Error: ".$obj->error, LOG_ERR);
  4923. return -1;
  4924. }
  4925. } else {
  4926. if (!$filefound) {
  4927. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4928. $this->errors[] = $this->error;
  4929. dol_syslog($this->error, LOG_ERR);
  4930. } else {
  4931. $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
  4932. $this->errors[] = $this->error;
  4933. dol_syslog($this->error, LOG_ERR);
  4934. }
  4935. return -1;
  4936. }
  4937. } else {
  4938. return $reshook;
  4939. }
  4940. }
  4941. /**
  4942. * Index a file into the ECM database
  4943. *
  4944. * @param string $destfull Full path of file to index
  4945. * @param int $update_main_doc_field Update field main_doc fied into the table of object.
  4946. * This param is set when called for a document generation if document generator hase
  4947. * ->update_main_doc_field set and returns ->result['fullpath'].
  4948. * @return int <0 if KO, >0 if OK
  4949. */
  4950. public function indexFile($destfull, $update_main_doc_field)
  4951. {
  4952. global $conf, $user;
  4953. $upload_dir = dirname($destfull);
  4954. $destfile = basename($destfull);
  4955. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  4956. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  4957. $filename = basename($destfile);
  4958. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4959. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4960. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4961. $ecmfile = new EcmFiles($this->db);
  4962. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  4963. // Set the public "share" key
  4964. $setsharekey = false;
  4965. if ($this->element == 'propal' || $this->element == 'proposal') {
  4966. if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
  4967. $setsharekey = true; // feature to make online signature is not set or set to on (default)
  4968. }
  4969. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4970. $setsharekey = true;
  4971. }
  4972. }
  4973. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  4974. $setsharekey = true;
  4975. }
  4976. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  4977. $setsharekey = true;
  4978. }
  4979. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4980. $setsharekey = true;
  4981. }
  4982. if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4983. $setsharekey = true;
  4984. }
  4985. if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4986. $setsharekey = true;
  4987. }
  4988. if ($setsharekey) {
  4989. if (empty($ecmfile->share)) { // Because object not found or share not set yet
  4990. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  4991. $ecmfile->share = getRandomPassword(true);
  4992. }
  4993. }
  4994. if ($result > 0) {
  4995. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4996. $ecmfile->fullpath_orig = '';
  4997. $ecmfile->gen_or_uploaded = 'generated';
  4998. $ecmfile->description = ''; // indexed content
  4999. $ecmfile->keywords = ''; // keyword content
  5000. $result = $ecmfile->update($user);
  5001. if ($result < 0) {
  5002. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  5003. return -1;
  5004. }
  5005. } else {
  5006. $ecmfile->entity = $conf->entity;
  5007. $ecmfile->filepath = $rel_dir;
  5008. $ecmfile->filename = $filename;
  5009. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  5010. $ecmfile->fullpath_orig = '';
  5011. $ecmfile->gen_or_uploaded = 'generated';
  5012. $ecmfile->description = ''; // indexed content
  5013. $ecmfile->keywords = ''; // keyword content
  5014. $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
  5015. $ecmfile->src_object_id = $this->id;
  5016. $result = $ecmfile->create($user);
  5017. if ($result < 0) {
  5018. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  5019. return -1;
  5020. }
  5021. }
  5022. /*$this->result['fullname']=$destfull;
  5023. $this->result['filepath']=$ecmfile->filepath;
  5024. $this->result['filename']=$ecmfile->filename;*/
  5025. //var_dump($obj->update_main_doc_field);exit;
  5026. if ($update_main_doc_field && !empty($this->table_element)) {
  5027. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
  5028. $sql .= " WHERE rowid = ".((int) $this->id);
  5029. $resql = $this->db->query($sql);
  5030. if (!$resql) {
  5031. dol_print_error($this->db);
  5032. return -1;
  5033. } else {
  5034. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  5035. }
  5036. }
  5037. }
  5038. return 1;
  5039. }
  5040. /**
  5041. * Build thumb
  5042. * @todo Move this into files.lib.php
  5043. *
  5044. * @param string $file Path file in UTF8 to original file to create thumbs from.
  5045. * @return void
  5046. */
  5047. public function addThumbs($file)
  5048. {
  5049. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  5050. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  5051. $file_osencoded = dol_osencode($file);
  5052. if (file_exists($file_osencoded)) {
  5053. // Create small thumbs for company (Ratio is near 16/9)
  5054. // Used on logon for example
  5055. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  5056. // Create mini thumbs for company (Ratio is near 16/9)
  5057. // Used on menu or for setup page for example
  5058. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  5059. }
  5060. }
  5061. /* Functions common to commonobject and commonobjectline */
  5062. /* For default values */
  5063. /**
  5064. * Return the default value to use for a field when showing the create form of object.
  5065. * Return values in this order:
  5066. * 1) If parameter is available into POST, we return it first.
  5067. * 2) If not but an alternate value was provided as parameter of function, we return it.
  5068. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  5069. * 4) Return value found into database (TODO No yet implemented)
  5070. *
  5071. * @param string $fieldname Name of field
  5072. * @param string $alternatevalue Alternate value to use
  5073. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  5074. **/
  5075. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
  5076. {
  5077. global $conf, $_POST;
  5078. // If param here has been posted, we use this value first.
  5079. if (GETPOSTISSET($fieldname)) {
  5080. return GETPOST($fieldname, 'alphanohtml', 3);
  5081. }
  5082. if (isset($alternatevalue)) {
  5083. return $alternatevalue;
  5084. }
  5085. $newelement = $this->element;
  5086. if ($newelement == 'facture') {
  5087. $newelement = 'invoice';
  5088. }
  5089. if ($newelement == 'commande') {
  5090. $newelement = 'order';
  5091. }
  5092. if (empty($newelement)) {
  5093. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  5094. return '';
  5095. }
  5096. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  5097. //var_dump($keyforfieldname);
  5098. if (isset($conf->global->$keyforfieldname)) {
  5099. return $conf->global->$keyforfieldname;
  5100. }
  5101. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  5102. }
  5103. /* For triggers */
  5104. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5105. /**
  5106. * Call trigger based on this instance.
  5107. * Some context information may also be provided into array property this->context.
  5108. * NB: Error from trigger are stacked in interface->errors
  5109. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  5110. *
  5111. * @param string $triggerName trigger's name to execute
  5112. * @param User $user Object user
  5113. * @return int Result of run_triggers
  5114. */
  5115. public function call_trigger($triggerName, $user)
  5116. {
  5117. // phpcs:enable
  5118. global $langs, $conf;
  5119. if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
  5120. dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.');
  5121. exit;
  5122. }
  5123. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  5124. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  5125. $langs = new Translate('', $conf);
  5126. }
  5127. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  5128. $interface = new Interfaces($this->db);
  5129. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  5130. if ($result < 0) {
  5131. if (!empty($this->errors)) {
  5132. $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.
  5133. } else {
  5134. $this->errors = $interface->errors;
  5135. }
  5136. }
  5137. return $result;
  5138. }
  5139. /* Functions for data in other language */
  5140. /**
  5141. * Function to get alternative languages of a data into $this->array_languages
  5142. * This method is NOT called by method fetch of objects but must be called separately.
  5143. *
  5144. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  5145. * @see fetch_optionnals()
  5146. */
  5147. public function fetchValuesForExtraLanguages()
  5148. {
  5149. // To avoid SQL errors. Probably not the better solution though
  5150. if (!$this->element) {
  5151. return 0;
  5152. }
  5153. if (!($this->id > 0)) {
  5154. return 0;
  5155. }
  5156. if (is_array($this->array_languages)) {
  5157. return 1;
  5158. }
  5159. $this->array_languages = array();
  5160. $element = $this->element;
  5161. if ($element == 'categorie') {
  5162. $element = 'categories'; // For compatibility
  5163. }
  5164. // Request to get translation values for object
  5165. $sql = "SELECT rowid, property, lang , value";
  5166. $sql .= " FROM ".$this->db->prefix()."object_lang";
  5167. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  5168. $sql .= " AND fk_object = ".((int) $this->id);
  5169. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5170. $resql = $this->db->query($sql);
  5171. if ($resql) {
  5172. $numrows = $this->db->num_rows($resql);
  5173. if ($numrows) {
  5174. $i = 0;
  5175. while ($i < $numrows) {
  5176. $obj = $this->db->fetch_object($resql);
  5177. $key = $obj->property;
  5178. $value = $obj->value;
  5179. $codelang = $obj->lang;
  5180. $type = $this->fields[$key]['type'];
  5181. // we can add this attribute to object
  5182. if (preg_match('/date/', $type)) {
  5183. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  5184. } else {
  5185. $this->array_languages[$key][$codelang] = $value;
  5186. }
  5187. $i++;
  5188. }
  5189. }
  5190. $this->db->free($resql);
  5191. if ($numrows) {
  5192. return $numrows;
  5193. } else {
  5194. return 0;
  5195. }
  5196. } else {
  5197. dol_print_error($this->db);
  5198. return -1;
  5199. }
  5200. }
  5201. /**
  5202. * Fill array_options property of object by extrafields value (using for data sent by forms)
  5203. *
  5204. * @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.
  5205. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  5206. */
  5207. public function setValuesForExtraLanguages($onlykey = '')
  5208. {
  5209. global $_POST, $langs;
  5210. // Get extra fields
  5211. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  5212. $tmparray = explode('-', $postfieldkey);
  5213. if ($tmparray[0] != 'field') {
  5214. continue;
  5215. }
  5216. $element = $tmparray[1];
  5217. $key = $tmparray[2];
  5218. $codelang = $tmparray[3];
  5219. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  5220. if (!empty($onlykey) && $key != $onlykey) {
  5221. continue;
  5222. }
  5223. if ($element != $this->element) {
  5224. continue;
  5225. }
  5226. $key_type = $this->fields[$key]['type'];
  5227. $enabled = 1;
  5228. if (isset($this->fields[$key]['enabled'])) {
  5229. $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
  5230. }
  5231. /*$perms = 1;
  5232. if (isset($this->fields[$key]['perms']))
  5233. {
  5234. $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
  5235. }*/
  5236. if (empty($enabled)) {
  5237. continue;
  5238. }
  5239. //if (empty($perms)) continue;
  5240. if (in_array($key_type, array('date'))) {
  5241. // Clean parameters
  5242. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5243. $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
  5244. } elseif (in_array($key_type, array('datetime'))) {
  5245. // Clean parameters
  5246. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5247. $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'));
  5248. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  5249. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  5250. if (!empty($value_arr)) {
  5251. $value_key = implode(',', $value_arr);
  5252. } else {
  5253. $value_key = '';
  5254. }
  5255. } elseif (in_array($key_type, array('price', 'double'))) {
  5256. $value_arr = GETPOST($postfieldkey, 'alpha');
  5257. $value_key = price2num($value_arr);
  5258. } else {
  5259. $value_key = GETPOST($postfieldkey);
  5260. if (in_array($key_type, array('link')) && $value_key == '-1') {
  5261. $value_key = '';
  5262. }
  5263. }
  5264. $this->array_languages[$key][$codelang] = $value_key;
  5265. /*if ($nofillrequired) {
  5266. $langs->load('errors');
  5267. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  5268. return -1;
  5269. }*/
  5270. }
  5271. return 1;
  5272. }
  5273. /* Functions for extrafields */
  5274. /**
  5275. * Function to make a fetch but set environment to avoid to load computed values before.
  5276. *
  5277. * @param int $id ID of object
  5278. * @return int >0 if OK, 0 if not found, <0 if KO
  5279. */
  5280. public function fetchNoCompute($id)
  5281. {
  5282. global $conf;
  5283. $savDisableCompute = $conf->disable_compute;
  5284. $conf->disable_compute = 1;
  5285. $ret = $this->fetch($id);
  5286. $conf->disable_compute = $savDisableCompute;
  5287. return $ret;
  5288. }
  5289. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5290. /**
  5291. * Function to get extra fields of an object into $this->array_options
  5292. * This method is in most cases called by method fetch of objects but you can call it separately.
  5293. *
  5294. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  5295. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  5296. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  5297. * @see fetchValuesForExtraLanguages()
  5298. */
  5299. public function fetch_optionals($rowid = null, $optionsArray = null)
  5300. {
  5301. // phpcs:enable
  5302. global $conf, $extrafields;
  5303. if (empty($rowid)) {
  5304. $rowid = $this->id;
  5305. }
  5306. if (empty($rowid) && isset($this->rowid)) {
  5307. $rowid = $this->rowid; // deprecated
  5308. }
  5309. // To avoid SQL errors. Probably not the better solution though
  5310. if (!$this->table_element) {
  5311. return 0;
  5312. }
  5313. $this->array_options = array();
  5314. if (!is_array($optionsArray)) {
  5315. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  5316. if (!isset($extrafields) || !is_object($extrafields)) {
  5317. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5318. $extrafields = new ExtraFields($this->db);
  5319. }
  5320. // Load array of extrafields for elementype = $this->table_element
  5321. if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
  5322. $extrafields->fetch_name_optionals_label($this->table_element);
  5323. }
  5324. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  5325. } else {
  5326. global $extrafields;
  5327. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  5328. }
  5329. $table_element = $this->table_element;
  5330. if ($table_element == 'categorie') {
  5331. $table_element = 'categories'; // For compatibility
  5332. }
  5333. // Request to get complementary values
  5334. if (is_array($optionsArray) && count($optionsArray) > 0) {
  5335. $sql = "SELECT rowid";
  5336. foreach ($optionsArray as $name => $label) {
  5337. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
  5338. $sql .= ", ".$name;
  5339. }
  5340. }
  5341. $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
  5342. $sql .= " WHERE fk_object = ".((int) $rowid);
  5343. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5344. $resql = $this->db->query($sql);
  5345. if ($resql) {
  5346. $numrows = $this->db->num_rows($resql);
  5347. if ($numrows) {
  5348. $tab = $this->db->fetch_array($resql);
  5349. foreach ($tab as $key => $value) {
  5350. // 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)
  5351. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
  5352. // we can add this attribute to object
  5353. if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
  5354. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  5355. $this->array_options["options_".$key] = $this->db->jdate($value);
  5356. } else {
  5357. $this->array_options["options_".$key] = $value;
  5358. }
  5359. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  5360. }
  5361. }
  5362. }
  5363. // If field is a computed field, value must become result of compute (regardless of whether a row exists
  5364. // in the element's extrafields table)
  5365. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
  5366. if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
  5367. //var_dump($conf->disable_compute);
  5368. if (empty($conf->disable_compute)) {
  5369. $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
  5370. }
  5371. }
  5372. }
  5373. $this->db->free($resql);
  5374. if ($numrows) {
  5375. return $numrows;
  5376. } else {
  5377. return 0;
  5378. }
  5379. } else {
  5380. $this->errors[]=$this->db->lasterror;
  5381. return -1;
  5382. }
  5383. }
  5384. return 0;
  5385. }
  5386. /**
  5387. * Delete all extra fields values for the current object.
  5388. *
  5389. * @return int <0 if KO, >0 if OK
  5390. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  5391. */
  5392. public function deleteExtraFields()
  5393. {
  5394. global $conf;
  5395. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5396. return 0;
  5397. }
  5398. $this->db->begin();
  5399. $table_element = $this->table_element;
  5400. if ($table_element == 'categorie') {
  5401. $table_element = 'categories'; // For compatibility
  5402. }
  5403. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  5404. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5405. $resql = $this->db->query($sql_del);
  5406. if (!$resql) {
  5407. $this->error = $this->db->lasterror();
  5408. $this->db->rollback();
  5409. return -1;
  5410. } else {
  5411. $this->db->commit();
  5412. return 1;
  5413. }
  5414. }
  5415. /**
  5416. * Add/Update all extra fields values for the current object.
  5417. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5418. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5419. *
  5420. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5421. * @param User $userused Object user
  5422. * @return int -1=error, O=did nothing, 1=OK
  5423. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  5424. */
  5425. public function insertExtraFields($trigger = '', $userused = null)
  5426. {
  5427. global $conf, $langs, $user;
  5428. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5429. return 0;
  5430. }
  5431. if (empty($userused)) {
  5432. $userused = $user;
  5433. }
  5434. $error = 0;
  5435. if (!empty($this->array_options)) {
  5436. // Check parameters
  5437. $langs->load('admin');
  5438. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5439. $extrafields = new ExtraFields($this->db);
  5440. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  5441. // Eliminate copied source object extra fields that do not exist in target object
  5442. $new_array_options = array();
  5443. foreach ($this->array_options as $key => $value) {
  5444. if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
  5445. $new_array_options[$key] = $value;
  5446. } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
  5447. $new_array_options['options_'.$key] = $value;
  5448. }
  5449. }
  5450. foreach ($new_array_options as $key => $value) {
  5451. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5452. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  5453. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  5454. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  5455. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  5456. $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
  5457. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  5458. // If we clone, we have to clean unique extrafields to prevent duplicates.
  5459. // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
  5460. if (! empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && ! empty($attributeUnique)) {
  5461. $new_array_options[$key] = null;
  5462. }
  5463. // Similar code than into insertExtraFields
  5464. if ($attributeRequired) {
  5465. $mandatorypb = false;
  5466. if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
  5467. $mandatorypb = true;
  5468. }
  5469. if ($this->array_options[$key] === '') {
  5470. $mandatorypb = true;
  5471. }
  5472. if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
  5473. $mandatorypb = true;
  5474. }
  5475. if ($mandatorypb) {
  5476. $langs->load("errors");
  5477. dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
  5478. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5479. return -1;
  5480. }
  5481. }
  5482. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5483. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5484. if (!empty($attrfieldcomputed)) {
  5485. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5486. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5487. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5488. $new_array_options[$key] = $value;
  5489. } else {
  5490. $new_array_options[$key] = null;
  5491. }
  5492. }
  5493. switch ($attributeType) {
  5494. case 'int':
  5495. if (!is_numeric($value) && $value != '') {
  5496. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5497. return -1;
  5498. } elseif ($value == '') {
  5499. $new_array_options[$key] = null;
  5500. }
  5501. break;
  5502. case 'price':
  5503. case 'double':
  5504. $value = price2num($value);
  5505. if (!is_numeric($value) && $value != '') {
  5506. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5507. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5508. return -1;
  5509. } elseif ($value == '') {
  5510. $value = null;
  5511. }
  5512. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5513. $new_array_options[$key] = $value;
  5514. break;
  5515. /*case 'select': // Not required, we chosed value='0' for undefined values
  5516. if ($value=='-1')
  5517. {
  5518. $this->array_options[$key] = null;
  5519. }
  5520. break;*/
  5521. case 'password':
  5522. $algo = '';
  5523. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
  5524. // If there is an encryption choice, we use it to crypt data before insert
  5525. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  5526. $algo = reset($tmparrays);
  5527. if ($algo != '') {
  5528. //global $action; // $action may be 'create', 'update', 'update_extras'...
  5529. //var_dump($action);
  5530. //var_dump($this->oldcopy);exit;
  5531. 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
  5532. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  5533. if (isset($this->oldcopy->array_options[$key]) && $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.
  5534. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5535. } else {
  5536. // var_dump($algo);
  5537. $newvalue = dol_hash($this->array_options[$key], $algo);
  5538. $new_array_options[$key] = $newvalue;
  5539. }
  5540. } else {
  5541. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5542. }
  5543. }
  5544. } else // Common usage
  5545. {
  5546. $new_array_options[$key] = $this->array_options[$key];
  5547. }
  5548. break;
  5549. case 'date':
  5550. case 'datetime':
  5551. // If data is a string instead of a timestamp, we convert it
  5552. if (!is_int($this->array_options[$key])) {
  5553. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5554. }
  5555. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  5556. break;
  5557. case 'link':
  5558. $param_list = array_keys($attributeParam['options']);
  5559. // 0 : ObjectName
  5560. // 1 : classPath
  5561. $InfoFieldList = explode(":", $param_list[0]);
  5562. dol_include_once($InfoFieldList[1]);
  5563. if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
  5564. if ($value == '-1') { // -1 is key for no defined in combo list of objects
  5565. $new_array_options[$key] = '';
  5566. } elseif ($value) {
  5567. $object = new $InfoFieldList[0]($this->db);
  5568. if (is_numeric($value)) {
  5569. $res = $object->fetch($value); // Common case
  5570. } else {
  5571. $res = $object->fetch('', $value); // For compatibility
  5572. }
  5573. if ($res > 0) {
  5574. $new_array_options[$key] = $object->id;
  5575. } else {
  5576. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5577. $this->db->rollback();
  5578. return -1;
  5579. }
  5580. }
  5581. } else {
  5582. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5583. }
  5584. break;
  5585. }
  5586. }
  5587. $this->db->begin();
  5588. $table_element = $this->table_element;
  5589. if ($table_element == 'categorie') {
  5590. $table_element = 'categories'; // For compatibility
  5591. }
  5592. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  5593. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5594. $this->db->query($sql_del);
  5595. $sql = "INSERT INTO ".$this->db->prefix().$table_element."_extrafields (fk_object";
  5596. foreach ($new_array_options as $key => $value) {
  5597. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5598. // Add field of attribut
  5599. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
  5600. $sql .= ",".$attributeKey;
  5601. }
  5602. }
  5603. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5604. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5605. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5606. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5607. $sql .= ",".$tmpkey;
  5608. }
  5609. }
  5610. }
  5611. $sql .= ") VALUES (".$this->id;
  5612. foreach ($new_array_options as $key => $value) {
  5613. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5614. // Add field of attribute
  5615. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
  5616. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
  5617. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  5618. } else {
  5619. $sql .= ",null";
  5620. }
  5621. }
  5622. }
  5623. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5624. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5625. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5626. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5627. if (in_array($tmpval, array('int', 'double', 'price'))) {
  5628. $sql .= ", 0";
  5629. } else {
  5630. $sql .= ", ''";
  5631. }
  5632. }
  5633. }
  5634. }
  5635. $sql .= ")";
  5636. $resql = $this->db->query($sql);
  5637. if (!$resql) {
  5638. $this->error = $this->db->lasterror();
  5639. $error++;
  5640. }
  5641. if (!$error && $trigger) {
  5642. // Call trigger
  5643. $this->context = array('extrafieldaddupdate'=>1);
  5644. $result = $this->call_trigger($trigger, $userused);
  5645. if ($result < 0) {
  5646. $error++;
  5647. }
  5648. // End call trigger
  5649. }
  5650. if ($error) {
  5651. $this->db->rollback();
  5652. return -1;
  5653. } else {
  5654. $this->db->commit();
  5655. return 1;
  5656. }
  5657. } else {
  5658. return 0;
  5659. }
  5660. }
  5661. /**
  5662. * Add/Update all extra fields values for the current object.
  5663. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5664. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5665. *
  5666. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5667. * @param User $userused Object user
  5668. * @return int -1=error, O=did nothing, 1=OK
  5669. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  5670. */
  5671. public function insertExtraLanguages($trigger = '', $userused = null)
  5672. {
  5673. global $conf, $langs, $user;
  5674. if (empty($userused)) {
  5675. $userused = $user;
  5676. }
  5677. $error = 0;
  5678. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5679. return 0; // For avoid conflicts if trigger used
  5680. }
  5681. if (is_array($this->array_languages)) {
  5682. $new_array_languages = $this->array_languages;
  5683. foreach ($new_array_languages as $key => $value) {
  5684. $attributeKey = $key;
  5685. $attributeType = $this->fields[$attributeKey]['type'];
  5686. $attributeLabel = $this->fields[$attributeKey]['label'];
  5687. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5688. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5689. switch ($attributeType) {
  5690. case 'int':
  5691. if (!is_numeric($value) && $value != '') {
  5692. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5693. return -1;
  5694. } elseif ($value == '') {
  5695. $new_array_languages[$key] = null;
  5696. }
  5697. break;
  5698. case 'double':
  5699. $value = price2num($value);
  5700. if (!is_numeric($value) && $value != '') {
  5701. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5702. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5703. return -1;
  5704. } elseif ($value == '') {
  5705. $new_array_languages[$key] = null;
  5706. }
  5707. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5708. $new_array_languages[$key] = $value;
  5709. break;
  5710. /*case 'select': // Not required, we chosed value='0' for undefined values
  5711. if ($value=='-1')
  5712. {
  5713. $this->array_options[$key] = null;
  5714. }
  5715. break;*/
  5716. }
  5717. }
  5718. $this->db->begin();
  5719. $table_element = $this->table_element;
  5720. if ($table_element == 'categorie') {
  5721. $table_element = 'categories'; // For compatibility
  5722. }
  5723. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  5724. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  5725. foreach ($langcodearray as $langcode => $value) {
  5726. $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
  5727. $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  5728. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  5729. $this->db->query($sql_del);
  5730. if ($value !== '') {
  5731. $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
  5732. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  5733. $sql .= ")";
  5734. $resql = $this->db->query($sql);
  5735. if (!$resql) {
  5736. $this->error = $this->db->lasterror();
  5737. $error++;
  5738. break;
  5739. }
  5740. }
  5741. }
  5742. }
  5743. if (!$error && $trigger) {
  5744. // Call trigger
  5745. $this->context = array('extralanguagesaddupdate'=>1);
  5746. $result = $this->call_trigger($trigger, $userused);
  5747. if ($result < 0) {
  5748. $error++;
  5749. }
  5750. // End call trigger
  5751. }
  5752. if ($error) {
  5753. $this->db->rollback();
  5754. return -1;
  5755. } else {
  5756. $this->db->commit();
  5757. return 1;
  5758. }
  5759. } else {
  5760. return 0;
  5761. }
  5762. }
  5763. /**
  5764. * Update 1 extra field value for the current object. Keep other fields unchanged.
  5765. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5766. *
  5767. * @param string $key Key of the extrafield to update (without starting 'options_')
  5768. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5769. * @param User $userused Object user
  5770. * @return int -1=error, O=did nothing, 1=OK
  5771. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  5772. */
  5773. public function updateExtraField($key, $trigger = null, $userused = null)
  5774. {
  5775. global $conf, $langs, $user;
  5776. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5777. return 0;
  5778. }
  5779. if (empty($userused)) {
  5780. $userused = $user;
  5781. }
  5782. $error = 0;
  5783. if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
  5784. // Check parameters
  5785. $langs->load('admin');
  5786. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5787. $extrafields = new ExtraFields($this->db);
  5788. $extrafields->fetch_name_optionals_label($this->table_element);
  5789. $value = $this->array_options["options_".$key];
  5790. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  5791. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  5792. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  5793. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  5794. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  5795. // Similar code than into insertExtraFields
  5796. if ($attributeRequired) {
  5797. $mandatorypb = false;
  5798. if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
  5799. $mandatorypb = true;
  5800. }
  5801. if ($this->array_options["options_".$key] === '') {
  5802. $mandatorypb = true;
  5803. }
  5804. if ($mandatorypb) {
  5805. $langs->load("errors");
  5806. dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
  5807. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5808. return -1;
  5809. }
  5810. }
  5811. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5812. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5813. if (!empty($attrfieldcomputed)) {
  5814. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5815. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5816. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5817. $this->array_options["options_".$key] = $value;
  5818. } else {
  5819. $this->array_options["options_".$key] = null;
  5820. }
  5821. }
  5822. switch ($attributeType) {
  5823. case 'int':
  5824. if (!is_numeric($value) && $value != '') {
  5825. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5826. return -1;
  5827. } elseif ($value === '') {
  5828. $this->array_options["options_".$key] = null;
  5829. }
  5830. break;
  5831. case 'double':
  5832. $value = price2num($value);
  5833. if (!is_numeric($value) && $value != '') {
  5834. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5835. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5836. return -1;
  5837. } elseif ($value === '') {
  5838. $value = null;
  5839. }
  5840. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5841. $this->array_options["options_".$key] = $value;
  5842. break;
  5843. /*case 'select': // Not required, we chosed value='0' for undefined values
  5844. if ($value=='-1')
  5845. {
  5846. $this->array_options[$key] = null;
  5847. }
  5848. break;*/
  5849. case 'price':
  5850. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  5851. break;
  5852. case 'date':
  5853. case 'datetime':
  5854. if (empty($this->array_options["options_".$key])) {
  5855. $this->array_options["options_".$key] = null;
  5856. } else {
  5857. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5858. }
  5859. break;
  5860. case 'boolean':
  5861. if (empty($this->array_options["options_".$key])) {
  5862. $this->array_options["options_".$key] = null;
  5863. }
  5864. break;
  5865. /*
  5866. case 'link':
  5867. $param_list = array_keys($attributeParam['options']);
  5868. // 0 : ObjectName
  5869. // 1 : classPath
  5870. $InfoFieldList = explode(":", $param_list[0]);
  5871. dol_include_once($InfoFieldList[1]);
  5872. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  5873. {
  5874. if ($value == '-1') // -1 is key for no defined in combo list of objects
  5875. {
  5876. $new_array_options[$key] = '';
  5877. } elseif ($value) {
  5878. $object = new $InfoFieldList[0]($this->db);
  5879. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  5880. else $res = $object->fetch('', $value); // For compatibility
  5881. if ($res > 0) $new_array_options[$key] = $object->id;
  5882. else {
  5883. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5884. $this->db->rollback();
  5885. return -1;
  5886. }
  5887. }
  5888. } else {
  5889. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5890. }
  5891. break;
  5892. */
  5893. }
  5894. $this->db->begin();
  5895. $linealreadyfound = 0;
  5896. // 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)
  5897. $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5898. $resql = $this->db->query($sql);
  5899. if ($resql) {
  5900. $tmpobj = $this->db->fetch_object($resql);
  5901. if ($tmpobj) {
  5902. $linealreadyfound = $tmpobj->nb;
  5903. }
  5904. }
  5905. if ($linealreadyfound) {
  5906. if ($this->array_options["options_".$key] === null) {
  5907. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = null";
  5908. } else {
  5909. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
  5910. }
  5911. $sql .= " WHERE fk_object = ".((int) $this->id);
  5912. } else {
  5913. $result = $this->insertExtraFields('', $user);
  5914. if ($result < 0) {
  5915. $error++;
  5916. }
  5917. }
  5918. $resql = $this->db->query($sql);
  5919. if (!$resql) {
  5920. $error++;
  5921. $this->error = $this->db->lasterror();
  5922. }
  5923. if (!$error && $trigger) {
  5924. // Call trigger
  5925. $this->context = array('extrafieldupdate'=>1);
  5926. $result = $this->call_trigger($trigger, $userused);
  5927. if ($result < 0) {
  5928. $error++;
  5929. }
  5930. // End call trigger
  5931. }
  5932. if ($error) {
  5933. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  5934. $this->db->rollback();
  5935. return -1;
  5936. } else {
  5937. $this->db->commit();
  5938. return 1;
  5939. }
  5940. } else {
  5941. return 0;
  5942. }
  5943. }
  5944. /**
  5945. * Update an extra language value for the current object.
  5946. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5947. *
  5948. * @param string $key Key of the extrafield (without starting 'options_')
  5949. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5950. * @param User $userused Object user
  5951. * @return int -1=error, O=did nothing, 1=OK
  5952. * @see updateExtraFields(), insertExtraLanguages()
  5953. */
  5954. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  5955. {
  5956. global $conf, $langs, $user;
  5957. if (empty($userused)) {
  5958. $userused = $user;
  5959. }
  5960. $error = 0;
  5961. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5962. return 0; // For avoid conflicts if trigger used
  5963. }
  5964. return 0;
  5965. }
  5966. /**
  5967. * Return HTML string to put an input field into a page
  5968. * Code very similar with showInputField of extra fields
  5969. *
  5970. * @param array $val Array of properties for field to show (used only if ->fields not defined)
  5971. * @param string $key Key of attribute
  5972. * @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)
  5973. * @param string $moreparam To add more parameters on html input tag
  5974. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5975. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5976. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  5977. * @param int $nonewbutton Force to not show the new button on field that are links to object
  5978. * @return string
  5979. */
  5980. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  5981. {
  5982. global $conf, $langs, $form;
  5983. if (!is_object($form)) {
  5984. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  5985. $form = new Form($this->db);
  5986. }
  5987. if (!empty($this->fields)) {
  5988. $val = $this->fields[$key];
  5989. }
  5990. // Validation tests and output
  5991. $fieldValidationErrorMsg = '';
  5992. $validationClass = '';
  5993. $fieldValidationErrorMsg = $this->getFieldError($key);
  5994. if (!empty($fieldValidationErrorMsg)) {
  5995. $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
  5996. } else {
  5997. $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
  5998. }
  5999. $out = '';
  6000. $type = '';
  6001. $isDependList = 0;
  6002. $param = array();
  6003. $param['options'] = array();
  6004. $reg = array();
  6005. $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
  6006. // Because we work on extrafields
  6007. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6008. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  6009. $type = 'link';
  6010. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6011. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6012. $type = 'link';
  6013. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  6014. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  6015. $type = 'link';
  6016. } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6017. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  6018. $type = 'sellist';
  6019. } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6020. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6021. $type = 'sellist';
  6022. } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
  6023. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  6024. $type = 'sellist';
  6025. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  6026. $param['options'] = array();
  6027. $type = 'varchar';
  6028. $size = $reg[1];
  6029. } elseif (preg_match('/varchar/', $val['type'])) {
  6030. $param['options'] = array();
  6031. $type = 'varchar';
  6032. } else {
  6033. $param['options'] = array();
  6034. $type = $this->fields[$key]['type'];
  6035. }
  6036. // Special case that force options and type ($type can be integer, varchar, ...)
  6037. if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
  6038. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  6039. $type = 'select';
  6040. }
  6041. $label = $this->fields[$key]['label'];
  6042. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  6043. $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
  6044. $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
  6045. $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
  6046. $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
  6047. $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
  6048. $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
  6049. $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
  6050. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  6051. $objectid = $this->id;
  6052. if ($computed) {
  6053. if (!preg_match('/^search_/', $keyprefix)) {
  6054. return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  6055. } else {
  6056. return '';
  6057. }
  6058. }
  6059. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  6060. if (empty($morecss) && !empty($val['css'])) {
  6061. $morecss = $val['css'];
  6062. } elseif (empty($morecss)) {
  6063. if ($type == 'date') {
  6064. $morecss = 'minwidth100imp';
  6065. } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
  6066. $morecss = 'minwidth200imp';
  6067. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  6068. $morecss = 'maxwidth75';
  6069. } elseif ($type == 'url') {
  6070. $morecss = 'minwidth400';
  6071. } elseif ($type == 'boolean') {
  6072. $morecss = '';
  6073. } else {
  6074. if (round($size) < 12) {
  6075. $morecss = 'minwidth100';
  6076. } elseif (round($size) <= 48) {
  6077. $morecss = 'minwidth200';
  6078. } else {
  6079. $morecss = 'minwidth400';
  6080. }
  6081. }
  6082. }
  6083. // Add validation state class
  6084. if (!empty($validationClass)) {
  6085. $morecss.= $validationClass;
  6086. }
  6087. if (in_array($type, array('date'))) {
  6088. $tmp = explode(',', $size);
  6089. $newsize = $tmp[0];
  6090. $showtime = 0;
  6091. // Do not show current date when field not required (see selectDate() method)
  6092. if (!$required && $value == '') {
  6093. $value = '-1';
  6094. }
  6095. // TODO Must also support $moreparam
  6096. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  6097. } elseif (in_array($type, array('datetime'))) {
  6098. $tmp = explode(',', $size);
  6099. $newsize = $tmp[0];
  6100. $showtime = 1;
  6101. // Do not show current date when field not required (see selectDate() method)
  6102. if (!$required && $value == '') $value = '-1';
  6103. // TODO Must also support $moreparam
  6104. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
  6105. } elseif (in_array($type, array('duration'))) {
  6106. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  6107. } elseif (in_array($type, array('int', 'integer'))) {
  6108. $tmp = explode(',', $size);
  6109. $newsize = $tmp[0];
  6110. $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' : '').'>';
  6111. } elseif (in_array($type, array('real'))) {
  6112. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6113. } elseif (preg_match('/varchar/', $type)) {
  6114. $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' : '').'>';
  6115. } elseif (in_array($type, array('email', 'mail', 'phone', 'url'))) {
  6116. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6117. } elseif (preg_match('/^text/', $type)) {
  6118. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6119. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  6120. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  6121. $out = $doleditor->Create(1);
  6122. } else {
  6123. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  6124. }
  6125. } elseif (preg_match('/^html/', $type)) {
  6126. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6127. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  6128. $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%');
  6129. $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
  6130. } else {
  6131. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  6132. }
  6133. } elseif ($type == 'boolean') {
  6134. $checked = '';
  6135. if (!empty($value)) {
  6136. $checked = ' checked value="1" ';
  6137. } else {
  6138. $checked = ' value="1" ';
  6139. }
  6140. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  6141. } elseif ($type == 'price') {
  6142. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6143. $value = price($value);
  6144. }
  6145. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  6146. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  6147. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6148. $value = price($value);
  6149. }
  6150. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  6151. } elseif ($type == 'select') {
  6152. $out = '';
  6153. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6154. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6155. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6156. }
  6157. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6158. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
  6159. $out .= '<option value="0">&nbsp;</option>';
  6160. }
  6161. foreach ($param['options'] as $keyb => $valb) {
  6162. if ((string) $keyb == '') {
  6163. continue;
  6164. }
  6165. if (strpos($valb, "|") !== false) {
  6166. list($valb, $parent) = explode('|', $valb);
  6167. }
  6168. $out .= '<option value="'.$keyb.'"';
  6169. $out .= (((string) $value == (string) $keyb) ? ' selected' : '');
  6170. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6171. $out .= '>'.$valb.'</option>';
  6172. }
  6173. $out .= '</select>';
  6174. } elseif ($type == 'sellist') {
  6175. $out = '';
  6176. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6177. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6178. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6179. }
  6180. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6181. if (is_array($param['options'])) {
  6182. $param_list = array_keys($param['options']);
  6183. $InfoFieldList = explode(":", $param_list[0]);
  6184. $parentName = '';
  6185. $parentField = '';
  6186. // 0 : tableName
  6187. // 1 : label field name
  6188. // 2 : key fields name (if differ of rowid)
  6189. // 3 : key field parent (for dependent lists)
  6190. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6191. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6192. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6193. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6194. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6195. } else {
  6196. $keyList = $InfoFieldList[2].' as rowid';
  6197. }
  6198. }
  6199. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6200. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6201. $keyList .= ', '.$parentField;
  6202. }
  6203. $fields_label = explode('|', $InfoFieldList[1]);
  6204. if (is_array($fields_label)) {
  6205. $keyList .= ', ';
  6206. $keyList .= implode(', ', $fields_label);
  6207. }
  6208. $sqlwhere = '';
  6209. $sql = "SELECT ".$keyList;
  6210. $sql .= " FROM ".$this->db->prefix().$InfoFieldList[0];
  6211. if (!empty($InfoFieldList[4])) {
  6212. // can use SELECT request
  6213. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6214. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6215. }
  6216. // current object id can be use into filter
  6217. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6218. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6219. } else {
  6220. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6221. }
  6222. //We have to join on extrafield table
  6223. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6224. $sql .= " as main, ".$this->db->prefix().$InfoFieldList[0]."_extrafields as extra";
  6225. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  6226. } else {
  6227. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  6228. }
  6229. } else {
  6230. $sqlwhere .= ' WHERE 1=1';
  6231. }
  6232. // Some tables may have field, some other not. For the moment we disable it.
  6233. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6234. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  6235. }
  6236. $sql .= $sqlwhere;
  6237. //print $sql;
  6238. $sql .= ' ORDER BY '.implode(', ', $fields_label);
  6239. dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
  6240. $resql = $this->db->query($sql);
  6241. if ($resql) {
  6242. $out .= '<option value="0">&nbsp;</option>';
  6243. $num = $this->db->num_rows($resql);
  6244. $i = 0;
  6245. while ($i < $num) {
  6246. $labeltoshow = '';
  6247. $obj = $this->db->fetch_object($resql);
  6248. // Several field into label (eq table:code|libelle:rowid)
  6249. $notrans = false;
  6250. $fields_label = explode('|', $InfoFieldList[1]);
  6251. if (count($fields_label) > 1) {
  6252. $notrans = true;
  6253. foreach ($fields_label as $field_toshow) {
  6254. $labeltoshow .= $obj->$field_toshow.' ';
  6255. }
  6256. } else {
  6257. $labeltoshow = $obj->{$InfoFieldList[1]};
  6258. }
  6259. $labeltoshow = dol_trunc($labeltoshow, 45);
  6260. if ($value == $obj->rowid) {
  6261. foreach ($fields_label as $field_toshow) {
  6262. $translabel = $langs->trans($obj->$field_toshow);
  6263. if ($translabel != $obj->$field_toshow) {
  6264. $labeltoshow = dol_trunc($translabel).' ';
  6265. } else {
  6266. $labeltoshow = dol_trunc($obj->$field_toshow).' ';
  6267. }
  6268. }
  6269. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6270. } else {
  6271. if (!$notrans) {
  6272. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6273. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6274. $labeltoshow = dol_trunc($translabel, 18);
  6275. } else {
  6276. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
  6277. }
  6278. }
  6279. if (empty($labeltoshow)) {
  6280. $labeltoshow = '(not defined)';
  6281. }
  6282. if ($value == $obj->rowid) {
  6283. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6284. }
  6285. if (!empty($InfoFieldList[3]) && $parentField) {
  6286. $parent = $parentName.':'.$obj->{$parentField};
  6287. $isDependList = 1;
  6288. }
  6289. $out .= '<option value="'.$obj->rowid.'"';
  6290. $out .= ($value == $obj->rowid ? ' selected' : '');
  6291. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6292. $out .= '>'.$labeltoshow.'</option>';
  6293. }
  6294. $i++;
  6295. }
  6296. $this->db->free($resql);
  6297. } else {
  6298. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6299. }
  6300. }
  6301. $out .= '</select>';
  6302. } elseif ($type == 'checkbox') {
  6303. $value_arr = explode(',', $value);
  6304. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, $morecss, 0, '100%');
  6305. } elseif ($type == 'radio') {
  6306. $out = '';
  6307. foreach ($param['options'] as $keyopt => $valopt) {
  6308. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  6309. $out .= ' value="'.$keyopt.'"';
  6310. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  6311. $out .= ($value == $keyopt ? 'checked' : '');
  6312. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$valopt.'</label><br>';
  6313. }
  6314. } elseif ($type == 'chkbxlst') {
  6315. if (is_array($value)) {
  6316. $value_arr = $value;
  6317. } else {
  6318. $value_arr = explode(',', $value);
  6319. }
  6320. if (is_array($param['options'])) {
  6321. $param_list = array_keys($param['options']);
  6322. $InfoFieldList = explode(":", $param_list[0]);
  6323. $parentName = '';
  6324. $parentField = '';
  6325. // 0 : tableName
  6326. // 1 : label field name
  6327. // 2 : key fields name (if differ of rowid)
  6328. // 3 : key field parent (for dependent lists)
  6329. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6330. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6331. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6332. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6333. $keyList .= ', '.$parentField;
  6334. }
  6335. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6336. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6337. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6338. } else {
  6339. $keyList = $InfoFieldList[2].' as rowid';
  6340. }
  6341. }
  6342. $fields_label = explode('|', $InfoFieldList[1]);
  6343. if (is_array($fields_label)) {
  6344. $keyList .= ', ';
  6345. $keyList .= implode(', ', $fields_label);
  6346. }
  6347. $sqlwhere = '';
  6348. $sql = "SELECT ".$keyList;
  6349. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6350. if (!empty($InfoFieldList[4])) {
  6351. // can use SELECT request
  6352. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6353. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6354. }
  6355. // current object id can be use into filter
  6356. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6357. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6358. } else {
  6359. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6360. }
  6361. // We have to join on extrafield table
  6362. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6363. $sql .= ' as main, '.$this->db->prefix().$InfoFieldList[0].'_extrafields as extra';
  6364. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  6365. } else {
  6366. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  6367. }
  6368. } else {
  6369. $sqlwhere .= ' WHERE 1=1';
  6370. }
  6371. // Some tables may have field, some other not. For the moment we disable it.
  6372. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6373. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  6374. }
  6375. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  6376. // print $sql;
  6377. $sql .= $sqlwhere;
  6378. dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
  6379. $resql = $this->db->query($sql);
  6380. if ($resql) {
  6381. $num = $this->db->num_rows($resql);
  6382. $i = 0;
  6383. $data = array();
  6384. while ($i < $num) {
  6385. $labeltoshow = '';
  6386. $obj = $this->db->fetch_object($resql);
  6387. $notrans = false;
  6388. // Several field into label (eq table:code|libelle:rowid)
  6389. $fields_label = explode('|', $InfoFieldList[1]);
  6390. if (count($fields_label) > 1) {
  6391. $notrans = true;
  6392. foreach ($fields_label as $field_toshow) {
  6393. $labeltoshow .= $obj->$field_toshow.' ';
  6394. }
  6395. } else {
  6396. $labeltoshow = $obj->{$InfoFieldList[1]};
  6397. }
  6398. $labeltoshow = dol_trunc($labeltoshow, 45);
  6399. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6400. foreach ($fields_label as $field_toshow) {
  6401. $translabel = $langs->trans($obj->$field_toshow);
  6402. if ($translabel != $obj->$field_toshow) {
  6403. $labeltoshow = dol_trunc($translabel, 18).' ';
  6404. } else {
  6405. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  6406. }
  6407. }
  6408. $data[$obj->rowid] = $labeltoshow;
  6409. } else {
  6410. if (!$notrans) {
  6411. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6412. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6413. $labeltoshow = dol_trunc($translabel, 18);
  6414. } else {
  6415. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  6416. }
  6417. }
  6418. if (empty($labeltoshow)) {
  6419. $labeltoshow = '(not defined)';
  6420. }
  6421. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6422. $data[$obj->rowid] = $labeltoshow;
  6423. }
  6424. if (!empty($InfoFieldList[3]) && $parentField) {
  6425. $parent = $parentName.':'.$obj->{$parentField};
  6426. $isDependList = 1;
  6427. }
  6428. $data[$obj->rowid] = $labeltoshow;
  6429. }
  6430. $i++;
  6431. }
  6432. $this->db->free($resql);
  6433. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
  6434. } else {
  6435. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6436. }
  6437. }
  6438. } elseif ($type == 'link') {
  6439. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
  6440. $param_list_array = explode(':', $param_list[0]);
  6441. $showempty = (($required && $default != '') ? 0 : 1);
  6442. if (!preg_match('/search_/', $keyprefix)) {
  6443. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6444. if (!empty($this->fields[$key]['picto'])) {
  6445. $morecss .= ' widthcentpercentminusxx';
  6446. } else {
  6447. $morecss .= ' widthcentpercentminusx';
  6448. }
  6449. } else {
  6450. if (!empty($this->fields[$key]['picto'])) {
  6451. $morecss .= ' widthcentpercentminusx';
  6452. }
  6453. }
  6454. }
  6455. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  6456. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6457. 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".
  6458. list($class, $classfile) = explode(':', $param_list[0]);
  6459. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
  6460. $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  6461. } else {
  6462. $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  6463. }
  6464. $paramforthenewlink = '';
  6465. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  6466. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  6467. $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin='.GETPOST('origin', 'aZ09') : '');
  6468. $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid='.GETPOST('originid', 'int') : '');
  6469. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  6470. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  6471. $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>';
  6472. }
  6473. }
  6474. } elseif ($type == 'password') {
  6475. // If prefix is 'search_', field is used as a filter, we use a common text field.
  6476. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  6477. } elseif ($type == 'array') {
  6478. $newval = $val;
  6479. $newval['type'] = 'varchar(256)';
  6480. $out = '';
  6481. if (!empty($value)) {
  6482. foreach ($value as $option) {
  6483. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6484. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  6485. }
  6486. }
  6487. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6488. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6489. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  6490. if (!empty($conf->use_javascript_ajax)) {
  6491. $out .= '
  6492. <script>
  6493. $(document).ready(function() {
  6494. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  6495. $("'.dol_escape_js($newInput).'").insertBefore(this);
  6496. });
  6497. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  6498. $(this).parent().remove();
  6499. });
  6500. });
  6501. </script>';
  6502. }
  6503. }
  6504. if (!empty($hidden)) {
  6505. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  6506. }
  6507. if ($isDependList==1) {
  6508. $out .= $this->getJSListDependancies('_common');
  6509. }
  6510. /* Add comments
  6511. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  6512. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  6513. */
  6514. // Display error message for field
  6515. if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
  6516. $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
  6517. }
  6518. return $out;
  6519. }
  6520. /**
  6521. * Return HTML string to show a field into a page
  6522. * Code very similar with showOutputField of extra fields
  6523. *
  6524. * @param array $val Array of properties of field to show
  6525. * @param string $key Key of attribute
  6526. * @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)
  6527. * @param string $moreparam To add more parametes on html input tag
  6528. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6529. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6530. * @param mixed $morecss Value for css to define size. May also be a numeric.
  6531. * @return string
  6532. */
  6533. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  6534. {
  6535. global $conf, $langs, $form;
  6536. if (!is_object($form)) {
  6537. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6538. $form = new Form($this->db);
  6539. }
  6540. $objectid = $this->id; // Not used ???
  6541. $label = empty($val['label']) ? '' : $val['label'];
  6542. $type = empty($val['type']) ? '' : $val['type'];
  6543. $size = empty($val['css']) ? '' : $val['css'];
  6544. $reg = array();
  6545. // Convert var to be able to share same code than showOutputField of extrafields
  6546. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6547. $type = 'varchar'; // convert varchar(xx) int varchar
  6548. $size = $reg[1];
  6549. } elseif (preg_match('/varchar/', $type)) {
  6550. $type = 'varchar'; // convert varchar(xx) int varchar
  6551. }
  6552. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6553. $type = 'select';
  6554. }
  6555. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6556. $type = 'link';
  6557. }
  6558. $default = empty($val['default']) ? '' : $val['default'];
  6559. $computed = empty($val['computed']) ? '' : $val['computed'];
  6560. $unique = empty($val['unique']) ? '' : $val['unique'];
  6561. $required = empty($val['required']) ? '' : $val['required'];
  6562. $param = array();
  6563. $param['options'] = array();
  6564. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6565. $param['options'] = $val['arrayofkeyval'];
  6566. }
  6567. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6568. $type = 'link';
  6569. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6570. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6571. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6572. $type = 'sellist';
  6573. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6574. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6575. $type = 'sellist';
  6576. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6577. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6578. $type = 'sellist';
  6579. }
  6580. $langfile = empty($val['langfile']) ? '' : $val['langfile'];
  6581. $list = (empty($val['list']) ? '' : $val['list']);
  6582. $help = (empty($val['help']) ? '' : $val['help']);
  6583. $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)
  6584. if ($hidden) {
  6585. return '';
  6586. }
  6587. // If field is a computed field, value must become result of compute
  6588. if ($computed) {
  6589. // Make the eval of compute string
  6590. //var_dump($computed);
  6591. $value = dol_eval($computed, 1, 0, '');
  6592. }
  6593. if (empty($morecss)) {
  6594. if ($type == 'date') {
  6595. $morecss = 'minwidth100imp';
  6596. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6597. $morecss = 'minwidth200imp';
  6598. } elseif (in_array($type, array('int', 'double', 'price'))) {
  6599. $morecss = 'maxwidth75';
  6600. } elseif ($type == 'url') {
  6601. $morecss = 'minwidth400';
  6602. } elseif ($type == 'boolean') {
  6603. $morecss = '';
  6604. } else {
  6605. if (is_numeric($size) && round($size) < 12) {
  6606. $morecss = 'minwidth100';
  6607. } elseif (is_numeric($size) && round($size) <= 48) {
  6608. $morecss = 'minwidth200';
  6609. } else {
  6610. $morecss = 'minwidth400';
  6611. }
  6612. }
  6613. }
  6614. // Format output value differently according to properties of field
  6615. if (in_array($key, array('rowid', 'ref')) && method_exists($this, 'getNomUrl')) {
  6616. if ($key != 'rowid' || empty($this->fields['ref'])) { // If we want ref field or if we want ID and there is no ref field, we show the link.
  6617. $value = $this->getNomUrl(1, '', 0, '', 1);
  6618. }
  6619. } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
  6620. $value = $this->getLibStatut(3);
  6621. } elseif ($type == 'date') {
  6622. if (!empty($value)) {
  6623. $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
  6624. } else {
  6625. $value = '';
  6626. }
  6627. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6628. if (!empty($value)) {
  6629. $value = dol_print_date($value, 'dayhour', 'tzuserrel');
  6630. } else {
  6631. $value = '';
  6632. }
  6633. } elseif ($type == 'duration') {
  6634. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6635. if (!is_null($value) && $value !== '') {
  6636. $value = convertSecondToTime($value, 'allhourmin');
  6637. }
  6638. } elseif ($type == 'double' || $type == 'real') {
  6639. if (!is_null($value) && $value !== '') {
  6640. $value = price($value);
  6641. }
  6642. } elseif ($type == 'boolean') {
  6643. $checked = '';
  6644. if (!empty($value)) {
  6645. $checked = ' checked ';
  6646. }
  6647. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  6648. } elseif ($type == 'mail' || $type == 'email') {
  6649. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  6650. } elseif ($type == 'url') {
  6651. $value = dol_print_url($value, '_blank', 32, 1);
  6652. } elseif ($type == 'phone') {
  6653. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 'phone');
  6654. } elseif ($type == 'price') {
  6655. if (!is_null($value) && $value !== '') {
  6656. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  6657. }
  6658. } elseif ($type == 'select') {
  6659. $value = isset($param['options'][$value])?$param['options'][$value]:'';
  6660. } elseif ($type == 'sellist') {
  6661. $param_list = array_keys($param['options']);
  6662. $InfoFieldList = explode(":", $param_list[0]);
  6663. $selectkey = "rowid";
  6664. $keyList = 'rowid';
  6665. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6666. $selectkey = $InfoFieldList[2];
  6667. $keyList = $InfoFieldList[2].' as rowid';
  6668. }
  6669. $fields_label = explode('|', $InfoFieldList[1]);
  6670. if (is_array($fields_label)) {
  6671. $keyList .= ', ';
  6672. $keyList .= implode(', ', $fields_label);
  6673. }
  6674. $sql = "SELECT ".$keyList;
  6675. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6676. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6677. $sql .= ' as main';
  6678. }
  6679. if ($selectkey == 'rowid' && empty($value)) {
  6680. $sql .= " WHERE ".$selectkey." = 0";
  6681. } elseif ($selectkey == 'rowid') {
  6682. $sql .= " WHERE ".$selectkey." = ".((int) $value);
  6683. } else {
  6684. $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
  6685. }
  6686. //$sql.= ' AND entity = '.$conf->entity;
  6687. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  6688. $resql = $this->db->query($sql);
  6689. if ($resql) {
  6690. $value = ''; // value was used, so now we reste it to use it to build final output
  6691. $numrows = $this->db->num_rows($resql);
  6692. if ($numrows) {
  6693. $obj = $this->db->fetch_object($resql);
  6694. // Several field into label (eq table:code|libelle:rowid)
  6695. $fields_label = explode('|', $InfoFieldList[1]);
  6696. if (is_array($fields_label) && count($fields_label) > 1) {
  6697. foreach ($fields_label as $field_toshow) {
  6698. $translabel = '';
  6699. if (!empty($obj->$field_toshow)) {
  6700. $translabel = $langs->trans($obj->$field_toshow);
  6701. }
  6702. if ($translabel != $field_toshow) {
  6703. $value .= dol_trunc($translabel, 18).' ';
  6704. } else {
  6705. $value .= $obj->$field_toshow.' ';
  6706. }
  6707. }
  6708. } else {
  6709. $translabel = '';
  6710. if (!empty($obj->{$InfoFieldList[1]})) {
  6711. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6712. }
  6713. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6714. $value = dol_trunc($translabel, 18);
  6715. } else {
  6716. $value = $obj->{$InfoFieldList[1]};
  6717. }
  6718. }
  6719. }
  6720. } else {
  6721. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6722. }
  6723. } elseif ($type == 'radio') {
  6724. $value = $param['options'][$value];
  6725. } elseif ($type == 'checkbox') {
  6726. $value_arr = explode(',', $value);
  6727. $value = '';
  6728. if (is_array($value_arr) && count($value_arr) > 0) {
  6729. $toprint = array();
  6730. foreach ($value_arr as $keyval => $valueval) {
  6731. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  6732. }
  6733. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6734. }
  6735. } elseif ($type == 'chkbxlst') {
  6736. $value_arr = explode(',', $value);
  6737. $param_list = array_keys($param['options']);
  6738. $InfoFieldList = explode(":", $param_list[0]);
  6739. $selectkey = "rowid";
  6740. $keyList = 'rowid';
  6741. if (count($InfoFieldList) >= 3) {
  6742. $selectkey = $InfoFieldList[2];
  6743. $keyList = $InfoFieldList[2].' as rowid';
  6744. }
  6745. $fields_label = explode('|', $InfoFieldList[1]);
  6746. if (is_array($fields_label)) {
  6747. $keyList .= ', ';
  6748. $keyList .= implode(', ', $fields_label);
  6749. }
  6750. $sql = "SELECT ".$keyList;
  6751. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6752. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6753. $sql .= ' as main';
  6754. }
  6755. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  6756. // $sql.= ' AND entity = '.$conf->entity;
  6757. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  6758. $resql = $this->db->query($sql);
  6759. if ($resql) {
  6760. $value = ''; // value was used, so now we reste it to use it to build final output
  6761. $toprint = array();
  6762. while ($obj = $this->db->fetch_object($resql)) {
  6763. // Several field into label (eq table:code|libelle:rowid)
  6764. $fields_label = explode('|', $InfoFieldList[1]);
  6765. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6766. if (is_array($fields_label) && count($fields_label) > 1) {
  6767. foreach ($fields_label as $field_toshow) {
  6768. $translabel = '';
  6769. if (!empty($obj->$field_toshow)) {
  6770. $translabel = $langs->trans($obj->$field_toshow);
  6771. }
  6772. if ($translabel != $field_toshow) {
  6773. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6774. } else {
  6775. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->$field_toshow.'</li>';
  6776. }
  6777. }
  6778. } else {
  6779. $translabel = '';
  6780. if (!empty($obj->{$InfoFieldList[1]})) {
  6781. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6782. }
  6783. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6784. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6785. } else {
  6786. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->{$InfoFieldList[1]}.'</li>';
  6787. }
  6788. }
  6789. }
  6790. }
  6791. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6792. } else {
  6793. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6794. }
  6795. } elseif ($type == 'link') {
  6796. $out = '';
  6797. // only if something to display (perf)
  6798. if ($value) {
  6799. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6800. $InfoFieldList = explode(":", $param_list[0]);
  6801. $classname = $InfoFieldList[0];
  6802. $classpath = $InfoFieldList[1];
  6803. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  6804. $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
  6805. if (!empty($classpath)) {
  6806. dol_include_once($InfoFieldList[1]);
  6807. if ($classname && class_exists($classname)) {
  6808. $object = new $classname($this->db);
  6809. if ($object->element === 'product') { // Special cas for product because default valut of fetch are wrong
  6810. $result = $object->fetch($value, '', '', '', 0, 1, 1);
  6811. } else {
  6812. $result = $object->fetch($value);
  6813. }
  6814. if ($result > 0) {
  6815. $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
  6816. } else {
  6817. $value = '';
  6818. }
  6819. }
  6820. } else {
  6821. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  6822. return 'Error bad setup of extrafield';
  6823. }
  6824. } else {
  6825. $value = '';
  6826. }
  6827. } elseif ($type == 'password') {
  6828. $value = preg_replace('/./i', '*', $value);
  6829. } elseif ($type == 'array') {
  6830. $value = implode('<br>', $value);
  6831. } else { // text|html|varchar
  6832. $value = dol_htmlentitiesbr($value);
  6833. }
  6834. //print $type.'-'.$size.'-'.$value;
  6835. $out = $value;
  6836. return $out;
  6837. }
  6838. /**
  6839. * clear validation message result for a field
  6840. *
  6841. * @param string $fieldKey Key of attribute to clear
  6842. * @return null
  6843. */
  6844. public function clearFieldError($fieldKey)
  6845. {
  6846. $this->error = '';
  6847. unset($this->validateFieldsErrors[$fieldKey]);
  6848. }
  6849. /**
  6850. * set validation error message a field
  6851. *
  6852. * @param string $fieldKey Key of attribute
  6853. * @param string $msg the field error message
  6854. * @return null
  6855. */
  6856. public function setFieldError($fieldKey, $msg = '')
  6857. {
  6858. global $langs;
  6859. if (empty($msg)) { $msg = $langs->trans("UnknowError"); }
  6860. $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
  6861. }
  6862. /**
  6863. * get field error message
  6864. *
  6865. * @param string $fieldKey Key of attribute
  6866. * @return string
  6867. */
  6868. public function getFieldError($fieldKey)
  6869. {
  6870. if (!empty($this->validateFieldsErrors[$fieldKey])) {
  6871. return $this->validateFieldsErrors[$fieldKey];
  6872. }
  6873. return '';
  6874. }
  6875. /**
  6876. * Return validation test result for a field
  6877. *
  6878. * @param array $val Array of properties of field to show
  6879. * @param string $fieldKey Key of attribute
  6880. * @param string $fieldValue value of attribute
  6881. * @return bool return false if fail true on success, see $this->error for error message
  6882. */
  6883. public function validateField($val, $fieldKey, $fieldValue)
  6884. {
  6885. global $langs;
  6886. if (!class_exists('Validate')) { require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php'; }
  6887. $this->clearFieldError($fieldKey);
  6888. if (!isset($val[$fieldKey])) {
  6889. $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
  6890. return false;
  6891. }
  6892. $param = array();
  6893. $param['options'] = array();
  6894. $type = $val[$fieldKey]['type'];
  6895. $required = false;
  6896. if (isset($val[$fieldKey]['notnull']) && $val[$fieldKey]['notnull'] === 1) {
  6897. // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  6898. $required = true;
  6899. }
  6900. $maxSize = 0;
  6901. $minSize = 0;
  6902. //
  6903. // PREPARE Elements
  6904. //
  6905. // Convert var to be able to share same code than showOutputField of extrafields
  6906. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6907. $type = 'varchar'; // convert varchar(xx) int varchar
  6908. $maxSize = $reg[1];
  6909. } elseif (preg_match('/varchar/', $type)) {
  6910. $type = 'varchar'; // convert varchar(xx) int varchar
  6911. }
  6912. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6913. $type = 'select';
  6914. }
  6915. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6916. $type = 'link';
  6917. }
  6918. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6919. $param['options'] = $val['arrayofkeyval'];
  6920. }
  6921. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6922. $type = 'link';
  6923. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6924. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6925. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6926. $type = 'sellist';
  6927. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6928. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6929. $type = 'sellist';
  6930. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6931. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6932. $type = 'sellist';
  6933. }
  6934. //
  6935. // TEST Value
  6936. //
  6937. // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
  6938. $validate = new Validate($this->db, $langs);
  6939. // little trick : to perform tests with good performances sort tests by quick to low
  6940. //
  6941. // COMMON TESTS
  6942. //
  6943. // Required test and empty value
  6944. if ($required && !$validate->isNotEmptyString($fieldValue)) {
  6945. $this->setFieldError($fieldKey, $validate->error);
  6946. return false;
  6947. } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
  6948. // if no value sent and the field is not mandatory, no need to perform tests
  6949. return true;
  6950. }
  6951. // MAX Size test
  6952. if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
  6953. $this->setFieldError($fieldKey, $validate->error);
  6954. return false;
  6955. }
  6956. // MIN Size test
  6957. if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
  6958. $this->setFieldError($fieldKey, $validate->error);
  6959. return false;
  6960. }
  6961. //
  6962. // TESTS for TYPE
  6963. //
  6964. if (in_array($type, array('date', 'datetime', 'timestamp'))) {
  6965. if (!$validate->isTimestamp($fieldValue)) {
  6966. $this->setFieldError($fieldKey, $validate->error);
  6967. return false;
  6968. } else { return true; }
  6969. } elseif ($type == 'duration') {
  6970. if (!$validate->isDuration($fieldValue)) {
  6971. $this->setFieldError($fieldKey, $validate->error);
  6972. return false;
  6973. } else { return true; }
  6974. } elseif (in_array($type, array('double', 'real', 'price'))) {
  6975. // is numeric
  6976. if (!$validate->isNumeric($fieldValue)) {
  6977. $this->setFieldError($fieldKey, $validate->error);
  6978. return false;
  6979. } else { return true; }
  6980. } elseif ($type == 'boolean') {
  6981. if (!$validate->isBool($fieldValue)) {
  6982. $this->setFieldError($fieldKey, $validate->error);
  6983. return false;
  6984. } else { return true; }
  6985. } elseif ($type == 'mail') {
  6986. if (!$validate->isEmail($fieldValue)) {
  6987. $this->setFieldError($fieldKey, $validate->error);
  6988. return false;
  6989. }
  6990. } elseif ($type == 'url') {
  6991. if (!$validate->isUrl($fieldValue)) {
  6992. $this->setFieldError($fieldKey, $validate->error);
  6993. return false;
  6994. } else { return true; }
  6995. } elseif ($type == 'phone') {
  6996. if (!$validate->isPhone($fieldValue)) {
  6997. $this->setFieldError($fieldKey, $validate->error);
  6998. return false;
  6999. } else { return true; }
  7000. } elseif ($type == 'select' || $type == 'radio') {
  7001. if (!isset($param['options'][$fieldValue])) {
  7002. $this->error = $langs->trans('RequireValidValue');
  7003. return false;
  7004. } else { return true; }
  7005. } elseif ($type == 'sellist' || $type == 'chkbxlst') {
  7006. $param_list = array_keys($param['options']);
  7007. $InfoFieldList = explode(":", $param_list[0]);
  7008. $value_arr = explode(',', $fieldValue);
  7009. $value_arr = array_map(array($this->db, 'escape'), $value_arr);
  7010. $selectkey = "rowid";
  7011. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  7012. $selectkey = $InfoFieldList[2];
  7013. }
  7014. if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
  7015. $this->setFieldError($fieldKey, $validate->error);
  7016. return false;
  7017. } else { return true; }
  7018. } elseif ($type == 'link') {
  7019. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  7020. $InfoFieldList = explode(":", $param_list[0]);
  7021. $classname = $InfoFieldList[0];
  7022. $classpath = $InfoFieldList[1];
  7023. if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
  7024. $this->setFieldError($fieldKey, $validate->error);
  7025. return false;
  7026. } else { return true; }
  7027. }
  7028. // if no test failled all is ok
  7029. return true;
  7030. }
  7031. /**
  7032. * Function to show lines of extrafields with output datas.
  7033. * 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
  7034. *
  7035. * @param Extrafields $extrafields Extrafield Object
  7036. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  7037. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  7038. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  7039. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  7040. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  7041. * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...)
  7042. * @return string String with html content to show
  7043. */
  7044. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
  7045. {
  7046. global $db, $conf, $langs, $action, $form, $hookmanager;
  7047. if (!is_object($form)) {
  7048. $form = new Form($db);
  7049. }
  7050. if (!is_object($extrafields)) {
  7051. dol_syslog('Bad parameter extrafields for showOptionals', LOG_ERR);
  7052. return 'Bad parameter extrafields for showOptionals';
  7053. }
  7054. if (!is_array($extrafields->attributes[$this->table_element])) {
  7055. dol_syslog("extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
  7056. }
  7057. $out = '';
  7058. $parameters = array();
  7059. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  7060. if (empty($reshook)) {
  7061. if (is_array($extrafields->attributes[$this->table_element]) && key_exists('label', $extrafields->attributes[$this->table_element]) && is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0) {
  7062. $out .= "\n";
  7063. $out .= '<!-- commonobject:showOptionals --> ';
  7064. $out .= "\n";
  7065. $extrafields_collapse_num = '';
  7066. $e = 0;
  7067. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
  7068. // Show only the key field in params
  7069. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
  7070. continue;
  7071. }
  7072. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  7073. $enabled = 1;
  7074. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  7075. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '1');
  7076. }
  7077. if (empty($enabled)) {
  7078. continue;
  7079. }
  7080. $visibility = 1;
  7081. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  7082. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '1');
  7083. }
  7084. $perms = 1;
  7085. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  7086. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '1');
  7087. }
  7088. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
  7089. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  7090. } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
  7091. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  7092. } elseif ($mode == 'view' && empty($visibility)) {
  7093. continue;
  7094. }
  7095. if (empty($perms)) {
  7096. continue;
  7097. }
  7098. // Load language if required
  7099. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  7100. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  7101. }
  7102. $colspan = 0;
  7103. if (is_array($params) && count($params) > 0 && $display_type=='card') {
  7104. if (array_key_exists('cols', $params)) {
  7105. $colspan = $params['cols'];
  7106. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  7107. $reg = array();
  7108. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  7109. $colspan = $reg[1];
  7110. } else {
  7111. $colspan = $params['colspan'];
  7112. }
  7113. }
  7114. }
  7115. $colspan = intval($colspan);
  7116. switch ($mode) {
  7117. case "view":
  7118. $value = ((!empty($this->array_options) && array_key_exists("options_".$key.$keysuffix, $this->array_options)) ? $this->array_options["options_".$key.$keysuffix] : null); // Value may be cleaned or formated later
  7119. break;
  7120. case "create":
  7121. case "edit":
  7122. // We get the value of property found with GETPOST so it takes into account:
  7123. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  7124. $check = 'alphanohtml';
  7125. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  7126. $check = 'restricthtml';
  7127. }
  7128. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  7129. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  7130. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
  7131. if (is_array($getposttemp)) {
  7132. // $getposttemp is an array but following code expects a comma separated string
  7133. $value = implode(",", $getposttemp);
  7134. } else {
  7135. $value = $getposttemp;
  7136. }
  7137. } else {
  7138. $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.
  7139. }
  7140. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  7141. break;
  7142. }
  7143. // Output value of the current field
  7144. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  7145. $extrafields_collapse_num = '';
  7146. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  7147. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  7148. $extrafield_param_list = array_keys($extrafield_param['options']);
  7149. if (count($extrafield_param_list) > 0) {
  7150. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  7151. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  7152. $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  7153. }
  7154. }
  7155. }
  7156. // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
  7157. $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
  7158. } else {
  7159. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  7160. $csstyle = '';
  7161. if (is_array($params) && count($params) > 0) {
  7162. if (array_key_exists('class', $params)) {
  7163. $class .= $params['class'].' ';
  7164. }
  7165. if (array_key_exists('style', $params)) {
  7166. $csstyle = $params['style'];
  7167. }
  7168. }
  7169. // add html5 elements
  7170. $domData = ' data-element="extrafield"';
  7171. $domData .= ' data-targetelement="'.$this->element.'"';
  7172. $domData .= ' data-targetid="'.$this->id.'"';
  7173. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  7174. if ($display_type=='card') {
  7175. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
  7176. $colspan = 0;
  7177. }
  7178. if ($action == 'selectlines') {
  7179. $colspan++;
  7180. }
  7181. }
  7182. // Convert date into timestamp format (value in memory must be a timestamp)
  7183. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
  7184. $datenotinstring = null;
  7185. if (array_key_exists('options_'.$key, $this->array_options)) {
  7186. $datenotinstring = $this->array_options['options_'.$key];
  7187. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7188. $datenotinstring = $this->db->jdate($datenotinstring);
  7189. }
  7190. }
  7191. $datekey = $keyprefix.'options_'.$key.$keysuffix;
  7192. $value = (GETPOSTISSET($datekey)) ? dol_mktime(12, 0, 0, GETPOST($datekey.'month', 'int', 3), GETPOST($datekey.'day', 'int', 3), GETPOST($datekey.'year', 'int', 3)) : $datenotinstring;
  7193. }
  7194. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
  7195. $datenotinstring = null;
  7196. if (array_key_exists('options_'.$key, $this->array_options)) {
  7197. $datenotinstring = $this->array_options['options_'.$key];
  7198. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7199. $datenotinstring = $this->db->jdate($datenotinstring);
  7200. }
  7201. }
  7202. $timekey = $keyprefix.'options_'.$key.$keysuffix;
  7203. $value = (GETPOSTISSET($timekey)) ? dol_mktime(GETPOST($timekey.'hour', 'int', 3), GETPOST($timekey.'min', 'int', 3), GETPOST($timekey.'sec', 'int', 3), GETPOST($timekey.'month', 'int', 3), GETPOST($timekey.'day', 'int', 3), GETPOST($timekey.'year', 'int', 3), 'tzuserrel') : $datenotinstring;
  7204. }
  7205. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  7206. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
  7207. if (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) {
  7208. $value = price2num($value);
  7209. } elseif (isset($this->array_options['options_'.$key])) {
  7210. $value = $this->array_options['options_'.$key];
  7211. }
  7212. }
  7213. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  7214. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int', 'boolean'))) {
  7215. if ($action == 'create') {
  7216. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  7217. }
  7218. }
  7219. $labeltoshow = $langs->trans($label);
  7220. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  7221. if ($display_type == 'card') {
  7222. $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="field_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >';
  7223. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action == 'view' || $action == 'valid' || $action == 'editline')) {
  7224. $out .= '<td></td>';
  7225. }
  7226. $out .= '<td class="titlefieldcreate wordbreak';
  7227. } elseif ($display_type == 'line') {
  7228. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="fieldline_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >';
  7229. $out .= '<div style="display: inline-block; padding-right:4px" class="titlefieldcreate wordbreak';
  7230. }
  7231. //$out .= "titlefield";
  7232. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  7233. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  7234. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  7235. if ($tpl_context != "public") { // Public page : red dot instead of fieldrequired characters
  7236. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7237. $out .= ' fieldrequired';
  7238. }
  7239. }
  7240. $out .= '">';
  7241. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  7242. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7243. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7244. } else {
  7245. $out .= $labeltoshow;
  7246. }
  7247. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7248. $out .= '&nbsp;<span style="color: red">*</span>';
  7249. }
  7250. } else {
  7251. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7252. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7253. } else {
  7254. $out .= $labeltoshow;
  7255. }
  7256. }
  7257. $out .= ($display_type == 'card' ? '</td>' : '</div>');
  7258. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  7259. if ($display_type == 'card') {
  7260. // 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
  7261. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="valuefieldcreate '.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  7262. } elseif ($display_type == 'line') {
  7263. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').' style="display: inline-block" class="valuefieldcreate '.$this->element.'_extras_'.$key.' extra_inline_'.$extrafields->attributes[$this->table_element]['type'][$key].'">';
  7264. }
  7265. switch ($mode) {
  7266. case "view":
  7267. $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
  7268. break;
  7269. case "create":
  7270. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7271. break;
  7272. case "edit":
  7273. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7274. break;
  7275. }
  7276. $out .= ($display_type=='card' ? '</td>' : '</div>');
  7277. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
  7278. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7279. } else {
  7280. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7281. }
  7282. $e++;
  7283. }
  7284. }
  7285. $out .= "\n";
  7286. // Add code to manage list depending on others
  7287. if (!empty($conf->use_javascript_ajax)) {
  7288. $out .= $this->getJSListDependancies();
  7289. }
  7290. $out .= '<!-- commonobject:showOptionals end --> '."\n";
  7291. }
  7292. }
  7293. $out .= $hookmanager->resPrint;
  7294. return $out;
  7295. }
  7296. /**
  7297. * @param string $type Type for prefix
  7298. * @return string Javacript code to manage dependency
  7299. */
  7300. public function getJSListDependancies($type = '_extra')
  7301. {
  7302. $out = '
  7303. <script>
  7304. jQuery(document).ready(function() {
  7305. function showOptions'.$type.'(child_list, parent_list, orig_select)
  7306. {
  7307. var val = $("select[name=\""+parent_list+"\"]").val();
  7308. var parentVal = parent_list + ":" + val;
  7309. if(typeof val == "string"){
  7310. if(val != "") {
  7311. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7312. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7313. $("select[name=\""+child_list+"\"]").append(options);
  7314. } else {
  7315. var options = orig_select.find("option[parent]").clone();
  7316. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7317. $("select[name=\""+child_list+"\"]").append(options);
  7318. }
  7319. } else if(val > 0) {
  7320. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7321. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7322. $("select[name=\""+child_list+"\"]").append(options);
  7323. } else {
  7324. var options = orig_select.find("option[parent]").clone();
  7325. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7326. $("select[name=\""+child_list+"\"]").append(options);
  7327. }
  7328. }
  7329. function setListDependencies'.$type.'() {
  7330. jQuery("select option[parent]").parent().each(function() {
  7331. var orig_select = {};
  7332. var child_list = $(this).attr("name");
  7333. orig_select[child_list] = $(this).clone();
  7334. var parent = $(this).find("option[parent]:first").attr("parent");
  7335. var infos = parent.split(":");
  7336. var parent_list = infos[0];
  7337. //Hide daughters lists
  7338. if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
  7339. $("#"+child_list).hide();
  7340. //Show mother lists
  7341. } else if ($("#"+parent_list).val() != 0){
  7342. $("#"+parent_list).show();
  7343. }
  7344. //Show the child list if the parent list value is selected
  7345. $("select[name=\""+parent_list+"\"]").click(function() {
  7346. if ($(this).val() != 0){
  7347. $("#"+child_list).show()
  7348. }
  7349. });
  7350. //When we change parent list
  7351. $("select[name=\""+parent_list+"\"]").change(function() {
  7352. showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
  7353. //Select the value 0 on child list after a change on the parent list
  7354. $("#"+child_list).val(0).trigger("change");
  7355. //Hide child lists if the parent value is set to 0
  7356. if ($(this).val() == 0){
  7357. $("#"+child_list).hide();
  7358. }
  7359. });
  7360. });
  7361. }
  7362. setListDependencies'.$type.'();
  7363. });
  7364. </script>'."\n";
  7365. return $out;
  7366. }
  7367. /**
  7368. * Returns the rights used for this class
  7369. * @return stdClass
  7370. */
  7371. public function getRights()
  7372. {
  7373. global $user;
  7374. $element = $this->element;
  7375. if ($element == 'facturerec') {
  7376. $element = 'facture';
  7377. } elseif ($element == 'invoice_supplier_rec') {
  7378. return $user->rights->fournisseur->facture;
  7379. }
  7380. return $user->rights->{$element};
  7381. }
  7382. /**
  7383. * Function used to replace a thirdparty id with another one.
  7384. * This function is meant to be called from replaceThirdparty with the appropriate tables
  7385. * Column name fk_soc MUST be used to identify thirdparties
  7386. *
  7387. * @param DoliDB $db Database handler
  7388. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  7389. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  7390. * @param string[] $tables Tables that need to be changed
  7391. * @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)
  7392. * @return bool True if success, False if error
  7393. */
  7394. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7395. {
  7396. foreach ($tables as $table) {
  7397. $sql = 'UPDATE '.$db->prefix().$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
  7398. if (!$db->query($sql)) {
  7399. if ($ignoreerrors) {
  7400. 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.
  7401. }
  7402. //$this->errors = $db->lasterror();
  7403. return false;
  7404. }
  7405. }
  7406. return true;
  7407. }
  7408. /**
  7409. * Function used to replace a product id with another one.
  7410. * This function is meant to be called from replaceProduct with the appropriate tables
  7411. * Column name fk_product MUST be used to identify products
  7412. *
  7413. * @param DoliDB $db Database handler
  7414. * @param int $origin_id Old product id (the product to delete)
  7415. * @param int $dest_id New product id (the product that will received element of the other)
  7416. * @param string[] $tables Tables that need to be changed
  7417. * @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)
  7418. * @return bool True if success, False if error
  7419. */
  7420. public static function commonReplaceProduct(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7421. {
  7422. foreach ($tables as $table) {
  7423. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_product = '.((int) $dest_id).' WHERE fk_product = '.((int) $origin_id);
  7424. if (!$db->query($sql)) {
  7425. if ($ignoreerrors) {
  7426. 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.
  7427. }
  7428. //$this->errors = $db->lasterror();
  7429. return false;
  7430. }
  7431. }
  7432. return true;
  7433. }
  7434. /**
  7435. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  7436. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  7437. * elseif calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  7438. * elseif calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  7439. * else set min buy price as buy price
  7440. *
  7441. * @param float $unitPrice Product unit price
  7442. * @param float $discountPercent Line discount percent
  7443. * @param int $fk_product Product id
  7444. * @return float <0 if KO, buyprice if OK
  7445. */
  7446. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  7447. {
  7448. global $conf;
  7449. $buyPrice = 0;
  7450. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
  7451. // When ForceBuyingPriceIfNull is set
  7452. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  7453. } else {
  7454. // Get cost price for margin calculation
  7455. if (!empty($fk_product) && $fk_product > 0) {
  7456. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
  7457. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7458. $product = new Product($this->db);
  7459. $result = $product->fetch($fk_product);
  7460. if ($result <= 0) {
  7461. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7462. return -1;
  7463. }
  7464. if ($product->cost_price > 0) {
  7465. $buyPrice = $product->cost_price;
  7466. } elseif ($product->pmp > 0) {
  7467. $buyPrice = $product->pmp;
  7468. }
  7469. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
  7470. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7471. $product = new Product($this->db);
  7472. $result = $product->fetch($fk_product);
  7473. if ($result <= 0) {
  7474. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7475. return -1;
  7476. }
  7477. if ($product->pmp > 0) {
  7478. $buyPrice = $product->pmp;
  7479. }
  7480. }
  7481. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
  7482. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  7483. $productFournisseur = new ProductFournisseur($this->db);
  7484. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
  7485. $buyPrice = $productFournisseur->fourn_unitprice;
  7486. } elseif ($result < 0) {
  7487. $this->errors[] = $productFournisseur->error;
  7488. return -2;
  7489. }
  7490. }
  7491. }
  7492. }
  7493. return $buyPrice;
  7494. }
  7495. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7496. /**
  7497. * Show photos of an object (nbmax maximum), into several columns
  7498. *
  7499. * @param string $modulepart 'product', 'ticket', ...
  7500. * @param string $sdir Directory to scan (full absolute path)
  7501. * @param int $size 0=original size, 1='small' use thumbnail if possible
  7502. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  7503. * @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'.
  7504. * @param int $showfilename 1=Show filename
  7505. * @param int $showaction 1=Show icon with action links (resize, delete)
  7506. * @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.
  7507. * @param int $maxWidth Max width of original image when size='small'
  7508. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  7509. * @param int $notitle Do not add title tag on image
  7510. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  7511. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  7512. */
  7513. 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)
  7514. {
  7515. // phpcs:enable
  7516. global $conf, $user, $langs;
  7517. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7518. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  7519. $sortfield = 'position_name';
  7520. $sortorder = 'asc';
  7521. $dir = $sdir.'/';
  7522. $pdir = '/';
  7523. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7524. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7525. // For backward compatibility
  7526. if ($modulepart == 'product') {
  7527. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  7528. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7529. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7530. }
  7531. }
  7532. // Defined relative dir to DOL_DATA_ROOT
  7533. $relativedir = '';
  7534. if ($dir) {
  7535. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  7536. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  7537. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  7538. }
  7539. $dirthumb = $dir.'thumbs/';
  7540. $pdirthumb = $pdir.'thumbs/';
  7541. $return = '<!-- Photo -->'."\n";
  7542. $nbphoto = 0;
  7543. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  7544. /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
  7545. {
  7546. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  7547. $filearray=array_merge($filearray, $filearrayold);
  7548. }*/
  7549. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  7550. if (count($filearray)) {
  7551. if ($sortfield && $sortorder) {
  7552. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  7553. }
  7554. foreach ($filearray as $key => $val) {
  7555. $photo = '';
  7556. $file = $val['name'];
  7557. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  7558. if (image_format_supported($file) >= 0) {
  7559. $nbphoto++;
  7560. $photo = $file;
  7561. $viewfilename = $file;
  7562. if ($size == 1 || $size == 'small') { // Format vignette
  7563. // Find name of thumb file
  7564. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  7565. if (!dol_is_file($dirthumb.$photo_vignette)) {
  7566. $photo_vignette = '';
  7567. }
  7568. // Get filesize of original file
  7569. $imgarray = dol_getImageSize($dir.$photo);
  7570. if ($nbbyrow > 0) {
  7571. if ($nbphoto == 1) {
  7572. $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  7573. }
  7574. if ($nbphoto % $nbbyrow == 1) {
  7575. $return .= '<tr class="center valignmiddle" style="border: 1px">';
  7576. }
  7577. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
  7578. } elseif ($nbbyrow < 0) {
  7579. $return .= '<div class="inline-block">';
  7580. }
  7581. $return .= "\n";
  7582. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  7583. if (empty($nolink)) {
  7584. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  7585. if ($urladvanced) {
  7586. $return .= '<a href="'.$urladvanced.'">';
  7587. } else {
  7588. $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
  7589. }
  7590. }
  7591. // Show image (width height=$maxHeight)
  7592. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  7593. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  7594. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  7595. if ($notitle) {
  7596. $alt = '';
  7597. }
  7598. $addphotorefcss = 1;
  7599. if ($usesharelink) {
  7600. if ($val['share']) {
  7601. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7602. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  7603. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7604. } else {
  7605. $return .= '<!-- Show original file -->';
  7606. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7607. }
  7608. } else {
  7609. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  7610. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  7611. }
  7612. } else {
  7613. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7614. $return .= '<!-- Show thumb -->';
  7615. $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).'">';
  7616. } else {
  7617. $return .= '<!-- Show original file -->';
  7618. $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).'">';
  7619. }
  7620. }
  7621. if (empty($nolink)) {
  7622. $return .= '</a>';
  7623. }
  7624. $return .= "\n";
  7625. if ($showfilename) {
  7626. $return .= '<br>'.$viewfilename;
  7627. }
  7628. if ($showaction) {
  7629. $return .= '<br>';
  7630. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  7631. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
  7632. $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>';
  7633. }
  7634. // Special cas for product
  7635. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7636. // Link to resize
  7637. $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; ';
  7638. // Link to delete
  7639. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7640. $return .= img_delete().'</a>';
  7641. }
  7642. }
  7643. $return .= "\n";
  7644. if ($nbbyrow > 0) {
  7645. $return .= '</td>';
  7646. if (($nbphoto % $nbbyrow) == 0) {
  7647. $return .= '</tr>';
  7648. }
  7649. } elseif ($nbbyrow < 0) {
  7650. $return .= '</div>';
  7651. }
  7652. }
  7653. if (empty($size)) { // Format origine
  7654. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  7655. if ($showfilename) {
  7656. $return .= '<br>'.$viewfilename;
  7657. }
  7658. if ($showaction) {
  7659. // Special case for product
  7660. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7661. // Link to resize
  7662. $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; ';
  7663. // Link to delete
  7664. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7665. $return .= img_delete().'</a>';
  7666. }
  7667. }
  7668. }
  7669. // On continue ou on arrete de boucler ?
  7670. if ($nbmax && $nbphoto >= $nbmax) {
  7671. break;
  7672. }
  7673. }
  7674. }
  7675. if ($size == 1 || $size == 'small') {
  7676. if ($nbbyrow > 0) {
  7677. // Ferme tableau
  7678. while ($nbphoto % $nbbyrow) {
  7679. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  7680. $nbphoto++;
  7681. }
  7682. if ($nbphoto) {
  7683. $return .= '</table>';
  7684. }
  7685. }
  7686. }
  7687. }
  7688. $this->nbphoto = $nbphoto;
  7689. return $return;
  7690. }
  7691. /**
  7692. * Function test if type is array
  7693. *
  7694. * @param array $info content informations of field
  7695. * @return bool true if array
  7696. */
  7697. protected function isArray($info)
  7698. {
  7699. if (is_array($info)) {
  7700. if (isset($info['type']) && $info['type'] == 'array') {
  7701. return true;
  7702. } else {
  7703. return false;
  7704. }
  7705. }
  7706. return false;
  7707. }
  7708. /**
  7709. * Function test if type is date
  7710. *
  7711. * @param array $info content informations of field
  7712. * @return bool true if date
  7713. */
  7714. public function isDate($info)
  7715. {
  7716. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
  7717. return true;
  7718. }
  7719. return false;
  7720. }
  7721. /**
  7722. * Function test if type is duration
  7723. *
  7724. * @param array $info content informations of field
  7725. * @return bool true if field of type duration
  7726. */
  7727. public function isDuration($info)
  7728. {
  7729. if (is_array($info)) {
  7730. if (isset($info['type']) && ($info['type'] == 'duration')) {
  7731. return true;
  7732. } else {
  7733. return false;
  7734. }
  7735. } else {
  7736. return false;
  7737. }
  7738. }
  7739. /**
  7740. * Function test if type is integer
  7741. *
  7742. * @param array $info content informations of field
  7743. * @return bool true if integer
  7744. */
  7745. public function isInt($info)
  7746. {
  7747. if (is_array($info)) {
  7748. if (isset($info['type']) && (preg_match('/(^int|int$)/i', $info['type']))) {
  7749. return true;
  7750. } else {
  7751. return false;
  7752. }
  7753. } else {
  7754. return false;
  7755. }
  7756. }
  7757. /**
  7758. * Function test if type is float
  7759. *
  7760. * @param array $info content informations of field
  7761. * @return bool true if float
  7762. */
  7763. public function isFloat($info)
  7764. {
  7765. if (is_array($info)) {
  7766. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
  7767. return true;
  7768. } else {
  7769. return false;
  7770. }
  7771. }
  7772. return false;
  7773. }
  7774. /**
  7775. * Function test if type is text
  7776. *
  7777. * @param array $info content informations of field
  7778. * @return bool true if type text
  7779. */
  7780. public function isText($info)
  7781. {
  7782. if (is_array($info)) {
  7783. if (isset($info['type']) && $info['type'] == 'text') {
  7784. return true;
  7785. } else {
  7786. return false;
  7787. }
  7788. }
  7789. return false;
  7790. }
  7791. /**
  7792. * Function test if field can be null
  7793. *
  7794. * @param array $info content informations of field
  7795. * @return bool true if it can be null
  7796. */
  7797. protected function canBeNull($info)
  7798. {
  7799. if (is_array($info)) {
  7800. if (isset($info['notnull']) && $info['notnull'] != '1') {
  7801. return true;
  7802. } else {
  7803. return false;
  7804. }
  7805. }
  7806. return true;
  7807. }
  7808. /**
  7809. * Function test if field is forced to null if zero or empty
  7810. *
  7811. * @param array $info content informations of field
  7812. * @return bool true if forced to null
  7813. */
  7814. protected function isForcedToNullIfZero($info)
  7815. {
  7816. if (is_array($info)) {
  7817. if (isset($info['notnull']) && $info['notnull'] == '-1') {
  7818. return true;
  7819. } else {
  7820. return false;
  7821. }
  7822. }
  7823. return false;
  7824. }
  7825. /**
  7826. * Function test if is indexed
  7827. *
  7828. * @param array $info content informations of field
  7829. * @return bool
  7830. */
  7831. protected function isIndex($info)
  7832. {
  7833. if (is_array($info)) {
  7834. if (isset($info['index']) && $info['index'] == true) {
  7835. return true;
  7836. } else {
  7837. return false;
  7838. }
  7839. }
  7840. return false;
  7841. }
  7842. /**
  7843. * Function to prepare a part of the query for insert.
  7844. * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
  7845. * $this->${field} should be a clean value. The page can run
  7846. *
  7847. * @return array
  7848. */
  7849. protected function setSaveQuery()
  7850. {
  7851. global $conf;
  7852. $queryarray = array();
  7853. foreach ($this->fields as $field => $info) { // Loop on definition of fields
  7854. // Depending on field type ('datetime', ...)
  7855. if ($this->isDate($info)) {
  7856. if (empty($this->{$field})) {
  7857. $queryarray[$field] = null;
  7858. } else {
  7859. $queryarray[$field] = $this->db->idate($this->{$field});
  7860. }
  7861. } elseif ($this->isDuration($info)) {
  7862. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7863. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7864. if (!isset($this->{$field})) {
  7865. $queryarray[$field] = 0;
  7866. } else {
  7867. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7868. }
  7869. } else {
  7870. $queryarray[$field] = null;
  7871. }
  7872. } elseif ($this->isInt($info) || $this->isFloat($info)) {
  7873. if ($field == 'entity' && is_null($this->{$field})) {
  7874. $queryarray[$field] = $conf->entity;
  7875. } else {
  7876. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7877. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7878. if (!isset($this->{$field})) {
  7879. $queryarray[$field] = 0;
  7880. } elseif ($this->isInt($info)) {
  7881. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7882. } elseif ($this->isFloat($info)) {
  7883. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7884. }
  7885. } else {
  7886. $queryarray[$field] = null;
  7887. }
  7888. }
  7889. } else {
  7890. // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
  7891. // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
  7892. $queryarray[$field] = $this->{$field};
  7893. }
  7894. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
  7895. unset($queryarray[$field]);
  7896. }
  7897. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
  7898. $queryarray[$field] = null; // May force 0 to null
  7899. }
  7900. }
  7901. return $queryarray;
  7902. }
  7903. /**
  7904. * Function to load data from a SQL pointer into properties of current object $this
  7905. *
  7906. * @param stdClass $obj Contain data of object from database
  7907. * @return void
  7908. */
  7909. public function setVarsFromFetchObj(&$obj)
  7910. {
  7911. global $db;
  7912. foreach ($this->fields as $field => $info) {
  7913. if ($this->isDate($info)) {
  7914. if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
  7915. $this->{$field} = '';
  7916. } else {
  7917. $this->{$field} = $db->jdate($obj->{$field});
  7918. }
  7919. } elseif ($this->isInt($info)) {
  7920. if ($field == 'rowid') {
  7921. $this->id = (int) $obj->{$field};
  7922. } else {
  7923. if ($this->isForcedToNullIfZero($info)) {
  7924. if (empty($obj->{$field})) {
  7925. $this->{$field} = null;
  7926. } else {
  7927. $this->{$field} = (double) $obj->{$field};
  7928. }
  7929. } else {
  7930. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7931. $this->{$field} = (int) $obj->{$field};
  7932. } else {
  7933. $this->{$field} = null;
  7934. }
  7935. }
  7936. }
  7937. } elseif ($this->isFloat($info)) {
  7938. if ($this->isForcedToNullIfZero($info)) {
  7939. if (empty($obj->{$field})) {
  7940. $this->{$field} = null;
  7941. } else {
  7942. $this->{$field} = (double) $obj->{$field};
  7943. }
  7944. } else {
  7945. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7946. $this->{$field} = (double) $obj->{$field};
  7947. } else {
  7948. $this->{$field} = null;
  7949. }
  7950. }
  7951. } else {
  7952. $this->{$field} = isset($obj->{$field}) ? $obj->{$field} : null;
  7953. }
  7954. }
  7955. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  7956. if (!isset($this->fields['ref']) && isset($this->id)) {
  7957. $this->ref = $this->id;
  7958. }
  7959. }
  7960. /**
  7961. * Function to concat keys of fields
  7962. *
  7963. * @param string $alias String of alias of table for fields. For example 't'.
  7964. * @return string list of alias fields
  7965. */
  7966. public function getFieldList($alias = '')
  7967. {
  7968. $keys = array_keys($this->fields);
  7969. if (!empty($alias)) {
  7970. $keys_with_alias = array();
  7971. foreach ($keys as $fieldname) {
  7972. $keys_with_alias[] = $alias . '.' . $fieldname;
  7973. }
  7974. return implode(',', $keys_with_alias);
  7975. } else {
  7976. return implode(',', $keys);
  7977. }
  7978. }
  7979. /**
  7980. * Add quote to field value if necessary
  7981. *
  7982. * @param string|int $value Value to protect
  7983. * @param array $fieldsentry Properties of field
  7984. * @return string
  7985. */
  7986. protected function quote($value, $fieldsentry)
  7987. {
  7988. if (is_null($value)) {
  7989. return 'NULL';
  7990. } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
  7991. return price2num("$value");
  7992. } elseif (preg_match('/int$/i', $fieldsentry['type'])) {
  7993. return (int) $value;
  7994. } elseif ($fieldsentry['type'] == 'boolean') {
  7995. if ($value) {
  7996. return 'true';
  7997. } else {
  7998. return 'false';
  7999. }
  8000. } else {
  8001. return "'".$this->db->escape($value)."'";
  8002. }
  8003. }
  8004. /**
  8005. * Create object into database
  8006. *
  8007. * @param User $user User that creates
  8008. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8009. * @return int <0 if KO, Id of created object if OK
  8010. */
  8011. public function createCommon(User $user, $notrigger = false)
  8012. {
  8013. global $langs;
  8014. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  8015. $error = 0;
  8016. $now = dol_now();
  8017. $fieldvalues = $this->setSaveQuery();
  8018. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
  8019. $fieldvalues['date_creation'] = $this->db->idate($now);
  8020. }
  8021. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
  8022. $fieldvalues['fk_user_creat'] = $user->id;
  8023. }
  8024. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  8025. if (array_key_exists('ref', $fieldvalues)) {
  8026. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8027. }
  8028. $keys = array();
  8029. $values = array(); // Array to store string forged for SQL syntax
  8030. foreach ($fieldvalues as $k => $v) {
  8031. $keys[$k] = $k;
  8032. $value = $this->fields[$k];
  8033. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  8034. }
  8035. // Clean and check mandatory
  8036. foreach ($keys as $key) {
  8037. // If field is an implicit foreign key field (so type = 'integer:...')
  8038. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8039. $values[$key] = '';
  8040. }
  8041. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8042. $values[$key] = '';
  8043. }
  8044. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
  8045. $error++;
  8046. $langs->load("errors");
  8047. dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
  8048. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8049. }
  8050. // If value is null and there is a default value for field
  8051. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
  8052. $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
  8053. }
  8054. // If field is an implicit foreign key field (so type = 'integer:...')
  8055. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  8056. if (isset($this->fields[$key]['default'])) {
  8057. $values[$key] = ((int) $this->fields[$key]['default']);
  8058. } else {
  8059. $values[$key] = 'null';
  8060. }
  8061. }
  8062. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
  8063. $values[$key] = 'null';
  8064. }
  8065. }
  8066. if ($error) {
  8067. return -1;
  8068. }
  8069. $this->db->begin();
  8070. if (!$error) {
  8071. $sql = "INSERT INTO ".$this->db->prefix().$this->table_element;
  8072. $sql .= " (".implode(", ", $keys).')';
  8073. $sql .= " VALUES (".implode(", ", $values).")"; // $values can contains 'abc' or 123
  8074. $res = $this->db->query($sql);
  8075. if (!$res) {
  8076. $error++;
  8077. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  8078. $this->errors[] = "ErrorRefAlreadyExists";
  8079. } else {
  8080. $this->errors[] = $this->db->lasterror();
  8081. }
  8082. }
  8083. }
  8084. if (!$error) {
  8085. $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
  8086. }
  8087. // If we have a field ref with a default value of (PROV)
  8088. if (!$error) {
  8089. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
  8090. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
  8091. $resqlupdate = $this->db->query($sql);
  8092. if ($resqlupdate === false) {
  8093. $error++;
  8094. $this->errors[] = $this->db->lasterror();
  8095. } else {
  8096. $this->ref = '(PROV'.$this->id.')';
  8097. }
  8098. }
  8099. }
  8100. // Create extrafields
  8101. if (!$error) {
  8102. $result = $this->insertExtraFields();
  8103. if ($result < 0) {
  8104. $error++;
  8105. }
  8106. }
  8107. // Create lines
  8108. if (!empty($this->table_element_line) && !empty($this->fk_element)) {
  8109. $num = (is_array($this->lines) ? count($this->lines) : 0);
  8110. for ($i = 0; $i < $num; $i++) {
  8111. $line = $this->lines[$i];
  8112. $keyforparent = $this->fk_element;
  8113. $line->$keyforparent = $this->id;
  8114. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  8115. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  8116. if (!is_object($line)) {
  8117. $line = (object) $line;
  8118. }
  8119. $result = $line->create($user, 1);
  8120. if ($result < 0) {
  8121. $this->error = $line->error;
  8122. $this->db->rollback();
  8123. return -1;
  8124. }
  8125. }
  8126. }
  8127. // Triggers
  8128. if (!$error && !$notrigger) {
  8129. // Call triggers
  8130. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  8131. if ($result < 0) {
  8132. $error++;
  8133. }
  8134. // End call triggers
  8135. }
  8136. // Commit or rollback
  8137. if ($error) {
  8138. $this->db->rollback();
  8139. return -1;
  8140. } else {
  8141. $this->db->commit();
  8142. return $this->id;
  8143. }
  8144. }
  8145. /**
  8146. * Load object in memory from the database
  8147. *
  8148. * @param int $id Id object
  8149. * @param string $ref Ref
  8150. * @param string $morewhere More SQL filters (' AND ...')
  8151. * @return int <0 if KO, 0 if not found, >0 if OK
  8152. */
  8153. public function fetchCommon($id, $ref = null, $morewhere = '')
  8154. {
  8155. if (empty($id) && empty($ref) && empty($morewhere)) {
  8156. return -1;
  8157. }
  8158. $fieldlist = $this->getFieldList('t');
  8159. if (empty($fieldlist)) {
  8160. return 0;
  8161. }
  8162. $sql = "SELECT ".$fieldlist;
  8163. $sql .= " FROM ".$this->db->prefix().$this->table_element.' as t';
  8164. if (!empty($id)) {
  8165. $sql .= ' WHERE t.rowid = '.((int) $id);
  8166. } elseif (!empty($ref)) {
  8167. $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
  8168. } else {
  8169. $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  8170. }
  8171. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  8172. $sql .= ' AND t.entity IN ('.getEntity($this->table_element).')';
  8173. }
  8174. if ($morewhere) {
  8175. $sql .= $morewhere;
  8176. }
  8177. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  8178. $res = $this->db->query($sql);
  8179. if ($res) {
  8180. $obj = $this->db->fetch_object($res);
  8181. if ($obj) {
  8182. $this->setVarsFromFetchObj($obj);
  8183. // Retrieve all extrafield
  8184. // fetch optionals attributes and labels
  8185. $this->fetch_optionals();
  8186. return $this->id;
  8187. } else {
  8188. return 0;
  8189. }
  8190. } else {
  8191. $this->error = $this->db->lasterror();
  8192. $this->errors[] = $this->error;
  8193. return -1;
  8194. }
  8195. }
  8196. /**
  8197. * Load object in memory from the database
  8198. *
  8199. * @param string $morewhere More SQL filters (' AND ...')
  8200. * @return int <0 if KO, 0 if not found, >0 if OK
  8201. */
  8202. public function fetchLinesCommon($morewhere = '')
  8203. {
  8204. $objectlineclassname = get_class($this).'Line';
  8205. if (!class_exists($objectlineclassname)) {
  8206. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  8207. return -1;
  8208. }
  8209. $objectline = new $objectlineclassname($this->db);
  8210. $sql = "SELECT ".$objectline->getFieldList('l');
  8211. $sql .= " FROM ".$this->db->prefix().$objectline->table_element." as l";
  8212. $sql .= " WHERE l.fk_".$this->db->escape($this->element)." = ".((int) $this->id);
  8213. if ($morewhere) {
  8214. $sql .= $morewhere;
  8215. }
  8216. if (isset($objectline->fields['position'])) {
  8217. $sql .= $this->db->order('position', 'ASC');
  8218. }
  8219. $resql = $this->db->query($sql);
  8220. if ($resql) {
  8221. $num_rows = $this->db->num_rows($resql);
  8222. $i = 0;
  8223. while ($i < $num_rows) {
  8224. $obj = $this->db->fetch_object($resql);
  8225. if ($obj) {
  8226. $newline = new $objectlineclassname($this->db);
  8227. $newline->setVarsFromFetchObj($obj);
  8228. $this->lines[] = $newline;
  8229. }
  8230. $i++;
  8231. }
  8232. return 1;
  8233. } else {
  8234. $this->error = $this->db->lasterror();
  8235. $this->errors[] = $this->error;
  8236. return -1;
  8237. }
  8238. }
  8239. /**
  8240. * Update object into database
  8241. *
  8242. * @param User $user User that modifies
  8243. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8244. * @return int <0 if KO, >0 if OK
  8245. */
  8246. public function updateCommon(User $user, $notrigger = false)
  8247. {
  8248. global $conf, $langs;
  8249. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  8250. $error = 0;
  8251. $now = dol_now();
  8252. $fieldvalues = $this->setSaveQuery();
  8253. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
  8254. $fieldvalues['date_modification'] = $this->db->idate($now);
  8255. }
  8256. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
  8257. $fieldvalues['fk_user_modif'] = $user->id;
  8258. }
  8259. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  8260. if (array_key_exists('ref', $fieldvalues)) {
  8261. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8262. }
  8263. // Add quotes and escape on fields with type string
  8264. $keys = array();
  8265. $values = array();
  8266. $tmp = array();
  8267. foreach ($fieldvalues as $k => $v) {
  8268. $keys[$k] = $k;
  8269. $value = $this->fields[$k];
  8270. $values[$k] = $this->quote($v, $value);
  8271. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  8272. }
  8273. // Clean and check mandatory fields
  8274. foreach ($keys as $key) {
  8275. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8276. $values[$key] = ''; // This is an implicit foreign key field
  8277. }
  8278. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8279. $values[$key] = ''; // This is an explicit foreign key field
  8280. }
  8281. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  8282. /*
  8283. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  8284. {
  8285. $error++;
  8286. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8287. }*/
  8288. }
  8289. $sql = 'UPDATE '.$this->db->prefix().$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
  8290. $this->db->begin();
  8291. if (!$error) {
  8292. $res = $this->db->query($sql);
  8293. if (!$res) {
  8294. $error++;
  8295. $this->errors[] = $this->db->lasterror();
  8296. }
  8297. }
  8298. // Update extrafield
  8299. if (!$error) {
  8300. $result = $this->insertExtraFields();
  8301. if ($result < 0) {
  8302. $error++;
  8303. }
  8304. }
  8305. // Triggers
  8306. if (!$error && !$notrigger) {
  8307. // Call triggers
  8308. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  8309. if ($result < 0) {
  8310. $error++;
  8311. } //Do also here what you must do to rollback action if trigger fail
  8312. // End call triggers
  8313. }
  8314. // Commit or rollback
  8315. if ($error) {
  8316. $this->db->rollback();
  8317. return -1;
  8318. } else {
  8319. $this->db->commit();
  8320. return $this->id;
  8321. }
  8322. }
  8323. /**
  8324. * Delete object in database
  8325. *
  8326. * @param User $user User that deletes
  8327. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8328. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  8329. * @return int <=0 if KO, 0=Nothing done because object has child, >0 if OK
  8330. */
  8331. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  8332. {
  8333. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  8334. $error = 0;
  8335. $this->db->begin();
  8336. if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
  8337. foreach ($this->childtables as $table) {
  8338. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8339. $resql = $this->db->query($sql);
  8340. if (!$resql) {
  8341. $this->error = $this->db->lasterror();
  8342. $this->errors[] = $this->error;
  8343. $this->db->rollback();
  8344. return -1;
  8345. }
  8346. }
  8347. } elseif (!empty($this->fk_element) && !empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
  8348. $objectisused = $this->isObjectUsed($this->id);
  8349. if (!empty($objectisused)) {
  8350. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  8351. $this->error = 'ErrorRecordHasChildren';
  8352. $this->errors[] = $this->error;
  8353. $this->db->rollback();
  8354. return 0;
  8355. }
  8356. }
  8357. // Delete cascade first
  8358. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  8359. foreach ($this->childtablesoncascade as $table) {
  8360. $deleteFromObject = explode(':', $table);
  8361. if (count($deleteFromObject) >= 2) {
  8362. $className = str_replace('@', '', $deleteFromObject[0]);
  8363. $filePath = $deleteFromObject[1];
  8364. $columnName = $deleteFromObject[2];
  8365. $TMoreSQL = array();
  8366. $more_sql = $deleteFromObject[3];
  8367. if (!empty($more_sql)) {
  8368. $TMoreSQL['customsql'] = $more_sql;
  8369. }
  8370. if (dol_include_once($filePath)) {
  8371. $childObject = new $className($this->db);
  8372. if (method_exists($childObject, 'deleteByParentField')) {
  8373. $result = $childObject->deleteByParentField($this->id, $columnName, $TMoreSQL);
  8374. if ($result < 0) {
  8375. $error++;
  8376. $this->errors[] = $childObject->error;
  8377. break;
  8378. }
  8379. } else {
  8380. $error++;
  8381. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  8382. break;
  8383. }
  8384. } else {
  8385. $error++;
  8386. $this->errors[] = 'Cannot include child class file '.$filePath;
  8387. break;
  8388. }
  8389. } else {
  8390. // Delete record in child table
  8391. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8392. $resql = $this->db->query($sql);
  8393. if (!$resql) {
  8394. $error++;
  8395. $this->error = $this->db->lasterror();
  8396. $this->errors[] = $this->error;
  8397. break;
  8398. }
  8399. }
  8400. }
  8401. }
  8402. if (!$error) {
  8403. if (!$notrigger) {
  8404. // Call triggers
  8405. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  8406. if ($result < 0) {
  8407. $error++;
  8408. } // Do also here what you must do to rollback action if trigger fail
  8409. // End call triggers
  8410. }
  8411. }
  8412. // Delete llx_ecm_files
  8413. if (!$error) {
  8414. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  8415. if (!$res) {
  8416. $error++;
  8417. }
  8418. }
  8419. if (!$error && !empty($this->isextrafieldmanaged)) {
  8420. $result = $this->deleteExtraFields();
  8421. if ($result < 0) {
  8422. $error++;
  8423. }
  8424. }
  8425. if (!$error) {
  8426. $sql = 'DELETE FROM '.$this->db->prefix().$this->table_element.' WHERE rowid='.((int) $this->id);
  8427. $resql = $this->db->query($sql);
  8428. if (!$resql) {
  8429. $error++;
  8430. $this->errors[] = $this->db->lasterror();
  8431. }
  8432. }
  8433. // Commit or rollback
  8434. if ($error) {
  8435. $this->db->rollback();
  8436. return -1;
  8437. } else {
  8438. $this->db->commit();
  8439. return 1;
  8440. }
  8441. }
  8442. /**
  8443. * Delete all child object from a parent ID
  8444. *
  8445. * @param int $parentId Parent Id
  8446. * @param string $parentField Name of Foreign key parent column
  8447. * @param array $filter an array filter
  8448. * @param string $filtermode AND or OR
  8449. * @return int <0 if KO, >0 if OK
  8450. * @throws Exception
  8451. */
  8452. public function deleteByParentField($parentId = 0, $parentField = '', $filter = array(), $filtermode = "AND")
  8453. {
  8454. global $user;
  8455. $error = 0;
  8456. $deleted = 0;
  8457. if (!empty($parentId) && !empty($parentField)) {
  8458. $this->db->begin();
  8459. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
  8460. $sql .= " WHERE ".$parentField." = ".(int) $parentId;
  8461. // Manage filters
  8462. $sqlwhere = array();
  8463. if (count($filter) > 0) {
  8464. foreach ($filter as $key => $value) {
  8465. if ($key == 'customsql') {
  8466. $sqlwhere[] = $value;
  8467. } elseif (strpos($value, '%') === false) {
  8468. $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
  8469. } else {
  8470. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  8471. }
  8472. }
  8473. }
  8474. if (count($sqlwhere) > 0) {
  8475. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  8476. }
  8477. $resql = $this->db->query($sql);
  8478. if (!$resql) {
  8479. $this->errors[] = $this->db->lasterror();
  8480. $error++;
  8481. } else {
  8482. while ($obj = $this->db->fetch_object($resql)) {
  8483. $result = $this->fetch($obj->rowid);
  8484. if ($result < 0) {
  8485. $error++;
  8486. $this->errors[] = $this->error;
  8487. } else {
  8488. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  8489. $result = $this->delete();
  8490. } else {
  8491. $result = $this->delete($user);
  8492. }
  8493. if ($result < 0) {
  8494. $error++;
  8495. $this->errors[] = $this->error;
  8496. } else {
  8497. $deleted++;
  8498. }
  8499. }
  8500. }
  8501. }
  8502. if (empty($error)) {
  8503. $this->db->commit();
  8504. return $deleted;
  8505. } else {
  8506. $this->error = implode(', ', $this->errors);
  8507. $this->db->rollback();
  8508. return $error * -1;
  8509. }
  8510. }
  8511. return $deleted;
  8512. }
  8513. /**
  8514. * Delete a line of object in database
  8515. *
  8516. * @param User $user User that delete
  8517. * @param int $idline Id of line to delete
  8518. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8519. * @return int >0 if OK, <0 if KO
  8520. */
  8521. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  8522. {
  8523. global $conf;
  8524. $error = 0;
  8525. $tmpforobjectclass = get_class($this);
  8526. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  8527. // Call trigger
  8528. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  8529. if ($result < 0) {
  8530. return -1;
  8531. }
  8532. // End call triggers
  8533. $this->db->begin();
  8534. $sql = "DELETE FROM ".$this->db->prefix().$this->table_element_line;
  8535. $sql .= " WHERE rowid = ".((int) $idline);
  8536. dol_syslog(get_class($this)."::deleteLineCommon", LOG_DEBUG);
  8537. $resql = $this->db->query($sql);
  8538. if (!$resql) {
  8539. $this->error = "Error ".$this->db->lasterror();
  8540. $error++;
  8541. }
  8542. if (empty($error)) {
  8543. // Remove extrafields
  8544. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  8545. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  8546. $tmpobjectline->id = $idline;
  8547. $result = $tmpobjectline->deleteExtraFields();
  8548. if ($result < 0) {
  8549. $error++;
  8550. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  8551. }
  8552. }
  8553. }
  8554. if (empty($error)) {
  8555. $this->db->commit();
  8556. return 1;
  8557. } else {
  8558. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  8559. $this->db->rollback();
  8560. return -1;
  8561. }
  8562. }
  8563. /**
  8564. * Set to a status
  8565. *
  8566. * @param User $user Object user that modify
  8567. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  8568. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  8569. * @param string $triggercode Trigger code to use
  8570. * @return int <0 if KO, >0 if OK
  8571. */
  8572. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  8573. {
  8574. $error = 0;
  8575. $this->db->begin();
  8576. $statusfield = 'status';
  8577. if ($this->element == 'don' || $this->element == 'donation') {
  8578. $statusfield = 'fk_statut';
  8579. }
  8580. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  8581. $sql .= " SET ".$statusfield." = ".((int) $status);
  8582. $sql .= " WHERE rowid = ".((int) $this->id);
  8583. if ($this->db->query($sql)) {
  8584. if (!$error) {
  8585. $this->oldcopy = clone $this;
  8586. }
  8587. if (!$error && !$notrigger) {
  8588. // Call trigger
  8589. $result = $this->call_trigger($triggercode, $user);
  8590. if ($result < 0) {
  8591. $error++;
  8592. }
  8593. }
  8594. if (!$error) {
  8595. $this->status = $status;
  8596. $this->db->commit();
  8597. return 1;
  8598. } else {
  8599. $this->db->rollback();
  8600. return -1;
  8601. }
  8602. } else {
  8603. $this->error = $this->db->error();
  8604. $this->db->rollback();
  8605. return -1;
  8606. }
  8607. }
  8608. /**
  8609. * Initialise object with example values
  8610. * Id must be 0 if object instance is a specimen
  8611. *
  8612. * @return int
  8613. */
  8614. public function initAsSpecimenCommon()
  8615. {
  8616. global $user;
  8617. $this->id = 0;
  8618. $this->specimen = 1;
  8619. $fields = array(
  8620. 'label' => 'This is label',
  8621. 'ref' => 'ABCD1234',
  8622. 'description' => 'This is a description',
  8623. 'qty' => 123.12,
  8624. 'note_public' => 'Public note',
  8625. 'note_private' => 'Private note',
  8626. 'date_creation' => (dol_now() - 3600 * 48),
  8627. 'date_modification' => (dol_now() - 3600 * 24),
  8628. 'fk_user_creat' => $user->id,
  8629. 'fk_user_modif' => $user->id,
  8630. 'date' => dol_now(),
  8631. );
  8632. foreach ($fields as $key => $value) {
  8633. if (array_key_exists($key, $this->fields)) {
  8634. $this->{$key} = $value;
  8635. }
  8636. }
  8637. return 1;
  8638. }
  8639. /* Part for comments */
  8640. /**
  8641. * Load comments linked with current task
  8642. * @return boolean 1 if ok
  8643. */
  8644. public function fetchComments()
  8645. {
  8646. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  8647. $comment = new Comment($this->db);
  8648. $result = $comment->fetchAllFor($this->element, $this->id);
  8649. if ($result < 0) {
  8650. $this->errors = array_merge($this->errors, $comment->errors);
  8651. return -1;
  8652. } else {
  8653. $this->comments = $comment->comments;
  8654. }
  8655. return count($this->comments);
  8656. }
  8657. /**
  8658. * Return nb comments already posted
  8659. *
  8660. * @return int
  8661. */
  8662. public function getNbComments()
  8663. {
  8664. return count($this->comments);
  8665. }
  8666. /**
  8667. * Trim object parameters
  8668. *
  8669. * @param string[] $parameters array of parameters to trim
  8670. * @return void
  8671. */
  8672. public function trimParameters($parameters)
  8673. {
  8674. if (!is_array($parameters)) {
  8675. return;
  8676. }
  8677. foreach ($parameters as $parameter) {
  8678. if (isset($this->$parameter)) {
  8679. $this->$parameter = trim($this->$parameter);
  8680. }
  8681. }
  8682. }
  8683. /* Part for categories/tags */
  8684. /**
  8685. * Sets object to given categories.
  8686. *
  8687. * Deletes object from existing categories not supplied.
  8688. * Adds it to non existing supplied categories.
  8689. * Existing categories are left untouch.
  8690. *
  8691. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  8692. * @return int Array of category objects or < 0 if KO
  8693. */
  8694. public function getCategoriesCommon($type_categ)
  8695. {
  8696. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8697. // Get current categories
  8698. $c = new Categorie($this->db);
  8699. $existing = $c->containing($this->id, $type_categ, 'id');
  8700. return $existing;
  8701. }
  8702. /**
  8703. * Sets object to given categories.
  8704. *
  8705. * Adds it to non existing supplied categories.
  8706. * Deletes object from existing categories not supplied (if remove_existing==true).
  8707. * Existing categories are left untouch.
  8708. *
  8709. * @param int[]|int $categories Category ID or array of Categories IDs
  8710. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) definied into const class Categorie type
  8711. * @param boolean $remove_existing True: Remove existings categories from Object if not supplies by $categories, False: let them
  8712. * @return int <0 if KO, >0 if OK
  8713. */
  8714. public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
  8715. {
  8716. // Handle single category
  8717. if (!is_array($categories)) {
  8718. $categories = array($categories);
  8719. }
  8720. dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
  8721. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8722. if (empty($type_categ)) {
  8723. dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
  8724. return -1;
  8725. }
  8726. // Get current categories
  8727. $c = new Categorie($this->db);
  8728. $existing = $c->containing($this->id, $type_categ, 'id');
  8729. if ($remove_existing) {
  8730. // Diff
  8731. if (is_array($existing)) {
  8732. $to_del = array_diff($existing, $categories);
  8733. $to_add = array_diff($categories, $existing);
  8734. } else {
  8735. $to_del = array(); // Nothing to delete
  8736. $to_add = $categories;
  8737. }
  8738. } else {
  8739. $to_del = array(); // Nothing to delete
  8740. $to_add = array_diff($categories, $existing);
  8741. }
  8742. $error = 0;
  8743. $ok = 0;
  8744. // Process
  8745. foreach ($to_del as $del) {
  8746. if ($c->fetch($del) > 0) {
  8747. $result=$c->del_type($this, $type_categ);
  8748. if ($result < 0) {
  8749. $error++;
  8750. $this->error = $c->error;
  8751. $this->errors = $c->errors;
  8752. break;
  8753. } else {
  8754. $ok += $result;
  8755. }
  8756. }
  8757. }
  8758. foreach ($to_add as $add) {
  8759. if ($c->fetch($add) > 0) {
  8760. $result = $c->add_type($this, $type_categ);
  8761. if ($result < 0) {
  8762. $error++;
  8763. $this->error = $c->error;
  8764. $this->errors = $c->errors;
  8765. break;
  8766. } else {
  8767. $ok += $result;
  8768. }
  8769. }
  8770. }
  8771. return $error ? -1 * $error : $ok;
  8772. }
  8773. /**
  8774. * Copy related categories to another object
  8775. *
  8776. * @param int $fromId Id object source
  8777. * @param int $toId Id object cible
  8778. * @param string $type Type of category ('product', ...)
  8779. * @return int < 0 if error, > 0 if ok
  8780. */
  8781. public function cloneCategories($fromId, $toId, $type = '')
  8782. {
  8783. $this->db->begin();
  8784. if (empty($type)) {
  8785. $type = $this->table_element;
  8786. }
  8787. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8788. $categorystatic = new Categorie($this->db);
  8789. $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  8790. $sql .= " SELECT fk_categorie, $toId FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  8791. $sql .= " WHERE fk_product = ".((int) $fromId);
  8792. if (!$this->db->query($sql)) {
  8793. $this->error = $this->db->lasterror();
  8794. $this->db->rollback();
  8795. return -1;
  8796. }
  8797. $this->db->commit();
  8798. return 1;
  8799. }
  8800. /**
  8801. * Delete related files of object in database
  8802. *
  8803. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  8804. * @return bool True if OK, False if KO
  8805. */
  8806. public function deleteEcmFiles($mode = 0)
  8807. {
  8808. global $conf;
  8809. $this->db->begin();
  8810. // Delete in database with mode 0
  8811. if ($mode == 0) {
  8812. switch ($this->element) {
  8813. case 'propal':
  8814. $element = 'propale';
  8815. break;
  8816. case 'product':
  8817. $element = 'produit';
  8818. break;
  8819. case 'order_supplier':
  8820. $element = 'fournisseur/commande';
  8821. break;
  8822. case 'invoice_supplier':
  8823. $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  8824. break;
  8825. case 'shipping':
  8826. $element = 'expedition/sending';
  8827. break;
  8828. default:
  8829. $element = $this->element;
  8830. }
  8831. // Delete ecm_files extrafields
  8832. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files_extrafields WHERE fk_object IN (";
  8833. $sql .= " SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8834. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  8835. $sql .= ")";
  8836. if (!$this->db->query($sql)) {
  8837. $this->error = $this->db->lasterror();
  8838. $this->db->rollback();
  8839. return false;
  8840. }
  8841. // Delete ecm_files
  8842. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files";
  8843. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8844. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  8845. if (!$this->db->query($sql)) {
  8846. $this->error = $this->db->lasterror();
  8847. $this->db->rollback();
  8848. return false;
  8849. }
  8850. }
  8851. // Delete in database with mode 1
  8852. if ($mode == 1) {
  8853. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files_extrafields";
  8854. $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).")";
  8855. $resql = $this->db->query($sql);
  8856. if (!$resql) {
  8857. $this->error = $this->db->lasterror();
  8858. $this->db->rollback();
  8859. return false;
  8860. }
  8861. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files";
  8862. $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
  8863. $resql = $this->db->query($sql);
  8864. if (!$resql) {
  8865. $this->error = $this->db->lasterror();
  8866. $this->db->rollback();
  8867. return false;
  8868. }
  8869. }
  8870. $this->db->commit();
  8871. return true;
  8872. }
  8873. }