commonobject.class.php 298 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551
  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 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-2020 Frédéric France <frederic.france@netlogic.fr>
  16. * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
  17. *
  18. * This program is free software; you can redistribute it and/or modify
  19. * it under the terms of the GNU General Public License as published by
  20. * the Free Software Foundation; either version 3 of the License, or
  21. * (at your option) any later version.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU General Public License
  29. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  30. */
  31. /**
  32. * \file htdocs/core/class/commonobject.class.php
  33. * \ingroup core
  34. * \brief File of parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  35. */
  36. /**
  37. * Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  38. */
  39. abstract class CommonObject
  40. {
  41. /**
  42. * @var DoliDb Database handler (result of a new DoliDB)
  43. */
  44. public $db;
  45. /**
  46. * @var int The object identifier
  47. */
  48. public $id;
  49. /**
  50. * @var int The environment ID when using a multicompany module
  51. */
  52. public $entity;
  53. /**
  54. * @var string Error string
  55. * @see $errors
  56. */
  57. public $error;
  58. /**
  59. * @var string Error string that is hidden but can be used to store complementatry technical code.
  60. */
  61. public $errorhidden;
  62. /**
  63. * @var string[] Array of error strings
  64. */
  65. public $errors = array();
  66. /**
  67. * @var string ID to identify managed object
  68. */
  69. public $element;
  70. /**
  71. * @var string Name of table without prefix where object is stored
  72. */
  73. public $table_element;
  74. /**
  75. * @var string Name of subtable line
  76. */
  77. public $table_element_line = '';
  78. /**
  79. * @var string Key value used to track if data is coming from import wizard
  80. */
  81. public $import_key;
  82. /**
  83. * @var mixed Contains data to manage extrafields
  84. */
  85. public $array_options = array();
  86. /**
  87. * @var mixed Array to store alternative languages values of object
  88. */
  89. public $array_languages = null; // Value is array() when load already tried
  90. /**
  91. * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked
  92. */
  93. public $linkedObjectsIds;
  94. /**
  95. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  96. */
  97. public $linkedObjects;
  98. /**
  99. * @var Object To store a cloned copy of object before to edit it and keep track of old properties
  100. */
  101. public $oldcopy;
  102. /**
  103. * @var string Column name of the ref field.
  104. */
  105. protected $table_ref_field = '';
  106. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  107. /**
  108. * @var array<string,mixed> Can be used to pass information when only object is provided to method
  109. */
  110. public $context = array();
  111. /**
  112. * @var string Contains canvas name if record is an alternative canvas record
  113. */
  114. public $canvas;
  115. /**
  116. * @var Project The related project
  117. * @see fetch_projet()
  118. */
  119. public $project;
  120. /**
  121. * @var int The related project ID
  122. * @see setProject(), project
  123. */
  124. public $fk_project;
  125. /**
  126. * @deprecated
  127. * @see project
  128. */
  129. public $projet;
  130. /**
  131. * @var Contact a related contact
  132. * @see fetch_contact()
  133. */
  134. public $contact;
  135. /**
  136. * @var int The related contact ID
  137. * @see fetch_contact()
  138. */
  139. public $contact_id;
  140. /**
  141. * @var Societe A related thirdparty
  142. * @see fetch_thirdparty()
  143. */
  144. public $thirdparty;
  145. /**
  146. * @var User A related user
  147. * @see fetch_user()
  148. */
  149. public $user;
  150. /**
  151. * @var string The type of originating object ('commande', 'facture', ...)
  152. * @see fetch_origin()
  153. */
  154. public $origin;
  155. /**
  156. * @var int The id of originating object
  157. * @see fetch_origin()
  158. */
  159. public $origin_id;
  160. /**
  161. * @var string The object's reference
  162. */
  163. public $ref;
  164. /**
  165. * @var string An external reference for the object
  166. */
  167. public $ref_ext;
  168. /**
  169. * @var string The object's previous reference
  170. */
  171. public $ref_previous;
  172. /**
  173. * @var string The object's next reference
  174. */
  175. public $ref_next;
  176. /**
  177. * @var int The object's status
  178. * @see setStatut()
  179. */
  180. public $statut;
  181. /**
  182. * @var string
  183. * @see getFullAddress()
  184. */
  185. public $country;
  186. /**
  187. * @var int
  188. * @see getFullAddress(), country
  189. */
  190. public $country_id;
  191. /**
  192. * @var string
  193. * @see getFullAddress(), isInEEC(), country
  194. */
  195. public $country_code;
  196. /**
  197. * @var string
  198. * @see getFullAddress()
  199. */
  200. public $state;
  201. /**
  202. * @var int
  203. * @see getFullAddress(), state
  204. */
  205. public $state_id;
  206. /**
  207. * @var string
  208. * @see getFullAddress(), $state
  209. */
  210. public $state_code;
  211. /**
  212. * @var int
  213. * @see getFullAddress(), $region_code, $region
  214. */
  215. public $region_id;
  216. /**
  217. * @var string
  218. * @see getFullAddress(), $region_id, $region
  219. */
  220. public $region_code;
  221. /**
  222. * @var string
  223. * @see getFullAddress(), $region_id, $region_code
  224. */
  225. public $region;
  226. /**
  227. * @var int
  228. * @see fetch_barcode()
  229. */
  230. public $barcode_type;
  231. /**
  232. * @var string
  233. * @see fetch_barcode(), barcode_type
  234. */
  235. public $barcode_type_code;
  236. /**
  237. * @var string
  238. * @see fetch_barcode(), barcode_type
  239. */
  240. public $barcode_type_label;
  241. /**
  242. * @var string
  243. * @see fetch_barcode(), barcode_type
  244. */
  245. public $barcode_type_coder;
  246. /**
  247. * @var int Payment method ID (cheque, cash, ...)
  248. * @see setPaymentMethods()
  249. */
  250. public $mode_reglement_id;
  251. /**
  252. * @var int Payment terms ID
  253. * @see setPaymentTerms()
  254. */
  255. public $cond_reglement_id;
  256. /**
  257. * @var int Demand reason ID
  258. */
  259. public $demand_reason_id;
  260. /**
  261. * @var int Transport mode ID (For module intracomm report)
  262. * @see setTransportMode()
  263. */
  264. public $transport_mode_id;
  265. /**
  266. * @var int Payment terms ID
  267. * @deprecated Kept for compatibility
  268. * @see cond_reglement_id;
  269. */
  270. public $cond_reglement;
  271. /**
  272. * @var int Delivery address ID
  273. * @see setDeliveryAddress()
  274. * @deprecated
  275. */
  276. public $fk_delivery_address;
  277. /**
  278. * @var int Shipping method ID
  279. * @see setShippingMethod()
  280. */
  281. public $shipping_method_id;
  282. /**
  283. * @var string
  284. * @see SetDocModel()
  285. */
  286. public $model_pdf;
  287. /**
  288. * @var string
  289. * Contains relative path of last generated main file
  290. */
  291. public $last_main_doc;
  292. /**
  293. * @var int Bank account ID
  294. * @deprecated
  295. * @see $fk_account
  296. */
  297. public $fk_bank;
  298. /**
  299. * @var int Bank account ID
  300. * @see SetBankAccount()
  301. */
  302. public $fk_account;
  303. /**
  304. * @var string Open ID
  305. */
  306. public $openid;
  307. /**
  308. * @var string Public note
  309. * @see update_note()
  310. */
  311. public $note_public;
  312. /**
  313. * @var string Private note
  314. * @see update_note()
  315. */
  316. public $note_private;
  317. /**
  318. * @deprecated
  319. * @see $note_private
  320. */
  321. public $note;
  322. /**
  323. * @var float Total amount before taxes
  324. * @see update_price()
  325. */
  326. public $total_ht;
  327. /**
  328. * @var float Total VAT amount
  329. * @see update_price()
  330. */
  331. public $total_tva;
  332. /**
  333. * @var float Total local tax 1 amount
  334. * @see update_price()
  335. */
  336. public $total_localtax1;
  337. /**
  338. * @var float Total local tax 2 amount
  339. * @see update_price()
  340. */
  341. public $total_localtax2;
  342. /**
  343. * @var float Total amount with taxes
  344. * @see update_price()
  345. */
  346. public $total_ttc;
  347. /**
  348. * @var CommonObjectLine[]
  349. */
  350. public $lines;
  351. /**
  352. * @var mixed Contains comments
  353. * @see fetchComments()
  354. */
  355. public $comments = array();
  356. /**
  357. * @var string The name
  358. */
  359. public $name;
  360. /**
  361. * @var string The lastname
  362. */
  363. public $lastname;
  364. /**
  365. * @var string The firstname
  366. */
  367. public $firstname;
  368. /**
  369. * @var string The civility code, not an integer
  370. */
  371. public $civility_id;
  372. // Dates
  373. /**
  374. * @var integer|string date_creation
  375. */
  376. public $date_creation;
  377. /**
  378. * @var integer|string $date_validation;
  379. */
  380. public $date_validation; // Date validation
  381. /**
  382. * @var integer|string $date_modification;
  383. */
  384. public $date_modification; // Date last change (tms field)
  385. public $next_prev_filter;
  386. /**
  387. * @var int 1 if object is specimen
  388. */
  389. public $specimen = 0;
  390. /**
  391. * @var int Id of contact to send object (used by the trigger of module Agenda)
  392. */
  393. public $sendtoid;
  394. /**
  395. * @var array List of child tables. To test if we can delete object.
  396. */
  397. protected $childtables = array();
  398. /**
  399. * @var array List of child tables. To know object to delete on cascade.
  400. * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
  401. * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
  402. */
  403. protected $childtablesoncascade = array();
  404. // No constructor as it is an abstract class
  405. /**
  406. * Check an object id/ref exists
  407. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  408. *
  409. * @param string $element String of element ('product', 'facture', ...)
  410. * @param int $id Id of object
  411. * @param string $ref Ref of object to check
  412. * @param string $ref_ext Ref ext of object to check
  413. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  414. */
  415. public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
  416. {
  417. global $db, $conf;
  418. $sql = "SELECT rowid, ref, ref_ext";
  419. $sql .= " FROM ".MAIN_DB_PREFIX.$element;
  420. $sql .= " WHERE entity IN (".getEntity($element).")";
  421. if ($id > 0) $sql .= " AND rowid = ".$db->escape($id);
  422. elseif ($ref) $sql .= " AND ref = '".$db->escape($ref)."'";
  423. elseif ($ref_ext) $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
  424. else {
  425. $error = 'ErrorWrongParameters';
  426. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  427. return -1;
  428. }
  429. if ($ref || $ref_ext) $sql .= " AND entity = ".$conf->entity;
  430. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  431. $resql = $db->query($sql);
  432. if ($resql)
  433. {
  434. $num = $db->num_rows($resql);
  435. if ($num > 0) return 1;
  436. else return 0;
  437. }
  438. return -1;
  439. }
  440. /**
  441. * Method to output saved errors
  442. *
  443. * @return string String with errors
  444. */
  445. public function errorsToString()
  446. {
  447. return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
  448. }
  449. /**
  450. * Return customer ref for screen output.
  451. *
  452. * @param string $objref Customer ref
  453. * @return string Customer ref formated
  454. */
  455. public function getFormatedCustomerRef($objref)
  456. {
  457. global $hookmanager;
  458. $parameters = array('objref'=>$objref);
  459. $action = '';
  460. $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  461. if ($reshook > 0)
  462. {
  463. return $hookmanager->resArray['objref'];
  464. }
  465. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  466. }
  467. /**
  468. * Return supplier ref for screen output.
  469. *
  470. * @param string $objref Supplier ref
  471. * @return string Supplier ref formated
  472. */
  473. public function getFormatedSupplierRef($objref)
  474. {
  475. global $hookmanager;
  476. $parameters = array('objref'=>$objref);
  477. $action = '';
  478. $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  479. if ($reshook > 0)
  480. {
  481. return $hookmanager->resArray['objref'];
  482. }
  483. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  484. }
  485. /**
  486. * Return full name (civility+' '+name+' '+lastname)
  487. *
  488. * @param Translate $langs Language object for translation of civility (used only if option is 1)
  489. * @param int $option 0=No option, 1=Add civility
  490. * @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
  491. * @param int $maxlen Maximum length
  492. * @return string String with full name
  493. */
  494. public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
  495. {
  496. //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
  497. $lastname = $this->lastname;
  498. $firstname = $this->firstname;
  499. if (empty($lastname)) $lastname = (isset($this->lastname) ? $this->lastname : (isset($this->name) ? $this->name : (isset($this->nom) ? $this->nom : (isset($this->societe) ? $this->societe : (isset($this->company) ? $this->company : '')))));
  500. $ret = '';
  501. if ($option && $this->civility_code)
  502. {
  503. if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
  504. else $ret .= $this->civility_code.' ';
  505. }
  506. $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
  507. return dol_trunc($ret, $maxlen);
  508. }
  509. /**
  510. * Set to upper or ucwords/lower if needed
  511. *
  512. * @return void;
  513. */
  514. public function setUpperOrLowerCase()
  515. {
  516. global $conf;
  517. if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
  518. $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
  519. $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
  520. $this->name = dol_ucwords(dol_strtolower($this->name));
  521. }
  522. if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
  523. $this->lastname = dol_strtoupper($this->lastname);
  524. $this->name = dol_strtoupper($this->name);
  525. }
  526. if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
  527. $this->town = dol_strtoupper($this->town);
  528. }
  529. }
  530. /**
  531. * Return clicable link of object (with eventually picto)
  532. *
  533. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  534. * @return string HTML Code for Kanban thumb.
  535. */
  536. public function getKanbanView($option = '')
  537. {
  538. $return = '<div class="box-flex-item">';
  539. $return .= '<div class="info-box info-box-sm">';
  540. $return .= '<span class="info-box-icon bg-infobox-action">';
  541. $return .= '<i class="fa fa-dol-action"></i>'; // Can be image
  542. $return .= '</span>';
  543. $return .= '<div class="info-box-content">';
  544. $return .= '<span class="info-box-title">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  545. $return .= '</div>';
  546. $return .= '</div>';
  547. $return .= '</div>';
  548. return $return;
  549. }
  550. /**
  551. * Return full address of contact
  552. *
  553. * @param int $withcountry 1=Add country into address string
  554. * @param string $sep Separator to use to build string
  555. * @param int $withregion 1=Add region into address string
  556. * @param string $extralangcode User extralanguages as value
  557. * @return string Full address string
  558. */
  559. public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
  560. {
  561. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country)))
  562. {
  563. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  564. $tmparray = getCountry($this->country_id, 'all');
  565. $this->country_code = $tmparray['code'];
  566. $this->country = $tmparray['label'];
  567. }
  568. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code)))
  569. {
  570. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  571. $tmparray = getState($this->state_id, 'all', 0, 1);
  572. $this->state_code = $tmparray['code'];
  573. $this->state = $tmparray['label'];
  574. $this->region_code = $tmparray['region_code'];
  575. $this->region = $tmparray['region'];
  576. }
  577. return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
  578. }
  579. /**
  580. * Return full address for banner
  581. *
  582. * @param string $htmlkey HTML id to make banner content unique
  583. * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member)
  584. * @return string Full address string
  585. */
  586. public function getBannerAddress($htmlkey, $object)
  587. {
  588. global $conf, $langs, $form, $extralanguages;
  589. $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
  590. $contactid = 0;
  591. $thirdpartyid = 0;
  592. $elementforaltlanguage = $this->element;
  593. if ($this->element == 'societe') {
  594. $thirdpartyid = $this->id;
  595. }
  596. if ($this->element == 'contact') {
  597. $contactid = $this->id;
  598. $thirdpartyid = $object->fk_soc;
  599. }
  600. if ($this->element == 'user') {
  601. $contactid = $this->contact_id;
  602. $thirdpartyid = $object->fk_soc;
  603. }
  604. $out = '';
  605. $outdone = 0;
  606. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT);
  607. if ($coords)
  608. {
  609. if (!empty($conf->use_javascript_ajax))
  610. {
  611. // Add picto with tooltip on map
  612. $namecoords = '';
  613. if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS))
  614. {
  615. $namecoords .= $object->name.'<br>';
  616. }
  617. $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
  618. // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
  619. $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
  620. $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
  621. $out .= '</a> ';
  622. }
  623. $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', '); $outdone++;
  624. $outdone++;
  625. // List of extra languages
  626. $arrayoflangcode = array();
  627. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  628. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  629. if (!is_object($extralanguages)) {
  630. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  631. $extralanguages = new ExtraLanguages($this->db);
  632. }
  633. $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
  634. if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town']))
  635. {
  636. $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
  637. $this->fetchValuesForExtraLanguages();
  638. if (!is_object($form)) $form = new Form($this->db);
  639. $htmltext = '';
  640. // If there is extra languages
  641. foreach ($arrayoflangcode as $extralangcode) {
  642. $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  643. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
  644. $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  645. }
  646. $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  647. }
  648. }
  649. }
  650. 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
  651. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state)
  652. {
  653. if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
  654. $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
  655. } else {
  656. $out .= ($outdone ? ' - ' : '').$this->state;
  657. }
  658. $outdone++;
  659. }
  660. if (!empty($this->phone) || !empty($this->phone_pro) || !empty($this->phone_mobile) || !empty($this->phone_perso) || !empty($this->fax) || !empty($this->office_phone) || !empty($this->user_mobile) || !empty($this->office_fax)) $out .= ($outdone ? '<br>' : '');
  661. if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  662. $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  663. $outdone++;
  664. }
  665. if (!empty($this->phone_pro)) {
  666. $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  667. $outdone++;
  668. }
  669. if (!empty($this->phone_mobile)) {
  670. $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  671. $outdone++;
  672. }
  673. if (!empty($this->phone_perso)) {
  674. $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
  675. $outdone++;
  676. }
  677. if (!empty($this->office_phone)) {
  678. $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  679. $outdone++;
  680. }
  681. if (!empty($this->user_mobile)) {
  682. $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  683. $outdone++;
  684. }
  685. if (!empty($this->fax)) {
  686. $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  687. $outdone++;
  688. }
  689. if (!empty($this->office_fax)) {
  690. $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  691. $outdone++;
  692. }
  693. if ($out) $out .= '<div style="clear: both;"></div>';
  694. $outdone = 0;
  695. if (!empty($this->email)) {
  696. $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
  697. $outdone++;
  698. }
  699. if (!empty($this->url)) {
  700. //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
  701. $out .= dol_print_url($this->url, '_blank', 0, 1);
  702. $outdone++;
  703. }
  704. if (!empty($conf->socialnetworks->enabled)) {
  705. $outsocialnetwork = '';
  706. if (is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
  707. $socialnetworksdict = getArrayOfSocialNetworks();
  708. foreach ($this->socialnetworks as $key => $value) {
  709. if ($value) {
  710. $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
  711. }
  712. $outdone++;
  713. }
  714. } else { // Old code to remove
  715. if ($this->skype) $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
  716. $outdone++;
  717. if ($this->jabberid) $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
  718. $outdone++;
  719. if ($this->twitter) $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
  720. $outdone++;
  721. if ($this->facebook) $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
  722. $outdone++;
  723. if ($this->linkedin) $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
  724. $outdone++;
  725. }
  726. if ($outsocialnetwork) {
  727. $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
  728. }
  729. }
  730. if ($out) return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
  731. else return '';
  732. }
  733. /**
  734. * Return the link of last main doc file for direct public download.
  735. *
  736. * @param string $modulepart Module related to document
  737. * @param int $initsharekey Init the share key if it was not yet defined
  738. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  739. * @return string Link or empty string if there is no download link
  740. */
  741. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  742. {
  743. global $user, $dolibarr_main_url_root;
  744. if (empty($this->last_main_doc))
  745. {
  746. return ''; // No way to known which document name to use
  747. }
  748. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  749. $ecmfile = new EcmFiles($this->db);
  750. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  751. if ($result < 0)
  752. {
  753. $this->error = $ecmfile->error;
  754. $this->errors = $ecmfile->errors;
  755. return -1;
  756. }
  757. if (empty($ecmfile->id))
  758. {
  759. // Add entry into index
  760. if ($initsharekey)
  761. {
  762. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  763. // TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first
  764. /*
  765. $ecmfile->filepath = $rel_dir;
  766. $ecmfile->filename = $filename;
  767. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  768. $ecmfile->fullpath_orig = '';
  769. $ecmfile->gen_or_uploaded = 'generated';
  770. $ecmfile->description = ''; // indexed content
  771. $ecmfile->keyword = ''; // keyword content
  772. $ecmfile->share = getRandomPassword(true);
  773. $result = $ecmfile->create($user);
  774. if ($result < 0)
  775. {
  776. $this->error = $ecmfile->error;
  777. $this->errors = $ecmfile->errors;
  778. }
  779. */
  780. } else return '';
  781. } elseif (empty($ecmfile->share))
  782. {
  783. // Add entry into index
  784. if ($initsharekey)
  785. {
  786. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  787. $ecmfile->share = getRandomPassword(true);
  788. $ecmfile->update($user);
  789. } else return '';
  790. }
  791. // Define $urlwithroot
  792. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  793. // This is to use external domain name found into config file
  794. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  795. //else
  796. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  797. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  798. $forcedownload = 0;
  799. $paramlink = '';
  800. //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  801. //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  802. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  803. if (!empty($ecmfile->share)) $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
  804. if ($forcedownload) $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  805. if ($relativelink)
  806. {
  807. $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
  808. } else {
  809. $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  810. }
  811. // Here $ecmfile->share is defined
  812. return $linktoreturn;
  813. }
  814. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  815. /**
  816. * Add a link between element $this->element and a contact
  817. *
  818. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  819. * @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
  820. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  821. * @param int $notrigger Disable all triggers
  822. * @return int <0 if KO, >0 if OK
  823. */
  824. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  825. {
  826. // phpcs:enable
  827. global $user, $langs;
  828. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  829. // Check parameters
  830. if ($fk_socpeople <= 0)
  831. {
  832. $langs->load("errors");
  833. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  834. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  835. return -1;
  836. }
  837. if (!$type_contact)
  838. {
  839. $langs->load("errors");
  840. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  841. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  842. return -2;
  843. }
  844. $id_type_contact = 0;
  845. if (is_numeric($type_contact))
  846. {
  847. $id_type_contact = $type_contact;
  848. } else {
  849. // We look for id type_contact
  850. $sql = "SELECT tc.rowid";
  851. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  852. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  853. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  854. $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  855. //print $sql;
  856. $resql = $this->db->query($sql);
  857. if ($resql)
  858. {
  859. $obj = $this->db->fetch_object($resql);
  860. if ($obj) $id_type_contact = $obj->rowid;
  861. }
  862. }
  863. if ($id_type_contact == 0)
  864. {
  865. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  866. 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");
  867. return -3;
  868. }
  869. $datecreate = dol_now();
  870. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  871. $TListeContacts = $this->liste_contact(-1, $source);
  872. $already_added = false;
  873. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  874. foreach ($TListeContacts as $array_contact) {
  875. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  876. $already_added = true;
  877. break;
  878. }
  879. }
  880. }
  881. if (!$already_added) {
  882. $this->db->begin();
  883. // Insert into database
  884. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact";
  885. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  886. $sql .= " VALUES (".$this->id.", ".$fk_socpeople." , ";
  887. $sql .= "'".$this->db->idate($datecreate)."'";
  888. $sql .= ", 4, ".$id_type_contact;
  889. $sql .= ")";
  890. $resql = $this->db->query($sql);
  891. if ($resql)
  892. {
  893. if (!$notrigger)
  894. {
  895. $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  896. if ($result < 0)
  897. {
  898. $this->db->rollback();
  899. return -1;
  900. }
  901. }
  902. $this->db->commit();
  903. return 1;
  904. } else {
  905. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
  906. {
  907. $this->error = $this->db->errno();
  908. $this->db->rollback();
  909. echo 'err rollback';
  910. return -2;
  911. } else {
  912. $this->error = $this->db->error();
  913. $this->db->rollback();
  914. return -1;
  915. }
  916. }
  917. } else return 0;
  918. }
  919. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  920. /**
  921. * Copy contact from one element to current
  922. *
  923. * @param CommonObject $objFrom Source element
  924. * @param string $source Nature of contact ('internal' or 'external')
  925. * @return int >0 if OK, <0 if KO
  926. */
  927. public function copy_linked_contact($objFrom, $source = 'internal')
  928. {
  929. // phpcs:enable
  930. $contacts = $objFrom->liste_contact(-1, $source);
  931. foreach ($contacts as $contact)
  932. {
  933. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0)
  934. {
  935. $this->error = $this->db->lasterror();
  936. return -1;
  937. }
  938. }
  939. return 1;
  940. }
  941. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  942. /**
  943. * Update a link to contact line
  944. *
  945. * @param int $rowid Id of line contact-element
  946. * @param int $statut New status of link
  947. * @param int $type_contact_id Id of contact type (not modified if 0)
  948. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  949. * @return int <0 if KO, >= 0 if OK
  950. */
  951. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  952. {
  953. // phpcs:enable
  954. // Insert into database
  955. $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set";
  956. $sql .= " statut = ".$statut;
  957. if ($type_contact_id) $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
  958. if ($fk_socpeople) $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
  959. $sql .= " where rowid = ".$rowid;
  960. $resql = $this->db->query($sql);
  961. if ($resql)
  962. {
  963. return 0;
  964. } else {
  965. $this->error = $this->db->lasterror();
  966. return -1;
  967. }
  968. }
  969. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  970. /**
  971. * Delete a link to contact line
  972. *
  973. * @param int $rowid Id of contact link line to delete
  974. * @param int $notrigger Disable all triggers
  975. * @return int >0 if OK, <0 if KO
  976. */
  977. public function delete_contact($rowid, $notrigger = 0)
  978. {
  979. // phpcs:enable
  980. global $user;
  981. $this->db->begin();
  982. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  983. $sql .= " WHERE rowid =".$rowid;
  984. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  985. if ($this->db->query($sql))
  986. {
  987. if (!$notrigger)
  988. {
  989. $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  990. if ($result < 0) { $this->db->rollback(); return -1; }
  991. }
  992. $this->db->commit();
  993. return 1;
  994. } else {
  995. $this->error = $this->db->lasterror();
  996. $this->db->rollback();
  997. return -1;
  998. }
  999. }
  1000. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1001. /**
  1002. * Delete all links between an object $this and all its contacts
  1003. *
  1004. * @param string $source '' or 'internal' or 'external'
  1005. * @param string $code Type of contact (code or id)
  1006. * @return int >0 if OK, <0 if KO
  1007. */
  1008. public function delete_linked_contact($source = '', $code = '')
  1009. {
  1010. // phpcs:enable
  1011. $temp = array();
  1012. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  1013. foreach ($typeContact as $key => $value)
  1014. {
  1015. array_push($temp, $key);
  1016. }
  1017. $listId = implode(",", $temp);
  1018. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  1019. $sql .= " WHERE element_id = ".$this->id;
  1020. if ($listId)
  1021. $sql .= " AND fk_c_type_contact IN (".$listId.")";
  1022. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  1023. if ($this->db->query($sql))
  1024. {
  1025. return 1;
  1026. } else {
  1027. $this->error = $this->db->lasterror();
  1028. return -1;
  1029. }
  1030. }
  1031. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1032. /**
  1033. * Get array of all contacts for an object
  1034. *
  1035. * @param int $status Status of links to get (-1=all)
  1036. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  1037. * @param int $list 0:Return array contains all properties, 1:Return array contains just id
  1038. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1039. * @return array|int Array of contacts, -1 if error
  1040. */
  1041. public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
  1042. {
  1043. // phpcs:enable
  1044. global $langs;
  1045. $tab = array();
  1046. $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
  1047. if ($source == 'internal') $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  1048. if ($source == 'external' || $source == 'thirdparty') $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1049. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  1050. $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
  1051. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
  1052. $sql .= ", ".MAIN_DB_PREFIX."element_contact ec";
  1053. if ($source == 'internal') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
  1054. if ($source == 'external' || $source == 'thirdparty') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
  1055. $sql .= " WHERE ec.element_id =".$this->id;
  1056. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1057. $sql .= " AND tc.element='".$this->db->escape($this->element)."'";
  1058. if ($code) $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1059. if ($source == 'internal') $sql .= " AND tc.source = 'internal'";
  1060. if ($source == 'external' || $source == 'thirdparty') $sql .= " AND tc.source = 'external'";
  1061. $sql .= " AND tc.active=1";
  1062. if ($status >= 0) $sql .= " AND ec.statut = ".$status;
  1063. $sql .= " ORDER BY t.lastname ASC";
  1064. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  1065. $resql = $this->db->query($sql);
  1066. if ($resql)
  1067. {
  1068. $num = $this->db->num_rows($resql);
  1069. $i = 0;
  1070. while ($i < $num)
  1071. {
  1072. $obj = $this->db->fetch_object($resql);
  1073. if (!$list)
  1074. {
  1075. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1076. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1077. $tab[$i] = array('source'=>$obj->source, 'socid'=>$obj->socid, 'id'=>$obj->id,
  1078. 'nom'=>$obj->lastname, // For backward compatibility
  1079. 'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'login'=>$obj->login, 'photo'=>$obj->photo, 'statuscontact'=>$obj->statuscontact,
  1080. 'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact);
  1081. } else {
  1082. $tab[$i] = $obj->id;
  1083. }
  1084. $i++;
  1085. }
  1086. return $tab;
  1087. } else {
  1088. $this->error = $this->db->lasterror();
  1089. dol_print_error($this->db);
  1090. return -1;
  1091. }
  1092. }
  1093. /**
  1094. * Update status of a contact linked to object
  1095. *
  1096. * @param int $rowid Id of link between object and contact
  1097. * @return int <0 if KO, >=0 if OK
  1098. */
  1099. public function swapContactStatus($rowid)
  1100. {
  1101. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1102. $sql .= " tc.code, tc.libelle";
  1103. $sql .= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)";
  1104. $sql .= " WHERE ec.rowid =".$rowid;
  1105. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1106. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1107. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  1108. $resql = $this->db->query($sql);
  1109. if ($resql)
  1110. {
  1111. $obj = $this->db->fetch_object($resql);
  1112. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1113. $result = $this->update_contact($rowid, $newstatut);
  1114. $this->db->free($resql);
  1115. return $result;
  1116. } else {
  1117. $this->error = $this->db->error();
  1118. dol_print_error($this->db);
  1119. return -1;
  1120. }
  1121. }
  1122. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1123. /**
  1124. * Return array with list of possible values for type of contacts
  1125. *
  1126. * @param string $source 'internal', 'external' or 'all'
  1127. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  1128. * @param int $option 0=Return array id->label, 1=Return array code->label
  1129. * @param int $activeonly 0=all status of contact, 1=only the active
  1130. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1131. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1132. */
  1133. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1134. {
  1135. // phpcs:enable
  1136. global $langs;
  1137. if (empty($order)) $order = 'position';
  1138. if ($order == 'position') $order .= ',code';
  1139. $tab = array();
  1140. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  1141. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  1142. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1143. if ($activeonly == 1) $sql .= " AND tc.active=1"; // only the active types
  1144. if (!empty($source) && $source != 'all') $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1145. if (!empty($code)) $sql .= " AND tc.code='".$this->db->escape($code)."'";
  1146. $sql .= $this->db->order($order, 'ASC');
  1147. //print "sql=".$sql;
  1148. $resql = $this->db->query($sql);
  1149. if ($resql)
  1150. {
  1151. $num = $this->db->num_rows($resql);
  1152. $i = 0;
  1153. while ($i < $num)
  1154. {
  1155. $obj = $this->db->fetch_object($resql);
  1156. $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
  1157. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1158. if (empty($option)) $tab[$obj->rowid] = $libelle_type;
  1159. else $tab[$obj->code] = $libelle_type;
  1160. $i++;
  1161. }
  1162. return $tab;
  1163. } else {
  1164. $this->error = $this->db->lasterror();
  1165. //dol_print_error($this->db);
  1166. return null;
  1167. }
  1168. }
  1169. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1170. /**
  1171. * Return array with list of possible values for type of contacts
  1172. *
  1173. * @param string $source 'internal', 'external' or 'all'
  1174. * @param int $option 0=Return array id->label, 1=Return array code->label
  1175. * @param int $activeonly 0=all status of contact, 1=only the active
  1176. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1177. * @param string $element Filter on 1 element type
  1178. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1179. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1180. */
  1181. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1182. {
  1183. // phpcs:enable
  1184. global $langs, $conf;
  1185. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1186. $tab = array();
  1187. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
  1188. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  1189. $sqlWhere = array();
  1190. if (!empty($element)) {
  1191. $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
  1192. }
  1193. if (!empty($excludeelement)) {
  1194. $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
  1195. }
  1196. if ($activeonly == 1)
  1197. $sqlWhere[] = " tc.active=1"; // only the active types
  1198. if (!empty($source) && $source != 'all')
  1199. $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
  1200. if (!empty($code))
  1201. $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
  1202. if (count($sqlWhere) > 0) {
  1203. $sql .= " WHERE ".implode(' AND ', $sqlWhere);
  1204. }
  1205. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1206. dol_syslog(__METHOD__, LOG_DEBUG);
  1207. $resql = $this->db->query($sql);
  1208. if ($resql) {
  1209. $num = $this->db->num_rows($resql);
  1210. if ($num > 0) {
  1211. while ($obj = $this->db->fetch_object($resql)) {
  1212. $modulename = $obj->element;
  1213. if (strpos($obj->element, 'project') !== false) {
  1214. $modulename = 'projet';
  1215. } elseif ($obj->element == 'contrat') {
  1216. $element = 'contract';
  1217. } elseif ($obj->element == 'action') {
  1218. $modulename = 'agenda';
  1219. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1220. $modulename = 'fournisseur';
  1221. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1222. $modulename = 'fournisseur';
  1223. }
  1224. if ($conf->{$modulename}->enabled) {
  1225. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1226. $transkey = "TypeContact_".$obj->element."_".$source."_".$obj->code;
  1227. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1228. if (empty($option))
  1229. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1230. else $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1231. }
  1232. }
  1233. }
  1234. return $tab;
  1235. } else {
  1236. $this->error = $this->db->lasterror();
  1237. return null;
  1238. }
  1239. }
  1240. /**
  1241. * Return id of contacts for a source and a contact code.
  1242. * Example: contact client de facturation ('external', 'BILLING')
  1243. * Example: contact client de livraison ('external', 'SHIPPING')
  1244. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1245. *
  1246. * @param string $source 'external' or 'internal'
  1247. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1248. * @param int $status limited to a certain status
  1249. * @return array List of id for such contacts
  1250. */
  1251. public function getIdContact($source, $code, $status = 0)
  1252. {
  1253. global $conf;
  1254. $result = array();
  1255. $i = 0;
  1256. //cas particulier pour les expeditions
  1257. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1258. $id = $this->origin_id;
  1259. $element = 'commande';
  1260. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1261. $id = $this->origin_id;
  1262. $element = 'order_supplier';
  1263. } else {
  1264. $id = $this->id;
  1265. $element = $this->element;
  1266. }
  1267. $sql = "SELECT ec.fk_socpeople";
  1268. $sql .= " FROM ".MAIN_DB_PREFIX."element_contact as ec,";
  1269. if ($source == 'internal') $sql .= " ".MAIN_DB_PREFIX."user as c,";
  1270. if ($source == 'external') $sql .= " ".MAIN_DB_PREFIX."socpeople as c,";
  1271. $sql .= " ".MAIN_DB_PREFIX."c_type_contact as tc";
  1272. $sql .= " WHERE ec.element_id = ".$id;
  1273. $sql .= " AND ec.fk_socpeople = c.rowid";
  1274. if ($source == 'internal') $sql .= " AND c.entity IN (".getEntity('user').")";
  1275. if ($source == 'external') $sql .= " AND c.entity IN (".getEntity('societe').")";
  1276. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1277. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1278. $sql .= " AND tc.source = '".$this->db->escape($source)."'";
  1279. if ($code) $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1280. $sql .= " AND tc.active = 1";
  1281. if ($status) $sql .= " AND ec.statut = ".$status;
  1282. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1283. $resql = $this->db->query($sql);
  1284. if ($resql)
  1285. {
  1286. while ($obj = $this->db->fetch_object($resql))
  1287. {
  1288. $result[$i] = $obj->fk_socpeople;
  1289. $i++;
  1290. }
  1291. } else {
  1292. $this->error = $this->db->error();
  1293. return null;
  1294. }
  1295. return $result;
  1296. }
  1297. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1298. /**
  1299. * Load object contact with id=$this->contact_id into $this->contact
  1300. *
  1301. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1302. * @return int <0 if KO, >0 if OK
  1303. */
  1304. public function fetch_contact($contactid = null)
  1305. {
  1306. // phpcs:enable
  1307. if (empty($contactid)) $contactid = $this->contact_id;
  1308. if (empty($contactid)) return 0;
  1309. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1310. $contact = new Contact($this->db);
  1311. $result = $contact->fetch($contactid);
  1312. $this->contact = $contact;
  1313. return $result;
  1314. }
  1315. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1316. /**
  1317. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1318. *
  1319. * @param int $force_thirdparty_id Force thirdparty id
  1320. * @return int <0 if KO, >0 if OK
  1321. */
  1322. public function fetch_thirdparty($force_thirdparty_id = 0)
  1323. {
  1324. // phpcs:enable
  1325. global $conf;
  1326. if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id))
  1327. return 0;
  1328. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1329. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
  1330. if ($force_thirdparty_id)
  1331. $idtofetch = $force_thirdparty_id;
  1332. if ($idtofetch) {
  1333. $thirdparty = new Societe($this->db);
  1334. $result = $thirdparty->fetch($idtofetch);
  1335. $this->thirdparty = $thirdparty;
  1336. // Use first price level if level not defined for third party
  1337. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1338. $this->thirdparty->price_level = 1;
  1339. }
  1340. return $result;
  1341. } else return -1;
  1342. }
  1343. /**
  1344. * Looks for an object with ref matching the wildcard provided
  1345. * It does only work when $this->table_ref_field is set
  1346. *
  1347. * @param string $ref Wildcard
  1348. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1349. */
  1350. public function fetchOneLike($ref)
  1351. {
  1352. if (!$this->table_ref_field) {
  1353. return 0;
  1354. }
  1355. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE '.$this->table_ref_field.' LIKE "'.$this->db->escape($ref).'" LIMIT 1';
  1356. $query = $this->db->query($sql);
  1357. if (!$this->db->num_rows($query)) {
  1358. return 0;
  1359. }
  1360. $result = $this->db->fetch_object($query);
  1361. return $this->fetch($result->rowid);
  1362. }
  1363. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1364. /**
  1365. * Load data for barcode into properties ->barcode_type*
  1366. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1367. * if it is not defined, ->element must be defined to know default barcode type.
  1368. *
  1369. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1370. */
  1371. public function fetch_barcode()
  1372. {
  1373. // phpcs:enable
  1374. global $conf;
  1375. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1376. $idtype = $this->barcode_type;
  1377. 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
  1378. {
  1379. if ($this->element == 'product') $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1380. elseif ($this->element == 'societe') $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1381. else dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1382. }
  1383. if ($idtype > 0)
  1384. {
  1385. 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
  1386. {
  1387. $sql = "SELECT rowid, code, libelle as label, coder";
  1388. $sql .= " FROM ".MAIN_DB_PREFIX."c_barcode_type";
  1389. $sql .= " WHERE rowid = ".$idtype;
  1390. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1391. $resql = $this->db->query($sql);
  1392. if ($resql)
  1393. {
  1394. $obj = $this->db->fetch_object($resql);
  1395. $this->barcode_type = $obj->rowid;
  1396. $this->barcode_type_code = $obj->code;
  1397. $this->barcode_type_label = $obj->label;
  1398. $this->barcode_type_coder = $obj->coder;
  1399. return 1;
  1400. } else {
  1401. dol_print_error($this->db);
  1402. return -1;
  1403. }
  1404. }
  1405. }
  1406. return 0;
  1407. }
  1408. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1409. /**
  1410. * Load the project with id $this->fk_project into this->project
  1411. *
  1412. * @return int <0 if KO, >=0 if OK
  1413. */
  1414. public function fetch_projet()
  1415. {
  1416. // phpcs:enable
  1417. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1418. if (empty($this->fk_project) && !empty($this->fk_projet)) $this->fk_project = $this->fk_projet; // For backward compatibility
  1419. if (empty($this->fk_project)) return 0;
  1420. $project = new Project($this->db);
  1421. $result = $project->fetch($this->fk_project);
  1422. $this->projet = $project; // deprecated
  1423. $this->project = $project;
  1424. return $result;
  1425. }
  1426. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1427. /**
  1428. * Load the product with id $this->fk_product into this->product
  1429. *
  1430. * @return int <0 if KO, >=0 if OK
  1431. */
  1432. public function fetch_product()
  1433. {
  1434. // phpcs:enable
  1435. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1436. if (empty($this->fk_product)) return 0;
  1437. $product = new Product($this->db);
  1438. $result = $product->fetch($this->fk_product);
  1439. $this->product = $product;
  1440. return $result;
  1441. }
  1442. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1443. /**
  1444. * Load the user with id $userid into this->user
  1445. *
  1446. * @param int $userid Id du contact
  1447. * @return int <0 if KO, >0 if OK
  1448. */
  1449. public function fetch_user($userid)
  1450. {
  1451. // phpcs:enable
  1452. $user = new User($this->db);
  1453. $result = $user->fetch($userid);
  1454. $this->user = $user;
  1455. return $result;
  1456. }
  1457. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1458. /**
  1459. * Read linked origin object
  1460. *
  1461. * @return void
  1462. */
  1463. public function fetch_origin()
  1464. {
  1465. // phpcs:enable
  1466. if ($this->origin == 'shipping') $this->origin = 'expedition';
  1467. if ($this->origin == 'delivery') $this->origin = 'livraison';
  1468. if ($this->origin == 'order_supplier') $this->origin = 'commandeFournisseur';
  1469. $origin = $this->origin;
  1470. $classname = ucfirst($origin);
  1471. $this->$origin = new $classname($this->db);
  1472. $this->$origin->fetch($this->origin_id);
  1473. }
  1474. /**
  1475. * Load object from specific field
  1476. *
  1477. * @param string $table Table element or element line
  1478. * @param string $field Field selected
  1479. * @param string $key Import key
  1480. * @param string $element Element name
  1481. * @return int <0 if KO, >0 if OK
  1482. */
  1483. public function fetchObjectFrom($table, $field, $key, $element = null)
  1484. {
  1485. global $conf;
  1486. $result = false;
  1487. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$table;
  1488. $sql .= " WHERE ".$field." = '".$key."'";
  1489. if (!empty($element)) {
  1490. $sql .= " AND entity IN (".getEntity($element).")";
  1491. } else {
  1492. $sql .= " AND entity = ".$conf->entity;
  1493. }
  1494. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1495. $resql = $this->db->query($sql);
  1496. if ($resql)
  1497. {
  1498. $row = $this->db->fetch_row($resql);
  1499. // Test for avoid error -1
  1500. if ($row[0] > 0) {
  1501. $result = $this->fetch($row[0]);
  1502. }
  1503. }
  1504. return $result;
  1505. }
  1506. /**
  1507. * Getter generic. Load value from a specific field
  1508. *
  1509. * @param string $table Table of element or element line
  1510. * @param int $id Element id
  1511. * @param string $field Field selected
  1512. * @return int <0 if KO, >0 if OK
  1513. */
  1514. public function getValueFrom($table, $id, $field)
  1515. {
  1516. $result = false;
  1517. if (!empty($id) && !empty($field) && !empty($table)) {
  1518. $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table;
  1519. $sql .= " WHERE rowid = ".$id;
  1520. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1521. $resql = $this->db->query($sql);
  1522. if ($resql)
  1523. {
  1524. $row = $this->db->fetch_row($resql);
  1525. $result = $row[0];
  1526. }
  1527. }
  1528. return $result;
  1529. }
  1530. /**
  1531. * Setter generic. Update a specific field into database.
  1532. * Warning: Trigger is run only if param trigkey is provided.
  1533. *
  1534. * @param string $field Field to update
  1535. * @param mixed $value New value
  1536. * @param string $table To force other table element or element line (should not be used)
  1537. * @param int $id To force other object id (should not be used)
  1538. * @param string $format Data format ('text', 'date'). 'text' is used if not defined
  1539. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1540. * @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'
  1541. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1542. * @param string $fk_user_field Name of field to save user id making change
  1543. * @return int <0 if KO, >0 if OK
  1544. * @see updateExtraField()
  1545. */
  1546. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1547. {
  1548. global $user, $langs, $conf;
  1549. if (empty($table)) $table = $this->table_element;
  1550. if (empty($id)) $id = $this->id;
  1551. if (empty($format)) $format = 'text';
  1552. if (empty($id_field)) $id_field = 'rowid';
  1553. $error = 0;
  1554. $this->db->begin();
  1555. // Special case
  1556. if ($table == 'product' && $field == 'note_private') $field = 'note';
  1557. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) $fk_user_field = 'fk_user_mod';
  1558. $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
  1559. if ($format == 'text') $sql .= $field." = '".$this->db->escape($value)."'";
  1560. elseif ($format == 'int') $sql .= $field." = ".$this->db->escape($value);
  1561. elseif ($format == 'date') $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1562. if ($fk_user_field)
  1563. {
  1564. if (!empty($fuser) && is_object($fuser)) $sql .= ", ".$fk_user_field." = ".$fuser->id;
  1565. elseif (empty($fuser) || $fuser != 'none') $sql .= ", ".$fk_user_field." = ".$user->id;
  1566. }
  1567. $sql .= " WHERE ".$id_field." = ".$id;
  1568. dol_syslog(__METHOD__."", LOG_DEBUG);
  1569. $resql = $this->db->query($sql);
  1570. if ($resql)
  1571. {
  1572. if ($trigkey)
  1573. {
  1574. // call trigger with updated object values
  1575. if (empty($this->fields) && method_exists($this, 'fetch'))
  1576. {
  1577. $result = $this->fetch($id);
  1578. } else {
  1579. $result = $this->fetchCommon($id);
  1580. }
  1581. if ($result >= 0) $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1582. if ($result < 0) $error++;
  1583. }
  1584. if (!$error)
  1585. {
  1586. if (property_exists($this, $field)) $this->$field = $value;
  1587. $this->db->commit();
  1588. return 1;
  1589. } else {
  1590. $this->db->rollback();
  1591. return -2;
  1592. }
  1593. } else {
  1594. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1595. $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
  1596. } else {
  1597. $this->error = $this->db->lasterror();
  1598. }
  1599. $this->db->rollback();
  1600. return -1;
  1601. }
  1602. }
  1603. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1604. /**
  1605. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1606. *
  1607. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')"
  1608. * @param string $fieldid Name of field to use for the select MAX and MIN
  1609. * @param int $nodbprefix Do not include DB prefix to forge table name
  1610. * @return int <0 if KO, >0 if OK
  1611. */
  1612. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1613. {
  1614. // phpcs:enable
  1615. global $conf, $user;
  1616. if (!$this->table_element)
  1617. {
  1618. dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1619. return -1;
  1620. }
  1621. if ($fieldid == 'none') return 1;
  1622. // Security on socid
  1623. $socid = 0;
  1624. if ($user->socid > 0) $socid = $user->socid;
  1625. // this->ismultientitymanaged contains
  1626. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1627. $aliastablesociete = 's';
  1628. if ($this->element == 'societe') $aliastablesociete = 'te'; // te as table_element
  1629. $sql = "SELECT MAX(te.".$fieldid.")";
  1630. $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1631. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1632. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  1633. }
  1634. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1635. $tmparray = explode('@', $this->ismultientitymanaged);
  1636. $sql .= ", ".MAIN_DB_PREFIX.$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1637. } elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid
  1638. elseif ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1639. if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1640. $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)
  1641. if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id;
  1642. if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)';
  1643. if (!empty($filter))
  1644. {
  1645. if (!preg_match('/^\s*AND/i', $filter)) $sql .= " AND "; // For backward compatibility
  1646. $sql .= $filter;
  1647. }
  1648. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1649. $tmparray = explode('@', $this->ismultientitymanaged);
  1650. $sql .= ' AND te.'.$tmparray[0].' = '.($tmparray[1] == 'societe' ? 's' : 'parenttable').'.rowid'; // If we need to link to this table to limit select to entity
  1651. } elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1652. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1653. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1654. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1655. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1656. } else {
  1657. $sql .= " AND ug.fk_user = te.rowid";
  1658. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1659. }
  1660. } else {
  1661. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1662. }
  1663. }
  1664. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1665. $tmparray = explode('@', $this->ismultientitymanaged);
  1666. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1667. }
  1668. if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql .= ' AND te.fk_soc = '.$socid;
  1669. if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql .= ' AND (te.fk_soc = '.$socid.' OR te.fk_soc IS NULL)';
  1670. if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql .= ' AND te.rowid = '.$socid;
  1671. //print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1672. $result = $this->db->query($sql);
  1673. if (!$result)
  1674. {
  1675. $this->error = $this->db->lasterror();
  1676. return -1;
  1677. }
  1678. $row = $this->db->fetch_row($result);
  1679. $this->ref_previous = $row[0];
  1680. $sql = "SELECT MIN(te.".$fieldid.")";
  1681. $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1682. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1683. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  1684. }
  1685. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1686. $tmparray = explode('@', $this->ismultientitymanaged);
  1687. $sql .= ", ".MAIN_DB_PREFIX.$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1688. } elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid
  1689. elseif ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1690. if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1691. $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)
  1692. if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id;
  1693. if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)';
  1694. if (!empty($filter))
  1695. {
  1696. if (!preg_match('/^\s*AND/i', $filter)) $sql .= " AND "; // For backward compatibility
  1697. $sql .= $filter;
  1698. }
  1699. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1700. $tmparray = explode('@', $this->ismultientitymanaged);
  1701. $sql .= ' AND te.'.$tmparray[0].' = '.($tmparray[1] == 'societe' ? 's' : 'parenttable').'.rowid'; // If we need to link to this table to limit select to entity
  1702. } elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1703. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1704. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1705. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1706. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1707. } else {
  1708. $sql .= " AND ug.fk_user = te.rowid";
  1709. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1710. }
  1711. } else {
  1712. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1713. }
  1714. }
  1715. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1716. $tmparray = explode('@', $this->ismultientitymanaged);
  1717. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1718. }
  1719. if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql .= ' AND te.fk_soc = '.$socid;
  1720. if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql .= ' AND (te.fk_soc = '.$socid.' OR te.fk_soc IS NULL)';
  1721. if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql .= ' AND te.rowid = '.$socid;
  1722. //print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1723. // 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
  1724. $result = $this->db->query($sql);
  1725. if (!$result)
  1726. {
  1727. $this->error = $this->db->lasterror();
  1728. return -2;
  1729. }
  1730. $row = $this->db->fetch_row($result);
  1731. $this->ref_next = $row[0];
  1732. return 1;
  1733. }
  1734. /**
  1735. * Return list of id of contacts of object
  1736. *
  1737. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  1738. * @return array Array of id of contacts (if source=external or internal)
  1739. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  1740. */
  1741. public function getListContactId($source = 'external')
  1742. {
  1743. $contactAlreadySelected = array();
  1744. $tab = $this->liste_contact(-1, $source);
  1745. $num = count($tab);
  1746. $i = 0;
  1747. while ($i < $num)
  1748. {
  1749. if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid'];
  1750. else $contactAlreadySelected[$i] = $tab[$i]['id'];
  1751. $i++;
  1752. }
  1753. return $contactAlreadySelected;
  1754. }
  1755. /**
  1756. * Link element with a project
  1757. *
  1758. * @param int $projectid Project id to link element to
  1759. * @return int <0 if KO, >0 if OK
  1760. */
  1761. public function setProject($projectid)
  1762. {
  1763. if (!$this->table_element)
  1764. {
  1765. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  1766. return -1;
  1767. }
  1768. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1769. if (!empty($this->fields['fk_project'])) // Common case
  1770. {
  1771. if ($projectid) $sql .= ' SET fk_project = '.$projectid;
  1772. else $sql .= ' SET fk_project = NULL';
  1773. $sql .= ' WHERE rowid = '.$this->id;
  1774. } elseif ($this->table_element == 'actioncomm') // Special case for actioncomm
  1775. {
  1776. if ($projectid) $sql .= ' SET fk_project = '.$projectid;
  1777. else $sql .= ' SET fk_project = NULL';
  1778. $sql .= ' WHERE id = '.$this->id;
  1779. } else // Special case for old architecture objects
  1780. {
  1781. if ($projectid) $sql .= ' SET fk_projet = '.$projectid;
  1782. else $sql .= ' SET fk_projet = NULL';
  1783. $sql .= ' WHERE rowid = '.$this->id;
  1784. }
  1785. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  1786. if ($this->db->query($sql))
  1787. {
  1788. $this->fk_project = $projectid;
  1789. return 1;
  1790. } else {
  1791. dol_print_error($this->db);
  1792. return -1;
  1793. }
  1794. }
  1795. /**
  1796. * Change the payments methods
  1797. *
  1798. * @param int $id Id of new payment method
  1799. * @return int >0 if OK, <0 if KO
  1800. */
  1801. public function setPaymentMethods($id)
  1802. {
  1803. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  1804. if ($this->statut >= 0 || $this->element == 'societe')
  1805. {
  1806. // TODO uniformize field name
  1807. $fieldname = 'fk_mode_reglement';
  1808. if ($this->element == 'societe') $fieldname = 'mode_reglement';
  1809. if (get_class($this) == 'Fournisseur') $fieldname = 'mode_reglement_supplier';
  1810. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1811. $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL');
  1812. $sql .= ' WHERE rowid='.$this->id;
  1813. if ($this->db->query($sql))
  1814. {
  1815. $this->mode_reglement_id = $id;
  1816. // for supplier
  1817. if (get_class($this) == 'Fournisseur') $this->mode_reglement_supplier_id = $id;
  1818. return 1;
  1819. } else {
  1820. dol_syslog(get_class($this).'::setPaymentMethods Error '.$sql.' - '.$this->db->error());
  1821. $this->error = $this->db->error();
  1822. return -1;
  1823. }
  1824. } else {
  1825. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  1826. $this->error = 'Status of the object is incompatible '.$this->statut;
  1827. return -2;
  1828. }
  1829. }
  1830. /**
  1831. * Change the multicurrency code
  1832. *
  1833. * @param string $code multicurrency code
  1834. * @return int >0 if OK, <0 if KO
  1835. */
  1836. public function setMulticurrencyCode($code)
  1837. {
  1838. dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
  1839. if ($this->statut >= 0 || $this->element == 'societe')
  1840. {
  1841. $fieldname = 'multicurrency_code';
  1842. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1843. $sql .= ' SET '.$fieldname." = '".$this->db->escape($code)."'";
  1844. $sql .= ' WHERE rowid='.$this->id;
  1845. if ($this->db->query($sql))
  1846. {
  1847. $this->multicurrency_code = $code;
  1848. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  1849. if ($rate) $this->setMulticurrencyRate($rate, 2);
  1850. return 1;
  1851. } else {
  1852. dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
  1853. $this->error = $this->db->error();
  1854. return -1;
  1855. }
  1856. } else {
  1857. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  1858. $this->error = 'Status of the object is incompatible '.$this->statut;
  1859. return -2;
  1860. }
  1861. }
  1862. /**
  1863. * Change the multicurrency rate
  1864. *
  1865. * @param double $rate multicurrency rate
  1866. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  1867. * @return int >0 if OK, <0 if KO
  1868. */
  1869. public function setMulticurrencyRate($rate, $mode = 1)
  1870. {
  1871. dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
  1872. if ($this->statut >= 0 || $this->element == 'societe')
  1873. {
  1874. $fieldname = 'multicurrency_tx';
  1875. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1876. $sql .= ' SET '.$fieldname.' = '.$rate;
  1877. $sql .= ' WHERE rowid='.$this->id;
  1878. if ($this->db->query($sql))
  1879. {
  1880. $this->multicurrency_tx = $rate;
  1881. // Update line price
  1882. if (!empty($this->lines))
  1883. {
  1884. foreach ($this->lines as &$line)
  1885. {
  1886. // Amounts in company currency will be recalculated
  1887. if ($mode == 1) {
  1888. $line->subprice = 0;
  1889. }
  1890. // Amounts in foreign currency will be recalculated
  1891. if ($mode == 2) {
  1892. $line->multicurrency_subprice = 0;
  1893. }
  1894. switch ($this->element) {
  1895. case 'propal':
  1896. $this->updateline(
  1897. $line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx,
  1898. ($line->description ? $line->description : $line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line,
  1899. $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->date_start,
  1900. $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
  1901. );
  1902. break;
  1903. case 'commande':
  1904. $this->updateline(
  1905. $line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->qty, $line->remise_percent,
  1906. $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->date_start, $line->date_end,
  1907. $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label,
  1908. $line->special_code, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
  1909. );
  1910. break;
  1911. case 'facture':
  1912. $this->updateline(
  1913. $line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->qty, $line->remise_percent,
  1914. $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits,
  1915. $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label,
  1916. $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice
  1917. );
  1918. break;
  1919. case 'supplier_proposal':
  1920. $this->updateline(
  1921. $line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx,
  1922. ($line->description ? $line->description : $line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line,
  1923. $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->array_options,
  1924. $line->ref_fourn, $line->multicurrency_subprice
  1925. );
  1926. break;
  1927. case 'order_supplier':
  1928. $this->updateline(
  1929. $line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->qty, $line->remise_percent,
  1930. $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, false,
  1931. $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
  1932. );
  1933. break;
  1934. case 'invoice_supplier':
  1935. $this->updateline(
  1936. $line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->tva_tx, $line->localtax1_tx,
  1937. $line->localtax2_tx, $line->qty, 0, 'HT', $line->info_bits, $line->product_type, $line->remise_percent, false,
  1938. $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
  1939. );
  1940. break;
  1941. default:
  1942. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  1943. break;
  1944. }
  1945. }
  1946. }
  1947. return 1;
  1948. } else {
  1949. dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
  1950. $this->error = $this->db->error();
  1951. return -1;
  1952. }
  1953. } else {
  1954. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  1955. $this->error = 'Status of the object is incompatible '.$this->statut;
  1956. return -2;
  1957. }
  1958. }
  1959. /**
  1960. * Change the payments terms
  1961. *
  1962. * @param int $id Id of new payment terms
  1963. * @return int >0 if OK, <0 if KO
  1964. */
  1965. public function setPaymentTerms($id)
  1966. {
  1967. dol_syslog(get_class($this).'::setPaymentTerms('.$id.')');
  1968. if ($this->statut >= 0 || $this->element == 'societe')
  1969. {
  1970. // TODO uniformize field name
  1971. $fieldname = 'fk_cond_reglement';
  1972. if ($this->element == 'societe') $fieldname = 'cond_reglement';
  1973. if (get_class($this) == 'Fournisseur') $fieldname = 'cond_reglement_supplier';
  1974. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1975. $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL');
  1976. $sql .= ' WHERE rowid='.$this->id;
  1977. if ($this->db->query($sql))
  1978. {
  1979. $this->cond_reglement_id = $id;
  1980. // for supplier
  1981. if (get_class($this) == 'Fournisseur') $this->cond_reglement_supplier_id = $id;
  1982. $this->cond_reglement = $id; // for compatibility
  1983. return 1;
  1984. } else {
  1985. dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
  1986. $this->error = $this->db->error();
  1987. return -1;
  1988. }
  1989. } else {
  1990. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  1991. $this->error = 'Status of the object is incompatible '.$this->statut;
  1992. return -2;
  1993. }
  1994. }
  1995. /**
  1996. * Change the transport mode methods
  1997. *
  1998. * @param int $id Id of new payment method
  1999. * @return int >0 if OK, <0 if KO
  2000. */
  2001. public function setTransportMode($id)
  2002. {
  2003. dol_syslog(get_class($this).'::setTransportMode('.$id.')');
  2004. if ($this->statut >= 0 || $this->element == 'societe')
  2005. {
  2006. $fieldname = 'fk_transport_mode';
  2007. if ($this->element == 'societe') $fieldname = 'transport_mode';
  2008. if (get_class($this) == 'Fournisseur') $fieldname = 'transport_mode_supplier';
  2009. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2010. $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL');
  2011. $sql .= ' WHERE rowid='.$this->id;
  2012. if ($this->db->query($sql))
  2013. {
  2014. $this->transport_mode_id = $id;
  2015. // for supplier
  2016. if (get_class($this) == 'Fournisseur') $this->transport_mode_supplier_id = $id;
  2017. return 1;
  2018. } else {
  2019. dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
  2020. $this->error = $this->db->error();
  2021. return -1;
  2022. }
  2023. } else {
  2024. dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
  2025. $this->error = 'Status of the object is incompatible '.$this->statut;
  2026. return -2;
  2027. }
  2028. }
  2029. /**
  2030. * Change the retained warranty payments terms
  2031. *
  2032. * @param int $id Id of new payment terms
  2033. * @return int >0 if OK, <0 if KO
  2034. */
  2035. public function setRetainedWarrantyPaymentTerms($id)
  2036. {
  2037. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
  2038. if ($this->statut >= 0 || $this->element == 'societe')
  2039. {
  2040. $fieldname = 'retained_warranty_fk_cond_reglement';
  2041. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2042. $sql .= ' SET '.$fieldname.' = '.$id;
  2043. $sql .= ' WHERE rowid='.$this->id;
  2044. if ($this->db->query($sql))
  2045. {
  2046. $this->retained_warranty_fk_cond_reglement = $id;
  2047. return 1;
  2048. } else {
  2049. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
  2050. $this->error = $this->db->error();
  2051. return -1;
  2052. }
  2053. } else {
  2054. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  2055. $this->error = 'Status of the object is incompatible '.$this->statut;
  2056. return -2;
  2057. }
  2058. }
  2059. /**
  2060. * Define delivery address
  2061. * @deprecated
  2062. *
  2063. * @param int $id Address id
  2064. * @return int <0 si ko, >0 si ok
  2065. */
  2066. public function setDeliveryAddress($id)
  2067. {
  2068. $fieldname = 'fk_delivery_address';
  2069. if ($this->element == 'delivery' || $this->element == 'shipping') $fieldname = 'fk_address';
  2070. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".$id;
  2071. $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0";
  2072. if ($this->db->query($sql))
  2073. {
  2074. $this->fk_delivery_address = $id;
  2075. return 1;
  2076. } else {
  2077. $this->error = $this->db->error();
  2078. dol_syslog(get_class($this).'::setDeliveryAddress Error '.$sql.' - '.$this->error);
  2079. return -1;
  2080. }
  2081. }
  2082. /**
  2083. * Change the shipping method
  2084. *
  2085. * @param int $shipping_method_id Id of shipping method
  2086. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2087. * @param User $userused Object user
  2088. *
  2089. * @return int 1 if OK, 0 if KO
  2090. */
  2091. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  2092. {
  2093. global $user;
  2094. if (empty($userused)) $userused = $user;
  2095. $error = 0;
  2096. if (!$this->table_element) {
  2097. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2098. return -1;
  2099. }
  2100. $this->db->begin();
  2101. if ($shipping_method_id < 0) $shipping_method_id = 'NULL';
  2102. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  2103. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2104. $sql .= " SET fk_shipping_method = ".$shipping_method_id;
  2105. $sql .= " WHERE rowid=".$this->id;
  2106. $resql = $this->db->query($sql);
  2107. if (!$resql) {
  2108. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  2109. $this->error = $this->db->lasterror();
  2110. $error++;
  2111. } else {
  2112. if (!$notrigger)
  2113. {
  2114. // Call trigger
  2115. $this->context = array('shippingmethodupdate'=>1);
  2116. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2117. if ($result < 0) $error++;
  2118. // End call trigger
  2119. }
  2120. }
  2121. if ($error)
  2122. {
  2123. $this->db->rollback();
  2124. return -1;
  2125. } else {
  2126. $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
  2127. $this->db->commit();
  2128. return 1;
  2129. }
  2130. }
  2131. /**
  2132. * Change the warehouse
  2133. *
  2134. * @param int $warehouse_id Id of warehouse
  2135. * @return int 1 if OK, 0 if KO
  2136. */
  2137. public function setWarehouse($warehouse_id)
  2138. {
  2139. if (!$this->table_element) {
  2140. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2141. return -1;
  2142. }
  2143. if ($warehouse_id < 0) $warehouse_id = 'NULL';
  2144. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  2145. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2146. $sql .= " SET fk_warehouse = ".$warehouse_id;
  2147. $sql .= " WHERE rowid=".$this->id;
  2148. if ($this->db->query($sql)) {
  2149. $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
  2150. return 1;
  2151. } else {
  2152. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  2153. $this->error = $this->db->error();
  2154. return 0;
  2155. }
  2156. }
  2157. /**
  2158. * Set last model used by doc generator
  2159. *
  2160. * @param User $user User object that make change
  2161. * @param string $modelpdf Modele name
  2162. * @return int <0 if KO, >0 if OK
  2163. */
  2164. public function setDocModel($user, $modelpdf)
  2165. {
  2166. if (!$this->table_element)
  2167. {
  2168. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2169. return -1;
  2170. }
  2171. $newmodelpdf = dol_trunc($modelpdf, 255);
  2172. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2173. $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  2174. $sql .= " WHERE rowid = ".$this->id;
  2175. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  2176. $resql = $this->db->query($sql);
  2177. if ($resql)
  2178. {
  2179. $this->model_pdf = $modelpdf;
  2180. $this->modelpdf = $modelpdf; // For bakward compatibility
  2181. return 1;
  2182. } else {
  2183. dol_print_error($this->db);
  2184. return 0;
  2185. }
  2186. }
  2187. /**
  2188. * Change the bank account
  2189. *
  2190. * @param int $fk_account Id of bank account
  2191. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2192. * @param User $userused Object user
  2193. * @return int 1 if OK, 0 if KO
  2194. */
  2195. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2196. {
  2197. global $user;
  2198. if (empty($userused)) $userused = $user;
  2199. $error = 0;
  2200. if (!$this->table_element) {
  2201. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2202. return -1;
  2203. }
  2204. $this->db->begin();
  2205. if ($fk_account < 0) $fk_account = 'NULL';
  2206. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  2207. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2208. $sql .= " SET fk_account = ".$fk_account;
  2209. $sql .= " WHERE rowid=".$this->id;
  2210. $resql = $this->db->query($sql);
  2211. if (!$resql)
  2212. {
  2213. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  2214. $this->error = $this->db->lasterror();
  2215. $error++;
  2216. } else {
  2217. if (!$notrigger)
  2218. {
  2219. // Call trigger
  2220. $this->context = array('bankaccountupdate'=>1);
  2221. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2222. if ($result < 0) $error++;
  2223. // End call trigger
  2224. }
  2225. }
  2226. if ($error)
  2227. {
  2228. $this->db->rollback();
  2229. return -1;
  2230. } else {
  2231. $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
  2232. $this->db->commit();
  2233. return 1;
  2234. }
  2235. }
  2236. // TODO: Move line related operations to CommonObjectLine?
  2237. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2238. /**
  2239. * Save a new position (field rang) for details lines.
  2240. * You can choose to set position for lines with already a position or lines without any position defined.
  2241. *
  2242. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2243. * @param string $rowidorder ASC or DESC
  2244. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2245. * @return int <0 if KO, >0 if OK
  2246. */
  2247. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2248. {
  2249. // phpcs:enable
  2250. if (!$this->table_element_line)
  2251. {
  2252. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2253. return -1;
  2254. }
  2255. if (!$this->fk_element)
  2256. {
  2257. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2258. return -1;
  2259. }
  2260. // Count number of lines to reorder (according to choice $renum)
  2261. $nl = 0;
  2262. $sql = 'SELECT count(rowid) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2263. $sql .= ' WHERE '.$this->fk_element.'='.$this->id;
  2264. if (!$renum) $sql .= ' AND rang = 0';
  2265. if ($renum) $sql .= ' AND rang <> 0';
  2266. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  2267. $resql = $this->db->query($sql);
  2268. if ($resql)
  2269. {
  2270. $row = $this->db->fetch_row($resql);
  2271. $nl = $row[0];
  2272. } else dol_print_error($this->db);
  2273. if ($nl > 0)
  2274. {
  2275. // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
  2276. $rows = array();
  2277. // We first search all lines that are parent lines (for multilevel details lines)
  2278. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2279. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2280. if ($fk_parent_line) $sql .= ' AND fk_parent_line IS NULL';
  2281. $sql .= ' ORDER BY rang ASC, rowid '.$rowidorder;
  2282. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  2283. $resql = $this->db->query($sql);
  2284. if ($resql)
  2285. {
  2286. $i = 0;
  2287. $num = $this->db->num_rows($resql);
  2288. while ($i < $num)
  2289. {
  2290. $row = $this->db->fetch_row($resql);
  2291. $rows[] = $row[0]; // Add parent line into array rows
  2292. $childrens = $this->getChildrenOfLine($row[0]);
  2293. if (!empty($childrens))
  2294. {
  2295. foreach ($childrens as $child)
  2296. {
  2297. array_push($rows, $child);
  2298. }
  2299. }
  2300. $i++;
  2301. }
  2302. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2303. if (!empty($rows))
  2304. {
  2305. foreach ($rows as $key => $row)
  2306. {
  2307. $this->updateRangOfLine($row, ($key + 1));
  2308. }
  2309. }
  2310. } else {
  2311. dol_print_error($this->db);
  2312. }
  2313. }
  2314. return 1;
  2315. }
  2316. /**
  2317. * Get children of line
  2318. *
  2319. * @param int $id Id of parent line
  2320. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2321. * @return array Array with list of children lines id
  2322. */
  2323. public function getChildrenOfLine($id, $includealltree = 0)
  2324. {
  2325. $rows = array();
  2326. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2327. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2328. $sql .= ' AND fk_parent_line = '.$id;
  2329. $sql .= ' ORDER BY rang ASC';
  2330. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id."", LOG_DEBUG);
  2331. $resql = $this->db->query($sql);
  2332. if ($resql)
  2333. {
  2334. if ($this->db->num_rows($resql) > 0) {
  2335. while ($row = $this->db->fetch_row($resql)) {
  2336. $rows[] = $row[0];
  2337. if (!empty($includealltree)) $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2338. }
  2339. }
  2340. }
  2341. return $rows;
  2342. }
  2343. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2344. /**
  2345. * Update a line to have a lower rank
  2346. *
  2347. * @param int $rowid Id of line
  2348. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2349. * @return void
  2350. */
  2351. public function line_up($rowid, $fk_parent_line = true)
  2352. {
  2353. // phpcs:enable
  2354. $this->line_order(false, 'ASC', $fk_parent_line);
  2355. // Get rang of line
  2356. $rang = $this->getRangOfLine($rowid);
  2357. // Update position of line
  2358. $this->updateLineUp($rowid, $rang);
  2359. }
  2360. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2361. /**
  2362. * Update a line to have a higher rank
  2363. *
  2364. * @param int $rowid Id of line
  2365. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2366. * @return void
  2367. */
  2368. public function line_down($rowid, $fk_parent_line = true)
  2369. {
  2370. // phpcs:enable
  2371. $this->line_order(false, 'ASC', $fk_parent_line);
  2372. // Get rang of line
  2373. $rang = $this->getRangOfLine($rowid);
  2374. // Get max value for rang
  2375. $max = $this->line_max();
  2376. // Update position of line
  2377. $this->updateLineDown($rowid, $rang, $max);
  2378. }
  2379. /**
  2380. * Update position of line (rang)
  2381. *
  2382. * @param int $rowid Id of line
  2383. * @param int $rang Position
  2384. * @return void
  2385. */
  2386. public function updateRangOfLine($rowid, $rang)
  2387. {
  2388. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2389. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
  2390. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang;
  2391. $sql .= ' WHERE rowid = '.$rowid;
  2392. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2393. if (!$this->db->query($sql))
  2394. {
  2395. dol_print_error($this->db);
  2396. }
  2397. }
  2398. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2399. /**
  2400. * Update position of line with ajax (rang)
  2401. *
  2402. * @param array $rows Array of rows
  2403. * @return void
  2404. */
  2405. public function line_ajaxorder($rows)
  2406. {
  2407. // phpcs:enable
  2408. $num = count($rows);
  2409. for ($i = 0; $i < $num; $i++)
  2410. {
  2411. $this->updateRangOfLine($rows[$i], ($i + 1));
  2412. }
  2413. }
  2414. /**
  2415. * Update position of line up (rang)
  2416. *
  2417. * @param int $rowid Id of line
  2418. * @param int $rang Position
  2419. * @return void
  2420. */
  2421. public function updateLineUp($rowid, $rang)
  2422. {
  2423. if ($rang > 1)
  2424. {
  2425. $fieldposition = 'rang';
  2426. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
  2427. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang;
  2428. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2429. $sql .= ' AND rang = '.($rang - 1);
  2430. if ($this->db->query($sql))
  2431. {
  2432. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.($rang - 1);
  2433. $sql .= ' WHERE rowid = '.$rowid;
  2434. if (!$this->db->query($sql))
  2435. {
  2436. dol_print_error($this->db);
  2437. }
  2438. } else {
  2439. dol_print_error($this->db);
  2440. }
  2441. }
  2442. }
  2443. /**
  2444. * Update position of line down (rang)
  2445. *
  2446. * @param int $rowid Id of line
  2447. * @param int $rang Position
  2448. * @param int $max Max
  2449. * @return void
  2450. */
  2451. public function updateLineDown($rowid, $rang, $max)
  2452. {
  2453. if ($rang < $max)
  2454. {
  2455. $fieldposition = 'rang';
  2456. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
  2457. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang;
  2458. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2459. $sql .= ' AND rang = '.($rang + 1);
  2460. if ($this->db->query($sql))
  2461. {
  2462. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.($rang + 1);
  2463. $sql .= ' WHERE rowid = '.$rowid;
  2464. if (!$this->db->query($sql))
  2465. {
  2466. dol_print_error($this->db);
  2467. }
  2468. } else {
  2469. dol_print_error($this->db);
  2470. }
  2471. }
  2472. }
  2473. /**
  2474. * Get position of line (rang)
  2475. *
  2476. * @param int $rowid Id of line
  2477. * @return int Value of rang in table of lines
  2478. */
  2479. public function getRangOfLine($rowid)
  2480. {
  2481. $sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2482. $sql .= ' WHERE rowid ='.$rowid;
  2483. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  2484. $resql = $this->db->query($sql);
  2485. if ($resql)
  2486. {
  2487. $row = $this->db->fetch_row($resql);
  2488. return $row[0];
  2489. }
  2490. }
  2491. /**
  2492. * Get rowid of the line relative to its position
  2493. *
  2494. * @param int $rang Rang value
  2495. * @return int Rowid of the line
  2496. */
  2497. public function getIdOfLine($rang)
  2498. {
  2499. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2500. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2501. $sql .= ' AND rang = '.$rang;
  2502. $resql = $this->db->query($sql);
  2503. if ($resql)
  2504. {
  2505. $row = $this->db->fetch_row($resql);
  2506. return $row[0];
  2507. }
  2508. }
  2509. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2510. /**
  2511. * Get max value used for position of line (rang)
  2512. *
  2513. * @param int $fk_parent_line Parent line id
  2514. * @return int Max value of rang in table of lines
  2515. */
  2516. public function line_max($fk_parent_line = 0)
  2517. {
  2518. // phpcs:enable
  2519. $positionfield = 'rang';
  2520. if ($this->table_element == 'bom_bom') $positionfield = 'position';
  2521. // Search the last rang with fk_parent_line
  2522. if ($fk_parent_line)
  2523. {
  2524. $sql = 'SELECT max('.$positionfield.') FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2525. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2526. $sql .= ' AND fk_parent_line = '.$fk_parent_line;
  2527. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2528. $resql = $this->db->query($sql);
  2529. if ($resql)
  2530. {
  2531. $row = $this->db->fetch_row($resql);
  2532. if (!empty($row[0]))
  2533. {
  2534. return $row[0];
  2535. } else {
  2536. return $this->getRangOfLine($fk_parent_line);
  2537. }
  2538. }
  2539. }
  2540. // If not, search the last rang of element
  2541. else {
  2542. $sql = 'SELECT max('.$positionfield.') FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2543. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2544. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2545. $resql = $this->db->query($sql);
  2546. if ($resql)
  2547. {
  2548. $row = $this->db->fetch_row($resql);
  2549. return $row[0];
  2550. }
  2551. }
  2552. }
  2553. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2554. /**
  2555. * Update external ref of element
  2556. *
  2557. * @param string $ref_ext Update field ref_ext
  2558. * @return int <0 if KO, >0 if OK
  2559. */
  2560. public function update_ref_ext($ref_ext)
  2561. {
  2562. // phpcs:enable
  2563. if (!$this->table_element)
  2564. {
  2565. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  2566. return -1;
  2567. }
  2568. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2569. $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  2570. $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".$this->id;
  2571. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  2572. if ($this->db->query($sql))
  2573. {
  2574. $this->ref_ext = $ref_ext;
  2575. return 1;
  2576. } else {
  2577. $this->error = $this->db->error();
  2578. return -1;
  2579. }
  2580. }
  2581. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2582. /**
  2583. * Update note of element
  2584. *
  2585. * @param string $note New value for note
  2586. * @param string $suffix '', '_public' or '_private'
  2587. * @return int <0 if KO, >0 if OK
  2588. */
  2589. public function update_note($note, $suffix = '')
  2590. {
  2591. // phpcs:enable
  2592. global $user;
  2593. if (!$this->table_element)
  2594. {
  2595. $this->error = 'update_note was called on objet with property table_element not defined';
  2596. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  2597. return -1;
  2598. }
  2599. if (!in_array($suffix, array('', '_public', '_private')))
  2600. {
  2601. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  2602. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  2603. return -2;
  2604. }
  2605. $newsuffix = $suffix;
  2606. // Special cas
  2607. if ($this->table_element == 'product' && $newsuffix == '_private') $newsuffix = '';
  2608. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2609. $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
  2610. $sql .= " ,".(in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment')) ? "fk_user_mod" : "fk_user_modif")." = ".$user->id;
  2611. $sql .= " WHERE rowid =".$this->id;
  2612. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  2613. if ($this->db->query($sql))
  2614. {
  2615. if ($suffix == '_public') $this->note_public = $note;
  2616. elseif ($suffix == '_private') $this->note_private = $note;
  2617. else {
  2618. $this->note = $note; // deprecated
  2619. $this->note_private = $note;
  2620. }
  2621. return 1;
  2622. } else {
  2623. $this->error = $this->db->lasterror();
  2624. return -1;
  2625. }
  2626. }
  2627. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2628. /**
  2629. * Update public note (kept for backward compatibility)
  2630. *
  2631. * @param string $note New value for note
  2632. * @return int <0 if KO, >0 if OK
  2633. * @deprecated
  2634. * @see update_note()
  2635. */
  2636. public function update_note_public($note)
  2637. {
  2638. // phpcs:enable
  2639. return $this->update_note($note, '_public');
  2640. }
  2641. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2642. /**
  2643. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  2644. * Must be called at end of methods addline or updateline.
  2645. *
  2646. * @param int $exclspec >0 = Exclude special product (product_type=9)
  2647. * @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
  2648. * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object.
  2649. * @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.
  2650. * @return int <0 if KO, >0 if OK
  2651. */
  2652. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  2653. {
  2654. // phpcs:enable
  2655. global $conf, $hookmanager, $action;
  2656. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  2657. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  2658. if ($reshook > 0) {
  2659. return 1; // replacement code
  2660. } elseif ($reshook < 0) {
  2661. return -1; // failure
  2662. } // reshook = 0 => execute normal code
  2663. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  2664. $MODULE = "";
  2665. if ($this->element == 'propal')
  2666. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  2667. elseif ($this->element == 'commande' || $this->element == 'order')
  2668. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  2669. elseif ($this->element == 'facture' || $this->element == 'invoice')
  2670. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  2671. elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier')
  2672. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  2673. elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order')
  2674. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  2675. elseif ($this->element == 'supplier_proposal')
  2676. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  2677. if (!empty($MODULE)) {
  2678. if (!empty($conf->global->$MODULE)) {
  2679. $modsactivated = explode(',', $conf->global->$MODULE);
  2680. foreach ($modsactivated as $mod) {
  2681. if ($conf->$mod->enabled)
  2682. return 1; // update was disabled by specific setup
  2683. }
  2684. }
  2685. }
  2686. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  2687. if ($roundingadjust == '-1') $roundingadjust = 'auto'; // For backward compatibility
  2688. $forcedroundingmode = $roundingadjust;
  2689. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) $forcedroundingmode = $conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
  2690. elseif ($forcedroundingmode == 'auto') $forcedroundingmode = '0';
  2691. $error = 0;
  2692. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  2693. // Define constants to find lines to sum
  2694. $fieldtva = 'total_tva';
  2695. $fieldlocaltax1 = 'total_localtax1';
  2696. $fieldlocaltax2 = 'total_localtax2';
  2697. $fieldup = 'subprice';
  2698. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
  2699. {
  2700. $fieldtva = 'tva';
  2701. $fieldup = 'pu_ht';
  2702. }
  2703. if ($this->element == 'expensereport')
  2704. {
  2705. $fieldup = 'value_unit';
  2706. }
  2707. $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,';
  2708. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  2709. if ($this->table_element_line == 'facturedet') $sql .= ', situation_percent';
  2710. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  2711. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2712. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2713. if ($exclspec)
  2714. {
  2715. $product_field = 'product_type';
  2716. if ($this->table_element_line == 'contratdet') $product_field = ''; // contratdet table has no product_type field
  2717. if ($product_field) $sql .= ' AND '.$product_field.' <> 9';
  2718. }
  2719. $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
  2720. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  2721. $resql = $this->db->query($sql);
  2722. if ($resql)
  2723. {
  2724. $this->total_ht = 0;
  2725. $this->total_tva = 0;
  2726. $this->total_localtax1 = 0;
  2727. $this->total_localtax2 = 0;
  2728. $this->total_ttc = 0;
  2729. $total_ht_by_vats = array();
  2730. $total_tva_by_vats = array();
  2731. $total_ttc_by_vats = array();
  2732. $this->multicurrency_total_ht = 0;
  2733. $this->multicurrency_total_tva = 0;
  2734. $this->multicurrency_total_ttc = 0;
  2735. $num = $this->db->num_rows($resql);
  2736. $i = 0;
  2737. while ($i < $num)
  2738. {
  2739. $obj = $this->db->fetch_object($resql);
  2740. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  2741. $parameters = array('fk_element' => $obj->rowid);
  2742. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  2743. 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'
  2744. {
  2745. // This part of code is to fix data. We should not call it too often.
  2746. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  2747. $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);
  2748. $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.
  2749. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  2750. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
  2751. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  2752. if ($diff_when_using_price_ht && $diff_on_current_total)
  2753. {
  2754. $sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
  2755. 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);
  2756. $resqlfix = $this->db->query($sqlfix);
  2757. if (!$resqlfix) dol_print_error($this->db, 'Failed to update line');
  2758. $obj->total_tva = $tmpcal[1];
  2759. $obj->total_ttc = $tmpcal[2];
  2760. }
  2761. }
  2762. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  2763. $this->total_tva += $obj->total_tva;
  2764. $this->total_localtax1 += $obj->total_localtax1;
  2765. $this->total_localtax2 += $obj->total_localtax2;
  2766. $this->total_ttc += $obj->total_ttc;
  2767. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  2768. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  2769. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  2770. if (!isset($total_ht_by_vats[$obj->vatrate])) $total_ht_by_vats[$obj->vatrate] = 0;
  2771. if (!isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate] = 0;
  2772. if (!isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate] = 0;
  2773. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  2774. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  2775. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  2776. if ($forcedroundingmode == '1') // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  2777. {
  2778. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  2779. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  2780. //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";
  2781. if ($diff)
  2782. {
  2783. if (abs($diff) > 0.1) {
  2784. $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.';
  2785. dol_syslog($errmsg, LOG_WARNING);
  2786. dol_print_error('', $errmsg);
  2787. exit;
  2788. }
  2789. $sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".($obj->total_tva - $diff).", total_ttc = ".($obj->total_ttc - $diff)." WHERE rowid = ".$obj->rowid;
  2790. 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);
  2791. $resqlfix = $this->db->query($sqlfix);
  2792. if (!$resqlfix) dol_print_error($this->db, 'Failed to update line');
  2793. $this->total_tva -= $diff;
  2794. $this->total_ttc -= $diff;
  2795. $total_tva_by_vats[$obj->vatrate] -= $diff;
  2796. $total_ttc_by_vats[$obj->vatrate] -= $diff;
  2797. }
  2798. }
  2799. $i++;
  2800. }
  2801. // Add revenue stamp to total
  2802. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  2803. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  2804. // Situations totals
  2805. if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE)
  2806. {
  2807. $prev_sits = $this->get_prev_sits();
  2808. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  2809. $this->total_ht -= $sit->total_ht;
  2810. $this->total_tva -= $sit->total_tva;
  2811. $this->total_localtax1 -= $sit->total_localtax1;
  2812. $this->total_localtax2 -= $sit->total_localtax2;
  2813. $this->total_ttc -= $sit->total_ttc;
  2814. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  2815. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  2816. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  2817. }
  2818. }
  2819. $this->db->free($resql);
  2820. // Now update global field total_ht, total_ttc and tva
  2821. $fieldht = 'total_ht';
  2822. $fieldtva = 'tva';
  2823. $fieldlocaltax1 = 'localtax1';
  2824. $fieldlocaltax2 = 'localtax2';
  2825. $fieldttc = 'total_ttc';
  2826. // Specific code for backward compatibility with old field names
  2827. if ($this->element == 'facture' || $this->element == 'facturerec') $fieldht = 'total';
  2828. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva = 'total_tva';
  2829. if ($this->element == 'propal') $fieldttc = 'total';
  2830. if ($this->element == 'expensereport') $fieldtva = 'total_tva';
  2831. if ($this->element == 'supplier_proposal') $fieldttc = 'total';
  2832. if (empty($nodatabaseupdate))
  2833. {
  2834. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
  2835. $sql .= " ".$fieldht."='".price2num($this->total_ht)."',";
  2836. $sql .= " ".$fieldtva."='".price2num($this->total_tva)."',";
  2837. $sql .= " ".$fieldlocaltax1."='".price2num($this->total_localtax1)."',";
  2838. $sql .= " ".$fieldlocaltax2."='".price2num($this->total_localtax2)."',";
  2839. $sql .= " ".$fieldttc."='".price2num($this->total_ttc)."'";
  2840. $sql .= ", multicurrency_total_ht='".price2num($this->multicurrency_total_ht, 'MT', 1)."'";
  2841. $sql .= ", multicurrency_total_tva='".price2num($this->multicurrency_total_tva, 'MT', 1)."'";
  2842. $sql .= ", multicurrency_total_ttc='".price2num($this->multicurrency_total_ttc, 'MT', 1)."'";
  2843. $sql .= ' WHERE rowid = '.$this->id;
  2844. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  2845. $resql = $this->db->query($sql);
  2846. if (!$resql)
  2847. {
  2848. $error++;
  2849. $this->error = $this->db->lasterror();
  2850. $this->errors[] = $this->db->lasterror();
  2851. }
  2852. }
  2853. if (!$error)
  2854. {
  2855. return 1;
  2856. } else {
  2857. return -1;
  2858. }
  2859. } else {
  2860. dol_print_error($this->db, 'Bad request in update_price');
  2861. return -1;
  2862. }
  2863. }
  2864. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2865. /**
  2866. * Add objects linked in llx_element_element.
  2867. *
  2868. * @param string $origin Linked element type
  2869. * @param int $origin_id Linked element id
  2870. * @return int <=0 if KO, >0 if OK
  2871. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  2872. */
  2873. public function add_object_linked($origin = null, $origin_id = null)
  2874. {
  2875. // phpcs:enable
  2876. $origin = (!empty($origin) ? $origin : $this->origin);
  2877. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  2878. // Special case
  2879. if ($origin == 'order') $origin = 'commande';
  2880. if ($origin == 'invoice') $origin = 'facture';
  2881. if ($origin == 'invoice_template') $origin = 'facturerec';
  2882. if ($origin == 'supplierorder') $origin = 'order_supplier';
  2883. $this->db->begin();
  2884. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
  2885. $sql .= "fk_source";
  2886. $sql .= ", sourcetype";
  2887. $sql .= ", fk_target";
  2888. $sql .= ", targettype";
  2889. $sql .= ") VALUES (";
  2890. $sql .= $origin_id;
  2891. $sql .= ", '".$this->db->escape($origin)."'";
  2892. $sql .= ", ".$this->id;
  2893. $sql .= ", '".$this->db->escape($this->element)."'";
  2894. $sql .= ")";
  2895. dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG);
  2896. if ($this->db->query($sql))
  2897. {
  2898. $this->db->commit();
  2899. return 1;
  2900. } else {
  2901. $this->error = $this->db->lasterror();
  2902. $this->db->rollback();
  2903. return 0;
  2904. }
  2905. }
  2906. /**
  2907. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  2908. * this->linkedObjectsIds array and
  2909. * this->linkedObjects array if $loadalsoobjects = 1
  2910. * Possible usage for parameters:
  2911. * - all parameters empty -> we look all link to current object (current object can be source or target)
  2912. * - source id+type -> will get target list linked to source
  2913. * - target id+type -> will get source list linked to target
  2914. * - source id+type + target type -> will get target list of the type
  2915. * - target id+type + target source -> will get source list of the type
  2916. *
  2917. * @param int $sourceid Object source id (if not defined, id of object)
  2918. * @param string $sourcetype Object source type (if not defined, element name of object)
  2919. * @param int $targetid Object target id (if not defined, id of object)
  2920. * @param string $targettype Object target type (if not defined, elemennt name of object)
  2921. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  2922. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  2923. * @param string $orderby SQL 'ORDER BY' clause
  2924. * @param int $loadalsoobjects Load also array this->linkedObjects (Use 0 to increase performances)
  2925. * @return int <0 if KO, >0 if OK
  2926. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  2927. */
  2928. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  2929. {
  2930. global $conf;
  2931. $this->linkedObjectsIds = array();
  2932. $this->linkedObjects = array();
  2933. $justsource = false;
  2934. $justtarget = false;
  2935. $withtargettype = false;
  2936. $withsourcetype = false;
  2937. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid))
  2938. {
  2939. $justsource = true; // the source (id and type) is a search criteria
  2940. if (!empty($targettype)) $withtargettype = true;
  2941. }
  2942. if (!empty($targetid) && !empty($targettype) && empty($sourceid))
  2943. {
  2944. $justtarget = true; // the target (id and type) is a search criteria
  2945. if (!empty($sourcetype)) $withsourcetype = true;
  2946. }
  2947. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  2948. $targetid = (!empty($targetid) ? $targetid : $this->id);
  2949. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  2950. $targettype = (!empty($targettype) ? $targettype : $this->element);
  2951. /*if (empty($sourceid) && empty($targetid))
  2952. {
  2953. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  2954. return -1;
  2955. }*/
  2956. // Links between objects are stored in table element_element
  2957. $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype';
  2958. $sql .= ' FROM '.MAIN_DB_PREFIX.'element_element';
  2959. $sql .= " WHERE ";
  2960. if ($justsource || $justtarget)
  2961. {
  2962. if ($justsource)
  2963. {
  2964. $sql .= "fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  2965. if ($withtargettype) $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
  2966. } elseif ($justtarget)
  2967. {
  2968. $sql .= "fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."'";
  2969. if ($withsourcetype) $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
  2970. }
  2971. } else {
  2972. $sql .= "(fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."')";
  2973. $sql .= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."')";
  2974. }
  2975. $sql .= ' ORDER BY '.$orderby;
  2976. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  2977. $resql = $this->db->query($sql);
  2978. if ($resql)
  2979. {
  2980. $num = $this->db->num_rows($resql);
  2981. $i = 0;
  2982. while ($i < $num)
  2983. {
  2984. $obj = $this->db->fetch_object($resql);
  2985. if ($justsource || $justtarget)
  2986. {
  2987. if ($justsource)
  2988. {
  2989. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  2990. } elseif ($justtarget)
  2991. {
  2992. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  2993. }
  2994. } else {
  2995. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype)
  2996. {
  2997. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  2998. }
  2999. if ($obj->fk_target == $targetid && $obj->targettype == $targettype)
  3000. {
  3001. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3002. }
  3003. }
  3004. $i++;
  3005. }
  3006. if (!empty($this->linkedObjectsIds))
  3007. {
  3008. $tmparray = $this->linkedObjectsIds;
  3009. foreach ($tmparray as $objecttype => $objectids) // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  3010. {
  3011. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  3012. $module = $element = $subelement = $objecttype;
  3013. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  3014. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs))
  3015. {
  3016. $module = $element = $regs[1];
  3017. $subelement = $regs[2];
  3018. }
  3019. $classpath = $element.'/class';
  3020. // To work with non standard classpath or module name
  3021. if ($objecttype == 'facture') {
  3022. $classpath = 'compta/facture/class';
  3023. } elseif ($objecttype == 'facturerec') {
  3024. $classpath = 'compta/facture/class'; $module = 'facture';
  3025. } elseif ($objecttype == 'propal') {
  3026. $classpath = 'comm/propal/class';
  3027. } elseif ($objecttype == 'supplier_proposal') {
  3028. $classpath = 'supplier_proposal/class';
  3029. } elseif ($objecttype == 'shipping') {
  3030. $classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon';
  3031. } elseif ($objecttype == 'delivery') {
  3032. $classpath = 'delivery/class'; $subelement = 'delivery'; $module = 'delivery_note';
  3033. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  3034. $classpath = 'fourn/class'; $module = 'fournisseur';
  3035. } elseif ($objecttype == 'fichinter') {
  3036. $classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter';
  3037. } elseif ($objecttype == 'subscription') {
  3038. $classpath = 'adherents/class'; $module = 'adherent';
  3039. } elseif ($objecttype == 'contact') {
  3040. $module = 'societe';
  3041. }
  3042. // Set classfile
  3043. $classfile = strtolower($subelement); $classname = ucfirst($subelement);
  3044. if ($objecttype == 'order') {
  3045. $classfile = 'commande'; $classname = 'Commande';
  3046. } elseif ($objecttype == 'invoice_supplier') {
  3047. $classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur';
  3048. } elseif ($objecttype == 'order_supplier') {
  3049. $classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur';
  3050. } elseif ($objecttype == 'supplier_proposal') {
  3051. $classfile = 'supplier_proposal'; $classname = 'SupplierProposal';
  3052. } elseif ($objecttype == 'facturerec') {
  3053. $classfile = 'facture-rec'; $classname = 'FactureRec';
  3054. } elseif ($objecttype == 'subscription') {
  3055. $classfile = 'subscription'; $classname = 'Subscription';
  3056. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  3057. $classpath = 'projet/class'; $classfile = 'project'; $classname = 'Project';
  3058. }
  3059. // Here $module, $classfile and $classname are set
  3060. if ($conf->$module->enabled && (($element != $this->element) || $alsosametype))
  3061. {
  3062. if ($loadalsoobjects)
  3063. {
  3064. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  3065. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  3066. if (class_exists($classname))
  3067. {
  3068. foreach ($objectids as $i => $objectid) // $i is rowid into llx_element_element
  3069. {
  3070. $object = new $classname($this->db);
  3071. $ret = $object->fetch($objectid);
  3072. if ($ret >= 0)
  3073. {
  3074. $this->linkedObjects[$objecttype][$i] = $object;
  3075. }
  3076. }
  3077. }
  3078. }
  3079. } else {
  3080. unset($this->linkedObjectsIds[$objecttype]);
  3081. }
  3082. }
  3083. }
  3084. return 1;
  3085. } else {
  3086. dol_print_error($this->db);
  3087. return -1;
  3088. }
  3089. }
  3090. /**
  3091. * Update object linked of a current object
  3092. *
  3093. * @param int $sourceid Object source id
  3094. * @param string $sourcetype Object source type
  3095. * @param int $targetid Object target id
  3096. * @param string $targettype Object target type
  3097. * @return int >0 if OK, <0 if KO
  3098. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3099. */
  3100. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '')
  3101. {
  3102. $updatesource = false;
  3103. $updatetarget = false;
  3104. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) $updatesource = true;
  3105. elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) $updatetarget = true;
  3106. $sql = "UPDATE ".MAIN_DB_PREFIX."element_element SET ";
  3107. if ($updatesource)
  3108. {
  3109. $sql .= "fk_source = ".$sourceid;
  3110. $sql .= ", sourcetype = '".$this->db->escape($sourcetype)."'";
  3111. $sql .= " WHERE fk_target = ".$this->id;
  3112. $sql .= " AND targettype = '".$this->db->escape($this->element)."'";
  3113. } elseif ($updatetarget)
  3114. {
  3115. $sql .= "fk_target = ".$targetid;
  3116. $sql .= ", targettype = '".$this->db->escape($targettype)."'";
  3117. $sql .= " WHERE fk_source = ".$this->id;
  3118. $sql .= " AND sourcetype = '".$this->db->escape($this->element)."'";
  3119. }
  3120. dol_syslog(get_class($this)."::updateObjectLinked", LOG_DEBUG);
  3121. if ($this->db->query($sql))
  3122. {
  3123. return 1;
  3124. } else {
  3125. $this->error = $this->db->lasterror();
  3126. return -1;
  3127. }
  3128. }
  3129. /**
  3130. * Delete all links between an object $this
  3131. *
  3132. * @param int $sourceid Object source id
  3133. * @param string $sourcetype Object source type
  3134. * @param int $targetid Object target id
  3135. * @param string $targettype Object target type
  3136. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3137. * @return int >0 if OK, <0 if KO
  3138. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3139. */
  3140. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '')
  3141. {
  3142. $deletesource = false;
  3143. $deletetarget = false;
  3144. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) $deletesource = true;
  3145. elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) $deletetarget = true;
  3146. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3147. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3148. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3149. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3150. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_element";
  3151. $sql .= " WHERE";
  3152. if ($rowid > 0)
  3153. {
  3154. $sql .= " rowid = ".$rowid;
  3155. } else {
  3156. if ($deletesource)
  3157. {
  3158. $sql .= " fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3159. $sql .= " AND fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."'";
  3160. } elseif ($deletetarget)
  3161. {
  3162. $sql .= " fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."'";
  3163. $sql .= " AND fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."'";
  3164. } else {
  3165. $sql .= " (fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."')";
  3166. $sql .= " OR";
  3167. $sql .= " (fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."')";
  3168. }
  3169. }
  3170. dol_syslog(get_class($this)."::deleteObjectLinked", LOG_DEBUG);
  3171. if ($this->db->query($sql))
  3172. {
  3173. return 1;
  3174. } else {
  3175. $this->error = $this->db->lasterror();
  3176. $this->errors[] = $this->error;
  3177. return -1;
  3178. }
  3179. }
  3180. /**
  3181. * Set status of an object
  3182. *
  3183. * @param int $status Status to set
  3184. * @param int $elementId Id of element to force (use this->id by default)
  3185. * @param string $elementType Type of element to force (use this->table_element by default)
  3186. * @param string $trigkey Trigger key to use for trigger
  3187. * @return int <0 if KO, >0 if OK
  3188. */
  3189. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '')
  3190. {
  3191. global $user, $langs, $conf;
  3192. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3193. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3194. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3195. $this->db->begin();
  3196. $fieldstatus = "fk_statut";
  3197. if ($elementTable == 'facture_rec') $fieldstatus = "suspended";
  3198. if ($elementTable == 'mailing') $fieldstatus = "statut";
  3199. if ($elementTable == 'cronjob') $fieldstatus = "status";
  3200. if ($elementTable == 'user') $fieldstatus = "statut";
  3201. if ($elementTable == 'expensereport') $fieldstatus = "fk_statut";
  3202. if ($elementTable == 'commande_fournisseur_dispatch') $fieldstatus = "status";
  3203. if (is_array($this->fields) && array_key_exists('status', $this->fields)) $fieldstatus = 'status';
  3204. $sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable;
  3205. $sql .= " SET ".$fieldstatus." = ".$status;
  3206. // If status = 1 = validated, update also fk_user_valid
  3207. if ($status == 1 && $elementTable == 'expensereport') $sql .= ", fk_user_valid = ".$user->id;
  3208. $sql .= " WHERE rowid=".$elementId;
  3209. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  3210. if ($this->db->query($sql))
  3211. {
  3212. $error = 0;
  3213. // Try autoset of trigkey
  3214. if (empty($trigkey))
  3215. {
  3216. if ($this->element == 'supplier_proposal' && $status == 2) $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3217. if ($this->element == 'supplier_proposal' && $status == 3) $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3218. if ($this->element == 'supplier_proposal' && $status == 4) $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3219. if ($this->element == 'fichinter' && $status == 3) $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3220. if ($this->element == 'fichinter' && $status == 2) $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3221. if ($this->element == 'fichinter' && $status == 1) $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3222. }
  3223. if ($trigkey)
  3224. {
  3225. // Call trigger
  3226. $result = $this->call_trigger($trigkey, $user);
  3227. if ($result < 0) $error++;
  3228. // End call triggers
  3229. }
  3230. if (!$error)
  3231. {
  3232. $this->db->commit();
  3233. if (empty($savElementId)) // If the element we update was $this (so $elementId is null)
  3234. {
  3235. $this->statut = $status;
  3236. $this->status = $status;
  3237. }
  3238. return 1;
  3239. } else {
  3240. $this->db->rollback();
  3241. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  3242. return -1;
  3243. }
  3244. } else {
  3245. $this->error = $this->db->lasterror();
  3246. $this->db->rollback();
  3247. return -1;
  3248. }
  3249. }
  3250. /**
  3251. * Load type of canvas of an object if it exists
  3252. *
  3253. * @param int $id Record id
  3254. * @param string $ref Record ref
  3255. * @return int <0 if KO, 0 if nothing done, >0 if OK
  3256. */
  3257. public function getCanvas($id = 0, $ref = '')
  3258. {
  3259. global $conf;
  3260. if (empty($id) && empty($ref)) return 0;
  3261. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) return 0; // To increase speed. Not enabled by default.
  3262. // Clean parameters
  3263. $ref = trim($ref);
  3264. $sql = "SELECT rowid, canvas";
  3265. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
  3266. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  3267. if (!empty($id)) $sql .= " AND rowid = ".$id;
  3268. if (!empty($ref)) $sql .= " AND ref = '".$this->db->escape($ref)."'";
  3269. $resql = $this->db->query($sql);
  3270. if ($resql)
  3271. {
  3272. $obj = $this->db->fetch_object($resql);
  3273. if ($obj)
  3274. {
  3275. $this->canvas = $obj->canvas;
  3276. return 1;
  3277. } else return 0;
  3278. } else {
  3279. dol_print_error($this->db);
  3280. return -1;
  3281. }
  3282. }
  3283. /**
  3284. * Get special code of a line
  3285. *
  3286. * @param int $lineid Id of line
  3287. * @return int Special code
  3288. */
  3289. public function getSpecialCode($lineid)
  3290. {
  3291. $sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  3292. $sql .= ' WHERE rowid = '.$lineid;
  3293. $resql = $this->db->query($sql);
  3294. if ($resql)
  3295. {
  3296. $row = $this->db->fetch_row($resql);
  3297. return $row[0];
  3298. }
  3299. }
  3300. /**
  3301. * Function to check if an object is used by others.
  3302. * Check is done into this->childtables. There is no check into llx_element_element.
  3303. *
  3304. * @param int $id Force id of object
  3305. * @return int <0 if KO, 0 if not used, >0 if already used
  3306. */
  3307. public function isObjectUsed($id = 0)
  3308. {
  3309. global $langs;
  3310. if (empty($id)) $id = $this->id;
  3311. // Check parameters
  3312. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0)
  3313. {
  3314. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  3315. return -1;
  3316. }
  3317. $arraytoscan = $this->childtables;
  3318. // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
  3319. $tmparray = array_keys($this->childtables);
  3320. if (is_numeric($tmparray[0]))
  3321. {
  3322. $arraytoscan = array_flip($this->childtables);
  3323. }
  3324. // Test if child exists
  3325. $haschild = 0;
  3326. foreach ($arraytoscan as $table => $elementname)
  3327. {
  3328. //print $id.'-'.$table.'-'.$elementname.'<br>';
  3329. // Check if third party can be deleted
  3330. $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table;
  3331. $sql .= " WHERE ".$this->fk_element." = ".$id;
  3332. $resql = $this->db->query($sql);
  3333. if ($resql)
  3334. {
  3335. $obj = $this->db->fetch_object($resql);
  3336. if ($obj->nb > 0)
  3337. {
  3338. $langs->load("errors");
  3339. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  3340. $haschild += $obj->nb;
  3341. if (is_numeric($elementname)) // old usage
  3342. {
  3343. $this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table);
  3344. } else // new usage: $elementname=Translation key
  3345. {
  3346. $this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname));
  3347. }
  3348. break; // We found at least one, we stop here
  3349. }
  3350. } else {
  3351. $this->errors[] = $this->db->lasterror();
  3352. return -1;
  3353. }
  3354. }
  3355. if ($haschild > 0)
  3356. {
  3357. $this->errors[] = "ErrorRecordHasChildren";
  3358. return $haschild;
  3359. } else return 0;
  3360. }
  3361. /**
  3362. * Function to say how many lines object contains
  3363. *
  3364. * @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
  3365. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  3366. */
  3367. public function hasProductsOrServices($predefined = -1)
  3368. {
  3369. $nb = 0;
  3370. foreach ($this->lines as $key => $val)
  3371. {
  3372. $qualified = 0;
  3373. if ($predefined == -1) $qualified = 1;
  3374. if ($predefined == 1 && $val->fk_product > 0) $qualified = 1;
  3375. if ($predefined == 0 && $val->fk_product <= 0) $qualified = 1;
  3376. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) $qualified = 1;
  3377. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) $qualified = 1;
  3378. if ($qualified) $nb++;
  3379. }
  3380. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  3381. return $nb;
  3382. }
  3383. /**
  3384. * Function that returns the total amount HT of discounts applied for all lines.
  3385. *
  3386. * @return float
  3387. */
  3388. public function getTotalDiscount()
  3389. {
  3390. $total_discount = 0.00;
  3391. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  3392. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element."det";
  3393. $sql .= " WHERE ".$this->fk_element." = ".$this->id;
  3394. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  3395. $resql = $this->db->query($sql);
  3396. if ($resql)
  3397. {
  3398. $num = $this->db->num_rows($resql);
  3399. $i = 0;
  3400. while ($i < $num)
  3401. {
  3402. $obj = $this->db->fetch_object($resql);
  3403. $pu_ht = $obj->pu_ht;
  3404. $qty = $obj->qty;
  3405. $total_ht = $obj->total_ht;
  3406. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  3407. $total_discount += $total_discount_line;
  3408. $i++;
  3409. }
  3410. }
  3411. //print $total_discount; exit;
  3412. return price2num($total_discount);
  3413. }
  3414. /**
  3415. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  3416. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  3417. *
  3418. * @return array array('weight'=>...,'volume'=>...)
  3419. */
  3420. public function getTotalWeightVolume()
  3421. {
  3422. $totalWeight = 0;
  3423. $totalVolume = 0;
  3424. // defined for shipment only
  3425. $totalOrdered = '';
  3426. // defined for shipment only
  3427. $totalToShip = '';
  3428. foreach ($this->lines as $line)
  3429. {
  3430. if (isset($line->qty_asked))
  3431. {
  3432. if (empty($totalOrdered)) $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  3433. $totalOrdered += $line->qty_asked; // defined for shipment only
  3434. }
  3435. if (isset($line->qty_shipped))
  3436. {
  3437. if (empty($totalToShip)) $totalToShip = 0; // Avoid warning because $totalToShip is ''
  3438. $totalToShip += $line->qty_shipped; // defined for shipment only
  3439. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty))
  3440. {
  3441. if (empty($totalToShip)) $totalToShip = 0;
  3442. $totalToShip += $line->qty; // defined for reception only
  3443. }
  3444. // Define qty, weight, volume, weight_units, volume_units
  3445. if ($this->element == 'shipping') {
  3446. // for shipments
  3447. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  3448. } else {
  3449. $qty = $line->qty ? $line->qty : 0;
  3450. }
  3451. $weight = $line->weight ? $line->weight : 0;
  3452. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  3453. $volume = $line->volume ? $line->volume : 0;
  3454. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  3455. $weight_units = $line->weight_units;
  3456. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  3457. $volume_units = $line->volume_units;
  3458. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  3459. $weightUnit = 0;
  3460. $volumeUnit = 0;
  3461. if (!empty($weight_units)) $weightUnit = $weight_units;
  3462. if (!empty($volume_units)) $volumeUnit = $volume_units;
  3463. if (empty($totalWeight)) $totalWeight = 0; // Avoid warning because $totalWeight is ''
  3464. if (empty($totalVolume)) $totalVolume = 0; // Avoid warning because $totalVolume is ''
  3465. //var_dump($line->volume_units);
  3466. if ($weight_units < 50) // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  3467. {
  3468. $trueWeightUnit = pow(10, $weightUnit);
  3469. $totalWeight += $weight * $qty * $trueWeightUnit;
  3470. } else {
  3471. if ($weight_units == 99) {
  3472. // conversion 1 Pound = 0.45359237 KG
  3473. $trueWeightUnit = 0.45359237;
  3474. $totalWeight += $weight * $qty * $trueWeightUnit;
  3475. } elseif ($weight_units == 98) {
  3476. // conversion 1 Ounce = 0.0283495 KG
  3477. $trueWeightUnit = 0.0283495;
  3478. $totalWeight += $weight * $qty * $trueWeightUnit;
  3479. } else {
  3480. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  3481. }
  3482. }
  3483. if ($volume_units < 50) // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  3484. {
  3485. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  3486. $trueVolumeUnit = pow(10, $volumeUnit);
  3487. //print $line->volume;
  3488. $totalVolume += $volume * $qty * $trueVolumeUnit;
  3489. } else {
  3490. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  3491. }
  3492. }
  3493. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  3494. }
  3495. /**
  3496. * Set extra parameters
  3497. *
  3498. * @return int <0 if KO, >0 if OK
  3499. */
  3500. public function setExtraParameters()
  3501. {
  3502. $this->db->begin();
  3503. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  3504. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  3505. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  3506. $sql .= " WHERE rowid = ".$this->id;
  3507. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  3508. $resql = $this->db->query($sql);
  3509. if (!$resql)
  3510. {
  3511. $this->error = $this->db->lasterror();
  3512. $this->db->rollback();
  3513. return -1;
  3514. } else {
  3515. $this->db->commit();
  3516. return 1;
  3517. }
  3518. }
  3519. // --------------------
  3520. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  3521. // --------------------
  3522. /* This is to show add lines */
  3523. /**
  3524. * Show add free and predefined products/services form
  3525. *
  3526. * @param int $dateSelector 1=Show also date range input fields
  3527. * @param Societe $seller Object thirdparty who sell
  3528. * @param Societe $buyer Object thirdparty who buy
  3529. * @param string $defaulttpldir Directory where to find the template
  3530. * @return void
  3531. */
  3532. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  3533. {
  3534. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  3535. global $form;
  3536. // Line extrafield
  3537. if (!is_object($extrafields))
  3538. {
  3539. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  3540. $extrafields = new ExtraFields($this->db);
  3541. }
  3542. $extrafields->fetch_name_optionals_label($this->table_element_line);
  3543. // Output template part (modules that overwrite templates must declare this into descriptor)
  3544. // Use global variables + $dateSelector + $seller and $buyer
  3545. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  3546. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  3547. foreach ($dirtpls as $module => $reldir)
  3548. {
  3549. if (!empty($module))
  3550. {
  3551. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  3552. } else {
  3553. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  3554. }
  3555. if (empty($conf->file->strict_mode)) {
  3556. $res = @include $tpl;
  3557. } else {
  3558. $res = include $tpl; // for debug
  3559. }
  3560. if ($res) break;
  3561. }
  3562. }
  3563. /* This is to show array of line of details */
  3564. /**
  3565. * Return HTML table for object lines
  3566. * TODO Move this into an output class file (htmlline.class.php)
  3567. * If lines are into a template, title must also be into a template
  3568. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  3569. *
  3570. * @param string $action Action code
  3571. * @param string $seller Object of seller third party
  3572. * @param string $buyer Object of buyer third party
  3573. * @param int $selected Object line selected
  3574. * @param int $dateSelector 1=Show also date range input fields
  3575. * @param string $defaulttpldir Directory where to find the template
  3576. * @return void
  3577. */
  3578. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  3579. {
  3580. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  3581. // TODO We should not use global var for this
  3582. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  3583. // Define usemargins
  3584. $usemargins = 0;
  3585. if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) $usemargins = 1;
  3586. $num = count($this->lines);
  3587. // Line extrafield
  3588. if (!is_object($extrafields))
  3589. {
  3590. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  3591. $extrafields = new ExtraFields($this->db);
  3592. }
  3593. $extrafields->fetch_name_optionals_label($this->table_element_line);
  3594. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  3595. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3596. if (empty($reshook))
  3597. {
  3598. // Output template part (modules that overwrite templates must declare this into descriptor)
  3599. // Use global variables + $dateSelector + $seller and $buyer
  3600. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  3601. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  3602. foreach ($dirtpls as $module => $reldir)
  3603. {
  3604. if (!empty($module))
  3605. {
  3606. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  3607. } else {
  3608. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  3609. }
  3610. if (empty($conf->file->strict_mode)) {
  3611. $res = @include $tpl;
  3612. } else {
  3613. $res = include $tpl; // for debug
  3614. }
  3615. if ($res) break;
  3616. }
  3617. }
  3618. $i = 0;
  3619. print "<!-- begin printObjectLines() --><tbody>\n";
  3620. foreach ($this->lines as $line)
  3621. {
  3622. //Line extrafield
  3623. $line->fetch_optionals();
  3624. //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  3625. if (is_object($hookmanager)) // Old code is commented on preceding line.
  3626. {
  3627. if (empty($line->fk_parent_line))
  3628. {
  3629. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  3630. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3631. } else {
  3632. $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);
  3633. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3634. }
  3635. }
  3636. if (empty($reshook))
  3637. {
  3638. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  3639. }
  3640. $i++;
  3641. }
  3642. print "</tbody><!-- end printObjectLines() -->\n";
  3643. }
  3644. /**
  3645. * Return HTML content of a detail line
  3646. * TODO Move this into an output class file (htmlline.class.php)
  3647. *
  3648. * @param string $action GET/POST action
  3649. * @param CommonObjectLine $line Selected object line to output
  3650. * @param string $var Is it a an odd line (true)
  3651. * @param int $num Number of line (0)
  3652. * @param int $i I
  3653. * @param int $dateSelector 1=Show also date range input fields
  3654. * @param string $seller Object of seller third party
  3655. * @param string $buyer Object of buyer third party
  3656. * @param int $selected Object line selected
  3657. * @param Extrafields $extrafields Object of extrafields
  3658. * @param string $defaulttpldir Directory where to find the template (deprecated)
  3659. * @return void
  3660. */
  3661. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  3662. {
  3663. global $conf, $langs, $user, $object, $hookmanager;
  3664. global $form;
  3665. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  3666. $object_rights = $this->getRights();
  3667. $element = $this->element;
  3668. $text = ''; $description = '';
  3669. // Line in view mode
  3670. if ($action != 'editline' || $selected != $line->id)
  3671. {
  3672. // Product
  3673. if ($line->fk_product > 0)
  3674. {
  3675. $product_static = new Product($this->db);
  3676. $product_static->fetch($line->fk_product);
  3677. $product_static->ref = $line->ref; //can change ref in hook
  3678. $product_static->label = $line->label; //can change label in hook
  3679. $text = $product_static->getNomUrl(1);
  3680. // Define output language and label
  3681. if (!empty($conf->global->MAIN_MULTILANGS))
  3682. {
  3683. if (property_exists($this, 'socid') && !is_object($this->thirdparty))
  3684. {
  3685. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  3686. return;
  3687. }
  3688. $prod = new Product($this->db);
  3689. $prod->fetch($line->fk_product);
  3690. $outputlangs = $langs;
  3691. $newlang = '';
  3692. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
  3693. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) $newlang = $this->thirdparty->default_lang; // To use language of customer
  3694. if (!empty($newlang))
  3695. {
  3696. $outputlangs = new Translate("", $conf);
  3697. $outputlangs->setDefaultLang($newlang);
  3698. }
  3699. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  3700. } else {
  3701. $label = $line->product_label;
  3702. }
  3703. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  3704. $description .= (!empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : dol_htmlentitiesbr($line->description)); // Description is what to show on popup. We shown nothing if already into desc.
  3705. }
  3706. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  3707. // Output template part (modules that overwrite templates must declare this into descriptor)
  3708. // Use global variables + $dateSelector + $seller and $buyer
  3709. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  3710. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  3711. foreach ($dirtpls as $module => $reldir)
  3712. {
  3713. if (!empty($module))
  3714. {
  3715. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  3716. } else {
  3717. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  3718. }
  3719. if (empty($conf->file->strict_mode)) {
  3720. $res = @include $tpl;
  3721. } else {
  3722. $res = include $tpl; // for debug
  3723. }
  3724. if ($res) break;
  3725. }
  3726. }
  3727. // Line in update mode
  3728. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id)
  3729. {
  3730. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  3731. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  3732. // Output template part (modules that overwrite templates must declare this into descriptor)
  3733. // Use global variables + $dateSelector + $seller and $buyer
  3734. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  3735. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  3736. foreach ($dirtpls as $module => $reldir)
  3737. {
  3738. if (!empty($module))
  3739. {
  3740. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  3741. } else {
  3742. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  3743. }
  3744. if (empty($conf->file->strict_mode)) {
  3745. $res = @include $tpl;
  3746. } else {
  3747. $res = include $tpl; // for debug
  3748. }
  3749. if ($res) break;
  3750. }
  3751. }
  3752. }
  3753. /* This is to show array of line of details of source object */
  3754. /**
  3755. * Return HTML table table of source object lines
  3756. * TODO Move this and previous function into output html class file (htmlline.class.php).
  3757. * If lines are into a template, title must also be into a template
  3758. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  3759. *
  3760. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  3761. * @param array $selectedLines Array of lines id for selected lines
  3762. * @return void
  3763. */
  3764. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  3765. {
  3766. global $langs, $hookmanager, $conf, $form;
  3767. print '<tr class="liste_titre">';
  3768. print '<td>'.$langs->trans('Ref').'</td>';
  3769. print '<td>'.$langs->trans('Description').'</td>';
  3770. print '<td class="right">'.$langs->trans('VATRate').'</td>';
  3771. print '<td class="right">'.$langs->trans('PriceUHT').'</td>';
  3772. if (!empty($conf->multicurrency->enabled)) print '<td class="right">'.$langs->trans('PriceUHTCurrency').'</td>';
  3773. print '<td class="right">'.$langs->trans('Qty').'</td>';
  3774. if (!empty($conf->global->PRODUCT_USE_UNITS))
  3775. {
  3776. print '<td class="left">'.$langs->trans('Unit').'</td>';
  3777. }
  3778. print '<td class="right">'.$langs->trans('ReductionShort').'</td>';
  3779. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  3780. print '</tr>';
  3781. $i = 0;
  3782. if (!empty($this->lines))
  3783. {
  3784. foreach ($this->lines as $line)
  3785. {
  3786. if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line)))
  3787. {
  3788. if (empty($line->fk_parent_line))
  3789. {
  3790. $parameters = array('line'=>$line, 'i'=>$i);
  3791. $action = '';
  3792. $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3793. }
  3794. } else {
  3795. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  3796. }
  3797. $i++;
  3798. }
  3799. }
  3800. }
  3801. /**
  3802. * Return HTML with a line of table array of source object lines
  3803. * TODO Move this and previous function into output html class file (htmlline.class.php).
  3804. * If lines are into a template, title must also be into a template
  3805. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  3806. *
  3807. * @param CommonObjectLine $line Line
  3808. * @param string $var Var
  3809. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  3810. * @param string $defaulttpldir Directory where to find the template
  3811. * @param array $selectedLines Array of lines id for selected lines
  3812. * @return void
  3813. */
  3814. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  3815. {
  3816. global $langs, $conf;
  3817. //var_dump($line);
  3818. if (!empty($line->date_start))
  3819. {
  3820. $date_start = $line->date_start;
  3821. } else {
  3822. $date_start = $line->date_debut_prevue;
  3823. if ($line->date_debut_reel) $date_start = $line->date_debut_reel;
  3824. }
  3825. if (!empty($line->date_end))
  3826. {
  3827. $date_end = $line->date_end;
  3828. } else {
  3829. $date_end = $line->date_fin_prevue;
  3830. if ($line->date_fin_reel) $date_end = $line->date_fin_reel;
  3831. }
  3832. $this->tpl['id'] = $line->id;
  3833. $this->tpl['label'] = '';
  3834. if (!empty($line->fk_parent_line)) $this->tpl['label'] .= img_picto('', 'rightarrow');
  3835. if (($line->info_bits & 2) == 2) // TODO Not sure this is used for source object
  3836. {
  3837. $discount = new DiscountAbsolute($this->db);
  3838. $discount->fk_soc = $this->socid;
  3839. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  3840. } elseif (!empty($line->fk_product))
  3841. {
  3842. $productstatic = new Product($this->db);
  3843. $productstatic->id = $line->fk_product;
  3844. $productstatic->ref = $line->ref;
  3845. $productstatic->type = $line->fk_product_type;
  3846. if (empty($productstatic->ref)) {
  3847. $line->fetch_product();
  3848. $productstatic = $line->product;
  3849. }
  3850. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  3851. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  3852. // Dates
  3853. if ($line->product_type == 1 && ($date_start || $date_end))
  3854. {
  3855. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  3856. }
  3857. } else {
  3858. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  3859. if (!empty($line->desc)) {
  3860. $this->tpl['label'] .= $line->desc;
  3861. } else {
  3862. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  3863. }
  3864. // Dates
  3865. if ($line->product_type == 1 && ($date_start || $date_end))
  3866. {
  3867. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  3868. }
  3869. }
  3870. if (!empty($line->desc))
  3871. {
  3872. if ($line->desc == '(CREDIT_NOTE)') // TODO Not sure this is used for source object
  3873. {
  3874. $discount = new DiscountAbsolute($this->db);
  3875. $discount->fetch($line->fk_remise_except);
  3876. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  3877. } elseif ($line->desc == '(DEPOSIT)') // TODO Not sure this is used for source object
  3878. {
  3879. $discount = new DiscountAbsolute($this->db);
  3880. $discount->fetch($line->fk_remise_except);
  3881. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  3882. } elseif ($line->desc == '(EXCESS RECEIVED)')
  3883. {
  3884. $discount = new DiscountAbsolute($this->db);
  3885. $discount->fetch($line->fk_remise_except);
  3886. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  3887. } elseif ($line->desc == '(EXCESS PAID)')
  3888. {
  3889. $discount = new DiscountAbsolute($this->db);
  3890. $discount->fetch($line->fk_remise_except);
  3891. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  3892. } else {
  3893. $this->tpl['description'] = dol_trunc($line->desc, 60);
  3894. }
  3895. } else {
  3896. $this->tpl['description'] = '&nbsp;';
  3897. }
  3898. // VAT Rate
  3899. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  3900. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  3901. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  3902. $this->tpl['price'] = price($line->subprice);
  3903. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  3904. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  3905. if (!empty($conf->global->PRODUCT_USE_UNITS)) $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  3906. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  3907. // Is the line strike or not
  3908. $this->tpl['strike'] = 0;
  3909. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) $this->tpl['strike'] = 1;
  3910. // Output template part (modules that overwrite templates must declare this into descriptor)
  3911. // Use global variables + $dateSelector + $seller and $buyer
  3912. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  3913. foreach ($dirtpls as $module => $reldir)
  3914. {
  3915. if (!empty($module))
  3916. {
  3917. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  3918. } else {
  3919. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  3920. }
  3921. if (empty($conf->file->strict_mode)) {
  3922. $res = @include $tpl;
  3923. } else {
  3924. $res = include $tpl; // for debug
  3925. }
  3926. if ($res) break;
  3927. }
  3928. }
  3929. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3930. /**
  3931. * Add resources to the current object : add entry into llx_element_resources
  3932. * Need $this->element & $this->id
  3933. *
  3934. * @param int $resource_id Resource id
  3935. * @param string $resource_type 'resource'
  3936. * @param int $busy Busy or not
  3937. * @param int $mandatory Mandatory or not
  3938. * @return int <=0 if KO, >0 if OK
  3939. */
  3940. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  3941. {
  3942. // phpcs:enable
  3943. $this->db->begin();
  3944. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources (";
  3945. $sql .= "resource_id";
  3946. $sql .= ", resource_type";
  3947. $sql .= ", element_id";
  3948. $sql .= ", element_type";
  3949. $sql .= ", busy";
  3950. $sql .= ", mandatory";
  3951. $sql .= ") VALUES (";
  3952. $sql .= $resource_id;
  3953. $sql .= ", '".$this->db->escape($resource_type)."'";
  3954. $sql .= ", '".$this->db->escape($this->id)."'";
  3955. $sql .= ", '".$this->db->escape($this->element)."'";
  3956. $sql .= ", '".$this->db->escape($busy)."'";
  3957. $sql .= ", '".$this->db->escape($mandatory)."'";
  3958. $sql .= ")";
  3959. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  3960. if ($this->db->query($sql))
  3961. {
  3962. $this->db->commit();
  3963. return 1;
  3964. } else {
  3965. $this->error = $this->db->lasterror();
  3966. $this->db->rollback();
  3967. return 0;
  3968. }
  3969. }
  3970. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3971. /**
  3972. * Delete a link to resource line
  3973. *
  3974. * @param int $rowid Id of resource line to delete
  3975. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  3976. * @param int $notrigger Disable all triggers
  3977. * @return int >0 if OK, <0 if KO
  3978. */
  3979. public function delete_resource($rowid, $element, $notrigger = 0)
  3980. {
  3981. // phpcs:enable
  3982. global $user;
  3983. $this->db->begin();
  3984. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
  3985. $sql .= " WHERE rowid=".$rowid;
  3986. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  3987. $resql = $this->db->query($sql);
  3988. if (!$resql)
  3989. {
  3990. $this->error = $this->db->lasterror();
  3991. $this->db->rollback();
  3992. return -1;
  3993. } else {
  3994. if (!$notrigger)
  3995. {
  3996. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  3997. if ($result < 0) { $this->db->rollback(); return -1; }
  3998. }
  3999. $this->db->commit();
  4000. return 1;
  4001. }
  4002. }
  4003. /**
  4004. * Overwrite magic function to solve problem of cloning object that are kept as references
  4005. *
  4006. * @return void
  4007. */
  4008. public function __clone()
  4009. {
  4010. // Force a copy of this->lines, otherwise it will point to same object.
  4011. if (isset($this->lines) && is_array($this->lines))
  4012. {
  4013. $nboflines = count($this->lines);
  4014. for ($i = 0; $i < $nboflines; $i++)
  4015. {
  4016. $this->lines[$i] = clone $this->lines[$i];
  4017. }
  4018. }
  4019. }
  4020. /**
  4021. * Common function for all objects extending CommonObject for generating documents
  4022. *
  4023. * @param string $modelspath Relative folder where generators are placed
  4024. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4025. * @param Translate $outputlangs Output language to use
  4026. * @param int $hidedetails 1 to hide details. 0 by default
  4027. * @param int $hidedesc 1 to hide product description. 0 by default
  4028. * @param int $hideref 1 to hide product reference. 0 by default
  4029. * @param null|array $moreparams Array to provide more information
  4030. * @return int >0 if OK, <0 if KO
  4031. * @see addFileIntoDatabaseIndex()
  4032. */
  4033. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4034. {
  4035. global $conf, $langs, $user, $hookmanager, $action;
  4036. $srctemplatepath = '';
  4037. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  4038. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4039. if (empty($reshook))
  4040. {
  4041. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4042. if (empty($modele)) {
  4043. $this->error = 'BadValueForParameterModele';
  4044. return -1;
  4045. }
  4046. // Increase limit for PDF build
  4047. $err = error_reporting();
  4048. error_reporting(0);
  4049. @set_time_limit(120);
  4050. error_reporting($err);
  4051. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4052. $tmp = explode(':', $modele, 2);
  4053. if (!empty($tmp[1]))
  4054. {
  4055. $modele = $tmp[0];
  4056. $srctemplatepath = $tmp[1];
  4057. }
  4058. // Search template files
  4059. $file = '';
  4060. $classname = '';
  4061. $filefound = '';
  4062. $dirmodels = array('/');
  4063. if (is_array($conf->modules_parts['models'])) $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4064. foreach ($dirmodels as $reldir)
  4065. {
  4066. foreach (array('doc', 'pdf') as $prefix)
  4067. {
  4068. if (in_array(get_class($this), array('Adherent'))) {
  4069. // Member module use prefix_modele.class.php
  4070. $file = $prefix."_".$modele.".class.php";
  4071. } else {
  4072. // Other module use prefix_modele.modules.php
  4073. $file = $prefix."_".$modele.".modules.php";
  4074. }
  4075. // On verifie l'emplacement du modele
  4076. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  4077. if (file_exists($file)) {
  4078. $filefound = $file;
  4079. $classname = $prefix.'_'.$modele;
  4080. break;
  4081. }
  4082. }
  4083. if ($filefound) break;
  4084. }
  4085. // If generator was found
  4086. if ($filefound)
  4087. {
  4088. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4089. require_once $file;
  4090. $obj = new $classname($this->db);
  4091. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4092. if ($obj->type == 'odt' && empty($srctemplatepath))
  4093. {
  4094. $varfortemplatedir = $obj->scandir;
  4095. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir))
  4096. {
  4097. $dirtoscan = $conf->global->$varfortemplatedir;
  4098. $listoffiles = array();
  4099. // Now we add first model found in directories scanned
  4100. $listofdir = explode(',', $dirtoscan);
  4101. foreach ($listofdir as $key => $tmpdir)
  4102. {
  4103. $tmpdir = trim($tmpdir);
  4104. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4105. if (!$tmpdir) { unset($listofdir[$key]); continue; }
  4106. if (is_dir($tmpdir))
  4107. {
  4108. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4109. if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles);
  4110. }
  4111. }
  4112. if (count($listoffiles))
  4113. {
  4114. foreach ($listoffiles as $record)
  4115. {
  4116. $srctemplatepath = $record['fullname'];
  4117. break;
  4118. }
  4119. }
  4120. }
  4121. if (empty($srctemplatepath))
  4122. {
  4123. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4124. return -1;
  4125. }
  4126. }
  4127. if ($obj->type == 'odt' && !empty($srctemplatepath))
  4128. {
  4129. if (!dol_is_file($srctemplatepath))
  4130. {
  4131. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  4132. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4133. return -1;
  4134. }
  4135. }
  4136. // We save charset_output to restore it because write_file can change it if needed for
  4137. // output format that does not support UTF8.
  4138. $sav_charset_output = $outputlangs->charset_output;
  4139. if (in_array(get_class($this), array('Adherent')))
  4140. {
  4141. $arrayofrecords = array(); // The write_file of templates of adherent class need this var
  4142. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams);
  4143. } else {
  4144. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4145. }
  4146. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4147. if ($resultwritefile > 0)
  4148. {
  4149. $outputlangs->charset_output = $sav_charset_output;
  4150. // We delete old preview
  4151. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4152. dol_delete_preview($this);
  4153. // Index file in database
  4154. if (!empty($obj->result['fullpath']))
  4155. {
  4156. $destfull = $obj->result['fullpath'];
  4157. $upload_dir = dirname($destfull);
  4158. $destfile = basename($destfull);
  4159. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  4160. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) // If not a tmp dir
  4161. {
  4162. $filename = basename($destfile);
  4163. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4164. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4165. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4166. $ecmfile = new EcmFiles($this->db);
  4167. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  4168. // Set the public "share" key
  4169. $setsharekey = false;
  4170. if ($this->element == 'propal')
  4171. {
  4172. $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok
  4173. if ($useonlinesignature) $setsharekey = true;
  4174. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey = true;
  4175. }
  4176. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  4177. $setsharekey = true;
  4178. }
  4179. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  4180. $setsharekey = true;
  4181. }
  4182. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4183. $setsharekey = true;
  4184. }
  4185. if ($setsharekey) {
  4186. if (empty($ecmfile->share)) // Because object not found or share not set yet
  4187. {
  4188. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  4189. $ecmfile->share = getRandomPassword(true);
  4190. }
  4191. }
  4192. if ($result > 0)
  4193. {
  4194. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4195. $ecmfile->fullpath_orig = '';
  4196. $ecmfile->gen_or_uploaded = 'generated';
  4197. $ecmfile->description = ''; // indexed content
  4198. $ecmfile->keyword = ''; // keyword content
  4199. $result = $ecmfile->update($user);
  4200. if ($result < 0) {
  4201. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4202. }
  4203. } else {
  4204. $ecmfile->entity = $conf->entity;
  4205. $ecmfile->filepath = $rel_dir;
  4206. $ecmfile->filename = $filename;
  4207. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4208. $ecmfile->fullpath_orig = '';
  4209. $ecmfile->gen_or_uploaded = 'generated';
  4210. $ecmfile->description = ''; // indexed content
  4211. $ecmfile->keyword = ''; // keyword content
  4212. $ecmfile->src_object_type = $this->table_element;
  4213. $ecmfile->src_object_id = $this->id;
  4214. $result = $ecmfile->create($user);
  4215. if ($result < 0) {
  4216. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4217. }
  4218. }
  4219. /*$this->result['fullname']=$destfull;
  4220. $this->result['filepath']=$ecmfile->filepath;
  4221. $this->result['filename']=$ecmfile->filename;*/
  4222. //var_dump($obj->update_main_doc_field);exit;
  4223. // Update the last_main_doc field into main object (if documenent generator has property ->update_main_doc_field set)
  4224. $update_main_doc_field = 0;
  4225. if (!empty($obj->update_main_doc_field)) $update_main_doc_field = 1;
  4226. if ($update_main_doc_field && !empty($this->table_element))
  4227. {
  4228. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath.'/'.$ecmfile->filename)."'";
  4229. $sql .= ' WHERE rowid = '.$this->id;
  4230. $resql = $this->db->query($sql);
  4231. if (!$resql) {
  4232. dol_print_error($this->db);
  4233. } else {
  4234. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  4235. }
  4236. }
  4237. }
  4238. } else {
  4239. 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);
  4240. }
  4241. // Success in building document. We build meta file.
  4242. dol_meta_create($this);
  4243. return 1;
  4244. } else {
  4245. $outputlangs->charset_output = $sav_charset_output;
  4246. dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
  4247. return -1;
  4248. }
  4249. } else {
  4250. if (!$filefound) {
  4251. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4252. dol_print_error('', $this->error);
  4253. } else {
  4254. $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
  4255. dol_print_error('', $this->error);
  4256. }
  4257. return -1;
  4258. }
  4259. } else return $reshook;
  4260. }
  4261. /**
  4262. * Build thumb
  4263. * @todo Move this into files.lib.php
  4264. *
  4265. * @param string $file Path file in UTF8 to original file to create thumbs from.
  4266. * @return void
  4267. */
  4268. public function addThumbs($file)
  4269. {
  4270. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  4271. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  4272. $file_osencoded = dol_osencode($file);
  4273. if (file_exists($file_osencoded))
  4274. {
  4275. // Create small thumbs for company (Ratio is near 16/9)
  4276. // Used on logon for example
  4277. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  4278. // Create mini thumbs for company (Ratio is near 16/9)
  4279. // Used on menu or for setup page for example
  4280. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  4281. }
  4282. }
  4283. /* Functions common to commonobject and commonobjectline */
  4284. /* For default values */
  4285. /**
  4286. * Return the default value to use for a field when showing the create form of object.
  4287. * Return values in this order:
  4288. * 1) If parameter is available into POST, we return it first.
  4289. * 2) If not but an alternate value was provided as parameter of function, we return it.
  4290. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  4291. * 4) Return value found into database (TODO No yet implemented)
  4292. *
  4293. * @param string $fieldname Name of field
  4294. * @param string $alternatevalue Alternate value to use
  4295. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  4296. **/
  4297. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
  4298. {
  4299. global $conf, $_POST;
  4300. // If param here has been posted, we use this value first.
  4301. if (GETPOSTISSET($fieldname)) return GETPOST($fieldname, 'alphanohtml', 3);
  4302. if (isset($alternatevalue)) return $alternatevalue;
  4303. $newelement = $this->element;
  4304. if ($newelement == 'facture') $newelement = 'invoice';
  4305. if ($newelement == 'commande') $newelement = 'order';
  4306. if (empty($newelement))
  4307. {
  4308. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  4309. return '';
  4310. }
  4311. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  4312. //var_dump($keyforfieldname);
  4313. if (isset($conf->global->$keyforfieldname)) return $conf->global->$keyforfieldname;
  4314. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  4315. }
  4316. /* For triggers */
  4317. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4318. /**
  4319. * Call trigger based on this instance.
  4320. * Some context information may also be provided into array property this->context.
  4321. * NB: Error from trigger are stacked in interface->errors
  4322. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  4323. *
  4324. * @param string $triggerName trigger's name to execute
  4325. * @param User $user Object user
  4326. * @return int Result of run_triggers
  4327. */
  4328. public function call_trigger($triggerName, $user)
  4329. {
  4330. // phpcs:enable
  4331. global $langs, $conf;
  4332. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  4333. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4334. $langs = new Translate('', $conf);
  4335. }
  4336. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  4337. $interface = new Interfaces($this->db);
  4338. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  4339. if ($result < 0)
  4340. {
  4341. if (!empty($this->errors))
  4342. {
  4343. $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.
  4344. } else {
  4345. $this->errors = $interface->errors;
  4346. }
  4347. }
  4348. return $result;
  4349. }
  4350. /* Functions for data in other language */
  4351. /**
  4352. * Function to get alternative languages of a data into $this->array_languages
  4353. * This method is NOT called by method fetch of objects but must be called separately.
  4354. *
  4355. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  4356. * @see fetch_optionnals()
  4357. */
  4358. public function fetchValuesForExtraLanguages()
  4359. {
  4360. // To avoid SQL errors. Probably not the better solution though
  4361. if (!$this->element) {
  4362. return 0;
  4363. }
  4364. if (!($this->id > 0)) {
  4365. return 0;
  4366. }
  4367. if (is_array($this->array_languages)) {
  4368. return 1;
  4369. }
  4370. $this->array_languages = array();
  4371. $element = $this->element;
  4372. if ($element == 'categorie') $element = 'categories'; // For compatibility
  4373. // Request to get translation values for object
  4374. $sql = "SELECT rowid, property, lang , value";
  4375. $sql .= " FROM ".MAIN_DB_PREFIX."object_lang";
  4376. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  4377. $sql .= " AND fk_object = ".$this->id;
  4378. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  4379. $resql = $this->db->query($sql);
  4380. if ($resql)
  4381. {
  4382. $numrows = $this->db->num_rows($resql);
  4383. if ($numrows)
  4384. {
  4385. $i = 0;
  4386. while ($i < $numrows) {
  4387. $obj = $this->db->fetch_object($resql);
  4388. $key = $obj->property;
  4389. $value = $obj->value;
  4390. $codelang = $obj->lang;
  4391. $type = $this->fields[$key]['type'];
  4392. // we can add this attribute to object
  4393. if (preg_match('/date/', $type))
  4394. {
  4395. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  4396. } else {
  4397. $this->array_languages[$key][$codelang] = $value;
  4398. }
  4399. $i++;
  4400. }
  4401. }
  4402. $this->db->free($resql);
  4403. if ($numrows) return $numrows;
  4404. else return 0;
  4405. } else {
  4406. dol_print_error($this->db);
  4407. return -1;
  4408. }
  4409. }
  4410. /**
  4411. * Fill array_options property of object by extrafields value (using for data sent by forms)
  4412. *
  4413. * @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.
  4414. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  4415. */
  4416. public function setValuesForExtraLanguages($onlykey = '')
  4417. {
  4418. global $_POST, $langs;
  4419. // Get extra fields
  4420. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  4421. $tmparray = explode('-', $postfieldkey);
  4422. if ($tmparray[0] != 'field') continue;
  4423. $element = $tmparray[1];
  4424. $key = $tmparray[2];
  4425. $codelang = $tmparray[3];
  4426. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  4427. if (!empty($onlykey) && $key != $onlykey) continue;
  4428. if ($element != $this->element) continue;
  4429. $key_type = $this->fields[$key]['type'];
  4430. $enabled = 1;
  4431. if (isset($this->fields[$key]['enabled']))
  4432. {
  4433. $enabled = dol_eval($this->fields[$key]['enabled'], 1);
  4434. }
  4435. /*$perms = 1;
  4436. if (isset($this->fields[$key]['perms']))
  4437. {
  4438. $perms = dol_eval($this->fields[$key]['perms'], 1);
  4439. }*/
  4440. if (empty($enabled)) continue;
  4441. //if (empty($perms)) continue;
  4442. if (in_array($key_type, array('date')))
  4443. {
  4444. // Clean parameters
  4445. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  4446. $value_key = dol_mktime(0, 0, 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]);
  4447. } elseif (in_array($key_type, array('datetime')))
  4448. {
  4449. // Clean parameters
  4450. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  4451. $value_key = dol_mktime($_POST[$postfieldkey."hour"], $_POST[$postfieldkey."min"], 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]);
  4452. } elseif (in_array($key_type, array('checkbox', 'chkbxlst')))
  4453. {
  4454. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  4455. if (!empty($value_arr)) {
  4456. $value_key = implode(',', $value_arr);
  4457. } else {
  4458. $value_key = '';
  4459. }
  4460. } elseif (in_array($key_type, array('price', 'double')))
  4461. {
  4462. $value_arr = GETPOST($postfieldkey, 'alpha');
  4463. $value_key = price2num($value_arr);
  4464. } else {
  4465. $value_key = GETPOST($postfieldkey);
  4466. if (in_array($key_type, array('link')) && $value_key == '-1') $value_key = '';
  4467. }
  4468. $this->array_languages[$key][$codelang] = $value_key;
  4469. /*if ($nofillrequired) {
  4470. $langs->load('errors');
  4471. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  4472. return -1;
  4473. }*/
  4474. }
  4475. return 1;
  4476. }
  4477. /* Functions for extrafields */
  4478. /**
  4479. * Function to make a fetch but set environment to avoid to load computed values before.
  4480. *
  4481. * @param int $id ID of object
  4482. * @return int >0 if OK, 0 if not found, <0 if KO
  4483. */
  4484. public function fetchNoCompute($id)
  4485. {
  4486. global $conf;
  4487. $savDisableCompute = $conf->disable_compute;
  4488. $conf->disable_compute = 1;
  4489. $ret = $this->fetch($id);
  4490. $conf->disable_compute = $savDisableCompute;
  4491. return $ret;
  4492. }
  4493. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4494. /**
  4495. * Function to get extra fields of an object into $this->array_options
  4496. * This method is in most cases called by method fetch of objects but you can call it separately.
  4497. *
  4498. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  4499. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  4500. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  4501. * @see fetchValuesForExtraLanguages()
  4502. */
  4503. public function fetch_optionals($rowid = null, $optionsArray = null)
  4504. {
  4505. // phpcs:enable
  4506. global $conf, $extrafields;
  4507. if (empty($rowid)) $rowid = $this->id;
  4508. if (empty($rowid) && isset($this->rowid)) $rowid = $this->rowid; // deprecated
  4509. // To avoid SQL errors. Probably not the better solution though
  4510. if (!$this->table_element) {
  4511. return 0;
  4512. }
  4513. $this->array_options = array();
  4514. if (!is_array($optionsArray))
  4515. {
  4516. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  4517. if (!isset($extrafields) || !is_object($extrafields))
  4518. {
  4519. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4520. $extrafields = new ExtraFields($this->db);
  4521. }
  4522. // Load array of extrafields for elementype = $this->table_element
  4523. if (empty($extrafields->attributes[$this->table_element]['loaded']))
  4524. {
  4525. $extrafields->fetch_name_optionals_label($this->table_element);
  4526. }
  4527. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  4528. } else {
  4529. global $extrafields;
  4530. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  4531. }
  4532. $table_element = $this->table_element;
  4533. if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
  4534. // Request to get complementary values
  4535. if (is_array($optionsArray) && count($optionsArray) > 0)
  4536. {
  4537. $sql = "SELECT rowid";
  4538. foreach ($optionsArray as $name => $label)
  4539. {
  4540. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate')
  4541. {
  4542. $sql .= ", ".$name;
  4543. }
  4544. }
  4545. $sql .= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
  4546. $sql .= " WHERE fk_object = ".((int) $rowid);
  4547. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  4548. $resql = $this->db->query($sql);
  4549. if ($resql)
  4550. {
  4551. $numrows = $this->db->num_rows($resql);
  4552. if ($numrows)
  4553. {
  4554. $tab = $this->db->fetch_array($resql);
  4555. foreach ($tab as $key => $value)
  4556. {
  4557. // 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)
  4558. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key))
  4559. {
  4560. // we can add this attribute to object
  4561. if (!empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime')))
  4562. {
  4563. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  4564. $this->array_options["options_".$key] = $this->db->jdate($value);
  4565. } else {
  4566. $this->array_options["options_".$key] = $value;
  4567. }
  4568. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  4569. }
  4570. }
  4571. // If field is a computed field, value must become result of compute
  4572. foreach ($tab as $key => $value) {
  4573. if (!empty($extrafields) && !empty($extrafields->attributes[$this->table_element]['computed'][$key]))
  4574. {
  4575. //var_dump($conf->disable_compute);
  4576. if (empty($conf->disable_compute)) {
  4577. $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0);
  4578. }
  4579. }
  4580. }
  4581. }
  4582. $this->db->free($resql);
  4583. if ($numrows) return $numrows;
  4584. else return 0;
  4585. } else {
  4586. dol_print_error($this->db);
  4587. return -1;
  4588. }
  4589. }
  4590. return 0;
  4591. }
  4592. /**
  4593. * Delete all extra fields values for the current object.
  4594. *
  4595. * @return int <0 if KO, >0 if OK
  4596. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  4597. */
  4598. public function deleteExtraFields()
  4599. {
  4600. global $conf;
  4601. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0;
  4602. $this->db->begin();
  4603. $table_element = $this->table_element;
  4604. if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
  4605. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
  4606. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  4607. $resql = $this->db->query($sql_del);
  4608. if (!$resql)
  4609. {
  4610. $this->error = $this->db->lasterror();
  4611. $this->db->rollback();
  4612. return -1;
  4613. } else {
  4614. $this->db->commit();
  4615. return 1;
  4616. }
  4617. }
  4618. /**
  4619. * Add/Update all extra fields values for the current object.
  4620. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  4621. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  4622. *
  4623. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  4624. * @param User $userused Object user
  4625. * @return int -1=error, O=did nothing, 1=OK
  4626. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  4627. */
  4628. public function insertExtraFields($trigger = '', $userused = null)
  4629. {
  4630. global $conf, $langs, $user;
  4631. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0;
  4632. if (empty($userused)) $userused = $user;
  4633. $error = 0;
  4634. if (!empty($this->array_options))
  4635. {
  4636. // Check parameters
  4637. $langs->load('admin');
  4638. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4639. $extrafields = new ExtraFields($this->db);
  4640. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  4641. // Eliminate copied source object extra fields that do not exist in target object
  4642. $new_array_options = array();
  4643. foreach ($this->array_options as $key => $value) {
  4644. if (in_array(substr($key, 8), array_keys($target_extrafields))) // We remove the 'options_' from $key for test
  4645. $new_array_options[$key] = $value;
  4646. elseif (in_array($key, array_keys($target_extrafields))) // We test on $key that does not contains the 'options_' prefix
  4647. $new_array_options['options_'.$key] = $value;
  4648. }
  4649. foreach ($new_array_options as $key => $value)
  4650. {
  4651. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  4652. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  4653. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  4654. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  4655. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  4656. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  4657. // Similar code than into insertExtraFields
  4658. if ($attributeRequired)
  4659. {
  4660. $mandatorypb = false;
  4661. if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb = true;
  4662. if ($this->array_options[$key] === '') $mandatorypb = true;
  4663. if ($mandatorypb)
  4664. {
  4665. dol_syslog("Mandatory extra field ".$key." is empty");
  4666. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  4667. return -1;
  4668. }
  4669. }
  4670. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  4671. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  4672. if (!empty($attrfieldcomputed))
  4673. {
  4674. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS))
  4675. {
  4676. $value = dol_eval($attrfieldcomputed, 1, 0);
  4677. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  4678. $new_array_options[$key] = $value;
  4679. } else {
  4680. $new_array_options[$key] = null;
  4681. }
  4682. }
  4683. switch ($attributeType)
  4684. {
  4685. case 'int':
  4686. if (!is_numeric($value) && $value != '')
  4687. {
  4688. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  4689. return -1;
  4690. } elseif ($value == '')
  4691. {
  4692. $new_array_options[$key] = null;
  4693. }
  4694. break;
  4695. case 'price':
  4696. case 'double':
  4697. $value = price2num($value);
  4698. if (!is_numeric($value) && $value != '')
  4699. {
  4700. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  4701. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  4702. return -1;
  4703. } elseif ($value == '')
  4704. {
  4705. $new_array_options[$key] = null;
  4706. }
  4707. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  4708. $new_array_options[$key] = $value;
  4709. break;
  4710. /*case 'select': // Not required, we chosed value='0' for undefined values
  4711. if ($value=='-1')
  4712. {
  4713. $this->array_options[$key] = null;
  4714. }
  4715. break;*/
  4716. case 'password':
  4717. $algo = '';
  4718. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']))
  4719. {
  4720. // If there is an encryption choice, we use it to crypt data before insert
  4721. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  4722. $algo = reset($tmparrays);
  4723. if ($algo != '')
  4724. {
  4725. //global $action; // $action may be 'create', 'update', 'update_extras'...
  4726. //var_dump($action);
  4727. //var_dump($this->oldcopy);exit;
  4728. 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
  4729. {
  4730. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  4731. if ($this->array_options[$key] == $this->oldcopy->array_options[$key]) // If old value crypted in database is same than submited new value, it means we don't change it, so we don't update.
  4732. {
  4733. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  4734. } else {
  4735. // var_dump($algo);
  4736. $newvalue = dol_hash($this->array_options[$key], $algo);
  4737. $new_array_options[$key] = $newvalue;
  4738. }
  4739. } else {
  4740. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  4741. }
  4742. }
  4743. } else // Common usage
  4744. {
  4745. $new_array_options[$key] = $this->array_options[$key];
  4746. }
  4747. break;
  4748. case 'date':
  4749. case 'datetime':
  4750. // If data is a string instead of a timestamp, we convert it
  4751. if (!is_int($this->array_options[$key])) {
  4752. $this->array_options[$key] = strtotime($this->array_options[$key]);
  4753. }
  4754. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  4755. break;
  4756. case 'link':
  4757. $param_list = array_keys($attributeParam['options']);
  4758. // 0 : ObjectName
  4759. // 1 : classPath
  4760. $InfoFieldList = explode(":", $param_list[0]);
  4761. dol_include_once($InfoFieldList[1]);
  4762. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  4763. {
  4764. if ($value == '-1') // -1 is key for no defined in combo list of objects
  4765. {
  4766. $new_array_options[$key] = '';
  4767. } elseif ($value) {
  4768. $object = new $InfoFieldList[0]($this->db);
  4769. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  4770. else $res = $object->fetch('', $value); // For compatibility
  4771. if ($res > 0) $new_array_options[$key] = $object->id;
  4772. else {
  4773. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  4774. $this->db->rollback();
  4775. return -1;
  4776. }
  4777. }
  4778. } else {
  4779. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  4780. }
  4781. break;
  4782. }
  4783. }
  4784. $this->db->begin();
  4785. $table_element = $this->table_element;
  4786. if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
  4787. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  4788. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
  4789. $this->db->query($sql_del);
  4790. $sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object";
  4791. foreach ($new_array_options as $key => $value)
  4792. {
  4793. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  4794. // Add field of attribut
  4795. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator
  4796. $sql .= ",".$attributeKey;
  4797. }
  4798. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  4799. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  4800. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  4801. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  4802. $sql .= ",".$tmpkey;
  4803. }
  4804. }
  4805. }
  4806. $sql .= ") VALUES (".$this->id;
  4807. foreach ($new_array_options as $key => $value) {
  4808. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  4809. // Add field of attribute
  4810. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
  4811. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
  4812. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  4813. } else {
  4814. $sql .= ",null";
  4815. }
  4816. }
  4817. }
  4818. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  4819. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  4820. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  4821. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  4822. if (in_array($tmpval, array('int', 'double', 'price'))) $sql .= ", 0";
  4823. else $sql .= ", ''";
  4824. }
  4825. }
  4826. }
  4827. $sql .= ")";
  4828. $resql = $this->db->query($sql);
  4829. if (!$resql)
  4830. {
  4831. $this->error = $this->db->lasterror();
  4832. $error++;
  4833. }
  4834. if (!$error && $trigger)
  4835. {
  4836. // Call trigger
  4837. $this->context = array('extrafieldaddupdate'=>1);
  4838. $result = $this->call_trigger($trigger, $userused);
  4839. if ($result < 0) $error++;
  4840. // End call trigger
  4841. }
  4842. if ($error)
  4843. {
  4844. $this->db->rollback();
  4845. return -1;
  4846. } else {
  4847. $this->db->commit();
  4848. return 1;
  4849. }
  4850. } else return 0;
  4851. }
  4852. /**
  4853. * Add/Update all extra fields values for the current object.
  4854. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  4855. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  4856. *
  4857. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  4858. * @param User $userused Object user
  4859. * @return int -1=error, O=did nothing, 1=OK
  4860. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  4861. */
  4862. public function insertExtraLanguages($trigger = '', $userused = null)
  4863. {
  4864. global $conf, $langs, $user;
  4865. if (empty($userused)) $userused = $user;
  4866. $error = 0;
  4867. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) return 0; // For avoid conflicts if trigger used
  4868. if (is_array($this->array_languages))
  4869. {
  4870. $new_array_languages = $this->array_languages;
  4871. foreach ($new_array_languages as $key => $value)
  4872. {
  4873. $attributeKey = $key;
  4874. $attributeType = $this->fields[$attributeKey]['type'];
  4875. $attributeLabel = $this->fields[$attributeKey]['label'];
  4876. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  4877. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  4878. switch ($attributeType)
  4879. {
  4880. case 'int':
  4881. if (!is_numeric($value) && $value != '')
  4882. {
  4883. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  4884. return -1;
  4885. } elseif ($value == '')
  4886. {
  4887. $new_array_languages[$key] = null;
  4888. }
  4889. break;
  4890. case 'double':
  4891. $value = price2num($value);
  4892. if (!is_numeric($value) && $value != '')
  4893. {
  4894. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  4895. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  4896. return -1;
  4897. } elseif ($value == '')
  4898. {
  4899. $new_array_languages[$key] = null;
  4900. }
  4901. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  4902. $new_array_languages[$key] = $value;
  4903. break;
  4904. /*case 'select': // Not required, we chosed value='0' for undefined values
  4905. if ($value=='-1')
  4906. {
  4907. $this->array_options[$key] = null;
  4908. }
  4909. break;*/
  4910. }
  4911. }
  4912. $this->db->begin();
  4913. $table_element = $this->table_element;
  4914. if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
  4915. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  4916. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  4917. foreach ($langcodearray as $langcode => $value) {
  4918. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX."object_lang";
  4919. $sql_del .= " WHERE fk_object = ".$this->id." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  4920. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  4921. $this->db->query($sql_del);
  4922. if ($value !== '') {
  4923. $sql = "INSERT INTO ".MAIN_DB_PREFIX."object_lang (fk_object, property, type_object, lang, value";
  4924. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  4925. $sql .= ")";
  4926. $resql = $this->db->query($sql);
  4927. if (!$resql)
  4928. {
  4929. $this->error = $this->db->lasterror();
  4930. $error++;
  4931. break;
  4932. }
  4933. }
  4934. }
  4935. }
  4936. if (!$error && $trigger)
  4937. {
  4938. // Call trigger
  4939. $this->context = array('extralanguagesaddupdate'=>1);
  4940. $result = $this->call_trigger($trigger, $userused);
  4941. if ($result < 0) $error++;
  4942. // End call trigger
  4943. }
  4944. if ($error)
  4945. {
  4946. $this->db->rollback();
  4947. return -1;
  4948. } else {
  4949. $this->db->commit();
  4950. return 1;
  4951. }
  4952. } else return 0;
  4953. }
  4954. /**
  4955. * Update 1 extra field value for the current object. Keep other fields unchanged.
  4956. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  4957. *
  4958. * @param string $key Key of the extrafield to update (without starting 'options_')
  4959. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  4960. * @param User $userused Object user
  4961. * @return int -1=error, O=did nothing, 1=OK
  4962. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  4963. */
  4964. public function updateExtraField($key, $trigger = null, $userused = null)
  4965. {
  4966. global $conf, $langs, $user;
  4967. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0;
  4968. if (empty($userused)) $userused = $user;
  4969. $error = 0;
  4970. if (!empty($this->array_options) && isset($this->array_options["options_".$key]))
  4971. {
  4972. // Check parameters
  4973. $langs->load('admin');
  4974. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4975. $extrafields = new ExtraFields($this->db);
  4976. $extrafields->fetch_name_optionals_label($this->table_element);
  4977. $value = $this->array_options["options_".$key];
  4978. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  4979. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  4980. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  4981. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  4982. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  4983. // Similar code than into insertExtraFields
  4984. if ($attributeRequired)
  4985. {
  4986. $mandatorypb = false;
  4987. if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') $mandatorypb = true;
  4988. if ($this->array_options["options_".$key] === '') $mandatorypb = true;
  4989. if ($mandatorypb)
  4990. {
  4991. dol_syslog("Mandatory extra field options_".$key." is empty");
  4992. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  4993. return -1;
  4994. }
  4995. }
  4996. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  4997. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  4998. if (!empty($attrfieldcomputed))
  4999. {
  5000. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS))
  5001. {
  5002. $value = dol_eval($attrfieldcomputed, 1, 0);
  5003. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5004. $this->array_options["options_".$key] = $value;
  5005. } else {
  5006. $this->array_options["options_".$key] = null;
  5007. }
  5008. }
  5009. switch ($attributeType)
  5010. {
  5011. case 'int':
  5012. if (!is_numeric($value) && $value != '')
  5013. {
  5014. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5015. return -1;
  5016. } elseif ($value === '')
  5017. {
  5018. $this->array_options["options_".$key] = null;
  5019. }
  5020. break;
  5021. case 'double':
  5022. $value = price2num($value);
  5023. if (!is_numeric($value) && $value != '')
  5024. {
  5025. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5026. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5027. return -1;
  5028. } elseif ($value === '')
  5029. {
  5030. $this->array_options["options_".$key] = null;
  5031. }
  5032. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5033. $this->array_options["options_".$key] = $value;
  5034. break;
  5035. /*case 'select': // Not required, we chosed value='0' for undefined values
  5036. if ($value=='-1')
  5037. {
  5038. $this->array_options[$key] = null;
  5039. }
  5040. break;*/
  5041. case 'price':
  5042. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  5043. break;
  5044. case 'date':
  5045. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5046. break;
  5047. case 'datetime':
  5048. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5049. break;
  5050. /*
  5051. case 'link':
  5052. $param_list = array_keys($attributeParam['options']);
  5053. // 0 : ObjectName
  5054. // 1 : classPath
  5055. $InfoFieldList = explode(":", $param_list[0]);
  5056. dol_include_once($InfoFieldList[1]);
  5057. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  5058. {
  5059. if ($value == '-1') // -1 is key for no defined in combo list of objects
  5060. {
  5061. $new_array_options[$key] = '';
  5062. } elseif ($value) {
  5063. $object = new $InfoFieldList[0]($this->db);
  5064. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  5065. else $res = $object->fetch('', $value); // For compatibility
  5066. if ($res > 0) $new_array_options[$key] = $object->id;
  5067. else {
  5068. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5069. $this->db->rollback();
  5070. return -1;
  5071. }
  5072. }
  5073. } else {
  5074. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5075. }
  5076. break;
  5077. */
  5078. }
  5079. $this->db->begin();
  5080. $linealreadyfound = 0;
  5081. // 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)
  5082. $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields WHERE fk_object = ".$this->id;
  5083. $resql = $this->db->query($sql);
  5084. if ($resql) {
  5085. $tmpobj = $this->db->fetch_object($resql);
  5086. if ($tmpobj) {
  5087. $linealreadyfound = $tmpobj->nb;
  5088. }
  5089. }
  5090. if ($linealreadyfound) {
  5091. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
  5092. $sql .= " WHERE fk_object = ".$this->id;
  5093. } else {
  5094. $result = $this->insertExtraFields('', $user);
  5095. if ($result < 0) $error++;
  5096. }
  5097. $resql = $this->db->query($sql);
  5098. if (!$resql)
  5099. {
  5100. $error++;
  5101. $this->error = $this->db->lasterror();
  5102. }
  5103. if (!$error && $trigger)
  5104. {
  5105. // Call trigger
  5106. $this->context = array('extrafieldupdate'=>1);
  5107. $result = $this->call_trigger($trigger, $userused);
  5108. if ($result < 0) $error++;
  5109. // End call trigger
  5110. }
  5111. if ($error)
  5112. {
  5113. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  5114. $this->db->rollback();
  5115. return -1;
  5116. } else {
  5117. $this->db->commit();
  5118. return 1;
  5119. }
  5120. } else return 0;
  5121. }
  5122. /**
  5123. * Update an extra language value for the current object.
  5124. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5125. *
  5126. * @param string $key Key of the extrafield (without starting 'options_')
  5127. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5128. * @param User $userused Object user
  5129. * @return int -1=error, O=did nothing, 1=OK
  5130. * @see updateExtraFields(), insertExtraLanguages()
  5131. */
  5132. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  5133. {
  5134. global $conf, $langs, $user;
  5135. if (empty($userused)) $userused = $user;
  5136. $error = 0;
  5137. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) return 0; // For avoid conflicts if trigger used
  5138. return 0;
  5139. }
  5140. /**
  5141. * Return HTML string to put an input field into a page
  5142. * Code very similar with showInputField of extra fields
  5143. *
  5144. * @param array $val Array of properties for field to show (used only if ->fields not defined)
  5145. * @param string $key Key of attribute
  5146. * @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)
  5147. * @param string $moreparam To add more parameters on html input tag
  5148. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5149. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5150. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  5151. * @param int $nonewbutton Force to not show the new button on field that are links to object
  5152. * @return string
  5153. */
  5154. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  5155. {
  5156. global $conf, $langs, $form;
  5157. if (!is_object($form))
  5158. {
  5159. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  5160. $form = new Form($this->db);
  5161. }
  5162. if (!empty($this->fields)) {
  5163. $val = $this->fields[$key];
  5164. }
  5165. $out = '';
  5166. $type = '';
  5167. $param = array();
  5168. $param['options'] = array();
  5169. $reg = array();
  5170. $size = $this->fields[$key]['size'];
  5171. // Because we work on extrafields
  5172. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5173. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5174. $type = 'link';
  5175. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5176. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5177. $type = 'link';
  5178. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  5179. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5180. $type = 'link';
  5181. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5182. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5183. $type = 'sellist';
  5184. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  5185. $param['options'] = array();
  5186. $type = 'varchar';
  5187. $size = $reg[1];
  5188. } elseif (preg_match('/varchar/', $val['type'])) {
  5189. $param['options'] = array();
  5190. $type = 'varchar';
  5191. } elseif (is_array($this->fields[$key]['arrayofkeyval'])) {
  5192. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  5193. $type = 'select';
  5194. } else {
  5195. $param['options'] = array();
  5196. $type = $this->fields[$key]['type'];
  5197. }
  5198. $label = $this->fields[$key]['label'];
  5199. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  5200. $default = $this->fields[$key]['default'];
  5201. $computed = $this->fields[$key]['computed'];
  5202. $unique = $this->fields[$key]['unique'];
  5203. $required = $this->fields[$key]['required'];
  5204. $autofocusoncreate = $this->fields[$key]['autofocusoncreate'];
  5205. $langfile = $this->fields[$key]['langfile'];
  5206. $list = $this->fields[$key]['list'];
  5207. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  5208. $objectid = $this->id;
  5209. if ($computed)
  5210. {
  5211. if (!preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  5212. else return '';
  5213. }
  5214. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  5215. if (empty($morecss) && !empty($val['css'])) {
  5216. $morecss = $val['css'];
  5217. } elseif (empty($morecss)) {
  5218. if ($type == 'date')
  5219. {
  5220. $morecss = 'minwidth100imp';
  5221. } elseif ($type == 'datetime' || $type == 'link') // link means an foreign key to another primary id
  5222. {
  5223. $morecss = 'minwidth200imp';
  5224. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type))
  5225. {
  5226. $morecss = 'maxwidth75';
  5227. } elseif ($type == 'url') {
  5228. $morecss = 'minwidth400';
  5229. } elseif ($type == 'boolean')
  5230. {
  5231. $morecss = '';
  5232. } else {
  5233. if (round($size) < 12)
  5234. {
  5235. $morecss = 'minwidth100';
  5236. } elseif (round($size) <= 48)
  5237. {
  5238. $morecss = 'minwidth200';
  5239. } else {
  5240. $morecss = 'minwidth400';
  5241. }
  5242. }
  5243. }
  5244. if (in_array($type, array('date', 'datetime'))) {
  5245. $tmp = explode(',', $size);
  5246. $newsize = $tmp[0];
  5247. $showtime = in_array($type, array('datetime')) ? 1 : 0;
  5248. // Do not show current date when field not required (see selectDate() method)
  5249. if (!$required && $value == '') $value = '-1';
  5250. // TODO Must also support $moreparam
  5251. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  5252. } elseif (in_array($type, array('duration'))) {
  5253. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  5254. } elseif (in_array($type, array('int', 'integer'))) {
  5255. $tmp = explode(',', $size);
  5256. $newsize = $tmp[0];
  5257. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$newsize.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5258. } elseif (in_array($type, array('real'))) {
  5259. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5260. } elseif (preg_match('/varchar/', $type)) {
  5261. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$size.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5262. } elseif (in_array($type, array('mail', 'phone', 'url'))) {
  5263. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5264. } elseif (preg_match('/^text/', $type)) {
  5265. if (!preg_match('/search_/', $keyprefix)) // If keyprefix is search_ or search_options_, we must just use a simple text field
  5266. {
  5267. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5268. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  5269. $out = $doleditor->Create(1);
  5270. } else {
  5271. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5272. }
  5273. } elseif (preg_match('/^html/', $type)) {
  5274. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  5275. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5276. $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%');
  5277. $out = $doleditor->Create(1);
  5278. } else {
  5279. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5280. }
  5281. } elseif ($type == 'boolean') {
  5282. $checked = '';
  5283. if (!empty($value)) {
  5284. $checked = ' checked value="1" ';
  5285. } else {
  5286. $checked = ' value="1" ';
  5287. }
  5288. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  5289. } elseif ($type == 'price') {
  5290. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5291. $value = price($value);
  5292. }
  5293. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  5294. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  5295. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5296. $value = price($value);
  5297. }
  5298. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  5299. } elseif ($type == 'select') {
  5300. $out = '';
  5301. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
  5302. {
  5303. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5304. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  5305. }
  5306. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  5307. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1))$out .= '<option value="0">&nbsp;</option>';
  5308. foreach ($param['options'] as $key => $val)
  5309. {
  5310. if ((string) $key == '') continue;
  5311. list($val, $parent) = explode('|', $val);
  5312. $out .= '<option value="'.$key.'"';
  5313. $out .= (((string) $value == (string) $key) ? ' selected' : '');
  5314. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  5315. $out .= '>'.$val.'</option>';
  5316. }
  5317. $out .= '</select>';
  5318. } elseif ($type == 'sellist') {
  5319. $out = '';
  5320. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) {
  5321. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5322. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  5323. }
  5324. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  5325. if (is_array($param['options'])) {
  5326. $param_list = array_keys($param['options']);
  5327. $InfoFieldList = explode(":", $param_list[0]);
  5328. $parentName = '';
  5329. $parentField = '';
  5330. // 0 : tableName
  5331. // 1 : label field name
  5332. // 2 : key fields name (if differ of rowid)
  5333. // 3 : key field parent (for dependent lists)
  5334. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  5335. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  5336. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4]))
  5337. {
  5338. if (strpos($InfoFieldList[4], 'extra.') !== false)
  5339. {
  5340. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  5341. } else {
  5342. $keyList = $InfoFieldList[2].' as rowid';
  5343. }
  5344. }
  5345. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3]))
  5346. {
  5347. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  5348. $keyList .= ', '.$parentField;
  5349. }
  5350. $fields_label = explode('|', $InfoFieldList[1]);
  5351. if (is_array($fields_label))
  5352. {
  5353. $keyList .= ', ';
  5354. $keyList .= implode(', ', $fields_label);
  5355. }
  5356. $sqlwhere = '';
  5357. $sql = 'SELECT '.$keyList;
  5358. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  5359. if (!empty($InfoFieldList[4]))
  5360. {
  5361. // can use SELECT request
  5362. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  5363. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  5364. }
  5365. // current object id can be use into filter
  5366. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  5367. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  5368. } else {
  5369. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  5370. }
  5371. //We have to join on extrafield table
  5372. if (strpos($InfoFieldList[4], 'extra') !== false)
  5373. {
  5374. $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
  5375. $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
  5376. } else {
  5377. $sqlwhere .= ' WHERE '.$InfoFieldList[4];
  5378. }
  5379. } else {
  5380. $sqlwhere .= ' WHERE 1=1';
  5381. }
  5382. // Some tables may have field, some other not. For the moment we disable it.
  5383. if (in_array($InfoFieldList[0], array('tablewithentity')))
  5384. {
  5385. $sqlwhere .= ' AND entity = '.$conf->entity;
  5386. }
  5387. $sql .= $sqlwhere;
  5388. //print $sql;
  5389. $sql .= ' ORDER BY '.implode(', ', $fields_label);
  5390. dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
  5391. $resql = $this->db->query($sql);
  5392. if ($resql)
  5393. {
  5394. $out .= '<option value="0">&nbsp;</option>';
  5395. $num = $this->db->num_rows($resql);
  5396. $i = 0;
  5397. while ($i < $num)
  5398. {
  5399. $labeltoshow = '';
  5400. $obj = $this->db->fetch_object($resql);
  5401. // Several field into label (eq table:code|libelle:rowid)
  5402. $notrans = false;
  5403. $fields_label = explode('|', $InfoFieldList[1]);
  5404. if (count($fields_label) > 1)
  5405. {
  5406. $notrans = true;
  5407. foreach ($fields_label as $field_toshow)
  5408. {
  5409. $labeltoshow .= $obj->$field_toshow.' ';
  5410. }
  5411. } else {
  5412. $labeltoshow = $obj->{$InfoFieldList[1]};
  5413. }
  5414. $labeltoshow = dol_trunc($labeltoshow, 45);
  5415. if ($value == $obj->rowid)
  5416. {
  5417. foreach ($fields_label as $field_toshow)
  5418. {
  5419. $translabel = $langs->trans($obj->$field_toshow);
  5420. if ($translabel != $obj->$field_toshow) {
  5421. $labeltoshow = dol_trunc($translabel, 18).' ';
  5422. } else {
  5423. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  5424. }
  5425. }
  5426. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  5427. } else {
  5428. if (!$notrans)
  5429. {
  5430. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  5431. if ($translabel != $obj->{$InfoFieldList[1]}) {
  5432. $labeltoshow = dol_trunc($translabel, 18);
  5433. } else {
  5434. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  5435. }
  5436. }
  5437. if (empty($labeltoshow)) $labeltoshow = '(not defined)';
  5438. if ($value == $obj->rowid)
  5439. {
  5440. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  5441. }
  5442. if (!empty($InfoFieldList[3]) && $parentField)
  5443. {
  5444. $parent = $parentName.':'.$obj->{$parentField};
  5445. }
  5446. $out .= '<option value="'.$obj->rowid.'"';
  5447. $out .= ($value == $obj->rowid ? ' selected' : '');
  5448. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  5449. $out .= '>'.$labeltoshow.'</option>';
  5450. }
  5451. $i++;
  5452. }
  5453. $this->db->free($resql);
  5454. } else {
  5455. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  5456. }
  5457. }
  5458. $out .= '</select>';
  5459. } elseif ($type == 'checkbox') {
  5460. $value_arr = explode(',', $value);
  5461. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
  5462. } elseif ($type == 'radio') {
  5463. $out = '';
  5464. foreach ($param['options'] as $keyopt => $val)
  5465. {
  5466. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  5467. $out .= ' value="'.$keyopt.'"';
  5468. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  5469. $out .= ($value == $keyopt ? 'checked' : '');
  5470. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
  5471. }
  5472. } elseif ($type == 'chkbxlst') {
  5473. if (is_array($value)) {
  5474. $value_arr = $value;
  5475. } else {
  5476. $value_arr = explode(',', $value);
  5477. }
  5478. if (is_array($param['options'])) {
  5479. $param_list = array_keys($param['options']);
  5480. $InfoFieldList = explode(":", $param_list[0]);
  5481. $parentName = '';
  5482. $parentField = '';
  5483. // 0 : tableName
  5484. // 1 : label field name
  5485. // 2 : key fields name (if differ of rowid)
  5486. // 3 : key field parent (for dependent lists)
  5487. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  5488. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  5489. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  5490. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  5491. $keyList .= ', '.$parentField;
  5492. }
  5493. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  5494. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  5495. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  5496. } else {
  5497. $keyList = $InfoFieldList[2].' as rowid';
  5498. }
  5499. }
  5500. $fields_label = explode('|', $InfoFieldList[1]);
  5501. if (is_array($fields_label)) {
  5502. $keyList .= ', ';
  5503. $keyList .= implode(', ', $fields_label);
  5504. }
  5505. $sqlwhere = '';
  5506. $sql = 'SELECT '.$keyList;
  5507. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  5508. if (!empty($InfoFieldList[4])) {
  5509. // can use SELECT request
  5510. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  5511. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  5512. }
  5513. // current object id can be use into filter
  5514. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  5515. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  5516. } else {
  5517. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  5518. }
  5519. // We have to join on extrafield table
  5520. if (strpos($InfoFieldList[4], 'extra') !== false) {
  5521. $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
  5522. $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
  5523. } else {
  5524. $sqlwhere .= ' WHERE '.$InfoFieldList[4];
  5525. }
  5526. } else {
  5527. $sqlwhere .= ' WHERE 1=1';
  5528. }
  5529. // Some tables may have field, some other not. For the moment we disable it.
  5530. if (in_array($InfoFieldList[0], array('tablewithentity')))
  5531. {
  5532. $sqlwhere .= ' AND entity = '.$conf->entity;
  5533. }
  5534. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  5535. // print $sql;
  5536. $sql .= $sqlwhere;
  5537. dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
  5538. $resql = $this->db->query($sql);
  5539. if ($resql) {
  5540. $num = $this->db->num_rows($resql);
  5541. $i = 0;
  5542. $data = array();
  5543. while ($i < $num) {
  5544. $labeltoshow = '';
  5545. $obj = $this->db->fetch_object($resql);
  5546. $notrans = false;
  5547. // Several field into label (eq table:code|libelle:rowid)
  5548. $fields_label = explode('|', $InfoFieldList[1]);
  5549. if (count($fields_label) > 1) {
  5550. $notrans = true;
  5551. foreach ($fields_label as $field_toshow) {
  5552. $labeltoshow .= $obj->$field_toshow.' ';
  5553. }
  5554. } else {
  5555. $labeltoshow = $obj->{$InfoFieldList[1]};
  5556. }
  5557. $labeltoshow = dol_trunc($labeltoshow, 45);
  5558. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  5559. foreach ($fields_label as $field_toshow) {
  5560. $translabel = $langs->trans($obj->$field_toshow);
  5561. if ($translabel != $obj->$field_toshow) {
  5562. $labeltoshow = dol_trunc($translabel, 18).' ';
  5563. } else {
  5564. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  5565. }
  5566. }
  5567. $data[$obj->rowid] = $labeltoshow;
  5568. } else {
  5569. if (!$notrans) {
  5570. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  5571. if ($translabel != $obj->{$InfoFieldList[1]}) {
  5572. $labeltoshow = dol_trunc($translabel, 18);
  5573. } else {
  5574. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  5575. }
  5576. }
  5577. if (empty($labeltoshow)) {
  5578. $labeltoshow = '(not defined)';
  5579. }
  5580. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  5581. $data[$obj->rowid] = $labeltoshow;
  5582. }
  5583. if (!empty($InfoFieldList[3]) && $parentField) {
  5584. $parent = $parentName.':'.$obj->{$parentField};
  5585. }
  5586. $data[$obj->rowid] = $labeltoshow;
  5587. }
  5588. $i++;
  5589. }
  5590. $this->db->free($resql);
  5591. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
  5592. } else {
  5593. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  5594. }
  5595. }
  5596. } elseif ($type == 'link') {
  5597. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter]]'
  5598. $param_list_array = explode(':', $param_list[0]);
  5599. $showempty = (($required && $default != '') ? 0 : 1);
  5600. if (!preg_match('/search_/', $keyprefix)) {
  5601. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  5602. if ($this->fields[$key]['picto']) {
  5603. $morecss .= ' widthcentpercentminusxx';
  5604. } else {
  5605. $morecss .= ' widthcentpercentminusx';
  5606. }
  5607. } else {
  5608. if ($this->fields[$key]['picto']) {
  5609. $morecss .= ' widthcentpercentminusx';
  5610. }
  5611. }
  5612. }
  5613. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  5614. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  5615. 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".
  5616. {
  5617. list($class, $classfile) = explode(':', $param_list[0]);
  5618. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  5619. else $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  5620. $paramforthenewlink = '';
  5621. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  5622. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  5623. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  5624. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  5625. $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>';
  5626. }
  5627. }
  5628. } elseif ($type == 'password') {
  5629. // If prefix is 'search_', field is used as a filter, we use a common text field.
  5630. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  5631. } elseif ($type == 'array') {
  5632. $newval = $val;
  5633. $newval['type'] = 'varchar(256)';
  5634. $out = '';
  5635. if (!empty($value)) {
  5636. foreach ($value as $option) {
  5637. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  5638. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  5639. }
  5640. }
  5641. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  5642. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  5643. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  5644. if (!empty($conf->use_javascript_ajax)) {
  5645. $out .= '
  5646. <script>
  5647. $(document).ready(function() {
  5648. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  5649. $("'.dol_escape_js($newInput).'").insertBefore(this);
  5650. });
  5651. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  5652. $(this).parent().remove();
  5653. });
  5654. });
  5655. </script>';
  5656. }
  5657. }
  5658. if (!empty($hidden)) {
  5659. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  5660. }
  5661. /* Add comments
  5662. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  5663. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  5664. */
  5665. return $out;
  5666. }
  5667. /**
  5668. * Return HTML string to show a field into a page
  5669. * Code very similar with showOutputField of extra fields
  5670. *
  5671. * @param array $val Array of properties of field to show
  5672. * @param string $key Key of attribute
  5673. * @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)
  5674. * @param string $moreparam To add more parametes on html input tag
  5675. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5676. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5677. * @param mixed $morecss Value for css to define size. May also be a numeric.
  5678. * @return string
  5679. */
  5680. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  5681. {
  5682. global $conf, $langs, $form;
  5683. if (!is_object($form))
  5684. {
  5685. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  5686. $form = new Form($this->db);
  5687. }
  5688. $objectid = $this->id;
  5689. $label = $val['label'];
  5690. $type = $val['type'];
  5691. $size = $val['css'];
  5692. $reg = array();
  5693. // Convert var to be able to share same code than showOutputField of extrafields
  5694. if (preg_match('/varchar\((\d+)\)/', $type, $reg))
  5695. {
  5696. $type = 'varchar'; // convert varchar(xx) int varchar
  5697. $size = $reg[1];
  5698. } elseif (preg_match('/varchar/', $type)) $type = 'varchar'; // convert varchar(xx) int varchar
  5699. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) $type = 'select';
  5700. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type = 'link';
  5701. $default = $val['default'];
  5702. $computed = $val['computed'];
  5703. $unique = $val['unique'];
  5704. $required = $val['required'];
  5705. $param = array();
  5706. $param['options'] = array();
  5707. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval'];
  5708. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg))
  5709. {
  5710. $type = 'link';
  5711. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  5712. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5713. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5714. $type = 'sellist';
  5715. }
  5716. $langfile = $val['langfile'];
  5717. $list = $val['list'];
  5718. $help = $val['help'];
  5719. $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)
  5720. if ($hidden) return '';
  5721. // If field is a computed field, value must become result of compute
  5722. if ($computed)
  5723. {
  5724. // Make the eval of compute string
  5725. //var_dump($computed);
  5726. $value = dol_eval($computed, 1, 0);
  5727. }
  5728. if (empty($morecss))
  5729. {
  5730. if ($type == 'date') {
  5731. $morecss = 'minwidth100imp';
  5732. } elseif ($type == 'datetime' || $type == 'timestamp') {
  5733. $morecss = 'minwidth200imp';
  5734. } elseif (in_array($type, array('int', 'double', 'price'))) {
  5735. $morecss = 'maxwidth75';
  5736. } elseif ($type == 'url') {
  5737. $morecss = 'minwidth400';
  5738. } elseif ($type == 'boolean') {
  5739. $morecss = '';
  5740. } else {
  5741. if (round($size) < 12) {
  5742. $morecss = 'minwidth100';
  5743. } elseif (round($size) <= 48) {
  5744. $morecss = 'minwidth200';
  5745. } else {
  5746. $morecss = 'minwidth400';
  5747. }
  5748. }
  5749. }
  5750. // Format output value differently according to properties of field
  5751. if ($key == 'ref' && method_exists($this, 'getNomUrl')) $value = $this->getNomUrl(1, '', 0, '', 1);
  5752. elseif ($key == 'status' && method_exists($this, 'getLibStatut')) $value = $this->getLibStatut(3);
  5753. elseif ($type == 'date') {
  5754. if (!empty($value)) {
  5755. $value = dol_print_date($value, 'day');
  5756. } else {
  5757. $value = '';
  5758. }
  5759. } elseif ($type == 'datetime' || $type == 'timestamp') {
  5760. if (!empty($value)) {
  5761. $value = dol_print_date($value, 'dayhour');
  5762. } else {
  5763. $value = '';
  5764. }
  5765. } elseif ($type == 'duration') {
  5766. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5767. if (!is_null($value) && $value !== '') {
  5768. $value = convertSecondToTime($value, 'allhourmin');
  5769. }
  5770. } elseif ($type == 'double' || $type == 'real') {
  5771. if (!is_null($value) && $value !== '') {
  5772. $value = price($value);
  5773. }
  5774. } elseif ($type == 'boolean') {
  5775. $checked = '';
  5776. if (!empty($value)) {
  5777. $checked = ' checked ';
  5778. }
  5779. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  5780. } elseif ($type == 'mail') {
  5781. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  5782. } elseif ($type == 'url') {
  5783. $value = dol_print_url($value, '_blank', 32, 1);
  5784. } elseif ($type == 'phone') {
  5785. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
  5786. } elseif ($type == 'price')
  5787. {
  5788. if (!is_null($value) && $value !== '') {
  5789. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  5790. }
  5791. } elseif ($type == 'select') {
  5792. $value = $param['options'][$value];
  5793. } elseif ($type == 'sellist') {
  5794. $param_list = array_keys($param['options']);
  5795. $InfoFieldList = explode(":", $param_list[0]);
  5796. $selectkey = "rowid";
  5797. $keyList = 'rowid';
  5798. if (count($InfoFieldList) >= 3)
  5799. {
  5800. $selectkey = $InfoFieldList[2];
  5801. $keyList = $InfoFieldList[2].' as rowid';
  5802. }
  5803. $fields_label = explode('|', $InfoFieldList[1]);
  5804. if (is_array($fields_label)) {
  5805. $keyList .= ', ';
  5806. $keyList .= implode(', ', $fields_label);
  5807. }
  5808. $sql = 'SELECT '.$keyList;
  5809. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  5810. if (strpos($InfoFieldList[4], 'extra') !== false)
  5811. {
  5812. $sql .= ' as main';
  5813. }
  5814. if ($selectkey == 'rowid' && empty($value)) {
  5815. $sql .= " WHERE ".$selectkey."=0";
  5816. } elseif ($selectkey == 'rowid') {
  5817. $sql .= " WHERE ".$selectkey."=".$this->db->escape($value);
  5818. } else {
  5819. $sql .= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  5820. }
  5821. //$sql.= ' AND entity = '.$conf->entity;
  5822. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  5823. $resql = $this->db->query($sql);
  5824. if ($resql)
  5825. {
  5826. $value = ''; // value was used, so now we reste it to use it to build final output
  5827. $obj = $this->db->fetch_object($resql);
  5828. // Several field into label (eq table:code|libelle:rowid)
  5829. $fields_label = explode('|', $InfoFieldList[1]);
  5830. if (is_array($fields_label) && count($fields_label) > 1)
  5831. {
  5832. foreach ($fields_label as $field_toshow)
  5833. {
  5834. $translabel = '';
  5835. if (!empty($obj->$field_toshow)) {
  5836. $translabel = $langs->trans($obj->$field_toshow);
  5837. }
  5838. if ($translabel != $field_toshow) {
  5839. $value .= dol_trunc($translabel, 18).' ';
  5840. } else {
  5841. $value .= $obj->$field_toshow.' ';
  5842. }
  5843. }
  5844. } else {
  5845. $translabel = '';
  5846. if (!empty($obj->{$InfoFieldList[1]})) {
  5847. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  5848. }
  5849. if ($translabel != $obj->{$InfoFieldList[1]}) {
  5850. $value = dol_trunc($translabel, 18);
  5851. } else {
  5852. $value = $obj->{$InfoFieldList[1]};
  5853. }
  5854. }
  5855. } else dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  5856. } elseif ($type == 'radio') {
  5857. $value = $param['options'][$value];
  5858. } elseif ($type == 'checkbox') {
  5859. $value_arr = explode(',', $value);
  5860. $value = '';
  5861. if (is_array($value_arr) && count($value_arr) > 0)
  5862. {
  5863. $toprint = array();
  5864. foreach ($value_arr as $keyval=>$valueval) {
  5865. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  5866. }
  5867. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  5868. }
  5869. } elseif ($type == 'chkbxlst') {
  5870. $value_arr = explode(',', $value);
  5871. $param_list = array_keys($param['options']);
  5872. $InfoFieldList = explode(":", $param_list[0]);
  5873. $selectkey = "rowid";
  5874. $keyList = 'rowid';
  5875. if (count($InfoFieldList) >= 3) {
  5876. $selectkey = $InfoFieldList[2];
  5877. $keyList = $InfoFieldList[2].' as rowid';
  5878. }
  5879. $fields_label = explode('|', $InfoFieldList[1]);
  5880. if (is_array($fields_label)) {
  5881. $keyList .= ', ';
  5882. $keyList .= implode(', ', $fields_label);
  5883. }
  5884. $sql = 'SELECT '.$keyList;
  5885. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  5886. if (strpos($InfoFieldList[4], 'extra') !== false) {
  5887. $sql .= ' as main';
  5888. }
  5889. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  5890. // $sql.= ' AND entity = '.$conf->entity;
  5891. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  5892. $resql = $this->db->query($sql);
  5893. if ($resql) {
  5894. $value = ''; // value was used, so now we reste it to use it to build final output
  5895. $toprint = array();
  5896. while ($obj = $this->db->fetch_object($resql)) {
  5897. // Several field into label (eq table:code|libelle:rowid)
  5898. $fields_label = explode('|', $InfoFieldList[1]);
  5899. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  5900. if (is_array($fields_label) && count($fields_label) > 1) {
  5901. foreach ($fields_label as $field_toshow) {
  5902. $translabel = '';
  5903. if (!empty($obj->$field_toshow)) {
  5904. $translabel = $langs->trans($obj->$field_toshow);
  5905. }
  5906. if ($translabel != $field_toshow) {
  5907. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  5908. } else {
  5909. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->$field_toshow.'</li>';
  5910. }
  5911. }
  5912. } else {
  5913. $translabel = '';
  5914. if (!empty($obj->{$InfoFieldList[1]})) {
  5915. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  5916. }
  5917. if ($translabel != $obj->{$InfoFieldList[1]}) {
  5918. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  5919. } else {
  5920. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->{$InfoFieldList[1]}.'</li>';
  5921. }
  5922. }
  5923. }
  5924. }
  5925. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  5926. } else {
  5927. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  5928. }
  5929. } elseif ($type == 'link') {
  5930. $out = '';
  5931. // only if something to display (perf)
  5932. if ($value)
  5933. {
  5934. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  5935. $InfoFieldList = explode(":", $param_list[0]);
  5936. $classname = $InfoFieldList[0];
  5937. $classpath = $InfoFieldList[1];
  5938. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  5939. if (!empty($classpath))
  5940. {
  5941. dol_include_once($InfoFieldList[1]);
  5942. if ($classname && class_exists($classname))
  5943. {
  5944. $object = new $classname($this->db);
  5945. $object->fetch($value);
  5946. $value = $object->getNomUrl($getnomurlparam);
  5947. }
  5948. } else {
  5949. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5950. return 'Error bad setup of extrafield';
  5951. }
  5952. } else $value = '';
  5953. } elseif (preg_match('/^(text|html)/', $type)) {
  5954. $value = dol_htmlentitiesbr($value);
  5955. } elseif ($type == 'password') {
  5956. $value = preg_replace('/./i', '*', $value);
  5957. } elseif ($type == 'array') {
  5958. $value = implode('<br>', $value);
  5959. }
  5960. //print $type.'-'.$size.'-'.$value;
  5961. $out = $value;
  5962. return $out;
  5963. }
  5964. /**
  5965. * Function to show lines of extrafields with output datas.
  5966. * This function is responsible to output the <tr> and <td> according to correct number of columns received into $params['colspan']
  5967. *
  5968. * @param Extrafields $extrafields Extrafield Object
  5969. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  5970. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  5971. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  5972. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  5973. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  5974. * @return string
  5975. */
  5976. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0)
  5977. {
  5978. global $db, $conf, $langs, $action, $form, $hookmanager;
  5979. if (!is_object($form)) $form = new Form($db);
  5980. $out = '';
  5981. $parameters = array();
  5982. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  5983. if (empty($reshook))
  5984. {
  5985. if (is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0)
  5986. {
  5987. $out .= "\n";
  5988. $out .= '<!-- showOptionals --> ';
  5989. $out .= "\n";
  5990. $extrafields_collapse_num = '';
  5991. $e = 0;
  5992. foreach ($extrafields->attributes[$this->table_element]['label'] as $key=>$label)
  5993. {
  5994. // Show only the key field in params
  5995. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) continue;
  5996. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  5997. $enabled = 1;
  5998. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key]))
  5999. {
  6000. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1);
  6001. }
  6002. if (empty($enabled)) continue;
  6003. $visibility = 1;
  6004. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key]))
  6005. {
  6006. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1);
  6007. }
  6008. $perms = 1;
  6009. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key]))
  6010. {
  6011. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1);
  6012. }
  6013. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  6014. elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  6015. elseif ($mode == 'view' && empty($visibility)) continue;
  6016. if (empty($perms)) continue;
  6017. // Load language if required
  6018. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  6019. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  6020. }
  6021. $colspan = '';
  6022. if (is_array($params) && count($params) > 0) {
  6023. if (array_key_exists('cols', $params)) {
  6024. $colspan = $params['cols'];
  6025. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  6026. $reg = array();
  6027. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  6028. $colspan = $reg[1];
  6029. } else {
  6030. $colspan = $params['colspan'];
  6031. }
  6032. }
  6033. }
  6034. switch ($mode) {
  6035. case "view":
  6036. $value = $this->array_options["options_".$key.$keysuffix]; // Value may be clean or formated later
  6037. break;
  6038. case "create":
  6039. case "edit":
  6040. // We get the value of property found with GETPOST so it takes into account:
  6041. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  6042. $check = 'alphanohtml';
  6043. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  6044. $check = 'restricthtml';
  6045. }
  6046. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  6047. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  6048. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix))
  6049. {
  6050. if (is_array($getposttemp)) {
  6051. // $getposttemp is an array but following code expects a comma separated string
  6052. $value = implode(",", $getposttemp);
  6053. } else {
  6054. $value = $getposttemp;
  6055. }
  6056. } else {
  6057. $value = $this->array_options["options_".$key]; // No GET, no POST, no default value, so we take value of object.
  6058. }
  6059. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  6060. break;
  6061. }
  6062. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate')
  6063. {
  6064. $extrafields_collapse_num = '';
  6065. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  6066. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  6067. $extrafield_param_list = array_keys($extrafield_param['options']);
  6068. if (count($extrafield_param_list) > 0) {
  6069. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  6070. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  6071. $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  6072. }
  6073. }
  6074. }
  6075. $out .= $extrafields->showSeparator($key, $this, ($colspan + 1));
  6076. } else {
  6077. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  6078. $csstyle = '';
  6079. if (is_array($params) && count($params) > 0) {
  6080. if (array_key_exists('class', $params)) {
  6081. $class .= $params['class'].' ';
  6082. }
  6083. if (array_key_exists('style', $params)) {
  6084. $csstyle = $params['style'];
  6085. }
  6086. }
  6087. // add html5 elements
  6088. $domData = ' data-element="extrafield"';
  6089. $domData .= ' data-targetelement="'.$this->element.'"';
  6090. $domData .= ' data-targetid="'.$this->id.'"';
  6091. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  6092. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) { $colspan = '0'; }
  6093. if ($action == 'selectlines') { $colspan++; }
  6094. // Convert date into timestamp format (value in memory must be a timestamp)
  6095. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime')))
  6096. {
  6097. $datenotinstring = $this->array_options['options_'.$key];
  6098. if (!is_numeric($this->array_options['options_'.$key])) // For backward compatibility
  6099. {
  6100. $datenotinstring = $this->db->jdate($datenotinstring);
  6101. }
  6102. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) ? dol_mktime(GETPOST($keyprefix.'options_'.$key.$keysuffix."hour", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."min", 'int', 3), 0, GETPOST($keyprefix.'options_'.$key.$keysuffix."month", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."day", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."year", 'int', 3)) : $datenotinstring;
  6103. }
  6104. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  6105. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double')))
  6106. {
  6107. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? price2num($value) : $this->array_options['options_'.$key];
  6108. }
  6109. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  6110. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int')))
  6111. {
  6112. if ($action == 'create') $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  6113. }
  6114. $labeltoshow = $langs->trans($label);
  6115. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  6116. $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="'.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.'" '.$domData.' >';
  6117. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && $action == 'view') {
  6118. $out .= '<td></td>';
  6119. }
  6120. $out .= '<td class="wordbreak';
  6121. //$out .= "titlefield";
  6122. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  6123. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  6124. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  6125. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  6126. $out .= '">';
  6127. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  6128. else $out .= $labeltoshow;
  6129. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= '&nbsp;<font color="red">*</font>';
  6130. } else {
  6131. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= ' fieldrequired';
  6132. $out .= '">';
  6133. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  6134. else $out .= $labeltoshow;
  6135. }
  6136. $out .= '</td>';
  6137. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  6138. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').'class="'.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  6139. switch ($mode) {
  6140. case "view":
  6141. $out .= $extrafields->showOutputField($key, $value);
  6142. break;
  6143. case "create":
  6144. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  6145. break;
  6146. case "edit":
  6147. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  6148. break;
  6149. }
  6150. $out .= '</td>';
  6151. /*for($ii = 0; $ii < ($colspan - 1); $ii++)
  6152. {
  6153. $out .='<td class="'.$this->element.'_extras_'.$key.'"></td>';
  6154. }*/
  6155. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) $out .= '</tr>';
  6156. else $out .= '</tr>';
  6157. $e++;
  6158. }
  6159. }
  6160. $out .= "\n";
  6161. // Add code to manage list depending on others
  6162. if (!empty($conf->use_javascript_ajax)) {
  6163. $out .= '
  6164. <script>
  6165. jQuery(document).ready(function() {
  6166. function showOptions(child_list, parent_list, orig_select)
  6167. {
  6168. var val = $("select[name=\""+parent_list+"\"]").val();
  6169. var parentVal = parent_list + ":" + val;
  6170. if(val > 0) {
  6171. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  6172. $("select[name=\""+child_list+"\"] option[parent]").remove();
  6173. $("select[name=\""+child_list+"\"]").append(options);
  6174. } else {
  6175. var options = orig_select.find("option[parent]").clone();
  6176. $("select[name=\""+child_list+"\"] option[parent]").remove();
  6177. $("select[name=\""+child_list+"\"]").append(options);
  6178. }
  6179. }
  6180. function setListDependencies() {
  6181. jQuery("select option[parent]").parent().each(function() {
  6182. var orig_select = {};
  6183. var child_list = $(this).attr("name");
  6184. orig_select[child_list] = $(this).clone();
  6185. var parent = $(this).find("option[parent]:first").attr("parent");
  6186. var infos = parent.split(":");
  6187. var parent_list = infos[0];
  6188. $("select[name=\""+parent_list+"\"]").change(function() {
  6189. showOptions(child_list, parent_list, orig_select[child_list]);
  6190. });
  6191. });
  6192. }
  6193. setListDependencies();
  6194. });
  6195. </script>'."\n";
  6196. }
  6197. $out .= '<!-- /showOptionals --> '."\n";
  6198. }
  6199. }
  6200. $out .= $hookmanager->resPrint;
  6201. return $out;
  6202. }
  6203. /**
  6204. * Returns the rights used for this class
  6205. * @return stdClass
  6206. */
  6207. public function getRights()
  6208. {
  6209. global $user;
  6210. $element = $this->element;
  6211. if ($element == 'facturerec') $element = 'facture';
  6212. return $user->rights->{$element};
  6213. }
  6214. /**
  6215. * Function used to replace a thirdparty id with another one.
  6216. * This function is meant to be called from replaceThirdparty with the appropiate tables
  6217. * Column name fk_soc MUST be used to identify thirdparties
  6218. *
  6219. * @param DoliDB $db Database handler
  6220. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  6221. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  6222. * @param string[] $tables Tables that need to be changed
  6223. * @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)
  6224. * @return bool True if success, False if error
  6225. */
  6226. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  6227. {
  6228. foreach ($tables as $table)
  6229. {
  6230. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.$dest_id.' WHERE fk_soc = '.$origin_id;
  6231. if (!$db->query($sql))
  6232. {
  6233. if ($ignoreerrors) return true; // TODO Not enough. If there is A-B on kept thirdarty and B-C on old one, we must get A-B-C after merge. Not A-B.
  6234. //$this->errors = $db->lasterror();
  6235. return false;
  6236. }
  6237. }
  6238. return true;
  6239. }
  6240. /**
  6241. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  6242. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  6243. * else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  6244. * else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  6245. * else set min buy price as buy price
  6246. *
  6247. * @param float $unitPrice Product unit price
  6248. * @param float $discountPercent Line discount percent
  6249. * @param int $fk_product Product id
  6250. * @return float <0 if KO, buyprice if OK
  6251. */
  6252. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  6253. {
  6254. global $conf;
  6255. $buyPrice = 0;
  6256. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) // In most cases, test here is false
  6257. {
  6258. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  6259. } else {
  6260. // Get cost price for margin calculation
  6261. if (!empty($fk_product))
  6262. {
  6263. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice')
  6264. {
  6265. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6266. $product = new Product($this->db);
  6267. $result = $product->fetch($fk_product);
  6268. if ($result <= 0)
  6269. {
  6270. $this->errors[] = 'ErrorProductIdDoesNotExists';
  6271. return -1;
  6272. }
  6273. if ($product->cost_price > 0)
  6274. {
  6275. $buyPrice = $product->cost_price;
  6276. } elseif ($product->pmp > 0)
  6277. {
  6278. $buyPrice = $product->pmp;
  6279. }
  6280. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp')
  6281. {
  6282. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6283. $product = new Product($this->db);
  6284. $result = $product->fetch($fk_product);
  6285. if ($result <= 0)
  6286. {
  6287. $this->errors[] = 'ErrorProductIdDoesNotExists';
  6288. return -1;
  6289. }
  6290. if ($product->pmp > 0)
  6291. {
  6292. $buyPrice = $product->pmp;
  6293. }
  6294. }
  6295. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice')))
  6296. {
  6297. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  6298. $productFournisseur = new ProductFournisseur($this->db);
  6299. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0)
  6300. {
  6301. $buyPrice = $productFournisseur->fourn_unitprice;
  6302. } elseif ($result < 0)
  6303. {
  6304. $this->errors[] = $productFournisseur->error;
  6305. return -2;
  6306. }
  6307. }
  6308. }
  6309. }
  6310. return $buyPrice;
  6311. }
  6312. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6313. /**
  6314. * Show photos of an object (nbmax maximum), into several columns
  6315. *
  6316. * @param string $modulepart 'product', 'ticket', ...
  6317. * @param string $sdir Directory to scan (full absolute path)
  6318. * @param int $size 0=original size, 1='small' use thumbnail if possible
  6319. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  6320. * @param int $nbbyrow Number of image per line or -1 to use div. Used only if size=1.
  6321. * @param int $showfilename 1=Show filename
  6322. * @param int $showaction 1=Show icon with action links (resize, delete)
  6323. * @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.
  6324. * @param int $maxWidth Max width of original image when size='small'
  6325. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  6326. * @param int $notitle Do not add title tag on image
  6327. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  6328. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  6329. */
  6330. 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)
  6331. {
  6332. // phpcs:enable
  6333. global $conf, $user, $langs;
  6334. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  6335. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  6336. $sortfield = 'position_name';
  6337. $sortorder = 'asc';
  6338. $dir = $sdir.'/';
  6339. $pdir = '/';
  6340. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/';
  6341. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/';
  6342. // For backward compatibility
  6343. if ($modulepart == 'product' && !empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
  6344. {
  6345. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  6346. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  6347. }
  6348. // Defined relative dir to DOL_DATA_ROOT
  6349. $relativedir = '';
  6350. if ($dir)
  6351. {
  6352. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  6353. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  6354. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  6355. }
  6356. $dirthumb = $dir.'thumbs/';
  6357. $pdirthumb = $pdir.'thumbs/';
  6358. $return = '<!-- Photo -->'."\n";
  6359. $nbphoto = 0;
  6360. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  6361. /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
  6362. {
  6363. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  6364. $filearray=array_merge($filearray, $filearrayold);
  6365. }*/
  6366. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  6367. if (count($filearray))
  6368. {
  6369. if ($sortfield && $sortorder)
  6370. {
  6371. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  6372. }
  6373. foreach ($filearray as $key => $val)
  6374. {
  6375. $photo = '';
  6376. $file = $val['name'];
  6377. //if (! utf8_check($file)) $file=utf8_encode($file); // To be sure file is stored in UTF8 in memory
  6378. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  6379. if (image_format_supported($file) >= 0)
  6380. {
  6381. $nbphoto++;
  6382. $photo = $file;
  6383. $viewfilename = $file;
  6384. if ($size == 1 || $size == 'small') { // Format vignette
  6385. // Find name of thumb file
  6386. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  6387. if (!dol_is_file($dirthumb.$photo_vignette)) $photo_vignette = '';
  6388. // Get filesize of original file
  6389. $imgarray = dol_getImageSize($dir.$photo);
  6390. if ($nbbyrow > 0)
  6391. {
  6392. if ($nbphoto == 1) $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  6393. if ($nbphoto % $nbbyrow == 1) $return .= '<tr class="center valignmiddle" style="border: 1px">';
  6394. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
  6395. } elseif ($nbbyrow < 0) $return .= '<div class="inline-block">';
  6396. $return .= "\n";
  6397. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  6398. if (empty($nolink))
  6399. {
  6400. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  6401. if ($urladvanced) $return .= '<a href="'.$urladvanced.'">';
  6402. else $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
  6403. }
  6404. // Show image (width height=$maxHeight)
  6405. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  6406. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  6407. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  6408. if ($notitle) $alt = '';
  6409. if ($usesharelink)
  6410. {
  6411. if ($val['share'])
  6412. {
  6413. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
  6414. {
  6415. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  6416. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  6417. } else {
  6418. $return .= '<!-- Show original file -->';
  6419. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  6420. }
  6421. } else {
  6422. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  6423. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  6424. }
  6425. } else {
  6426. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
  6427. {
  6428. $return .= '<!-- Show thumb -->';
  6429. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdirthumb.$photo_vignette).'" title="'.dol_escape_htmltag($alt).'">';
  6430. } else {
  6431. $return .= '<!-- Show original file -->';
  6432. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" title="'.dol_escape_htmltag($alt).'">';
  6433. }
  6434. }
  6435. if (empty($nolink)) $return .= '</a>';
  6436. $return .= "\n";
  6437. if ($showfilename) $return .= '<br>'.$viewfilename;
  6438. if ($showaction)
  6439. {
  6440. $return .= '<br>';
  6441. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  6442. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight))
  6443. {
  6444. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=addthumb&amp;file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'), 'refresh').'&nbsp;&nbsp;</a>';
  6445. }
  6446. // Special cas for product
  6447. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
  6448. {
  6449. // Link to resize
  6450. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&amp;file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  6451. // Link to delete
  6452. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;token='.newToken().'&amp;file='.urlencode($pdir.$viewfilename).'">';
  6453. $return .= img_delete().'</a>';
  6454. }
  6455. }
  6456. $return .= "\n";
  6457. if ($nbbyrow > 0)
  6458. {
  6459. $return .= '</td>';
  6460. if (($nbphoto % $nbbyrow) == 0) $return .= '</tr>';
  6461. } elseif ($nbbyrow < 0) $return .= '</div>';
  6462. }
  6463. if (empty($size)) { // Format origine
  6464. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  6465. if ($showfilename) $return .= '<br>'.$viewfilename;
  6466. if ($showaction)
  6467. {
  6468. // Special case for product
  6469. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
  6470. {
  6471. // Link to resize
  6472. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&amp;file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  6473. // Link to delete
  6474. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;token='.newToken().'&amp;file='.urlencode($pdir.$viewfilename).'">';
  6475. $return .= img_delete().'</a>';
  6476. }
  6477. }
  6478. }
  6479. // On continue ou on arrete de boucler ?
  6480. if ($nbmax && $nbphoto >= $nbmax) break;
  6481. }
  6482. }
  6483. if ($size == 1 || $size == 'small')
  6484. {
  6485. if ($nbbyrow > 0)
  6486. {
  6487. // Ferme tableau
  6488. while ($nbphoto % $nbbyrow)
  6489. {
  6490. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  6491. $nbphoto++;
  6492. }
  6493. if ($nbphoto) $return .= '</table>';
  6494. }
  6495. }
  6496. }
  6497. $this->nbphoto = $nbphoto;
  6498. return $return;
  6499. }
  6500. /**
  6501. * Function test if type is array
  6502. *
  6503. * @param array $info content informations of field
  6504. * @return bool true if array
  6505. */
  6506. protected function isArray($info)
  6507. {
  6508. if (is_array($info)) {
  6509. if (isset($info['type']) && $info['type'] == 'array') return true;
  6510. else return false;
  6511. }
  6512. return false;
  6513. }
  6514. /**
  6515. * Function test if type is date
  6516. *
  6517. * @param array $info content informations of field
  6518. * @return bool true if date
  6519. */
  6520. public function isDate($info)
  6521. {
  6522. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) return true;
  6523. return false;
  6524. }
  6525. /**
  6526. * Function test if type is duration
  6527. *
  6528. * @param array $info content informations of field
  6529. * @return bool true if field of type duration
  6530. */
  6531. public function isDuration($info)
  6532. {
  6533. if (is_array($info)) {
  6534. if (isset($info['type']) && ($info['type'] == 'duration')) return true;
  6535. else return false;
  6536. } else return false;
  6537. }
  6538. /**
  6539. * Function test if type is integer
  6540. *
  6541. * @param array $info content informations of field
  6542. * @return bool true if integer
  6543. */
  6544. public function isInt($info)
  6545. {
  6546. if (is_array($info)) {
  6547. if (isset($info['type']) && ($info['type'] == 'int' || preg_match('/^integer/i', $info['type']))) return true;
  6548. else return false;
  6549. } else return false;
  6550. }
  6551. /**
  6552. * Function test if type is float
  6553. *
  6554. * @param array $info content informations of field
  6555. * @return bool true if float
  6556. */
  6557. public function isFloat($info)
  6558. {
  6559. if (is_array($info)) {
  6560. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) return true;
  6561. else return false;
  6562. }
  6563. return false;
  6564. }
  6565. /**
  6566. * Function test if type is text
  6567. *
  6568. * @param array $info content informations of field
  6569. * @return bool true if type text
  6570. */
  6571. public function isText($info)
  6572. {
  6573. if (is_array($info)) {
  6574. if (isset($info['type']) && $info['type'] == 'text') return true;
  6575. else return false;
  6576. }
  6577. return false;
  6578. }
  6579. /**
  6580. * Function test if field can be null
  6581. *
  6582. * @param array $info content informations of field
  6583. * @return bool true if it can be null
  6584. */
  6585. protected function canBeNull($info)
  6586. {
  6587. if (is_array($info)) {
  6588. if (isset($info['notnull']) && $info['notnull'] != '1') return true;
  6589. else return false;
  6590. }
  6591. return true;
  6592. }
  6593. /**
  6594. * Function test if field is forced to null if zero or empty
  6595. *
  6596. * @param array $info content informations of field
  6597. * @return bool true if forced to null
  6598. */
  6599. protected function isForcedToNullIfZero($info)
  6600. {
  6601. if (is_array($info)) {
  6602. if (isset($info['notnull']) && $info['notnull'] == '-1') return true;
  6603. else return false;
  6604. }
  6605. return false;
  6606. }
  6607. /**
  6608. * Function test if is indexed
  6609. *
  6610. * @param array $info content informations of field
  6611. * @return bool
  6612. */
  6613. protected function isIndex($info)
  6614. {
  6615. if (is_array($info)) {
  6616. if (isset($info['index']) && $info['index'] == true) return true;
  6617. else return false;
  6618. }
  6619. return false;
  6620. }
  6621. /**
  6622. * Function to prepare a part of the query for insert.
  6623. * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
  6624. * $this->${field} should be a clean value. The page can run
  6625. *
  6626. * @return array
  6627. */
  6628. protected function setSaveQuery()
  6629. {
  6630. global $conf;
  6631. $queryarray = array();
  6632. foreach ($this->fields as $field => $info) // Loop on definition of fields
  6633. {
  6634. // Depending on field type ('datetime', ...)
  6635. if ($this->isDate($info))
  6636. {
  6637. if (empty($this->{$field})) {
  6638. $queryarray[$field] = null;
  6639. } else {
  6640. $queryarray[$field] = $this->db->idate($this->{$field});
  6641. }
  6642. } elseif ($this->isArray($info))
  6643. {
  6644. if (!empty($this->{$field})) {
  6645. if (!is_array($this->{$field})) {
  6646. $this->{$field} = array($this->{$field});
  6647. }
  6648. $queryarray[$field] = serialize($this->{$field});
  6649. } else {
  6650. $queryarray[$field] = null;
  6651. }
  6652. } elseif ($this->isDuration($info))
  6653. {
  6654. // $this->{$field} may be null, '', 0, '0', 123, '123'
  6655. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  6656. if (!isset($this->{$field})) {
  6657. $queryarray[$field] = 0;
  6658. } else {
  6659. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  6660. }
  6661. }
  6662. else $queryarray[$field] = null;
  6663. } elseif ($this->isInt($info) || $this->isFloat($info))
  6664. {
  6665. if ($field == 'entity' && is_null($this->{$field})) $queryarray[$field] = $conf->entity;
  6666. else {
  6667. // $this->{$field} may be null, '', 0, '0', 123, '123'
  6668. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  6669. if (!isset($this->{$field})) {
  6670. $queryarray[$field] = 0;
  6671. } elseif ($this->isInt($info)) {
  6672. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  6673. } elseif ($this->isFloat($info)) {
  6674. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  6675. }
  6676. } else $queryarray[$field] = null;
  6677. }
  6678. } else {
  6679. $queryarray[$field] = $this->{$field};
  6680. }
  6681. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) unset($queryarray[$field]);
  6682. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) $queryarray[$field] = null; // May force 0 to null
  6683. }
  6684. return $queryarray;
  6685. }
  6686. /**
  6687. * Function to load data from a SQL pointer into properties of current object $this
  6688. *
  6689. * @param stdClass $obj Contain data of object from database
  6690. * @return void
  6691. */
  6692. public function setVarsFromFetchObj(&$obj)
  6693. {
  6694. foreach ($this->fields as $field => $info)
  6695. {
  6696. if ($this->isDate($info)) {
  6697. if (empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0;
  6698. else $this->{$field} = strtotime($obj->{$field});
  6699. } elseif ($this->isArray($info))
  6700. {
  6701. if (!empty($obj->{$field})) {
  6702. $this->{$field} = @unserialize($obj->{$field});
  6703. // Hack for data not in UTF8
  6704. if ($this->{$field } === false) @unserialize(utf8_decode($obj->{$field}));
  6705. } else {
  6706. $this->{$field} = array();
  6707. }
  6708. } elseif ($this->isInt($info)) {
  6709. if ($field == 'rowid') $this->id = (int) $obj->{$field};
  6710. else {
  6711. if ($this->isForcedToNullIfZero($info)) {
  6712. if (empty($obj->{$field})) $this->{$field} = null;
  6713. else $this->{$field} = (double) $obj->{$field};
  6714. } else {
  6715. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  6716. $this->{$field} = (int) $obj->{$field};
  6717. } else {
  6718. $this->{$field} = null;
  6719. }
  6720. }
  6721. }
  6722. } elseif ($this->isFloat($info)) {
  6723. if ($this->isForcedToNullIfZero($info)) {
  6724. if (empty($obj->{$field})) $this->{$field} = null;
  6725. else $this->{$field} = (double) $obj->{$field};
  6726. } else {
  6727. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  6728. $this->{$field} = (double) $obj->{$field};
  6729. } else {
  6730. $this->{$field} = null;
  6731. }
  6732. }
  6733. } else {
  6734. $this->{$field} = $obj->{$field};
  6735. }
  6736. }
  6737. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  6738. if (!isset($this->fields['ref']) && isset($this->id)) $this->ref = $this->id;
  6739. }
  6740. /**
  6741. * Function to concat keys of fields
  6742. *
  6743. * @return string
  6744. */
  6745. protected function getFieldList()
  6746. {
  6747. $keys = array_keys($this->fields);
  6748. return implode(',', $keys);
  6749. }
  6750. /**
  6751. * Add quote to field value if necessary
  6752. *
  6753. * @param string|int $value Value to protect
  6754. * @param array $fieldsentry Properties of field
  6755. * @return string
  6756. */
  6757. protected function quote($value, $fieldsentry)
  6758. {
  6759. if (is_null($value)) return 'NULL';
  6760. elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) return $this->db->escape("$value");
  6761. elseif ($fieldsentry['type'] == 'boolean') {
  6762. if ($value) return 'true';
  6763. else return 'false';
  6764. }
  6765. else return "'".$this->db->escape($value)."'";
  6766. }
  6767. /**
  6768. * Create object into database
  6769. *
  6770. * @param User $user User that creates
  6771. * @param bool $notrigger false=launch triggers after, true=disable triggers
  6772. * @return int <0 if KO, Id of created object if OK
  6773. */
  6774. public function createCommon(User $user, $notrigger = false)
  6775. {
  6776. global $langs;
  6777. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  6778. $error = 0;
  6779. $now = dol_now();
  6780. $fieldvalues = $this->setSaveQuery();
  6781. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) $fieldvalues['date_creation'] = $this->db->idate($now);
  6782. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) $fieldvalues['fk_user_creat'] = $user->id;
  6783. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  6784. if (array_key_exists('ref', $fieldvalues)) $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  6785. $keys = array();
  6786. $values = array(); // Array to store string forged for SQL syntax
  6787. foreach ($fieldvalues as $k => $v) {
  6788. $keys[$k] = $k;
  6789. $value = $this->fields[$k];
  6790. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  6791. }
  6792. // Clean and check mandatory
  6793. foreach ($keys as $key)
  6794. {
  6795. // If field is an implicit foreign key field
  6796. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key] = '';
  6797. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key] = '';
  6798. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default']))
  6799. {
  6800. $error++;
  6801. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  6802. }
  6803. // If value is null and there is a default value for field
  6804. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default']))
  6805. {
  6806. $values[$key] = $this->fields[$key]['default'];
  6807. }
  6808. // If field is an implicit foreign key field
  6809. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  6810. if (isset($this->fields[$key]['default'])) $values[$key] = $this->fields[$key]['default'];
  6811. else $values[$key] = 'null';
  6812. }
  6813. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) $values[$key] = 'null';
  6814. }
  6815. if ($error) return -1;
  6816. $this->db->begin();
  6817. if (!$error)
  6818. {
  6819. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
  6820. $sql .= ' ('.implode(", ", $keys).')';
  6821. $sql .= ' VALUES ('.implode(", ", $values).')';
  6822. $res = $this->db->query($sql);
  6823. if ($res === false) {
  6824. $error++;
  6825. $this->errors[] = $this->db->lasterror();
  6826. }
  6827. }
  6828. if (!$error)
  6829. {
  6830. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
  6831. }
  6832. // If we have a field ref with a default value of (PROV)
  6833. if (!$error)
  6834. {
  6835. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && !is_null($this->fields['ref']['default']) && $this->fields['ref']['default'] == '(PROV)')
  6836. {
  6837. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ref = '(PROV".$this->id.")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".$this->id;
  6838. $resqlupdate = $this->db->query($sql);
  6839. if ($resqlupdate === false)
  6840. {
  6841. $error++;
  6842. $this->errors[] = $this->db->lasterror();
  6843. } else {
  6844. $this->ref = '(PROV'.$this->id.')';
  6845. }
  6846. }
  6847. }
  6848. // Create extrafields
  6849. if (!$error)
  6850. {
  6851. $result = $this->insertExtraFields();
  6852. if ($result < 0) $error++;
  6853. }
  6854. // Create lines
  6855. if (!empty($this->table_element_line) && !empty($this->fk_element))
  6856. {
  6857. $num = (is_array($this->lines) ? count($this->lines) : 0);
  6858. for ($i = 0; $i < $num; $i++)
  6859. {
  6860. $line = $this->lines[$i];
  6861. $keyforparent = $this->fk_element;
  6862. $line->$keyforparent = $this->id;
  6863. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  6864. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  6865. if (!is_object($line)) $line = (object) $line;
  6866. $result = $line->create($user, 1);
  6867. if ($result < 0)
  6868. {
  6869. $this->error = $this->db->lasterror();
  6870. $this->db->rollback();
  6871. return -1;
  6872. }
  6873. }
  6874. }
  6875. // Triggers
  6876. if (!$error && !$notrigger)
  6877. {
  6878. // Call triggers
  6879. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  6880. if ($result < 0) { $error++; }
  6881. // End call triggers
  6882. }
  6883. // Commit or rollback
  6884. if ($error) {
  6885. $this->db->rollback();
  6886. return -1;
  6887. } else {
  6888. $this->db->commit();
  6889. return $this->id;
  6890. }
  6891. }
  6892. /**
  6893. * Load object in memory from the database
  6894. *
  6895. * @param int $id Id object
  6896. * @param string $ref Ref
  6897. * @param string $morewhere More SQL filters (' AND ...')
  6898. * @return int <0 if KO, 0 if not found, >0 if OK
  6899. */
  6900. public function fetchCommon($id, $ref = null, $morewhere = '')
  6901. {
  6902. if (empty($id) && empty($ref) && empty($morewhere)) return -1;
  6903. $fieldlist = $this->getFieldList();
  6904. if (empty($fieldlist)) return 0;
  6905. $sql = 'SELECT '.$fieldlist;
  6906. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
  6907. if (!empty($id)) $sql .= ' WHERE rowid = '.$id;
  6908. elseif (!empty($ref)) $sql .= " WHERE ref = ".$this->quote($ref, $this->fields['ref']);
  6909. else $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  6910. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' AND entity IN ('.getEntity($this->table_element).')';
  6911. if ($morewhere) $sql .= $morewhere;
  6912. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  6913. $res = $this->db->query($sql);
  6914. if ($res)
  6915. {
  6916. $obj = $this->db->fetch_object($res);
  6917. if ($obj)
  6918. {
  6919. $this->setVarsFromFetchObj($obj);
  6920. // Retrieve all extrafield
  6921. // fetch optionals attributes and labels
  6922. $this->fetch_optionals();
  6923. return $this->id;
  6924. } else {
  6925. return 0;
  6926. }
  6927. } else {
  6928. $this->error = $this->db->lasterror();
  6929. $this->errors[] = $this->error;
  6930. return -1;
  6931. }
  6932. }
  6933. /**
  6934. * Load object in memory from the database
  6935. *
  6936. * @param string $morewhere More SQL filters (' AND ...')
  6937. * @return int <0 if KO, 0 if not found, >0 if OK
  6938. */
  6939. public function fetchLinesCommon($morewhere = '')
  6940. {
  6941. $objectlineclassname = get_class($this).'Line';
  6942. if (!class_exists($objectlineclassname))
  6943. {
  6944. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  6945. return -1;
  6946. }
  6947. $objectline = new $objectlineclassname($this->db);
  6948. $sql = 'SELECT '.$objectline->getFieldList();
  6949. $sql .= ' FROM '.MAIN_DB_PREFIX.$objectline->table_element;
  6950. $sql .= ' WHERE fk_'.$this->element.' = '.$this->id;
  6951. if ($morewhere) $sql .= $morewhere;
  6952. if (isset($objectline->fields['position'])) {
  6953. $sql .= $this->db->order('position', 'ASC');
  6954. }
  6955. $resql = $this->db->query($sql);
  6956. if ($resql)
  6957. {
  6958. $num_rows = $this->db->num_rows($resql);
  6959. $i = 0;
  6960. while ($i < $num_rows)
  6961. {
  6962. $obj = $this->db->fetch_object($resql);
  6963. if ($obj)
  6964. {
  6965. $newline = new $objectlineclassname($this->db);
  6966. $newline->setVarsFromFetchObj($obj);
  6967. $this->lines[] = $newline;
  6968. }
  6969. $i++;
  6970. }
  6971. return 1;
  6972. } else {
  6973. $this->error = $this->db->lasterror();
  6974. $this->errors[] = $this->error;
  6975. return -1;
  6976. }
  6977. }
  6978. /**
  6979. * Update object into database
  6980. *
  6981. * @param User $user User that modifies
  6982. * @param bool $notrigger false=launch triggers after, true=disable triggers
  6983. * @return int <0 if KO, >0 if OK
  6984. */
  6985. public function updateCommon(User $user, $notrigger = false)
  6986. {
  6987. global $conf, $langs;
  6988. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  6989. $error = 0;
  6990. $now = dol_now();
  6991. $fieldvalues = $this->setSaveQuery();
  6992. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) $fieldvalues['date_modification'] = $this->db->idate($now);
  6993. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) $fieldvalues['fk_user_modif'] = $user->id;
  6994. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  6995. if (array_key_exists('ref', $fieldvalues)) $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  6996. // Add quotes and escape on fields with type string
  6997. $keys = array();
  6998. $values = array();
  6999. $tmp = array();
  7000. foreach ($fieldvalues as $k => $v) {
  7001. $keys[$k] = $k;
  7002. $value = $this->fields[$k];
  7003. $values[$k] = $this->quote($v, $value);
  7004. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  7005. }
  7006. // Clean and check mandatory fields
  7007. foreach ($keys as $key)
  7008. {
  7009. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key] = ''; // This is an implicit foreign key field
  7010. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key] = ''; // This is an explicit foreign key field
  7011. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  7012. /*
  7013. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  7014. {
  7015. $error++;
  7016. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  7017. }*/
  7018. }
  7019. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.$this->id;
  7020. $this->db->begin();
  7021. if (!$error)
  7022. {
  7023. $res = $this->db->query($sql);
  7024. if ($res === false)
  7025. {
  7026. $error++;
  7027. $this->errors[] = $this->db->lasterror();
  7028. }
  7029. }
  7030. // Update extrafield
  7031. if (!$error)
  7032. {
  7033. $result = $this->insertExtraFields();
  7034. if ($result < 0)
  7035. {
  7036. $error++;
  7037. }
  7038. }
  7039. // Triggers
  7040. if (!$error && !$notrigger)
  7041. {
  7042. // Call triggers
  7043. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  7044. if ($result < 0) { $error++; } //Do also here what you must do to rollback action if trigger fail
  7045. // End call triggers
  7046. }
  7047. // Commit or rollback
  7048. if ($error) {
  7049. $this->db->rollback();
  7050. return -1;
  7051. } else {
  7052. $this->db->commit();
  7053. return $this->id;
  7054. }
  7055. }
  7056. /**
  7057. * Delete object in database
  7058. *
  7059. * @param User $user User that deletes
  7060. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7061. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  7062. * @return int <=0 if KO, >0 if OK
  7063. */
  7064. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  7065. {
  7066. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  7067. $error = 0;
  7068. $this->db->begin();
  7069. if ($forcechilddeletion) // Force also delete of childtables that should lock deletion in standard case when option force is off
  7070. {
  7071. foreach ($this->childtables as $table)
  7072. {
  7073. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
  7074. $resql = $this->db->query($sql);
  7075. if (!$resql)
  7076. {
  7077. $this->error = $this->db->lasterror();
  7078. $this->errors[] = $this->error;
  7079. $this->db->rollback();
  7080. return -1;
  7081. }
  7082. }
  7083. } elseif (!empty($this->fk_element) && !empty($this->childtables)) // If object has childs linked with a foreign key field, we check all child tables.
  7084. {
  7085. $objectisused = $this->isObjectUsed($this->id);
  7086. if (!empty($objectisused))
  7087. {
  7088. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  7089. $this->error = 'ErrorRecordHasChildren';
  7090. $this->errors[] = $this->error;
  7091. $this->db->rollback();
  7092. return 0;
  7093. }
  7094. }
  7095. // Delete cascade first
  7096. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  7097. foreach ($this->childtablesoncascade as $table)
  7098. {
  7099. $deleteFromObject = explode(':', $table);
  7100. if (count($deleteFromObject) >= 2) {
  7101. $className = str_replace('@', '', $deleteFromObject[0]);
  7102. $filePath = $deleteFromObject[1];
  7103. $columnName = $deleteFromObject[2];
  7104. if (dol_include_once($filePath)) {
  7105. $childObject = new $className($this->db);
  7106. if (method_exists($childObject, 'deleteByParentField')) {
  7107. $result = $childObject->deleteByParentField($this->id, $columnName);
  7108. if ($result < 0) {
  7109. $error++;
  7110. $this->errors[] = $childObject->error;
  7111. break;
  7112. }
  7113. } else {
  7114. $error++;
  7115. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  7116. break;
  7117. }
  7118. } else {
  7119. $error++;
  7120. $this->errors[] = 'Cannot include child class file '.$filePath;
  7121. break;
  7122. }
  7123. } else {
  7124. // Delete record in child table
  7125. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
  7126. $resql = $this->db->query($sql);
  7127. if (!$resql) {
  7128. $error++;
  7129. $this->error = $this->db->lasterror();
  7130. $this->errors[] = $this->error;
  7131. break;
  7132. }
  7133. }
  7134. }
  7135. }
  7136. if (!$error) {
  7137. if (!$notrigger) {
  7138. // Call triggers
  7139. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  7140. if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail
  7141. // End call triggers
  7142. }
  7143. }
  7144. // Delete llx_ecm_files
  7145. if (!$error) {
  7146. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  7147. if (!$res) {
  7148. $error++;
  7149. }
  7150. }
  7151. if (!$error && !empty($this->isextrafieldmanaged))
  7152. {
  7153. $result = $this->deleteExtraFields();
  7154. if ($result < 0) { $error++; }
  7155. }
  7156. if (!$error)
  7157. {
  7158. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id;
  7159. $res = $this->db->query($sql);
  7160. if ($res === false) {
  7161. $error++;
  7162. $this->errors[] = $this->db->lasterror();
  7163. }
  7164. }
  7165. // Commit or rollback
  7166. if ($error) {
  7167. $this->db->rollback();
  7168. return -1;
  7169. } else {
  7170. $this->db->commit();
  7171. return 1;
  7172. }
  7173. }
  7174. /**
  7175. * Delete all child object from a parent ID
  7176. *
  7177. * @param int $parentId Parent Id
  7178. * @param string $parentField Name of Foreign key parent column
  7179. * @return int <0 if KO, >0 if OK
  7180. * @throws Exception
  7181. */
  7182. public function deleteByParentField($parentId = 0, $parentField = '')
  7183. {
  7184. global $user;
  7185. $error = 0;
  7186. $deleted = 0;
  7187. if (!empty($parentId) && !empty($parentField)) {
  7188. $this->db->begin();
  7189. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$this->table_element;
  7190. $sql .= ' WHERE '.$parentField.' = '.(int) $parentId;
  7191. $resql = $this->db->query($sql);
  7192. if (!$resql) {
  7193. $this->errors[] = $this->db->lasterror();
  7194. $error++;
  7195. } else {
  7196. while ($obj = $this->db->fetch_object($resql)) {
  7197. $result = $this->fetch($obj->rowid);
  7198. if ($result < 0) {
  7199. $error++;
  7200. $this->errors[] = $this->error;
  7201. } else {
  7202. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  7203. $result = $this->delete();
  7204. } else {
  7205. $result = $this->delete($user);
  7206. }
  7207. if ($result < 0) {
  7208. $error++;
  7209. $this->errors[] = $this->error;
  7210. } else {
  7211. $deleted++;
  7212. }
  7213. }
  7214. }
  7215. }
  7216. if (empty($error)) {
  7217. $this->db->commit();
  7218. return $deleted;
  7219. } else {
  7220. $this->error = implode(', ', $this->errors);
  7221. $this->db->rollback();
  7222. return $error * -1;
  7223. }
  7224. }
  7225. return $deleted;
  7226. }
  7227. /**
  7228. * Delete a line of object in database
  7229. *
  7230. * @param User $user User that delete
  7231. * @param int $idline Id of line to delete
  7232. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7233. * @return int >0 if OK, <0 if KO
  7234. */
  7235. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  7236. {
  7237. global $conf;
  7238. $error = 0;
  7239. $tmpforobjectclass = get_class($this);
  7240. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  7241. // Call trigger
  7242. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  7243. if ($result < 0) return -1;
  7244. // End call triggers
  7245. $this->db->begin();
  7246. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  7247. $sql .= " WHERE rowid=".$idline;
  7248. dol_syslog(get_class($this)."::deleteLineCommon", LOG_DEBUG);
  7249. $resql = $this->db->query($sql);
  7250. if (!$resql)
  7251. {
  7252. $this->error = "Error ".$this->db->lasterror();
  7253. $error++;
  7254. }
  7255. if (empty($error)) {
  7256. // Remove extrafields
  7257. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  7258. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  7259. $tmpobjectline->id = $idline;
  7260. $result = $tmpobjectline->deleteExtraFields();
  7261. if ($result < 0)
  7262. {
  7263. $error++;
  7264. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  7265. }
  7266. }
  7267. }
  7268. if (empty($error)) {
  7269. $this->db->commit();
  7270. return 1;
  7271. } else {
  7272. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  7273. $this->db->rollback();
  7274. return -1;
  7275. }
  7276. }
  7277. /**
  7278. * Set to a status
  7279. *
  7280. * @param User $user Object user that modify
  7281. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  7282. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  7283. * @param string $triggercode Trigger code to use
  7284. * @return int <0 if KO, >0 if OK
  7285. */
  7286. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  7287. {
  7288. $error = 0;
  7289. $this->db->begin();
  7290. $statusfield = 'status';
  7291. if ($this->element == 'don' || $this->element == 'donation') $statusfield = 'fk_statut';
  7292. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  7293. $sql .= " SET ".$statusfield." = ".((int) $status);
  7294. $sql .= " WHERE rowid = ".$this->id;
  7295. if ($this->db->query($sql))
  7296. {
  7297. if (!$error)
  7298. {
  7299. $this->oldcopy = clone $this;
  7300. }
  7301. if (!$error && !$notrigger) {
  7302. // Call trigger
  7303. $result = $this->call_trigger($triggercode, $user);
  7304. if ($result < 0) $error++;
  7305. }
  7306. if (!$error) {
  7307. $this->status = $status;
  7308. $this->db->commit();
  7309. return 1;
  7310. } else {
  7311. $this->db->rollback();
  7312. return -1;
  7313. }
  7314. } else {
  7315. $this->error = $this->db->error();
  7316. $this->db->rollback();
  7317. return -1;
  7318. }
  7319. }
  7320. /**
  7321. * Initialise object with example values
  7322. * Id must be 0 if object instance is a specimen
  7323. *
  7324. * @return int
  7325. */
  7326. public function initAsSpecimenCommon()
  7327. {
  7328. global $user;
  7329. $this->id = 0;
  7330. $this->specimen = 1;
  7331. $fields = array(
  7332. 'label' => 'This is label',
  7333. 'ref' => 'ABCD1234',
  7334. 'description' => 'This is a description',
  7335. 'qty' => 123.12,
  7336. 'note_public' => 'Public note',
  7337. 'note_private' => 'Private note',
  7338. 'date_creation' => (dol_now() - 3600 * 48),
  7339. 'date_modification' => (dol_now() - 3600 * 24),
  7340. 'fk_user_creat' => $user->id,
  7341. 'fk_user_modif' => $user->id,
  7342. 'date' => dol_now(),
  7343. );
  7344. foreach ($fields as $key => $value) {
  7345. if (array_key_exists($key, $this->fields)) $this->{$key} = $value;
  7346. }
  7347. return 1;
  7348. }
  7349. /* Part for comments */
  7350. /**
  7351. * Load comments linked with current task
  7352. * @return boolean 1 if ok
  7353. */
  7354. public function fetchComments()
  7355. {
  7356. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  7357. $comment = new Comment($this->db);
  7358. $result = $comment->fetchAllFor($this->element, $this->id);
  7359. if ($result < 0) {
  7360. $this->errors = array_merge($this->errors, $comment->errors);
  7361. return -1;
  7362. } else {
  7363. $this->comments = $comment->comments;
  7364. }
  7365. return count($this->comments);
  7366. }
  7367. /**
  7368. * Return nb comments already posted
  7369. *
  7370. * @return int
  7371. */
  7372. public function getNbComments()
  7373. {
  7374. return count($this->comments);
  7375. }
  7376. /**
  7377. * Trim object parameters
  7378. *
  7379. * @param string[] $parameters array of parameters to trim
  7380. * @return void
  7381. */
  7382. public function trimParameters($parameters)
  7383. {
  7384. if (!is_array($parameters)) return;
  7385. foreach ($parameters as $parameter) {
  7386. if (isset($this->$parameter)) {
  7387. $this->$parameter = trim($this->$parameter);
  7388. }
  7389. }
  7390. }
  7391. /* Part for categories/tags */
  7392. /**
  7393. * Sets object to given categories.
  7394. *
  7395. * Deletes object from existing categories not supplied.
  7396. * Adds it to non existing supplied categories.
  7397. * Existing categories are left untouch.
  7398. *
  7399. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  7400. * @return int Array of category objects or < 0 if KO
  7401. */
  7402. public function getCategoriesCommon($type_categ)
  7403. {
  7404. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  7405. // Get current categories
  7406. $c = new Categorie($this->db);
  7407. $existing = $c->containing($this->id, $type_categ, 'id');
  7408. return $existing;
  7409. }
  7410. /**
  7411. * Sets object to given categories.
  7412. *
  7413. * Deletes object from existing categories not supplied.
  7414. * Adds it to non existing supplied categories.
  7415. * Existing categories are left untouch.
  7416. *
  7417. * @param int[]|int $categories Category ID or array of Categories IDs
  7418. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  7419. * @return int <0 if KO, >0 if OK
  7420. */
  7421. public function setCategoriesCommon($categories, $type_categ)
  7422. {
  7423. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  7424. // Handle single category
  7425. if (!is_array($categories)) {
  7426. $categories = array($categories);
  7427. }
  7428. // Get current categories
  7429. $c = new Categorie($this->db);
  7430. $existing = $c->containing($this->id, $type_categ, 'id');
  7431. // Diff
  7432. if (is_array($existing)) {
  7433. $to_del = array_diff($existing, $categories);
  7434. $to_add = array_diff($categories, $existing);
  7435. } else {
  7436. $to_del = array(); // Nothing to delete
  7437. $to_add = $categories;
  7438. }
  7439. $error = 0;
  7440. // Process
  7441. foreach ($to_del as $del) {
  7442. if ($c->fetch($del) > 0) {
  7443. $c->del_type($this, $type_categ);
  7444. }
  7445. }
  7446. foreach ($to_add as $add) {
  7447. if ($c->fetch($add) > 0)
  7448. {
  7449. $result = $c->add_type($this, $type_categ);
  7450. if ($result < 0)
  7451. {
  7452. $error++;
  7453. $this->error = $c->error;
  7454. $this->errors = $c->errors;
  7455. break;
  7456. }
  7457. }
  7458. }
  7459. return $error ? -1 : 1;
  7460. }
  7461. /**
  7462. * Copy related categories to another object
  7463. *
  7464. * @param int $fromId Id object source
  7465. * @param int $toId Id object cible
  7466. * @param string $type Type of category ('product', ...)
  7467. * @return int < 0 if error, > 0 if ok
  7468. */
  7469. public function cloneCategories($fromId, $toId, $type = '')
  7470. {
  7471. $this->db->begin();
  7472. if (empty($type)) $type = $this->table_element;
  7473. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  7474. $categorystatic = new Categorie($this->db);
  7475. $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  7476. $sql .= " SELECT fk_categorie, $toId FROM ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  7477. $sql .= " WHERE fk_product = ".((int) $fromId);
  7478. if (!$this->db->query($sql))
  7479. {
  7480. $this->error = $this->db->lasterror();
  7481. $this->db->rollback();
  7482. return -1;
  7483. }
  7484. $this->db->commit();
  7485. return 1;
  7486. }
  7487. /**
  7488. * Delete related files of object in database
  7489. *
  7490. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  7491. * @return bool True if OK, False if KO
  7492. */
  7493. public function deleteEcmFiles($mode = 0)
  7494. {
  7495. global $conf;
  7496. $this->db->begin();
  7497. // Delete in database with mode 0
  7498. if ($mode == 0) {
  7499. switch ($this->element) {
  7500. case 'propal':
  7501. $element = 'propale';
  7502. break;
  7503. case 'product':
  7504. $element = 'produit';
  7505. break;
  7506. case 'order_supplier':
  7507. $element = 'fournisseur/commande';
  7508. break;
  7509. case 'invoice_supplier':
  7510. $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  7511. break;
  7512. case 'shipping':
  7513. $element = 'expedition/sending';
  7514. break;
  7515. default:
  7516. $element = $this->element;
  7517. }
  7518. // Delete ecm_files extrafields
  7519. $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files_extrafields WHERE fk_object IN (";
  7520. $sql .= " SELECT rowid FROM ".MAIN_DB_PREFIX."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  7521. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".$conf->entity; // No need of getEntity here
  7522. $sql .= ")";
  7523. if (!$this->db->query($sql)) {
  7524. $this->error = $this->db->lasterror();
  7525. $this->db->rollback();
  7526. return false;
  7527. }
  7528. // Delete ecm_files
  7529. $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files";
  7530. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  7531. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".$conf->entity; // No need of getEntity here
  7532. if (!$this->db->query($sql)) {
  7533. $this->error = $this->db->lasterror();
  7534. $this->db->rollback();
  7535. return false;
  7536. }
  7537. }
  7538. // Delete in database with mode 1
  7539. if ($mode == 1) {
  7540. $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files_extrafields";
  7541. $sql .= " WHERE fk_object IN (SELECT rowid FROM ".MAIN_DB_PREFIX."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? '' : '@'.$this->module))."' AND src_object_id = ".$this->id.")";
  7542. $resql = $this->db->query($sql);
  7543. if (!$resql) {
  7544. $this->error = $this->db->lasterror();
  7545. $this->db->rollback();
  7546. return false;
  7547. }
  7548. $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files";
  7549. $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? '' : '@'.$this->module))."' AND src_object_id = ".$this->id;
  7550. $resql = $this->db->query($sql);
  7551. if (!$resql) {
  7552. $this->error = $this->db->lasterror();
  7553. $this->db->rollback();
  7554. return false;
  7555. }
  7556. }
  7557. $this->db->commit();
  7558. return true;
  7559. }
  7560. }