commonobject.class.php 290 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359
  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-2019 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 string Error string
  51. * @see $errors
  52. */
  53. public $error;
  54. /**
  55. * @var string[] Array of error strings
  56. */
  57. public $errors = array();
  58. /**
  59. * @var string ID to identify managed object
  60. */
  61. public $element;
  62. /**
  63. * @var string Name of table without prefix where object is stored
  64. */
  65. public $table_element;
  66. /**
  67. * @var string Name of subtable line
  68. */
  69. public $table_element_line = '';
  70. /**
  71. * @var string Key value used to track if data is coming from import wizard
  72. */
  73. public $import_key;
  74. /**
  75. * @var mixed Contains data to manage extrafields
  76. */
  77. public $array_options = array();
  78. /**
  79. * @var mixed Array to store alternative languages values of object
  80. */
  81. public $array_languages = null; // Value is array() when load already tried
  82. /**
  83. * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked
  84. */
  85. public $linkedObjectsIds;
  86. /**
  87. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  88. */
  89. public $linkedObjects;
  90. /**
  91. * @var Object To store a cloned copy of object before to edit it and keep track of old properties
  92. */
  93. public $oldcopy;
  94. /**
  95. * @var string Column name of the ref field.
  96. */
  97. protected $table_ref_field = '';
  98. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  99. /**
  100. * @var array<string,mixed> Can be used to pass information when only object is provided to method
  101. */
  102. public $context = array();
  103. /**
  104. * @var string Contains canvas name if record is an alternative canvas record
  105. */
  106. public $canvas;
  107. /**
  108. * @var Project The related project
  109. * @see fetch_projet()
  110. */
  111. public $project;
  112. /**
  113. * @var int The related project ID
  114. * @see setProject(), project
  115. */
  116. public $fk_project;
  117. /**
  118. * @deprecated
  119. * @see project
  120. */
  121. public $projet;
  122. /**
  123. * @var Contact a related contact
  124. * @see fetch_contact()
  125. */
  126. public $contact;
  127. /**
  128. * @var int The related contact ID
  129. * @see fetch_contact()
  130. */
  131. public $contact_id;
  132. /**
  133. * @var Societe A related thirdparty
  134. * @see fetch_thirdparty()
  135. */
  136. public $thirdparty;
  137. /**
  138. * @var User A related user
  139. * @see fetch_user()
  140. */
  141. public $user;
  142. /**
  143. * @var string The type of originating object ('commande', 'facture', ...)
  144. * @see fetch_origin()
  145. */
  146. public $origin;
  147. /**
  148. * @var int The id of originating object
  149. * @see fetch_origin()
  150. */
  151. public $origin_id;
  152. /**
  153. * @var string The object's reference
  154. */
  155. public $ref;
  156. /**
  157. * @var string The object's previous reference
  158. */
  159. public $ref_previous;
  160. /**
  161. * @var string The object's next reference
  162. */
  163. public $ref_next;
  164. /**
  165. * @var string An external reference for the object
  166. */
  167. public $ref_ext;
  168. /**
  169. * @var int The object's status
  170. * @see setStatut()
  171. */
  172. public $statut;
  173. /**
  174. * @var string
  175. * @see getFullAddress()
  176. */
  177. public $country;
  178. /**
  179. * @var int
  180. * @see getFullAddress(), country
  181. */
  182. public $country_id;
  183. /**
  184. * @var string
  185. * @see getFullAddress(), isInEEC(), country
  186. */
  187. public $country_code;
  188. /**
  189. * @var string
  190. * @see getFullAddress()
  191. */
  192. public $state;
  193. /**
  194. * @var int
  195. * @see getFullAddress(), state
  196. */
  197. public $state_id;
  198. /**
  199. * @var string
  200. * @see getFullAddress(), $state
  201. */
  202. public $state_code;
  203. /**
  204. * @var int
  205. * @see getFullAddress(), $region_code, $region
  206. */
  207. public $region_id;
  208. /**
  209. * @var string
  210. * @see getFullAddress(), $region_id, $region
  211. */
  212. public $region_code;
  213. /**
  214. * @var string
  215. * @see getFullAddress(), $region_id, $region_code
  216. */
  217. public $region;
  218. /**
  219. * @var int
  220. * @see fetch_barcode()
  221. */
  222. public $barcode_type;
  223. /**
  224. * @var string
  225. * @see fetch_barcode(), barcode_type
  226. */
  227. public $barcode_type_code;
  228. /**
  229. * @var string
  230. * @see fetch_barcode(), barcode_type
  231. */
  232. public $barcode_type_label;
  233. /**
  234. * @var string
  235. * @see fetch_barcode(), barcode_type
  236. */
  237. public $barcode_type_coder;
  238. /**
  239. * @var int Payment method ID (cheque, cash, ...)
  240. * @see setPaymentMethods()
  241. */
  242. public $mode_reglement_id;
  243. /**
  244. * @var int Payment terms ID
  245. * @see setPaymentTerms()
  246. */
  247. public $cond_reglement_id;
  248. /**
  249. * @var int Payment terms ID
  250. * @deprecated Kept for compatibility
  251. * @see cond_reglement_id;
  252. */
  253. public $cond_reglement;
  254. /**
  255. * @var int Delivery address ID
  256. * @see setDeliveryAddress()
  257. * @deprecated
  258. */
  259. public $fk_delivery_address;
  260. /**
  261. * @var int Shipping method ID
  262. * @see setShippingMethod()
  263. */
  264. public $shipping_method_id;
  265. /**
  266. * @var string
  267. * @see SetDocModel()
  268. */
  269. public $model_pdf;
  270. /**
  271. * @var string
  272. * Contains relative path of last generated main file
  273. */
  274. public $last_main_doc;
  275. /**
  276. * @var int Bank account ID
  277. * @see SetBankAccount()
  278. */
  279. public $fk_account;
  280. /**
  281. * @var string Public note
  282. * @see update_note()
  283. */
  284. public $note_public;
  285. /**
  286. * @var string Private note
  287. * @see update_note()
  288. */
  289. public $note_private;
  290. /**
  291. * @deprecated
  292. * @see $note_private
  293. */
  294. public $note;
  295. /**
  296. * @var float Total amount before taxes
  297. * @see update_price()
  298. */
  299. public $total_ht;
  300. /**
  301. * @var float Total VAT amount
  302. * @see update_price()
  303. */
  304. public $total_tva;
  305. /**
  306. * @var float Total local tax 1 amount
  307. * @see update_price()
  308. */
  309. public $total_localtax1;
  310. /**
  311. * @var float Total local tax 2 amount
  312. * @see update_price()
  313. */
  314. public $total_localtax2;
  315. /**
  316. * @var float Total amount with taxes
  317. * @see update_price()
  318. */
  319. public $total_ttc;
  320. /**
  321. * @var CommonObjectLine[]
  322. */
  323. public $lines;
  324. /**
  325. * @var mixed Contains comments
  326. * @see fetchComments()
  327. */
  328. public $comments = array();
  329. /**
  330. * @var string The name
  331. */
  332. public $name;
  333. /**
  334. * @var string The lastname
  335. */
  336. public $lastname;
  337. /**
  338. * @var string The firstname
  339. */
  340. public $firstname;
  341. /**
  342. * @var string The civility code, not an integer
  343. */
  344. public $civility_id;
  345. // Dates
  346. /**
  347. * @var integer|string date_creation
  348. */
  349. public $date_creation;
  350. /**
  351. * @var integer|string $date_validation;
  352. */
  353. public $date_validation; // Date validation
  354. /**
  355. * @var integer|string $date_modification;
  356. */
  357. public $date_modification; // Date last change (tms field)
  358. public $next_prev_filter;
  359. /**
  360. * @var array List of child tables. To test if we can delete object.
  361. */
  362. protected $childtables = array();
  363. /**
  364. * @var array List of child tables. To know object to delete on cascade.
  365. * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
  366. * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
  367. */
  368. protected $childtablesoncascade = array();
  369. // No constructor as it is an abstract class
  370. /**
  371. * Check an object id/ref exists
  372. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  373. *
  374. * @param string $element String of element ('product', 'facture', ...)
  375. * @param int $id Id of object
  376. * @param string $ref Ref of object to check
  377. * @param string $ref_ext Ref ext of object to check
  378. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  379. */
  380. public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
  381. {
  382. global $db, $conf;
  383. $sql = "SELECT rowid, ref, ref_ext";
  384. $sql .= " FROM ".MAIN_DB_PREFIX.$element;
  385. $sql .= " WHERE entity IN (".getEntity($element).")";
  386. if ($id > 0) $sql .= " AND rowid = ".$db->escape($id);
  387. elseif ($ref) $sql .= " AND ref = '".$db->escape($ref)."'";
  388. elseif ($ref_ext) $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
  389. else {
  390. $error = 'ErrorWrongParameters';
  391. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  392. return -1;
  393. }
  394. if ($ref || $ref_ext) $sql .= " AND entity = ".$conf->entity;
  395. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  396. $resql = $db->query($sql);
  397. if ($resql)
  398. {
  399. $num = $db->num_rows($resql);
  400. if ($num > 0) return 1;
  401. else return 0;
  402. }
  403. return -1;
  404. }
  405. /**
  406. * Method to output saved errors
  407. *
  408. * @return string String with errors
  409. */
  410. public function errorsToString()
  411. {
  412. return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
  413. }
  414. /**
  415. * Return customer ref for screen output.
  416. *
  417. * @param string $objref Customer ref
  418. * @return string Customer ref formated
  419. */
  420. public function getFormatedCustomerRef($objref)
  421. {
  422. global $hookmanager;
  423. $parameters = array('objref'=>$objref);
  424. $action = '';
  425. $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  426. if ($reshook > 0)
  427. {
  428. return $hookmanager->resArray['objref'];
  429. }
  430. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  431. }
  432. /**
  433. * Return supplier ref for screen output.
  434. *
  435. * @param string $objref Supplier ref
  436. * @return string Supplier ref formated
  437. */
  438. public function getFormatedSupplierRef($objref)
  439. {
  440. global $hookmanager;
  441. $parameters = array('objref'=>$objref);
  442. $action = '';
  443. $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  444. if ($reshook > 0)
  445. {
  446. return $hookmanager->resArray['objref'];
  447. }
  448. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  449. }
  450. /**
  451. * Return full name (civility+' '+name+' '+lastname)
  452. *
  453. * @param Translate $langs Language object for translation of civility (used only if option is 1)
  454. * @param int $option 0=No option, 1=Add civility
  455. * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname, 3=Firstname if defined else lastname
  456. * @param int $maxlen Maximum length
  457. * @return string String with full name
  458. */
  459. public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
  460. {
  461. //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
  462. $lastname = $this->lastname;
  463. $firstname = $this->firstname;
  464. 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 : '')))));
  465. $ret = '';
  466. if ($option && $this->civility_code)
  467. {
  468. if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
  469. else $ret .= $this->civility_code.' ';
  470. }
  471. $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
  472. return dol_trunc($ret, $maxlen);
  473. }
  474. /**
  475. * Return clicable link of object (with eventually picto)
  476. *
  477. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  478. * @return string HTML Code for Kanban thumb.
  479. */
  480. public function getKanbanView($option = '')
  481. {
  482. $return = '<div class="box-flex-item">';
  483. $return .= '<div class="info-box info-box-sm">';
  484. $return .= '<span class="info-box-icon bg-infobox-action">';
  485. $return .= '<i class="fa fa-dol-action"></i>'; // Can be image
  486. $return .= '</span>';
  487. $return .= '<div class="info-box-content">';
  488. $return .= '<span class="info-box-title">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  489. $return .= '</div>';
  490. $return .= '</div>';
  491. $return .= '</div>';
  492. return $return;
  493. }
  494. /**
  495. * Return full address of contact
  496. *
  497. * @param int $withcountry 1=Add country into address string
  498. * @param string $sep Separator to use to build string
  499. * @param int $withregion 1=Add region into address string
  500. * @param string $extralangcode User extralanguages as value
  501. * @return string Full address string
  502. */
  503. public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
  504. {
  505. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country)))
  506. {
  507. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  508. $tmparray = getCountry($this->country_id, 'all');
  509. $this->country_code = $tmparray['code'];
  510. $this->country = $tmparray['label'];
  511. }
  512. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code)))
  513. {
  514. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  515. $tmparray = getState($this->state_id, 'all', 0, 1);
  516. $this->state_code = $tmparray['code'];
  517. $this->state = $tmparray['label'];
  518. $this->region_code = $tmparray['region_code'];
  519. $this->region = $tmparray['region'];
  520. }
  521. return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
  522. }
  523. /**
  524. * Return full address for banner
  525. *
  526. * @param string $htmlkey HTML id to make banner content unique
  527. * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member)
  528. * @return string Full address string
  529. */
  530. public function getBannerAddress($htmlkey, $object)
  531. {
  532. global $conf, $langs, $form, $extralanguages;
  533. $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
  534. $contactid = 0;
  535. $thirdpartyid = 0;
  536. $elementforaltlanguage = $this->element;
  537. if ($this->element == 'societe')
  538. {
  539. $thirdpartyid = $this->id;
  540. }
  541. if ($this->element == 'contact')
  542. {
  543. $contactid = $this->id;
  544. $thirdpartyid = $object->fk_soc;
  545. }
  546. if ($this->element == 'user')
  547. {
  548. $contactid = $this->contact_id;
  549. $thirdpartyid = $object->fk_soc;
  550. }
  551. $out = '';
  552. $outdone = 0;
  553. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT);
  554. if ($coords)
  555. {
  556. if (!empty($conf->use_javascript_ajax))
  557. {
  558. // Add picto with tooltip on map
  559. $namecoords = '';
  560. if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS))
  561. {
  562. $namecoords .= $object->name.'<br>';
  563. }
  564. $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
  565. // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
  566. $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
  567. $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
  568. $out .= '</a> ';
  569. }
  570. $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', '); $outdone++;
  571. $outdone++;
  572. // List of extra languages
  573. $arrayoflangcode = array();
  574. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  575. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  576. if (!is_object($extralanguages)) {
  577. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  578. $extralanguages = new ExtraLanguages($this->db);
  579. }
  580. $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
  581. if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town']))
  582. {
  583. $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
  584. $this->fetchValuesForExtraLanguages();
  585. if (!is_object($form)) $form = new Form($this->db);
  586. $htmltext = '';
  587. // If there is extra languages
  588. foreach ($arrayoflangcode as $extralangcode) {
  589. $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  590. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
  591. $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  592. }
  593. $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  594. }
  595. }
  596. }
  597. 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
  598. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state)
  599. {
  600. if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
  601. $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
  602. } else {
  603. $out .= ($outdone ? ' - ' : '').$this->state;
  604. }
  605. $outdone++;
  606. }
  607. 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>' : '');
  608. if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  609. $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro")); $outdone++;
  610. }
  611. if (!empty($this->phone_pro)) {
  612. $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro")); $outdone++;
  613. }
  614. if (!empty($this->phone_mobile)) {
  615. $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile")); $outdone++;
  616. }
  617. if (!empty($this->phone_perso)) {
  618. $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso")); $outdone++;
  619. }
  620. if (!empty($this->office_phone)) {
  621. $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro")); $outdone++;
  622. }
  623. if (!empty($this->user_mobile)) {
  624. $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile")); $outdone++;
  625. }
  626. if (!empty($this->fax)) {
  627. $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax")); $outdone++;
  628. }
  629. if (!empty($this->office_fax)) {
  630. $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax")); $outdone++;
  631. }
  632. if ($out) $out .= '<div style="clear: both;"></div>';
  633. $outdone = 0;
  634. if (!empty($this->email))
  635. {
  636. $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
  637. $outdone++;
  638. }
  639. if (!empty($this->url))
  640. {
  641. //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
  642. $out .= dol_print_url($this->url, '_blank', 0, 1);
  643. $outdone++;
  644. }
  645. if (!empty($conf->socialnetworks->enabled))
  646. {
  647. $outsocialnetwork = '';
  648. if (is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
  649. foreach ($this->socialnetworks as $key => $value) {
  650. $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key);
  651. $outdone++;
  652. }
  653. } else {
  654. if ($this->skype) $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
  655. $outdone++;
  656. if ($this->jabberid) $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
  657. $outdone++;
  658. if ($this->twitter) $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
  659. $outdone++;
  660. if ($this->facebook) $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
  661. $outdone++;
  662. if ($this->linkedin) $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
  663. $outdone++;
  664. }
  665. if ($outsocialnetwork) {
  666. $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
  667. }
  668. }
  669. if ($out) return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
  670. else return '';
  671. }
  672. /**
  673. * Return the link of last main doc file for direct public download.
  674. *
  675. * @param string $modulepart Module related to document
  676. * @param int $initsharekey Init the share key if it was not yet defined
  677. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  678. * @return string Link or empty string if there is no download link
  679. */
  680. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  681. {
  682. global $user, $dolibarr_main_url_root;
  683. if (empty($this->last_main_doc))
  684. {
  685. return ''; // No way to known which document name to use
  686. }
  687. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  688. $ecmfile = new EcmFiles($this->db);
  689. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  690. if ($result < 0)
  691. {
  692. $this->error = $ecmfile->error;
  693. $this->errors = $ecmfile->errors;
  694. return -1;
  695. }
  696. if (empty($ecmfile->id))
  697. {
  698. // Add entry into index
  699. if ($initsharekey)
  700. {
  701. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  702. // TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first
  703. /*
  704. $ecmfile->filepath = $rel_dir;
  705. $ecmfile->filename = $filename;
  706. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  707. $ecmfile->fullpath_orig = '';
  708. $ecmfile->gen_or_uploaded = 'generated';
  709. $ecmfile->description = ''; // indexed content
  710. $ecmfile->keyword = ''; // keyword content
  711. $ecmfile->share = getRandomPassword(true);
  712. $result = $ecmfile->create($user);
  713. if ($result < 0)
  714. {
  715. $this->error = $ecmfile->error;
  716. $this->errors = $ecmfile->errors;
  717. }
  718. */
  719. } else return '';
  720. } elseif (empty($ecmfile->share))
  721. {
  722. // Add entry into index
  723. if ($initsharekey)
  724. {
  725. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  726. $ecmfile->share = getRandomPassword(true);
  727. $ecmfile->update($user);
  728. } else return '';
  729. }
  730. // Define $urlwithroot
  731. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  732. // This is to use external domain name found into config file
  733. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  734. //else
  735. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  736. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  737. $forcedownload = 0;
  738. $paramlink = '';
  739. //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  740. //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  741. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  742. if (!empty($ecmfile->share)) $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
  743. if ($forcedownload) $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  744. if ($relativelink)
  745. {
  746. $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
  747. } else {
  748. $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  749. }
  750. // Here $ecmfile->share is defined
  751. return $linktoreturn;
  752. }
  753. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  754. /**
  755. * Add a link between element $this->element and a contact
  756. *
  757. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  758. * @param int $type_contact Type of contact (code or id). Must be id or code found into table llx_c_type_contact. For example: SALESREPFOLL
  759. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  760. * @param int $notrigger Disable all triggers
  761. * @return int <0 if KO, >0 if OK
  762. */
  763. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  764. {
  765. // phpcs:enable
  766. global $user, $langs;
  767. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  768. // Check parameters
  769. if ($fk_socpeople <= 0)
  770. {
  771. $langs->load("errors");
  772. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  773. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  774. return -1;
  775. }
  776. if (!$type_contact)
  777. {
  778. $langs->load("errors");
  779. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  780. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  781. return -2;
  782. }
  783. $id_type_contact = 0;
  784. if (is_numeric($type_contact))
  785. {
  786. $id_type_contact = $type_contact;
  787. } else {
  788. // We look for id type_contact
  789. $sql = "SELECT tc.rowid";
  790. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  791. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  792. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  793. $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  794. //print $sql;
  795. $resql = $this->db->query($sql);
  796. if ($resql)
  797. {
  798. $obj = $this->db->fetch_object($resql);
  799. if ($obj) $id_type_contact = $obj->rowid;
  800. }
  801. }
  802. if ($id_type_contact == 0)
  803. {
  804. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  805. 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");
  806. return -3;
  807. }
  808. $datecreate = dol_now();
  809. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  810. $TListeContacts = $this->liste_contact(-1, $source);
  811. $already_added = false;
  812. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  813. foreach ($TListeContacts as $array_contact) {
  814. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  815. $already_added = true;
  816. break;
  817. }
  818. }
  819. }
  820. if (!$already_added) {
  821. $this->db->begin();
  822. // Insert into database
  823. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact";
  824. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  825. $sql .= " VALUES (".$this->id.", ".$fk_socpeople." , ";
  826. $sql .= "'".$this->db->idate($datecreate)."'";
  827. $sql .= ", 4, ".$id_type_contact;
  828. $sql .= ")";
  829. $resql = $this->db->query($sql);
  830. if ($resql)
  831. {
  832. if (!$notrigger)
  833. {
  834. $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  835. if ($result < 0)
  836. {
  837. $this->db->rollback();
  838. return -1;
  839. }
  840. }
  841. $this->db->commit();
  842. return 1;
  843. } else {
  844. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
  845. {
  846. $this->error = $this->db->errno();
  847. $this->db->rollback();
  848. echo 'err rollback';
  849. return -2;
  850. } else {
  851. $this->error = $this->db->error();
  852. $this->db->rollback();
  853. return -1;
  854. }
  855. }
  856. } else return 0;
  857. }
  858. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  859. /**
  860. * Copy contact from one element to current
  861. *
  862. * @param CommonObject $objFrom Source element
  863. * @param string $source Nature of contact ('internal' or 'external')
  864. * @return int >0 if OK, <0 if KO
  865. */
  866. public function copy_linked_contact($objFrom, $source = 'internal')
  867. {
  868. // phpcs:enable
  869. $contacts = $objFrom->liste_contact(-1, $source);
  870. foreach ($contacts as $contact)
  871. {
  872. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0)
  873. {
  874. $this->error = $this->db->lasterror();
  875. return -1;
  876. }
  877. }
  878. return 1;
  879. }
  880. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  881. /**
  882. * Update a link to contact line
  883. *
  884. * @param int $rowid Id of line contact-element
  885. * @param int $statut New status of link
  886. * @param int $type_contact_id Id of contact type (not modified if 0)
  887. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  888. * @return int <0 if KO, >= 0 if OK
  889. */
  890. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  891. {
  892. // phpcs:enable
  893. // Insert into database
  894. $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set";
  895. $sql .= " statut = ".$statut;
  896. if ($type_contact_id) $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
  897. if ($fk_socpeople) $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
  898. $sql .= " where rowid = ".$rowid;
  899. $resql = $this->db->query($sql);
  900. if ($resql)
  901. {
  902. return 0;
  903. } else {
  904. $this->error = $this->db->lasterror();
  905. return -1;
  906. }
  907. }
  908. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  909. /**
  910. * Delete a link to contact line
  911. *
  912. * @param int $rowid Id of contact link line to delete
  913. * @param int $notrigger Disable all triggers
  914. * @return int >0 if OK, <0 if KO
  915. */
  916. public function delete_contact($rowid, $notrigger = 0)
  917. {
  918. // phpcs:enable
  919. global $user;
  920. $this->db->begin();
  921. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  922. $sql .= " WHERE rowid =".$rowid;
  923. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  924. if ($this->db->query($sql))
  925. {
  926. if (!$notrigger)
  927. {
  928. $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  929. if ($result < 0) { $this->db->rollback(); return -1; }
  930. }
  931. $this->db->commit();
  932. return 1;
  933. } else {
  934. $this->error = $this->db->lasterror();
  935. $this->db->rollback();
  936. return -1;
  937. }
  938. }
  939. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  940. /**
  941. * Delete all links between an object $this and all its contacts
  942. *
  943. * @param string $source '' or 'internal' or 'external'
  944. * @param string $code Type of contact (code or id)
  945. * @return int >0 if OK, <0 if KO
  946. */
  947. public function delete_linked_contact($source = '', $code = '')
  948. {
  949. // phpcs:enable
  950. $temp = array();
  951. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  952. foreach ($typeContact as $key => $value)
  953. {
  954. array_push($temp, $key);
  955. }
  956. $listId = implode(",", $temp);
  957. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  958. $sql .= " WHERE element_id = ".$this->id;
  959. if ($listId)
  960. $sql .= " AND fk_c_type_contact IN (".$listId.")";
  961. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  962. if ($this->db->query($sql))
  963. {
  964. return 1;
  965. } else {
  966. $this->error = $this->db->lasterror();
  967. return -1;
  968. }
  969. }
  970. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  971. /**
  972. * Get array of all contacts for an object
  973. *
  974. * @param int $status Status of links to get (-1=all)
  975. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  976. * @param int $list 0:Return array contains all properties, 1:Return array contains just id
  977. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  978. * @return array|int Array of contacts, -1 if error
  979. */
  980. public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
  981. {
  982. // phpcs:enable
  983. global $langs;
  984. $tab = array();
  985. $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
  986. if ($source == 'internal') $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  987. if ($source == 'external' || $source == 'thirdparty') $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  988. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  989. $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
  990. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
  991. $sql .= ", ".MAIN_DB_PREFIX."element_contact ec";
  992. if ($source == 'internal') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
  993. if ($source == 'external' || $source == 'thirdparty') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
  994. $sql .= " WHERE ec.element_id =".$this->id;
  995. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  996. $sql .= " AND tc.element='".$this->db->escape($this->element)."'";
  997. if ($code) $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  998. if ($source == 'internal') $sql .= " AND tc.source = 'internal'";
  999. if ($source == 'external' || $source == 'thirdparty') $sql .= " AND tc.source = 'external'";
  1000. $sql .= " AND tc.active=1";
  1001. if ($status >= 0) $sql .= " AND ec.statut = ".$status;
  1002. $sql .= " ORDER BY t.lastname ASC";
  1003. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  1004. $resql = $this->db->query($sql);
  1005. if ($resql)
  1006. {
  1007. $num = $this->db->num_rows($resql);
  1008. $i = 0;
  1009. while ($i < $num)
  1010. {
  1011. $obj = $this->db->fetch_object($resql);
  1012. if (!$list)
  1013. {
  1014. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1015. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1016. $tab[$i] = array('source'=>$obj->source, 'socid'=>$obj->socid, 'id'=>$obj->id,
  1017. 'nom'=>$obj->lastname, // For backward compatibility
  1018. 'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'login'=>$obj->login, 'photo'=>$obj->photo, 'statuscontact'=>$obj->statuscontact,
  1019. 'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact);
  1020. } else {
  1021. $tab[$i] = $obj->id;
  1022. }
  1023. $i++;
  1024. }
  1025. return $tab;
  1026. } else {
  1027. $this->error = $this->db->lasterror();
  1028. dol_print_error($this->db);
  1029. return -1;
  1030. }
  1031. }
  1032. /**
  1033. * Update status of a contact linked to object
  1034. *
  1035. * @param int $rowid Id of link between object and contact
  1036. * @return int <0 if KO, >=0 if OK
  1037. */
  1038. public function swapContactStatus($rowid)
  1039. {
  1040. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1041. $sql .= " tc.code, tc.libelle";
  1042. //$sql.= ", s.fk_soc";
  1043. $sql .= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)";
  1044. //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as s ON ec.fk_socpeople=s.rowid"; // Si contact de type external, alors il est lie a une societe
  1045. $sql .= " WHERE ec.rowid =".$rowid;
  1046. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1047. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1048. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  1049. $resql = $this->db->query($sql);
  1050. if ($resql)
  1051. {
  1052. $obj = $this->db->fetch_object($resql);
  1053. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1054. $result = $this->update_contact($rowid, $newstatut);
  1055. $this->db->free($resql);
  1056. return $result;
  1057. } else {
  1058. $this->error = $this->db->error();
  1059. dol_print_error($this->db);
  1060. return -1;
  1061. }
  1062. }
  1063. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1064. /**
  1065. * Return array with list of possible values for type of contacts
  1066. *
  1067. * @param string $source 'internal', 'external' or 'all'
  1068. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  1069. * @param int $option 0=Return array id->label, 1=Return array code->label
  1070. * @param int $activeonly 0=all status of contact, 1=only the active
  1071. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1072. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1073. */
  1074. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1075. {
  1076. // phpcs:enable
  1077. global $langs;
  1078. if (empty($order)) $order = 'position';
  1079. if ($order == 'position') $order .= ',code';
  1080. $tab = array();
  1081. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  1082. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  1083. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1084. if ($activeonly == 1) $sql .= " AND tc.active=1"; // only the active types
  1085. if (!empty($source) && $source != 'all') $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1086. if (!empty($code)) $sql .= " AND tc.code='".$this->db->escape($code)."'";
  1087. $sql .= $this->db->order($order, 'ASC');
  1088. //print "sql=".$sql;
  1089. $resql = $this->db->query($sql);
  1090. if ($resql)
  1091. {
  1092. $num = $this->db->num_rows($resql);
  1093. $i = 0;
  1094. while ($i < $num)
  1095. {
  1096. $obj = $this->db->fetch_object($resql);
  1097. $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
  1098. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1099. if (empty($option)) $tab[$obj->rowid] = $libelle_type;
  1100. else $tab[$obj->code] = $libelle_type;
  1101. $i++;
  1102. }
  1103. return $tab;
  1104. } else {
  1105. $this->error = $this->db->lasterror();
  1106. //dol_print_error($this->db);
  1107. return null;
  1108. }
  1109. }
  1110. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1111. /**
  1112. * Return array with list of possible values for type of contacts
  1113. *
  1114. * @param string $source 'internal', 'external' or 'all'
  1115. * @param int $option 0=Return array id->label, 1=Return array code->label
  1116. * @param int $activeonly 0=all status of contact, 1=only the active
  1117. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1118. * @param string $element Filter on 1 element type
  1119. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1120. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1121. */
  1122. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1123. {
  1124. // phpcs:enable
  1125. global $langs, $conf;
  1126. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1127. $tab = array();
  1128. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
  1129. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  1130. $sqlWhere = array();
  1131. if (!empty($element)) {
  1132. $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
  1133. }
  1134. if (!empty($excludeelement)) {
  1135. $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
  1136. }
  1137. if ($activeonly == 1)
  1138. $sqlWhere[] = " tc.active=1"; // only the active types
  1139. if (!empty($source) && $source != 'all')
  1140. $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
  1141. if (!empty($code))
  1142. $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
  1143. if (count($sqlWhere) > 0) {
  1144. $sql .= " WHERE ".implode(' AND ', $sqlWhere);
  1145. }
  1146. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1147. dol_syslog(__METHOD__, LOG_DEBUG);
  1148. $resql = $this->db->query($sql);
  1149. if ($resql) {
  1150. $num = $this->db->num_rows($resql);
  1151. if ($num > 0) {
  1152. while ($obj = $this->db->fetch_object($resql)) {
  1153. $modulename = $obj->element;
  1154. if (strpos($obj->element, 'project') !== false) {
  1155. $modulename = 'projet';
  1156. } elseif ($obj->element == 'contrat') {
  1157. $element = 'contract';
  1158. } elseif ($obj->element == 'action') {
  1159. $modulename = 'agenda';
  1160. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1161. $modulename = 'fournisseur';
  1162. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1163. $modulename = 'fournisseur';
  1164. }
  1165. if ($conf->{$modulename}->enabled) {
  1166. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1167. $transkey = "TypeContact_".$obj->element."_".$source."_".$obj->code;
  1168. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1169. if (empty($option))
  1170. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1171. else $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1172. }
  1173. }
  1174. }
  1175. return $tab;
  1176. } else {
  1177. $this->error = $this->db->lasterror();
  1178. return null;
  1179. }
  1180. }
  1181. /**
  1182. * Return id of contacts for a source and a contact code.
  1183. * Example: contact client de facturation ('external', 'BILLING')
  1184. * Example: contact client de livraison ('external', 'SHIPPING')
  1185. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1186. *
  1187. * @param string $source 'external' or 'internal'
  1188. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1189. * @param int $status limited to a certain status
  1190. * @return array List of id for such contacts
  1191. */
  1192. public function getIdContact($source, $code, $status = 0)
  1193. {
  1194. global $conf;
  1195. $result = array();
  1196. $i = 0;
  1197. //cas particulier pour les expeditions
  1198. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1199. $id = $this->origin_id;
  1200. $element = 'commande';
  1201. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1202. $id = $this->origin_id;
  1203. $element = 'order_supplier';
  1204. } else {
  1205. $id = $this->id;
  1206. $element = $this->element;
  1207. }
  1208. $sql = "SELECT ec.fk_socpeople";
  1209. $sql .= " FROM ".MAIN_DB_PREFIX."element_contact as ec,";
  1210. if ($source == 'internal') $sql .= " ".MAIN_DB_PREFIX."user as c,";
  1211. if ($source == 'external') $sql .= " ".MAIN_DB_PREFIX."socpeople as c,";
  1212. $sql .= " ".MAIN_DB_PREFIX."c_type_contact as tc";
  1213. $sql .= " WHERE ec.element_id = ".$id;
  1214. $sql .= " AND ec.fk_socpeople = c.rowid";
  1215. if ($source == 'internal') $sql .= " AND c.entity IN (".getEntity('user').")";
  1216. if ($source == 'external') $sql .= " AND c.entity IN (".getEntity('societe').")";
  1217. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1218. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1219. $sql .= " AND tc.source = '".$this->db->escape($source)."'";
  1220. if ($code) $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1221. $sql .= " AND tc.active = 1";
  1222. if ($status) $sql .= " AND ec.statut = ".$status;
  1223. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1224. $resql = $this->db->query($sql);
  1225. if ($resql)
  1226. {
  1227. while ($obj = $this->db->fetch_object($resql))
  1228. {
  1229. $result[$i] = $obj->fk_socpeople;
  1230. $i++;
  1231. }
  1232. } else {
  1233. $this->error = $this->db->error();
  1234. return null;
  1235. }
  1236. return $result;
  1237. }
  1238. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1239. /**
  1240. * Load object contact with id=$this->contact_id into $this->contact
  1241. *
  1242. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1243. * @return int <0 if KO, >0 if OK
  1244. */
  1245. public function fetch_contact($contactid = null)
  1246. {
  1247. // phpcs:enable
  1248. if (empty($contactid)) $contactid = $this->contact_id;
  1249. if (empty($contactid)) return 0;
  1250. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1251. $contact = new Contact($this->db);
  1252. $result = $contact->fetch($contactid);
  1253. $this->contact = $contact;
  1254. return $result;
  1255. }
  1256. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1257. /**
  1258. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1259. *
  1260. * @param int $force_thirdparty_id Force thirdparty id
  1261. * @return int <0 if KO, >0 if OK
  1262. */
  1263. public function fetch_thirdparty($force_thirdparty_id = 0)
  1264. {
  1265. // phpcs:enable
  1266. global $conf;
  1267. if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id))
  1268. return 0;
  1269. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1270. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
  1271. if ($force_thirdparty_id)
  1272. $idtofetch = $force_thirdparty_id;
  1273. if ($idtofetch) {
  1274. $thirdparty = new Societe($this->db);
  1275. $result = $thirdparty->fetch($idtofetch);
  1276. $this->thirdparty = $thirdparty;
  1277. // Use first price level if level not defined for third party
  1278. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1279. $this->thirdparty->price_level = 1;
  1280. }
  1281. return $result;
  1282. } else return -1;
  1283. }
  1284. /**
  1285. * Looks for an object with ref matching the wildcard provided
  1286. * It does only work when $this->table_ref_field is set
  1287. *
  1288. * @param string $ref Wildcard
  1289. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1290. */
  1291. public function fetchOneLike($ref)
  1292. {
  1293. if (!$this->table_ref_field) {
  1294. return 0;
  1295. }
  1296. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE '.$this->table_ref_field.' LIKE "'.$this->db->escape($ref).'" LIMIT 1';
  1297. $query = $this->db->query($sql);
  1298. if (!$this->db->num_rows($query)) {
  1299. return 0;
  1300. }
  1301. $result = $this->db->fetch_object($query);
  1302. return $this->fetch($result->rowid);
  1303. }
  1304. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1305. /**
  1306. * Load data for barcode into properties ->barcode_type*
  1307. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1308. * if it is not defined, ->element must be defined to know default barcode type.
  1309. *
  1310. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1311. */
  1312. public function fetch_barcode()
  1313. {
  1314. // phpcs:enable
  1315. global $conf;
  1316. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1317. $idtype = $this->barcode_type;
  1318. 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
  1319. {
  1320. if ($this->element == 'product') $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1321. elseif ($this->element == 'societe') $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1322. else dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1323. }
  1324. if ($idtype > 0)
  1325. {
  1326. 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
  1327. {
  1328. $sql = "SELECT rowid, code, libelle as label, coder";
  1329. $sql .= " FROM ".MAIN_DB_PREFIX."c_barcode_type";
  1330. $sql .= " WHERE rowid = ".$idtype;
  1331. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1332. $resql = $this->db->query($sql);
  1333. if ($resql)
  1334. {
  1335. $obj = $this->db->fetch_object($resql);
  1336. $this->barcode_type = $obj->rowid;
  1337. $this->barcode_type_code = $obj->code;
  1338. $this->barcode_type_label = $obj->label;
  1339. $this->barcode_type_coder = $obj->coder;
  1340. return 1;
  1341. } else {
  1342. dol_print_error($this->db);
  1343. return -1;
  1344. }
  1345. }
  1346. }
  1347. return 0;
  1348. }
  1349. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1350. /**
  1351. * Load the project with id $this->fk_project into this->project
  1352. *
  1353. * @return int <0 if KO, >=0 if OK
  1354. */
  1355. public function fetch_projet()
  1356. {
  1357. // phpcs:enable
  1358. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1359. if (empty($this->fk_project) && !empty($this->fk_projet)) $this->fk_project = $this->fk_projet; // For backward compatibility
  1360. if (empty($this->fk_project)) return 0;
  1361. $project = new Project($this->db);
  1362. $result = $project->fetch($this->fk_project);
  1363. $this->projet = $project; // deprecated
  1364. $this->project = $project;
  1365. return $result;
  1366. }
  1367. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1368. /**
  1369. * Load the product with id $this->fk_product into this->product
  1370. *
  1371. * @return int <0 if KO, >=0 if OK
  1372. */
  1373. public function fetch_product()
  1374. {
  1375. // phpcs:enable
  1376. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1377. if (empty($this->fk_product)) return 0;
  1378. $product = new Product($this->db);
  1379. $result = $product->fetch($this->fk_product);
  1380. $this->product = $product;
  1381. return $result;
  1382. }
  1383. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1384. /**
  1385. * Load the user with id $userid into this->user
  1386. *
  1387. * @param int $userid Id du contact
  1388. * @return int <0 if KO, >0 if OK
  1389. */
  1390. public function fetch_user($userid)
  1391. {
  1392. // phpcs:enable
  1393. $user = new User($this->db);
  1394. $result = $user->fetch($userid);
  1395. $this->user = $user;
  1396. return $result;
  1397. }
  1398. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1399. /**
  1400. * Read linked origin object
  1401. *
  1402. * @return void
  1403. */
  1404. public function fetch_origin()
  1405. {
  1406. // phpcs:enable
  1407. if ($this->origin == 'shipping') $this->origin = 'expedition';
  1408. if ($this->origin == 'delivery') $this->origin = 'livraison';
  1409. if ($this->origin == 'order_supplier') $this->origin = 'commandeFournisseur';
  1410. $origin = $this->origin;
  1411. $classname = ucfirst($origin);
  1412. $this->$origin = new $classname($this->db);
  1413. $this->$origin->fetch($this->origin_id);
  1414. }
  1415. /**
  1416. * Load object from specific field
  1417. *
  1418. * @param string $table Table element or element line
  1419. * @param string $field Field selected
  1420. * @param string $key Import key
  1421. * @param string $element Element name
  1422. * @return int <0 if KO, >0 if OK
  1423. */
  1424. public function fetchObjectFrom($table, $field, $key, $element = null)
  1425. {
  1426. global $conf;
  1427. $result = false;
  1428. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$table;
  1429. $sql .= " WHERE ".$field." = '".$key."'";
  1430. if (!empty($element)) {
  1431. $sql .= " AND entity IN (".getEntity($element).")";
  1432. } else {
  1433. $sql .= " AND entity = ".$conf->entity;
  1434. }
  1435. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1436. $resql = $this->db->query($sql);
  1437. if ($resql)
  1438. {
  1439. $row = $this->db->fetch_row($resql);
  1440. // Test for avoid error -1
  1441. if ($row[0] > 0) {
  1442. $result = $this->fetch($row[0]);
  1443. }
  1444. }
  1445. return $result;
  1446. }
  1447. /**
  1448. * Getter generic. Load value from a specific field
  1449. *
  1450. * @param string $table Table of element or element line
  1451. * @param int $id Element id
  1452. * @param string $field Field selected
  1453. * @return int <0 if KO, >0 if OK
  1454. */
  1455. public function getValueFrom($table, $id, $field)
  1456. {
  1457. $result = false;
  1458. if (!empty($id) && !empty($field) && !empty($table)) {
  1459. $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table;
  1460. $sql .= " WHERE rowid = ".$id;
  1461. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1462. $resql = $this->db->query($sql);
  1463. if ($resql)
  1464. {
  1465. $row = $this->db->fetch_row($resql);
  1466. $result = $row[0];
  1467. }
  1468. }
  1469. return $result;
  1470. }
  1471. /**
  1472. * Setter generic. Update a specific field into database.
  1473. * Warning: Trigger is run only if param trigkey is provided.
  1474. *
  1475. * @param string $field Field to update
  1476. * @param mixed $value New value
  1477. * @param string $table To force other table element or element line (should not be used)
  1478. * @param int $id To force other object id (should not be used)
  1479. * @param string $format Data format ('text', 'date'). 'text' is used if not defined
  1480. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1481. * @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'
  1482. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1483. * @param string $fk_user_field Name of field to save user id making change
  1484. * @return int <0 if KO, >0 if OK
  1485. * @see updateExtraField()
  1486. */
  1487. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1488. {
  1489. global $user, $langs, $conf;
  1490. if (empty($table)) $table = $this->table_element;
  1491. if (empty($id)) $id = $this->id;
  1492. if (empty($format)) $format = 'text';
  1493. if (empty($id_field)) $id_field = 'rowid';
  1494. $error = 0;
  1495. $this->db->begin();
  1496. // Special case
  1497. if ($table == 'product' && $field == 'note_private') $field = 'note';
  1498. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) $fk_user_field = 'fk_user_mod';
  1499. $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
  1500. if ($format == 'text') $sql .= $field." = '".$this->db->escape($value)."'";
  1501. elseif ($format == 'int') $sql .= $field." = ".$this->db->escape($value);
  1502. elseif ($format == 'date') $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1503. if ($fk_user_field)
  1504. {
  1505. if (!empty($fuser) && is_object($fuser)) $sql .= ", ".$fk_user_field." = ".$fuser->id;
  1506. elseif (empty($fuser) || $fuser != 'none') $sql .= ", ".$fk_user_field." = ".$user->id;
  1507. }
  1508. $sql .= " WHERE ".$id_field." = ".$id;
  1509. dol_syslog(__METHOD__."", LOG_DEBUG);
  1510. $resql = $this->db->query($sql);
  1511. if ($resql)
  1512. {
  1513. if ($trigkey)
  1514. {
  1515. // call trigger with updated object values
  1516. if (empty($this->fields) && method_exists($this, 'fetch'))
  1517. {
  1518. $result = $this->fetch($id);
  1519. } else {
  1520. $result = $this->fetchCommon($id);
  1521. }
  1522. if ($result >= 0) $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1523. if ($result < 0) $error++;
  1524. }
  1525. if (!$error)
  1526. {
  1527. if (property_exists($this, $field)) $this->$field = $value;
  1528. $this->db->commit();
  1529. return 1;
  1530. } else {
  1531. $this->db->rollback();
  1532. return -2;
  1533. }
  1534. } else {
  1535. $this->error = $this->db->lasterror();
  1536. $this->db->rollback();
  1537. return -1;
  1538. }
  1539. }
  1540. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1541. /**
  1542. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1543. *
  1544. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')"
  1545. * @param string $fieldid Name of field to use for the select MAX and MIN
  1546. * @param int $nodbprefix Do not include DB prefix to forge table name
  1547. * @return int <0 if KO, >0 if OK
  1548. */
  1549. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1550. {
  1551. // phpcs:enable
  1552. global $conf, $user;
  1553. if (!$this->table_element)
  1554. {
  1555. dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1556. return -1;
  1557. }
  1558. if ($fieldid == 'none') return 1;
  1559. // Security on socid
  1560. $socid = 0;
  1561. if ($user->socid > 0) $socid = $user->socid;
  1562. // this->ismultientitymanaged contains
  1563. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1564. $aliastablesociete = 's';
  1565. if ($this->element == 'societe') $aliastablesociete = 'te'; // te as table_element
  1566. $sql = "SELECT MAX(te.".$fieldid.")";
  1567. $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1568. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1569. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  1570. }
  1571. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1572. $tmparray = explode('@', $this->ismultientitymanaged);
  1573. $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
  1574. } 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
  1575. 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
  1576. 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";
  1577. $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)
  1578. if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id;
  1579. if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)';
  1580. if (!empty($filter))
  1581. {
  1582. if (!preg_match('/^\s*AND/i', $filter)) $sql .= " AND "; // For backward compatibility
  1583. $sql .= $filter;
  1584. }
  1585. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1586. $tmparray = explode('@', $this->ismultientitymanaged);
  1587. $sql .= ' AND te.'.$tmparray[0].' = '.($tmparray[1] == 'societe' ? 's' : 'parenttable').'.rowid'; // If we need to link to this table to limit select to entity
  1588. } 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
  1589. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1590. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1591. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1592. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1593. } else {
  1594. $sql .= " AND ug.fk_user = te.rowid";
  1595. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1596. }
  1597. } else {
  1598. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1599. }
  1600. }
  1601. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1602. $tmparray = explode('@', $this->ismultientitymanaged);
  1603. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1604. }
  1605. if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql .= ' AND te.fk_soc = '.$socid;
  1606. if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql .= ' AND (te.fk_soc = '.$socid.' OR te.fk_soc IS NULL)';
  1607. if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql .= ' AND te.rowid = '.$socid;
  1608. //print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1609. $result = $this->db->query($sql);
  1610. if (!$result)
  1611. {
  1612. $this->error = $this->db->lasterror();
  1613. return -1;
  1614. }
  1615. $row = $this->db->fetch_row($result);
  1616. $this->ref_previous = $row[0];
  1617. $sql = "SELECT MIN(te.".$fieldid.")";
  1618. $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1619. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1620. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  1621. }
  1622. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1623. $tmparray = explode('@', $this->ismultientitymanaged);
  1624. $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
  1625. } 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
  1626. 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
  1627. 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";
  1628. $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)
  1629. if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id;
  1630. if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)';
  1631. if (!empty($filter))
  1632. {
  1633. if (!preg_match('/^\s*AND/i', $filter)) $sql .= " AND "; // For backward compatibility
  1634. $sql .= $filter;
  1635. }
  1636. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1637. $tmparray = explode('@', $this->ismultientitymanaged);
  1638. $sql .= ' AND te.'.$tmparray[0].' = '.($tmparray[1] == 'societe' ? 's' : 'parenttable').'.rowid'; // If we need to link to this table to limit select to entity
  1639. } 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
  1640. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1641. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1642. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1643. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1644. } else {
  1645. $sql .= " AND ug.fk_user = te.rowid";
  1646. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1647. }
  1648. } else {
  1649. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1650. }
  1651. }
  1652. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1653. $tmparray = explode('@', $this->ismultientitymanaged);
  1654. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1655. }
  1656. if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql .= ' AND te.fk_soc = '.$socid;
  1657. if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql .= ' AND (te.fk_soc = '.$socid.' OR te.fk_soc IS NULL)';
  1658. if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql .= ' AND te.rowid = '.$socid;
  1659. //print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1660. // 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
  1661. $result = $this->db->query($sql);
  1662. if (!$result)
  1663. {
  1664. $this->error = $this->db->lasterror();
  1665. return -2;
  1666. }
  1667. $row = $this->db->fetch_row($result);
  1668. $this->ref_next = $row[0];
  1669. return 1;
  1670. }
  1671. /**
  1672. * Return list of id of contacts of object
  1673. *
  1674. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  1675. * @return array Array of id of contacts (if source=external or internal)
  1676. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  1677. */
  1678. public function getListContactId($source = 'external')
  1679. {
  1680. $contactAlreadySelected = array();
  1681. $tab = $this->liste_contact(-1, $source);
  1682. $num = count($tab);
  1683. $i = 0;
  1684. while ($i < $num)
  1685. {
  1686. if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid'];
  1687. else $contactAlreadySelected[$i] = $tab[$i]['id'];
  1688. $i++;
  1689. }
  1690. return $contactAlreadySelected;
  1691. }
  1692. /**
  1693. * Link element with a project
  1694. *
  1695. * @param int $projectid Project id to link element to
  1696. * @return int <0 if KO, >0 if OK
  1697. */
  1698. public function setProject($projectid)
  1699. {
  1700. if (!$this->table_element)
  1701. {
  1702. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  1703. return -1;
  1704. }
  1705. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1706. if (!empty($this->fields['fk_project'])) // Common case
  1707. {
  1708. if ($projectid) $sql .= ' SET fk_project = '.$projectid;
  1709. else $sql .= ' SET fk_project = NULL';
  1710. $sql .= ' WHERE rowid = '.$this->id;
  1711. } elseif ($this->table_element == 'actioncomm') // Special case for actioncomm
  1712. {
  1713. if ($projectid) $sql .= ' SET fk_project = '.$projectid;
  1714. else $sql .= ' SET fk_project = NULL';
  1715. $sql .= ' WHERE id = '.$this->id;
  1716. } else // Special case for old architecture objects
  1717. {
  1718. if ($projectid) $sql .= ' SET fk_projet = '.$projectid;
  1719. else $sql .= ' SET fk_projet = NULL';
  1720. $sql .= ' WHERE rowid = '.$this->id;
  1721. }
  1722. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  1723. if ($this->db->query($sql))
  1724. {
  1725. $this->fk_project = $projectid;
  1726. return 1;
  1727. } else {
  1728. dol_print_error($this->db);
  1729. return -1;
  1730. }
  1731. }
  1732. /**
  1733. * Change the payments methods
  1734. *
  1735. * @param int $id Id of new payment method
  1736. * @return int >0 if OK, <0 if KO
  1737. */
  1738. public function setPaymentMethods($id)
  1739. {
  1740. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  1741. if ($this->statut >= 0 || $this->element == 'societe')
  1742. {
  1743. // TODO uniformize field name
  1744. $fieldname = 'fk_mode_reglement';
  1745. if ($this->element == 'societe') $fieldname = 'mode_reglement';
  1746. if (get_class($this) == 'Fournisseur') $fieldname = 'mode_reglement_supplier';
  1747. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1748. $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL');
  1749. $sql .= ' WHERE rowid='.$this->id;
  1750. if ($this->db->query($sql))
  1751. {
  1752. $this->mode_reglement_id = $id;
  1753. // for supplier
  1754. if (get_class($this) == 'Fournisseur') $this->mode_reglement_supplier_id = $id;
  1755. return 1;
  1756. } else {
  1757. dol_syslog(get_class($this).'::setPaymentMethods Erreur '.$sql.' - '.$this->db->error());
  1758. $this->error = $this->db->error();
  1759. return -1;
  1760. }
  1761. } else {
  1762. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  1763. $this->error = 'Status of the object is incompatible '.$this->statut;
  1764. return -2;
  1765. }
  1766. }
  1767. /**
  1768. * Change the multicurrency code
  1769. *
  1770. * @param string $code multicurrency code
  1771. * @return int >0 if OK, <0 if KO
  1772. */
  1773. public function setMulticurrencyCode($code)
  1774. {
  1775. dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
  1776. if ($this->statut >= 0 || $this->element == 'societe')
  1777. {
  1778. $fieldname = 'multicurrency_code';
  1779. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1780. $sql .= ' SET '.$fieldname." = '".$this->db->escape($code)."'";
  1781. $sql .= ' WHERE rowid='.$this->id;
  1782. if ($this->db->query($sql))
  1783. {
  1784. $this->multicurrency_code = $code;
  1785. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  1786. if ($rate) $this->setMulticurrencyRate($rate, 2);
  1787. return 1;
  1788. } else {
  1789. dol_syslog(get_class($this).'::setMulticurrencyCode Erreur '.$sql.' - '.$this->db->error());
  1790. $this->error = $this->db->error();
  1791. return -1;
  1792. }
  1793. } else {
  1794. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  1795. $this->error = 'Status of the object is incompatible '.$this->statut;
  1796. return -2;
  1797. }
  1798. }
  1799. /**
  1800. * Change the multicurrency rate
  1801. *
  1802. * @param double $rate multicurrency rate
  1803. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  1804. * @return int >0 if OK, <0 if KO
  1805. */
  1806. public function setMulticurrencyRate($rate, $mode = 1)
  1807. {
  1808. dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
  1809. if ($this->statut >= 0 || $this->element == 'societe')
  1810. {
  1811. $fieldname = 'multicurrency_tx';
  1812. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1813. $sql .= ' SET '.$fieldname.' = '.$rate;
  1814. $sql .= ' WHERE rowid='.$this->id;
  1815. if ($this->db->query($sql))
  1816. {
  1817. $this->multicurrency_tx = $rate;
  1818. // Update line price
  1819. if (!empty($this->lines))
  1820. {
  1821. foreach ($this->lines as &$line)
  1822. {
  1823. // Amounts in company currency will be recalculated
  1824. if ($mode == 1) {
  1825. $line->subprice = 0;
  1826. }
  1827. // Amounts in foreign currency will be recalculated
  1828. if ($mode == 2) {
  1829. $line->multicurrency_subprice = 0;
  1830. }
  1831. switch ($this->element) {
  1832. case 'propal':
  1833. $this->updateline(
  1834. $line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx,
  1835. ($line->description ? $line->description : $line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line,
  1836. $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->date_start,
  1837. $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
  1838. );
  1839. break;
  1840. case 'commande':
  1841. $this->updateline(
  1842. $line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->qty, $line->remise_percent,
  1843. $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->date_start, $line->date_end,
  1844. $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label,
  1845. $line->special_code, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
  1846. );
  1847. break;
  1848. case 'facture':
  1849. $this->updateline(
  1850. $line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->qty, $line->remise_percent,
  1851. $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits,
  1852. $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label,
  1853. $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice
  1854. );
  1855. break;
  1856. case 'supplier_proposal':
  1857. $this->updateline(
  1858. $line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx,
  1859. ($line->description ? $line->description : $line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line,
  1860. $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->array_options,
  1861. $line->ref_fourn, $line->multicurrency_subprice
  1862. );
  1863. break;
  1864. case 'order_supplier':
  1865. $this->updateline(
  1866. $line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->qty, $line->remise_percent,
  1867. $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, false,
  1868. $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
  1869. );
  1870. break;
  1871. case 'invoice_supplier':
  1872. $this->updateline(
  1873. $line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->tva_tx, $line->localtax1_tx,
  1874. $line->localtax2_tx, $line->qty, 0, 'HT', $line->info_bits, $line->product_type, $line->remise_percent, false,
  1875. $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
  1876. );
  1877. break;
  1878. default:
  1879. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  1880. break;
  1881. }
  1882. }
  1883. }
  1884. return 1;
  1885. } else {
  1886. dol_syslog(get_class($this).'::setMulticurrencyRate Erreur '.$sql.' - '.$this->db->error());
  1887. $this->error = $this->db->error();
  1888. return -1;
  1889. }
  1890. } else {
  1891. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  1892. $this->error = 'Status of the object is incompatible '.$this->statut;
  1893. return -2;
  1894. }
  1895. }
  1896. /**
  1897. * Change the payments terms
  1898. *
  1899. * @param int $id Id of new payment terms
  1900. * @return int >0 if OK, <0 if KO
  1901. */
  1902. public function setPaymentTerms($id)
  1903. {
  1904. dol_syslog(get_class($this).'::setPaymentTerms('.$id.')');
  1905. if ($this->statut >= 0 || $this->element == 'societe')
  1906. {
  1907. // TODO uniformize field name
  1908. $fieldname = 'fk_cond_reglement';
  1909. if ($this->element == 'societe') $fieldname = 'cond_reglement';
  1910. if (get_class($this) == 'Fournisseur') $fieldname = 'cond_reglement_supplier';
  1911. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1912. $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL');
  1913. $sql .= ' WHERE rowid='.$this->id;
  1914. if ($this->db->query($sql))
  1915. {
  1916. $this->cond_reglement_id = $id;
  1917. // for supplier
  1918. if (get_class($this) == 'Fournisseur') $this->cond_reglement_supplier_id = $id;
  1919. $this->cond_reglement = $id; // for compatibility
  1920. return 1;
  1921. } else {
  1922. dol_syslog(get_class($this).'::setPaymentTerms Erreur '.$sql.' - '.$this->db->error());
  1923. $this->error = $this->db->error();
  1924. return -1;
  1925. }
  1926. } else {
  1927. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  1928. $this->error = 'Status of the object is incompatible '.$this->statut;
  1929. return -2;
  1930. }
  1931. }
  1932. /**
  1933. * Change the retained warranty payments terms
  1934. *
  1935. * @param int $id Id of new payment terms
  1936. * @return int >0 if OK, <0 if KO
  1937. */
  1938. public function setRetainedWarrantyPaymentTerms($id)
  1939. {
  1940. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
  1941. if ($this->statut >= 0 || $this->element == 'societe')
  1942. {
  1943. $fieldname = 'retained_warranty_fk_cond_reglement';
  1944. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1945. $sql .= ' SET '.$fieldname.' = '.$id;
  1946. $sql .= ' WHERE rowid='.$this->id;
  1947. if ($this->db->query($sql))
  1948. {
  1949. $this->retained_warranty_fk_cond_reglement = $id;
  1950. return 1;
  1951. } else {
  1952. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Erreur '.$sql.' - '.$this->db->error());
  1953. $this->error = $this->db->error();
  1954. return -1;
  1955. }
  1956. } else {
  1957. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  1958. $this->error = 'Status of the object is incompatible '.$this->statut;
  1959. return -2;
  1960. }
  1961. }
  1962. /**
  1963. * Define delivery address
  1964. * @deprecated
  1965. *
  1966. * @param int $id Address id
  1967. * @return int <0 si ko, >0 si ok
  1968. */
  1969. public function setDeliveryAddress($id)
  1970. {
  1971. $fieldname = 'fk_delivery_address';
  1972. if ($this->element == 'delivery' || $this->element == 'shipping') $fieldname = 'fk_address';
  1973. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".$id;
  1974. $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0";
  1975. if ($this->db->query($sql))
  1976. {
  1977. $this->fk_delivery_address = $id;
  1978. return 1;
  1979. } else {
  1980. $this->error = $this->db->error();
  1981. dol_syslog(get_class($this).'::setDeliveryAddress Erreur '.$sql.' - '.$this->error);
  1982. return -1;
  1983. }
  1984. }
  1985. /**
  1986. * Change the shipping method
  1987. *
  1988. * @param int $shipping_method_id Id of shipping method
  1989. * @param bool $notrigger false=launch triggers after, true=disable triggers
  1990. * @param User $userused Object user
  1991. *
  1992. * @return int 1 if OK, 0 if KO
  1993. */
  1994. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  1995. {
  1996. global $user;
  1997. if (empty($userused)) $userused = $user;
  1998. $error = 0;
  1999. if (!$this->table_element) {
  2000. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2001. return -1;
  2002. }
  2003. $this->db->begin();
  2004. if ($shipping_method_id < 0) $shipping_method_id = 'NULL';
  2005. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  2006. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2007. $sql .= " SET fk_shipping_method = ".$shipping_method_id;
  2008. $sql .= " WHERE rowid=".$this->id;
  2009. $resql = $this->db->query($sql);
  2010. if (!$resql) {
  2011. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  2012. $this->error = $this->db->lasterror();
  2013. $error++;
  2014. } else {
  2015. if (!$notrigger)
  2016. {
  2017. // Call trigger
  2018. $this->context = array('shippingmethodupdate'=>1);
  2019. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2020. if ($result < 0) $error++;
  2021. // End call trigger
  2022. }
  2023. }
  2024. if ($error)
  2025. {
  2026. $this->db->rollback();
  2027. return -1;
  2028. } else {
  2029. $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
  2030. $this->db->commit();
  2031. return 1;
  2032. }
  2033. }
  2034. /**
  2035. * Change the warehouse
  2036. *
  2037. * @param int $warehouse_id Id of warehouse
  2038. * @return int 1 if OK, 0 if KO
  2039. */
  2040. public function setWarehouse($warehouse_id)
  2041. {
  2042. if (!$this->table_element) {
  2043. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2044. return -1;
  2045. }
  2046. if ($warehouse_id < 0) $warehouse_id = 'NULL';
  2047. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  2048. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2049. $sql .= " SET fk_warehouse = ".$warehouse_id;
  2050. $sql .= " WHERE rowid=".$this->id;
  2051. if ($this->db->query($sql)) {
  2052. $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
  2053. return 1;
  2054. } else {
  2055. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  2056. $this->error = $this->db->error();
  2057. return 0;
  2058. }
  2059. }
  2060. /**
  2061. * Set last model used by doc generator
  2062. *
  2063. * @param User $user User object that make change
  2064. * @param string $modelpdf Modele name
  2065. * @return int <0 if KO, >0 if OK
  2066. */
  2067. public function setDocModel($user, $modelpdf)
  2068. {
  2069. if (!$this->table_element)
  2070. {
  2071. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2072. return -1;
  2073. }
  2074. $newmodelpdf = dol_trunc($modelpdf, 255);
  2075. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2076. $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  2077. $sql .= " WHERE rowid = ".$this->id;
  2078. // if ($this->element == 'facture') $sql.= " AND fk_statut < 2";
  2079. // if ($this->element == 'propal') $sql.= " AND fk_statut = 0";
  2080. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  2081. $resql = $this->db->query($sql);
  2082. if ($resql)
  2083. {
  2084. $this->model_pdf = $modelpdf;
  2085. $this->modelpdf = $modelpdf; // For bakward compatibility
  2086. return 1;
  2087. } else {
  2088. dol_print_error($this->db);
  2089. return 0;
  2090. }
  2091. }
  2092. /**
  2093. * Change the bank account
  2094. *
  2095. * @param int $fk_account Id of bank account
  2096. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2097. * @param User $userused Object user
  2098. * @return int 1 if OK, 0 if KO
  2099. */
  2100. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2101. {
  2102. global $user;
  2103. if (empty($userused)) $userused = $user;
  2104. $error = 0;
  2105. if (!$this->table_element) {
  2106. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2107. return -1;
  2108. }
  2109. $this->db->begin();
  2110. if ($fk_account < 0) $fk_account = 'NULL';
  2111. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  2112. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2113. $sql .= " SET fk_account = ".$fk_account;
  2114. $sql .= " WHERE rowid=".$this->id;
  2115. $resql = $this->db->query($sql);
  2116. if (!$resql)
  2117. {
  2118. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  2119. $this->error = $this->db->lasterror();
  2120. $error++;
  2121. } else {
  2122. if (!$notrigger)
  2123. {
  2124. // Call trigger
  2125. $this->context = array('bankaccountupdate'=>1);
  2126. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2127. if ($result < 0) $error++;
  2128. // End call trigger
  2129. }
  2130. }
  2131. if ($error)
  2132. {
  2133. $this->db->rollback();
  2134. return -1;
  2135. } else {
  2136. $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
  2137. $this->db->commit();
  2138. return 1;
  2139. }
  2140. }
  2141. // TODO: Move line related operations to CommonObjectLine?
  2142. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2143. /**
  2144. * Save a new position (field rang) for details lines.
  2145. * You can choose to set position for lines with already a position or lines without any position defined.
  2146. *
  2147. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2148. * @param string $rowidorder ASC or DESC
  2149. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2150. * @return int <0 if KO, >0 if OK
  2151. */
  2152. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2153. {
  2154. // phpcs:enable
  2155. if (!$this->table_element_line)
  2156. {
  2157. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2158. return -1;
  2159. }
  2160. if (!$this->fk_element)
  2161. {
  2162. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2163. return -1;
  2164. }
  2165. // Count number of lines to reorder (according to choice $renum)
  2166. $nl = 0;
  2167. $sql = 'SELECT count(rowid) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2168. $sql .= ' WHERE '.$this->fk_element.'='.$this->id;
  2169. if (!$renum) $sql .= ' AND rang = 0';
  2170. if ($renum) $sql .= ' AND rang <> 0';
  2171. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  2172. $resql = $this->db->query($sql);
  2173. if ($resql)
  2174. {
  2175. $row = $this->db->fetch_row($resql);
  2176. $nl = $row[0];
  2177. } else dol_print_error($this->db);
  2178. if ($nl > 0)
  2179. {
  2180. // The goal of this part is to reorder all lines, with all children lines sharing the same
  2181. // counter that parents.
  2182. $rows = array();
  2183. // We first search all lines that are parent lines (for multilevel details lines)
  2184. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2185. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2186. if ($fk_parent_line) $sql .= ' AND fk_parent_line IS NULL';
  2187. $sql .= ' ORDER BY rang ASC, rowid '.$rowidorder;
  2188. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  2189. $resql = $this->db->query($sql);
  2190. if ($resql)
  2191. {
  2192. $i = 0;
  2193. $num = $this->db->num_rows($resql);
  2194. while ($i < $num)
  2195. {
  2196. $row = $this->db->fetch_row($resql);
  2197. $rows[] = $row[0]; // Add parent line into array rows
  2198. $childrens = $this->getChildrenOfLine($row[0]);
  2199. if (!empty($childrens))
  2200. {
  2201. foreach ($childrens as $child)
  2202. {
  2203. array_push($rows, $child);
  2204. }
  2205. }
  2206. $i++;
  2207. }
  2208. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2209. if (!empty($rows))
  2210. {
  2211. foreach ($rows as $key => $row)
  2212. {
  2213. $this->updateRangOfLine($row, ($key + 1));
  2214. }
  2215. }
  2216. } else {
  2217. dol_print_error($this->db);
  2218. }
  2219. }
  2220. return 1;
  2221. }
  2222. /**
  2223. * Get children of line
  2224. *
  2225. * @param int $id Id of parent line
  2226. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2227. * @return array Array with list of children lines id
  2228. */
  2229. public function getChildrenOfLine($id, $includealltree = 0)
  2230. {
  2231. $rows = array();
  2232. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2233. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2234. $sql .= ' AND fk_parent_line = '.$id;
  2235. $sql .= ' ORDER BY rang ASC';
  2236. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id."", LOG_DEBUG);
  2237. $resql = $this->db->query($sql);
  2238. if ($resql)
  2239. {
  2240. if ($this->db->num_rows($resql) > 0) {
  2241. while ($row = $this->db->fetch_row($resql)) {
  2242. $rows[] = $row[0];
  2243. if (!empty($includealltree)) $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2244. }
  2245. }
  2246. }
  2247. return $rows;
  2248. }
  2249. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2250. /**
  2251. * Update a line to have a lower rank
  2252. *
  2253. * @param int $rowid Id of line
  2254. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2255. * @return void
  2256. */
  2257. public function line_up($rowid, $fk_parent_line = true)
  2258. {
  2259. // phpcs:enable
  2260. $this->line_order(false, 'ASC', $fk_parent_line);
  2261. // Get rang of line
  2262. $rang = $this->getRangOfLine($rowid);
  2263. // Update position of line
  2264. $this->updateLineUp($rowid, $rang);
  2265. }
  2266. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2267. /**
  2268. * Update a line to have a higher rank
  2269. *
  2270. * @param int $rowid Id of line
  2271. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2272. * @return void
  2273. */
  2274. public function line_down($rowid, $fk_parent_line = true)
  2275. {
  2276. // phpcs:enable
  2277. $this->line_order(false, 'ASC', $fk_parent_line);
  2278. // Get rang of line
  2279. $rang = $this->getRangOfLine($rowid);
  2280. // Get max value for rang
  2281. $max = $this->line_max();
  2282. // Update position of line
  2283. $this->updateLineDown($rowid, $rang, $max);
  2284. }
  2285. /**
  2286. * Update position of line (rang)
  2287. *
  2288. * @param int $rowid Id of line
  2289. * @param int $rang Position
  2290. * @return void
  2291. */
  2292. public function updateRangOfLine($rowid, $rang)
  2293. {
  2294. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2295. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
  2296. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang;
  2297. $sql .= ' WHERE rowid = '.$rowid;
  2298. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2299. if (!$this->db->query($sql))
  2300. {
  2301. dol_print_error($this->db);
  2302. }
  2303. }
  2304. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2305. /**
  2306. * Update position of line with ajax (rang)
  2307. *
  2308. * @param array $rows Array of rows
  2309. * @return void
  2310. */
  2311. public function line_ajaxorder($rows)
  2312. {
  2313. // phpcs:enable
  2314. $num = count($rows);
  2315. for ($i = 0; $i < $num; $i++)
  2316. {
  2317. $this->updateRangOfLine($rows[$i], ($i + 1));
  2318. }
  2319. }
  2320. /**
  2321. * Update position of line up (rang)
  2322. *
  2323. * @param int $rowid Id of line
  2324. * @param int $rang Position
  2325. * @return void
  2326. */
  2327. public function updateLineUp($rowid, $rang)
  2328. {
  2329. if ($rang > 1)
  2330. {
  2331. $fieldposition = 'rang';
  2332. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
  2333. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang;
  2334. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2335. $sql .= ' AND rang = '.($rang - 1);
  2336. if ($this->db->query($sql))
  2337. {
  2338. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.($rang - 1);
  2339. $sql .= ' WHERE rowid = '.$rowid;
  2340. if (!$this->db->query($sql))
  2341. {
  2342. dol_print_error($this->db);
  2343. }
  2344. } else {
  2345. dol_print_error($this->db);
  2346. }
  2347. }
  2348. }
  2349. /**
  2350. * Update position of line down (rang)
  2351. *
  2352. * @param int $rowid Id of line
  2353. * @param int $rang Position
  2354. * @param int $max Max
  2355. * @return void
  2356. */
  2357. public function updateLineDown($rowid, $rang, $max)
  2358. {
  2359. if ($rang < $max)
  2360. {
  2361. $fieldposition = 'rang';
  2362. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
  2363. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang;
  2364. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2365. $sql .= ' AND rang = '.($rang + 1);
  2366. if ($this->db->query($sql))
  2367. {
  2368. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.($rang + 1);
  2369. $sql .= ' WHERE rowid = '.$rowid;
  2370. if (!$this->db->query($sql))
  2371. {
  2372. dol_print_error($this->db);
  2373. }
  2374. } else {
  2375. dol_print_error($this->db);
  2376. }
  2377. }
  2378. }
  2379. /**
  2380. * Get position of line (rang)
  2381. *
  2382. * @param int $rowid Id of line
  2383. * @return int Value of rang in table of lines
  2384. */
  2385. public function getRangOfLine($rowid)
  2386. {
  2387. $sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2388. $sql .= ' WHERE rowid ='.$rowid;
  2389. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  2390. $resql = $this->db->query($sql);
  2391. if ($resql)
  2392. {
  2393. $row = $this->db->fetch_row($resql);
  2394. return $row[0];
  2395. }
  2396. }
  2397. /**
  2398. * Get rowid of the line relative to its position
  2399. *
  2400. * @param int $rang Rang value
  2401. * @return int Rowid of the line
  2402. */
  2403. public function getIdOfLine($rang)
  2404. {
  2405. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2406. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2407. $sql .= ' AND rang = '.$rang;
  2408. $resql = $this->db->query($sql);
  2409. if ($resql)
  2410. {
  2411. $row = $this->db->fetch_row($resql);
  2412. return $row[0];
  2413. }
  2414. }
  2415. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2416. /**
  2417. * Get max value used for position of line (rang)
  2418. *
  2419. * @param int $fk_parent_line Parent line id
  2420. * @return int Max value of rang in table of lines
  2421. */
  2422. public function line_max($fk_parent_line = 0)
  2423. {
  2424. // phpcs:enable
  2425. $positionfield = 'rang';
  2426. if ($this->table_element == 'bom') $positionfield = 'position';
  2427. // Search the last rang with fk_parent_line
  2428. if ($fk_parent_line)
  2429. {
  2430. $sql = 'SELECT max('.$positionfield.') FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2431. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2432. $sql .= ' AND fk_parent_line = '.$fk_parent_line;
  2433. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2434. $resql = $this->db->query($sql);
  2435. if ($resql)
  2436. {
  2437. $row = $this->db->fetch_row($resql);
  2438. if (!empty($row[0]))
  2439. {
  2440. return $row[0];
  2441. } else {
  2442. return $this->getRangOfLine($fk_parent_line);
  2443. }
  2444. }
  2445. }
  2446. // If not, search the last rang of element
  2447. else {
  2448. $sql = 'SELECT max('.$positionfield.') FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2449. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2450. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2451. $resql = $this->db->query($sql);
  2452. if ($resql)
  2453. {
  2454. $row = $this->db->fetch_row($resql);
  2455. return $row[0];
  2456. }
  2457. }
  2458. }
  2459. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2460. /**
  2461. * Update external ref of element
  2462. *
  2463. * @param string $ref_ext Update field ref_ext
  2464. * @return int <0 if KO, >0 if OK
  2465. */
  2466. public function update_ref_ext($ref_ext)
  2467. {
  2468. // phpcs:enable
  2469. if (!$this->table_element)
  2470. {
  2471. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  2472. return -1;
  2473. }
  2474. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2475. $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  2476. $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".$this->id;
  2477. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  2478. if ($this->db->query($sql))
  2479. {
  2480. $this->ref_ext = $ref_ext;
  2481. return 1;
  2482. } else {
  2483. $this->error = $this->db->error();
  2484. return -1;
  2485. }
  2486. }
  2487. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2488. /**
  2489. * Update note of element
  2490. *
  2491. * @param string $note New value for note
  2492. * @param string $suffix '', '_public' or '_private'
  2493. * @return int <0 if KO, >0 if OK
  2494. */
  2495. public function update_note($note, $suffix = '')
  2496. {
  2497. // phpcs:enable
  2498. global $user;
  2499. if (!$this->table_element)
  2500. {
  2501. $this->error = 'update_note was called on objet with property table_element not defined';
  2502. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  2503. return -1;
  2504. }
  2505. if (!in_array($suffix, array('', '_public', '_private')))
  2506. {
  2507. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  2508. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  2509. return -2;
  2510. }
  2511. $newsuffix = $suffix;
  2512. // Special cas
  2513. if ($this->table_element == 'product' && $newsuffix == '_private') $newsuffix = '';
  2514. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2515. $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
  2516. $sql .= " ,".(in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment')) ? "fk_user_mod" : "fk_user_modif")." = ".$user->id;
  2517. $sql .= " WHERE rowid =".$this->id;
  2518. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  2519. if ($this->db->query($sql))
  2520. {
  2521. if ($suffix == '_public') $this->note_public = $note;
  2522. elseif ($suffix == '_private') $this->note_private = $note;
  2523. else {
  2524. $this->note = $note; // deprecated
  2525. $this->note_private = $note;
  2526. }
  2527. return 1;
  2528. } else {
  2529. $this->error = $this->db->lasterror();
  2530. return -1;
  2531. }
  2532. }
  2533. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2534. /**
  2535. * Update public note (kept for backward compatibility)
  2536. *
  2537. * @param string $note New value for note
  2538. * @return int <0 if KO, >0 if OK
  2539. * @deprecated
  2540. * @see update_note()
  2541. */
  2542. public function update_note_public($note)
  2543. {
  2544. // phpcs:enable
  2545. return $this->update_note($note, '_public');
  2546. }
  2547. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2548. /**
  2549. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  2550. * Must be called at end of methods addline or updateline.
  2551. *
  2552. * @param int $exclspec >0 = Exclude special product (product_type=9)
  2553. * @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
  2554. * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object.
  2555. * @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.
  2556. * @return int <0 if KO, >0 if OK
  2557. */
  2558. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  2559. {
  2560. // phpcs:enable
  2561. global $conf, $hookmanager, $action;
  2562. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  2563. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  2564. if ($reshook > 0) {
  2565. return 1; // replacement code
  2566. } elseif ($reshook < 0) {
  2567. return -1; // failure
  2568. } // reshook = 0 => execute normal code
  2569. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  2570. $MODULE = "";
  2571. if ($this->element == 'propal')
  2572. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  2573. elseif ($this->element == 'commande' || $this->element == 'order')
  2574. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  2575. elseif ($this->element == 'facture' || $this->element == 'invoice')
  2576. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  2577. elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier')
  2578. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  2579. elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order')
  2580. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  2581. elseif ($this->element == 'supplier_proposal')
  2582. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  2583. if (!empty($MODULE)) {
  2584. if (!empty($conf->global->$MODULE)) {
  2585. $modsactivated = explode(',', $conf->global->$MODULE);
  2586. foreach ($modsactivated as $mod) {
  2587. if ($conf->$mod->enabled)
  2588. return 1; // update was disabled by specific setup
  2589. }
  2590. }
  2591. }
  2592. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  2593. if ($roundingadjust == '-1') $roundingadjust = 'auto'; // For backward compatibility
  2594. $forcedroundingmode = $roundingadjust;
  2595. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) $forcedroundingmode = $conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
  2596. elseif ($forcedroundingmode == 'auto') $forcedroundingmode = '0';
  2597. $error = 0;
  2598. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  2599. // Define constants to find lines to sum
  2600. $fieldtva = 'total_tva';
  2601. $fieldlocaltax1 = 'total_localtax1';
  2602. $fieldlocaltax2 = 'total_localtax2';
  2603. $fieldup = 'subprice';
  2604. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
  2605. {
  2606. $fieldtva = 'tva';
  2607. $fieldup = 'pu_ht';
  2608. }
  2609. if ($this->element == 'expensereport')
  2610. {
  2611. $fieldup = 'value_unit';
  2612. }
  2613. $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,';
  2614. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  2615. if ($this->table_element_line == 'facturedet') $sql .= ', situation_percent';
  2616. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  2617. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2618. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2619. if ($exclspec)
  2620. {
  2621. $product_field = 'product_type';
  2622. if ($this->table_element_line == 'contratdet') $product_field = ''; // contratdet table has no product_type field
  2623. if ($product_field) $sql .= ' AND '.$product_field.' <> 9';
  2624. }
  2625. $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
  2626. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  2627. $resql = $this->db->query($sql);
  2628. if ($resql)
  2629. {
  2630. $this->total_ht = 0;
  2631. $this->total_tva = 0;
  2632. $this->total_localtax1 = 0;
  2633. $this->total_localtax2 = 0;
  2634. $this->total_ttc = 0;
  2635. $total_ht_by_vats = array();
  2636. $total_tva_by_vats = array();
  2637. $total_ttc_by_vats = array();
  2638. $this->multicurrency_total_ht = 0;
  2639. $this->multicurrency_total_tva = 0;
  2640. $this->multicurrency_total_ttc = 0;
  2641. $num = $this->db->num_rows($resql);
  2642. $i = 0;
  2643. while ($i < $num)
  2644. {
  2645. $obj = $this->db->fetch_object($resql);
  2646. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  2647. $parameters = array('fk_element' => $obj->rowid);
  2648. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  2649. 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'
  2650. {
  2651. // This part of code is to fix data. We should not call it too often.
  2652. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  2653. $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);
  2654. $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.
  2655. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  2656. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
  2657. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  2658. if ($diff_when_using_price_ht && $diff_on_current_total)
  2659. {
  2660. $sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
  2661. 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);
  2662. $resqlfix = $this->db->query($sqlfix);
  2663. if (!$resqlfix) dol_print_error($this->db, 'Failed to update line');
  2664. $obj->total_tva = $tmpcal[1];
  2665. $obj->total_ttc = $tmpcal[2];
  2666. }
  2667. }
  2668. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  2669. $this->total_tva += $obj->total_tva;
  2670. $this->total_localtax1 += $obj->total_localtax1;
  2671. $this->total_localtax2 += $obj->total_localtax2;
  2672. $this->total_ttc += $obj->total_ttc;
  2673. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  2674. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  2675. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  2676. if (!isset($total_ht_by_vats[$obj->vatrate])) $total_ht_by_vats[$obj->vatrate] = 0;
  2677. if (!isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate] = 0;
  2678. if (!isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate] = 0;
  2679. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  2680. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  2681. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  2682. if ($forcedroundingmode == '1') // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  2683. {
  2684. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  2685. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  2686. //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";
  2687. if ($diff)
  2688. {
  2689. if (abs($diff) > 0.1) {
  2690. $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.';
  2691. dol_syslog($errmsg, LOG_WARNING);
  2692. dol_print_error('', $errmsg);
  2693. exit;
  2694. }
  2695. $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;
  2696. 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);
  2697. $resqlfix = $this->db->query($sqlfix);
  2698. if (!$resqlfix) dol_print_error($this->db, 'Failed to update line');
  2699. $this->total_tva -= $diff;
  2700. $this->total_ttc -= $diff;
  2701. $total_tva_by_vats[$obj->vatrate] -= $diff;
  2702. $total_ttc_by_vats[$obj->vatrate] -= $diff;
  2703. }
  2704. }
  2705. $i++;
  2706. }
  2707. // Add revenue stamp to total
  2708. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  2709. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  2710. // Situations totals
  2711. if ($this->situation_cycle_ref && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE)
  2712. {
  2713. $prev_sits = $this->get_prev_sits();
  2714. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  2715. $this->total_ht -= $sit->total_ht;
  2716. $this->total_tva -= $sit->total_tva;
  2717. $this->total_localtax1 -= $sit->total_localtax1;
  2718. $this->total_localtax2 -= $sit->total_localtax2;
  2719. $this->total_ttc -= $sit->total_ttc;
  2720. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  2721. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  2722. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  2723. }
  2724. }
  2725. $this->db->free($resql);
  2726. // Now update global field total_ht, total_ttc and tva
  2727. $fieldht = 'total_ht';
  2728. $fieldtva = 'tva';
  2729. $fieldlocaltax1 = 'localtax1';
  2730. $fieldlocaltax2 = 'localtax2';
  2731. $fieldttc = 'total_ttc';
  2732. // Specific code for backward compatibility with old field names
  2733. if ($this->element == 'facture' || $this->element == 'facturerec') $fieldht = 'total';
  2734. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva = 'total_tva';
  2735. if ($this->element == 'propal') $fieldttc = 'total';
  2736. if ($this->element == 'expensereport') $fieldtva = 'total_tva';
  2737. if ($this->element == 'supplier_proposal') $fieldttc = 'total';
  2738. if (empty($nodatabaseupdate))
  2739. {
  2740. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
  2741. $sql .= " ".$fieldht."='".price2num($this->total_ht)."',";
  2742. $sql .= " ".$fieldtva."='".price2num($this->total_tva)."',";
  2743. $sql .= " ".$fieldlocaltax1."='".price2num($this->total_localtax1)."',";
  2744. $sql .= " ".$fieldlocaltax2."='".price2num($this->total_localtax2)."',";
  2745. $sql .= " ".$fieldttc."='".price2num($this->total_ttc)."'";
  2746. $sql .= ", multicurrency_total_ht='".price2num($this->multicurrency_total_ht, 'MT', 1)."'";
  2747. $sql .= ", multicurrency_total_tva='".price2num($this->multicurrency_total_tva, 'MT', 1)."'";
  2748. $sql .= ", multicurrency_total_ttc='".price2num($this->multicurrency_total_ttc, 'MT', 1)."'";
  2749. $sql .= ' WHERE rowid = '.$this->id;
  2750. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  2751. $resql = $this->db->query($sql);
  2752. if (!$resql)
  2753. {
  2754. $error++;
  2755. $this->error = $this->db->lasterror();
  2756. $this->errors[] = $this->db->lasterror();
  2757. }
  2758. }
  2759. if (!$error)
  2760. {
  2761. return 1;
  2762. } else {
  2763. return -1;
  2764. }
  2765. } else {
  2766. dol_print_error($this->db, 'Bad request in update_price');
  2767. return -1;
  2768. }
  2769. }
  2770. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2771. /**
  2772. * Add objects linked in llx_element_element.
  2773. *
  2774. * @param string $origin Linked element type
  2775. * @param int $origin_id Linked element id
  2776. * @return int <=0 if KO, >0 if OK
  2777. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  2778. */
  2779. public function add_object_linked($origin = null, $origin_id = null)
  2780. {
  2781. // phpcs:enable
  2782. $origin = (!empty($origin) ? $origin : $this->origin);
  2783. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  2784. // Special case
  2785. if ($origin == 'order') $origin = 'commande';
  2786. if ($origin == 'invoice') $origin = 'facture';
  2787. if ($origin == 'invoice_template') $origin = 'facturerec';
  2788. if ($origin == 'supplierorder') $origin = 'order_supplier';
  2789. $this->db->begin();
  2790. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
  2791. $sql .= "fk_source";
  2792. $sql .= ", sourcetype";
  2793. $sql .= ", fk_target";
  2794. $sql .= ", targettype";
  2795. $sql .= ") VALUES (";
  2796. $sql .= $origin_id;
  2797. $sql .= ", '".$this->db->escape($origin)."'";
  2798. $sql .= ", ".$this->id;
  2799. $sql .= ", '".$this->db->escape($this->element)."'";
  2800. $sql .= ")";
  2801. dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG);
  2802. if ($this->db->query($sql))
  2803. {
  2804. $this->db->commit();
  2805. return 1;
  2806. } else {
  2807. $this->error = $this->db->lasterror();
  2808. $this->db->rollback();
  2809. return 0;
  2810. }
  2811. }
  2812. /**
  2813. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  2814. * this->linkedObjectsIds array and
  2815. * this->linkedObjects array if $loadalsoobjects = 1
  2816. * Possible usage for parameters:
  2817. * - all parameters empty -> we look all link to current object (current object can be source or target)
  2818. * - source id+type -> will get target list linked to source
  2819. * - target id+type -> will get source list linked to target
  2820. * - source id+type + target type -> will get target list of the type
  2821. * - target id+type + target source -> will get source list of the type
  2822. *
  2823. * @param int $sourceid Object source id (if not defined, id of object)
  2824. * @param string $sourcetype Object source type (if not defined, element name of object)
  2825. * @param int $targetid Object target id (if not defined, id of object)
  2826. * @param string $targettype Object target type (if not defined, elemennt name of object)
  2827. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  2828. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  2829. * @param string $orderby SQL 'ORDER BY' clause
  2830. * @param int $loadalsoobjects Load also array this->linkedObjects (Use 0 to increase performances)
  2831. * @return int <0 if KO, >0 if OK
  2832. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  2833. */
  2834. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  2835. {
  2836. global $conf;
  2837. $this->linkedObjectsIds = array();
  2838. $this->linkedObjects = array();
  2839. $justsource = false;
  2840. $justtarget = false;
  2841. $withtargettype = false;
  2842. $withsourcetype = false;
  2843. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid))
  2844. {
  2845. $justsource = true; // the source (id and type) is a search criteria
  2846. if (!empty($targettype)) $withtargettype = true;
  2847. }
  2848. if (!empty($targetid) && !empty($targettype) && empty($sourceid))
  2849. {
  2850. $justtarget = true; // the target (id and type) is a search criteria
  2851. if (!empty($sourcetype)) $withsourcetype = true;
  2852. }
  2853. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  2854. $targetid = (!empty($targetid) ? $targetid : $this->id);
  2855. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  2856. $targettype = (!empty($targettype) ? $targettype : $this->element);
  2857. /*if (empty($sourceid) && empty($targetid))
  2858. {
  2859. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  2860. return -1;
  2861. }*/
  2862. // Links between objects are stored in table element_element
  2863. $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype';
  2864. $sql .= ' FROM '.MAIN_DB_PREFIX.'element_element';
  2865. $sql .= " WHERE ";
  2866. if ($justsource || $justtarget)
  2867. {
  2868. if ($justsource)
  2869. {
  2870. $sql .= "fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  2871. if ($withtargettype) $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
  2872. } elseif ($justtarget)
  2873. {
  2874. $sql .= "fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."'";
  2875. if ($withsourcetype) $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
  2876. }
  2877. } else {
  2878. $sql .= "(fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."')";
  2879. $sql .= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."')";
  2880. }
  2881. $sql .= ' ORDER BY '.$orderby;
  2882. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  2883. $resql = $this->db->query($sql);
  2884. if ($resql)
  2885. {
  2886. $num = $this->db->num_rows($resql);
  2887. $i = 0;
  2888. while ($i < $num)
  2889. {
  2890. $obj = $this->db->fetch_object($resql);
  2891. if ($justsource || $justtarget)
  2892. {
  2893. if ($justsource)
  2894. {
  2895. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  2896. } elseif ($justtarget)
  2897. {
  2898. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  2899. }
  2900. } else {
  2901. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype)
  2902. {
  2903. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  2904. }
  2905. if ($obj->fk_target == $targetid && $obj->targettype == $targettype)
  2906. {
  2907. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  2908. }
  2909. }
  2910. $i++;
  2911. }
  2912. if (!empty($this->linkedObjectsIds))
  2913. {
  2914. $tmparray = $this->linkedObjectsIds;
  2915. foreach ($tmparray as $objecttype => $objectids) // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  2916. {
  2917. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  2918. $module = $element = $subelement = $objecttype;
  2919. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  2920. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs))
  2921. {
  2922. $module = $element = $regs[1];
  2923. $subelement = $regs[2];
  2924. }
  2925. $classpath = $element.'/class';
  2926. // To work with non standard classpath or module name
  2927. if ($objecttype == 'facture') {
  2928. $classpath = 'compta/facture/class';
  2929. } elseif ($objecttype == 'facturerec') {
  2930. $classpath = 'compta/facture/class'; $module = 'facture';
  2931. } elseif ($objecttype == 'propal') {
  2932. $classpath = 'comm/propal/class';
  2933. } elseif ($objecttype == 'supplier_proposal') {
  2934. $classpath = 'supplier_proposal/class';
  2935. } elseif ($objecttype == 'shipping') {
  2936. $classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon';
  2937. } elseif ($objecttype == 'delivery') {
  2938. $classpath = 'delivery/class'; $subelement = 'delivery'; $module = 'delivery_note';
  2939. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  2940. $classpath = 'fourn/class'; $module = 'fournisseur';
  2941. } elseif ($objecttype == 'fichinter') {
  2942. $classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter';
  2943. } elseif ($objecttype == 'subscription') {
  2944. $classpath = 'adherents/class'; $module = 'adherent';
  2945. } elseif ($objecttype == 'contact') {
  2946. $module = 'societe';
  2947. }
  2948. // Set classfile
  2949. $classfile = strtolower($subelement); $classname = ucfirst($subelement);
  2950. if ($objecttype == 'order') {
  2951. $classfile = 'commande'; $classname = 'Commande';
  2952. } elseif ($objecttype == 'invoice_supplier') {
  2953. $classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur';
  2954. } elseif ($objecttype == 'order_supplier') {
  2955. $classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur';
  2956. } elseif ($objecttype == 'supplier_proposal') {
  2957. $classfile = 'supplier_proposal'; $classname = 'SupplierProposal';
  2958. } elseif ($objecttype == 'facturerec') {
  2959. $classfile = 'facture-rec'; $classname = 'FactureRec';
  2960. } elseif ($objecttype == 'subscription') {
  2961. $classfile = 'subscription'; $classname = 'Subscription';
  2962. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  2963. $classpath = 'projet/class'; $classfile = 'project'; $classname = 'Project';
  2964. }
  2965. // Here $module, $classfile and $classname are set
  2966. if ($conf->$module->enabled && (($element != $this->element) || $alsosametype))
  2967. {
  2968. if ($loadalsoobjects)
  2969. {
  2970. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  2971. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  2972. if (class_exists($classname))
  2973. {
  2974. foreach ($objectids as $i => $objectid) // $i is rowid into llx_element_element
  2975. {
  2976. $object = new $classname($this->db);
  2977. $ret = $object->fetch($objectid);
  2978. if ($ret >= 0)
  2979. {
  2980. $this->linkedObjects[$objecttype][$i] = $object;
  2981. }
  2982. }
  2983. }
  2984. }
  2985. } else {
  2986. unset($this->linkedObjectsIds[$objecttype]);
  2987. }
  2988. }
  2989. }
  2990. return 1;
  2991. } else {
  2992. dol_print_error($this->db);
  2993. return -1;
  2994. }
  2995. }
  2996. /**
  2997. * Update object linked of a current object
  2998. *
  2999. * @param int $sourceid Object source id
  3000. * @param string $sourcetype Object source type
  3001. * @param int $targetid Object target id
  3002. * @param string $targettype Object target type
  3003. * @return int >0 if OK, <0 if KO
  3004. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3005. */
  3006. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '')
  3007. {
  3008. $updatesource = false;
  3009. $updatetarget = false;
  3010. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) $updatesource = true;
  3011. elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) $updatetarget = true;
  3012. $sql = "UPDATE ".MAIN_DB_PREFIX."element_element SET ";
  3013. if ($updatesource)
  3014. {
  3015. $sql .= "fk_source = ".$sourceid;
  3016. $sql .= ", sourcetype = '".$this->db->escape($sourcetype)."'";
  3017. $sql .= " WHERE fk_target = ".$this->id;
  3018. $sql .= " AND targettype = '".$this->db->escape($this->element)."'";
  3019. } elseif ($updatetarget)
  3020. {
  3021. $sql .= "fk_target = ".$targetid;
  3022. $sql .= ", targettype = '".$this->db->escape($targettype)."'";
  3023. $sql .= " WHERE fk_source = ".$this->id;
  3024. $sql .= " AND sourcetype = '".$this->db->escape($this->element)."'";
  3025. }
  3026. dol_syslog(get_class($this)."::updateObjectLinked", LOG_DEBUG);
  3027. if ($this->db->query($sql))
  3028. {
  3029. return 1;
  3030. } else {
  3031. $this->error = $this->db->lasterror();
  3032. return -1;
  3033. }
  3034. }
  3035. /**
  3036. * Delete all links between an object $this
  3037. *
  3038. * @param int $sourceid Object source id
  3039. * @param string $sourcetype Object source type
  3040. * @param int $targetid Object target id
  3041. * @param string $targettype Object target type
  3042. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3043. * @return int >0 if OK, <0 if KO
  3044. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3045. */
  3046. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '')
  3047. {
  3048. $deletesource = false;
  3049. $deletetarget = false;
  3050. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) $deletesource = true;
  3051. elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) $deletetarget = true;
  3052. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3053. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3054. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3055. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3056. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_element";
  3057. $sql .= " WHERE";
  3058. if ($rowid > 0)
  3059. {
  3060. $sql .= " rowid = ".$rowid;
  3061. } else {
  3062. if ($deletesource)
  3063. {
  3064. $sql .= " fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3065. $sql .= " AND fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."'";
  3066. } elseif ($deletetarget)
  3067. {
  3068. $sql .= " fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."'";
  3069. $sql .= " AND fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."'";
  3070. } else {
  3071. $sql .= " (fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."')";
  3072. $sql .= " OR";
  3073. $sql .= " (fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."')";
  3074. }
  3075. }
  3076. dol_syslog(get_class($this)."::deleteObjectLinked", LOG_DEBUG);
  3077. if ($this->db->query($sql))
  3078. {
  3079. return 1;
  3080. } else {
  3081. $this->error = $this->db->lasterror();
  3082. $this->errors[] = $this->error;
  3083. return -1;
  3084. }
  3085. }
  3086. /**
  3087. * Set status of an object
  3088. *
  3089. * @param int $status Status to set
  3090. * @param int $elementId Id of element to force (use this->id by default)
  3091. * @param string $elementType Type of element to force (use this->table_element by default)
  3092. * @param string $trigkey Trigger key to use for trigger
  3093. * @return int <0 if KO, >0 if OK
  3094. */
  3095. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '')
  3096. {
  3097. global $user, $langs, $conf;
  3098. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3099. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3100. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3101. $this->db->begin();
  3102. $fieldstatus = "fk_statut";
  3103. if ($elementTable == 'facture_rec') $fieldstatus = "suspended";
  3104. if ($elementTable == 'mailing') $fieldstatus = "statut";
  3105. if ($elementTable == 'cronjob') $fieldstatus = "status";
  3106. if ($elementTable == 'user') $fieldstatus = "statut";
  3107. if ($elementTable == 'expensereport') $fieldstatus = "fk_statut";
  3108. if ($elementTable == 'commande_fournisseur_dispatch') $fieldstatus = "status";
  3109. if (is_array($this->fields) && array_key_exists('status', $this->fields)) $fieldstatus = 'status';
  3110. $sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable;
  3111. $sql .= " SET ".$fieldstatus." = ".$status;
  3112. // If status = 1 = validated, update also fk_user_valid
  3113. if ($status == 1 && $elementTable == 'expensereport') $sql .= ", fk_user_valid = ".$user->id;
  3114. $sql .= " WHERE rowid=".$elementId;
  3115. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  3116. if ($this->db->query($sql))
  3117. {
  3118. $error = 0;
  3119. // Try autoset of trigkey
  3120. if (empty($trigkey))
  3121. {
  3122. if ($this->element == 'supplier_proposal' && $status == 2) $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3123. if ($this->element == 'supplier_proposal' && $status == 3) $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3124. if ($this->element == 'supplier_proposal' && $status == 4) $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3125. if ($this->element == 'fichinter' && $status == 3) $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3126. if ($this->element == 'fichinter' && $status == 2) $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3127. if ($this->element == 'fichinter' && $status == 1) $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3128. }
  3129. if ($trigkey)
  3130. {
  3131. // Call trigger
  3132. $result = $this->call_trigger($trigkey, $user);
  3133. if ($result < 0) $error++;
  3134. // End call triggers
  3135. }
  3136. if (!$error)
  3137. {
  3138. $this->db->commit();
  3139. if (empty($savElementId)) // If the element we update was $this (so $elementId is null)
  3140. {
  3141. $this->statut = $status;
  3142. $this->status = $status;
  3143. }
  3144. return 1;
  3145. } else {
  3146. $this->db->rollback();
  3147. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  3148. return -1;
  3149. }
  3150. } else {
  3151. $this->error = $this->db->lasterror();
  3152. $this->db->rollback();
  3153. return -1;
  3154. }
  3155. }
  3156. /**
  3157. * Load type of canvas of an object if it exists
  3158. *
  3159. * @param int $id Record id
  3160. * @param string $ref Record ref
  3161. * @return int <0 if KO, 0 if nothing done, >0 if OK
  3162. */
  3163. public function getCanvas($id = 0, $ref = '')
  3164. {
  3165. global $conf;
  3166. if (empty($id) && empty($ref)) return 0;
  3167. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) return 0; // To increase speed. Not enabled by default.
  3168. // Clean parameters
  3169. $ref = trim($ref);
  3170. $sql = "SELECT rowid, canvas";
  3171. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
  3172. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  3173. if (!empty($id)) $sql .= " AND rowid = ".$id;
  3174. if (!empty($ref)) $sql .= " AND ref = '".$this->db->escape($ref)."'";
  3175. $resql = $this->db->query($sql);
  3176. if ($resql)
  3177. {
  3178. $obj = $this->db->fetch_object($resql);
  3179. if ($obj)
  3180. {
  3181. $this->canvas = $obj->canvas;
  3182. return 1;
  3183. } else return 0;
  3184. } else {
  3185. dol_print_error($this->db);
  3186. return -1;
  3187. }
  3188. }
  3189. /**
  3190. * Get special code of a line
  3191. *
  3192. * @param int $lineid Id of line
  3193. * @return int Special code
  3194. */
  3195. public function getSpecialCode($lineid)
  3196. {
  3197. $sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  3198. $sql .= ' WHERE rowid = '.$lineid;
  3199. $resql = $this->db->query($sql);
  3200. if ($resql)
  3201. {
  3202. $row = $this->db->fetch_row($resql);
  3203. return $row[0];
  3204. }
  3205. }
  3206. /**
  3207. * Function to check if an object is used by others.
  3208. * Check is done into this->childtables. There is no check into llx_element_element.
  3209. *
  3210. * @param int $id Force id of object
  3211. * @return int <0 if KO, 0 if not used, >0 if already used
  3212. */
  3213. public function isObjectUsed($id = 0)
  3214. {
  3215. global $langs;
  3216. if (empty($id)) $id = $this->id;
  3217. // Check parameters
  3218. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0)
  3219. {
  3220. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  3221. return -1;
  3222. }
  3223. $arraytoscan = $this->childtables;
  3224. // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
  3225. $tmparray = array_keys($this->childtables);
  3226. if (is_numeric($tmparray[0]))
  3227. {
  3228. $arraytoscan = array_flip($this->childtables);
  3229. }
  3230. // Test if child exists
  3231. $haschild = 0;
  3232. foreach ($arraytoscan as $table => $elementname)
  3233. {
  3234. //print $id.'-'.$table.'-'.$elementname.'<br>';
  3235. // Check if third party can be deleted
  3236. $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table;
  3237. $sql .= " WHERE ".$this->fk_element." = ".$id;
  3238. $resql = $this->db->query($sql);
  3239. if ($resql)
  3240. {
  3241. $obj = $this->db->fetch_object($resql);
  3242. if ($obj->nb > 0)
  3243. {
  3244. $langs->load("errors");
  3245. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  3246. $haschild += $obj->nb;
  3247. if (is_numeric($elementname)) // old usage
  3248. {
  3249. $this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table);
  3250. } else // new usage: $elementname=Translation key
  3251. {
  3252. $this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname));
  3253. }
  3254. break; // We found at least one, we stop here
  3255. }
  3256. } else {
  3257. $this->errors[] = $this->db->lasterror();
  3258. return -1;
  3259. }
  3260. }
  3261. if ($haschild > 0)
  3262. {
  3263. $this->errors[] = "ErrorRecordHasChildren";
  3264. return $haschild;
  3265. } else return 0;
  3266. }
  3267. /**
  3268. * Function to say how many lines object contains
  3269. *
  3270. * @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
  3271. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  3272. */
  3273. public function hasProductsOrServices($predefined = -1)
  3274. {
  3275. $nb = 0;
  3276. foreach ($this->lines as $key => $val)
  3277. {
  3278. $qualified = 0;
  3279. if ($predefined == -1) $qualified = 1;
  3280. if ($predefined == 1 && $val->fk_product > 0) $qualified = 1;
  3281. if ($predefined == 0 && $val->fk_product <= 0) $qualified = 1;
  3282. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) $qualified = 1;
  3283. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) $qualified = 1;
  3284. if ($qualified) $nb++;
  3285. }
  3286. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  3287. return $nb;
  3288. }
  3289. /**
  3290. * Function that returns the total amount HT of discounts applied for all lines.
  3291. *
  3292. * @return float
  3293. */
  3294. public function getTotalDiscount()
  3295. {
  3296. $total_discount = 0.00;
  3297. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  3298. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element."det";
  3299. $sql .= " WHERE ".$this->fk_element." = ".$this->id;
  3300. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  3301. $resql = $this->db->query($sql);
  3302. if ($resql)
  3303. {
  3304. $num = $this->db->num_rows($resql);
  3305. $i = 0;
  3306. while ($i < $num)
  3307. {
  3308. $obj = $this->db->fetch_object($resql);
  3309. $pu_ht = $obj->pu_ht;
  3310. $qty = $obj->qty;
  3311. $total_ht = $obj->total_ht;
  3312. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  3313. $total_discount += $total_discount_line;
  3314. $i++;
  3315. }
  3316. }
  3317. //print $total_discount; exit;
  3318. return price2num($total_discount);
  3319. }
  3320. /**
  3321. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  3322. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  3323. *
  3324. * @return array array('weight'=>...,'volume'=>...)
  3325. */
  3326. public function getTotalWeightVolume()
  3327. {
  3328. $totalWeight = 0;
  3329. $totalVolume = 0;
  3330. // defined for shipment only
  3331. $totalOrdered = '';
  3332. // defined for shipment only
  3333. $totalToShip = '';
  3334. foreach ($this->lines as $line)
  3335. {
  3336. if (isset($line->qty_asked))
  3337. {
  3338. if (empty($totalOrdered)) $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  3339. $totalOrdered += $line->qty_asked; // defined for shipment only
  3340. }
  3341. if (isset($line->qty_shipped))
  3342. {
  3343. if (empty($totalToShip)) $totalToShip = 0; // Avoid warning because $totalToShip is ''
  3344. $totalToShip += $line->qty_shipped; // defined for shipment only
  3345. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty))
  3346. {
  3347. if (empty($totalToShip)) $totalToShip = 0;
  3348. $totalToShip += $line->qty; // defined for reception only
  3349. }
  3350. // Define qty, weight, volume, weight_units, volume_units
  3351. if ($this->element == 'shipping') {
  3352. // for shipments
  3353. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  3354. } else {
  3355. $qty = $line->qty ? $line->qty : 0;
  3356. }
  3357. $weight = $line->weight ? $line->weight : 0;
  3358. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  3359. $volume = $line->volume ? $line->volume : 0;
  3360. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  3361. $weight_units = $line->weight_units;
  3362. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  3363. $volume_units = $line->volume_units;
  3364. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  3365. $weightUnit = 0;
  3366. $volumeUnit = 0;
  3367. if (!empty($weight_units)) $weightUnit = $weight_units;
  3368. if (!empty($volume_units)) $volumeUnit = $volume_units;
  3369. if (empty($totalWeight)) $totalWeight = 0; // Avoid warning because $totalWeight is ''
  3370. if (empty($totalVolume)) $totalVolume = 0; // Avoid warning because $totalVolume is ''
  3371. //var_dump($line->volume_units);
  3372. if ($weight_units < 50) // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  3373. {
  3374. $trueWeightUnit = pow(10, $weightUnit);
  3375. $totalWeight += $weight * $qty * $trueWeightUnit;
  3376. } else {
  3377. if ($weight_units == 99) {
  3378. // conversion 1 Pound = 0.45359237 KG
  3379. $trueWeightUnit = 0.45359237;
  3380. $totalWeight += $weight * $qty * $trueWeightUnit;
  3381. } elseif ($weight_units == 98) {
  3382. // conversion 1 Ounce = 0.0283495 KG
  3383. $trueWeightUnit = 0.0283495;
  3384. $totalWeight += $weight * $qty * $trueWeightUnit;
  3385. } else {
  3386. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  3387. }
  3388. }
  3389. if ($volume_units < 50) // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  3390. {
  3391. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  3392. $trueVolumeUnit = pow(10, $volumeUnit);
  3393. //print $line->volume;
  3394. $totalVolume += $volume * $qty * $trueVolumeUnit;
  3395. } else {
  3396. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  3397. }
  3398. }
  3399. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  3400. }
  3401. /**
  3402. * Set extra parameters
  3403. *
  3404. * @return int <0 if KO, >0 if OK
  3405. */
  3406. public function setExtraParameters()
  3407. {
  3408. $this->db->begin();
  3409. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  3410. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  3411. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  3412. $sql .= " WHERE rowid = ".$this->id;
  3413. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  3414. $resql = $this->db->query($sql);
  3415. if (!$resql)
  3416. {
  3417. $this->error = $this->db->lasterror();
  3418. $this->db->rollback();
  3419. return -1;
  3420. } else {
  3421. $this->db->commit();
  3422. return 1;
  3423. }
  3424. }
  3425. // --------------------
  3426. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  3427. // --------------------
  3428. /* This is to show add lines */
  3429. /**
  3430. * Show add free and predefined products/services form
  3431. *
  3432. * @param int $dateSelector 1=Show also date range input fields
  3433. * @param Societe $seller Object thirdparty who sell
  3434. * @param Societe $buyer Object thirdparty who buy
  3435. * @param string $defaulttpldir Directory where to find the template
  3436. * @return void
  3437. */
  3438. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  3439. {
  3440. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  3441. global $form;
  3442. // Line extrafield
  3443. if (!is_object($extrafields))
  3444. {
  3445. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  3446. $extrafields = new ExtraFields($this->db);
  3447. }
  3448. $extrafields->fetch_name_optionals_label($this->table_element_line);
  3449. // Output template part (modules that overwrite templates must declare this into descriptor)
  3450. // Use global variables + $dateSelector + $seller and $buyer
  3451. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  3452. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  3453. foreach ($dirtpls as $module => $reldir)
  3454. {
  3455. if (!empty($module))
  3456. {
  3457. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  3458. } else {
  3459. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  3460. }
  3461. if (empty($conf->file->strict_mode)) {
  3462. $res = @include $tpl;
  3463. } else {
  3464. $res = include $tpl; // for debug
  3465. }
  3466. if ($res) break;
  3467. }
  3468. }
  3469. /* This is to show array of line of details */
  3470. /**
  3471. * Return HTML table for object lines
  3472. * TODO Move this into an output class file (htmlline.class.php)
  3473. * If lines are into a template, title must also be into a template
  3474. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  3475. *
  3476. * @param string $action Action code
  3477. * @param string $seller Object of seller third party
  3478. * @param string $buyer Object of buyer third party
  3479. * @param int $selected Object line selected
  3480. * @param int $dateSelector 1=Show also date range input fields
  3481. * @param string $defaulttpldir Directory where to find the template
  3482. * @return void
  3483. */
  3484. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  3485. {
  3486. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  3487. // TODO We should not use global var for this
  3488. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  3489. // Define usemargins
  3490. $usemargins = 0;
  3491. if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) $usemargins = 1;
  3492. $num = count($this->lines);
  3493. // Line extrafield
  3494. if (!is_object($extrafields))
  3495. {
  3496. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  3497. $extrafields = new ExtraFields($this->db);
  3498. }
  3499. $extrafields->fetch_name_optionals_label($this->table_element_line);
  3500. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  3501. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3502. if (empty($reshook))
  3503. {
  3504. // Output template part (modules that overwrite templates must declare this into descriptor)
  3505. // Use global variables + $dateSelector + $seller and $buyer
  3506. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  3507. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  3508. foreach ($dirtpls as $module => $reldir)
  3509. {
  3510. if (!empty($module))
  3511. {
  3512. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  3513. } else {
  3514. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  3515. }
  3516. if (empty($conf->file->strict_mode)) {
  3517. $res = @include $tpl;
  3518. } else {
  3519. $res = include $tpl; // for debug
  3520. }
  3521. if ($res) break;
  3522. }
  3523. }
  3524. $i = 0;
  3525. print "<!-- begin printObjectLines() --><tbody>\n";
  3526. foreach ($this->lines as $line)
  3527. {
  3528. //Line extrafield
  3529. $line->fetch_optionals();
  3530. //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  3531. if (is_object($hookmanager)) // Old code is commented on preceding line.
  3532. {
  3533. if (empty($line->fk_parent_line))
  3534. {
  3535. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  3536. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3537. } else {
  3538. $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);
  3539. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3540. }
  3541. }
  3542. if (empty($reshook))
  3543. {
  3544. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  3545. }
  3546. $i++;
  3547. }
  3548. print "</tbody><!-- end printObjectLines() -->\n";
  3549. }
  3550. /**
  3551. * Return HTML content of a detail line
  3552. * TODO Move this into an output class file (htmlline.class.php)
  3553. *
  3554. * @param string $action GET/POST action
  3555. * @param CommonObjectLine $line Selected object line to output
  3556. * @param string $var Is it a an odd line (true)
  3557. * @param int $num Number of line (0)
  3558. * @param int $i I
  3559. * @param int $dateSelector 1=Show also date range input fields
  3560. * @param string $seller Object of seller third party
  3561. * @param string $buyer Object of buyer third party
  3562. * @param int $selected Object line selected
  3563. * @param Extrafields $extrafields Object of extrafields
  3564. * @param string $defaulttpldir Directory where to find the template (deprecated)
  3565. * @return void
  3566. */
  3567. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  3568. {
  3569. global $conf, $langs, $user, $object, $hookmanager;
  3570. global $form;
  3571. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  3572. $object_rights = $this->getRights();
  3573. $element = $this->element;
  3574. $text = ''; $description = '';
  3575. // Line in view mode
  3576. if ($action != 'editline' || $selected != $line->id)
  3577. {
  3578. // Product
  3579. if ($line->fk_product > 0)
  3580. {
  3581. $product_static = new Product($this->db);
  3582. $product_static->fetch($line->fk_product);
  3583. $product_static->ref = $line->ref; //can change ref in hook
  3584. $product_static->label = $line->label; //can change label in hook
  3585. $text = $product_static->getNomUrl(1);
  3586. // Define output language and label
  3587. if (!empty($conf->global->MAIN_MULTILANGS))
  3588. {
  3589. if (property_exists($this, 'socid') && !is_object($this->thirdparty))
  3590. {
  3591. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  3592. return;
  3593. }
  3594. $prod = new Product($this->db);
  3595. $prod->fetch($line->fk_product);
  3596. $outputlangs = $langs;
  3597. $newlang = '';
  3598. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
  3599. 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
  3600. if (!empty($newlang))
  3601. {
  3602. $outputlangs = new Translate("", $conf);
  3603. $outputlangs->setDefaultLang($newlang);
  3604. }
  3605. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  3606. } else {
  3607. $label = $line->product_label;
  3608. }
  3609. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  3610. $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.
  3611. }
  3612. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  3613. // Output template part (modules that overwrite templates must declare this into descriptor)
  3614. // Use global variables + $dateSelector + $seller and $buyer
  3615. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  3616. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  3617. foreach ($dirtpls as $module => $reldir)
  3618. {
  3619. if (!empty($module))
  3620. {
  3621. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  3622. } else {
  3623. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  3624. }
  3625. if (empty($conf->file->strict_mode)) {
  3626. $res = @include $tpl;
  3627. } else {
  3628. $res = include $tpl; // for debug
  3629. }
  3630. if ($res) break;
  3631. }
  3632. }
  3633. // Line in update mode
  3634. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id)
  3635. {
  3636. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  3637. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  3638. // Output template part (modules that overwrite templates must declare this into descriptor)
  3639. // Use global variables + $dateSelector + $seller and $buyer
  3640. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  3641. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  3642. foreach ($dirtpls as $module => $reldir)
  3643. {
  3644. if (!empty($module))
  3645. {
  3646. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  3647. } else {
  3648. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  3649. }
  3650. if (empty($conf->file->strict_mode)) {
  3651. $res = @include $tpl;
  3652. } else {
  3653. $res = include $tpl; // for debug
  3654. }
  3655. if ($res) break;
  3656. }
  3657. }
  3658. }
  3659. /* This is to show array of line of details of source object */
  3660. /**
  3661. * Return HTML table table of source object lines
  3662. * TODO Move this and previous function into output html class file (htmlline.class.php).
  3663. * If lines are into a template, title must also be into a template
  3664. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  3665. *
  3666. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  3667. * @param array $selectedLines Array of lines id for selected lines
  3668. * @return void
  3669. */
  3670. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  3671. {
  3672. global $langs, $hookmanager, $conf, $form;
  3673. print '<tr class="liste_titre">';
  3674. print '<td>'.$langs->trans('Ref').'</td>';
  3675. print '<td>'.$langs->trans('Description').'</td>';
  3676. print '<td class="right">'.$langs->trans('VATRate').'</td>';
  3677. print '<td class="right">'.$langs->trans('PriceUHT').'</td>';
  3678. if (!empty($conf->multicurrency->enabled)) print '<td class="right">'.$langs->trans('PriceUHTCurrency').'</td>';
  3679. print '<td class="right">'.$langs->trans('Qty').'</td>';
  3680. if ($conf->global->PRODUCT_USE_UNITS)
  3681. {
  3682. print '<td class="left">'.$langs->trans('Unit').'</td>';
  3683. }
  3684. print '<td class="right">'.$langs->trans('ReductionShort').'</td>';
  3685. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  3686. print '</tr>';
  3687. $i = 0;
  3688. if (!empty($this->lines))
  3689. {
  3690. foreach ($this->lines as $line)
  3691. {
  3692. if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line)))
  3693. {
  3694. if (empty($line->fk_parent_line))
  3695. {
  3696. $parameters = array('line'=>$line, 'i'=>$i);
  3697. $action = '';
  3698. $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3699. }
  3700. } else {
  3701. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  3702. }
  3703. $i++;
  3704. }
  3705. }
  3706. }
  3707. /**
  3708. * Return HTML with a line of table array of source object lines
  3709. * TODO Move this and previous function into output html class file (htmlline.class.php).
  3710. * If lines are into a template, title must also be into a template
  3711. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  3712. *
  3713. * @param CommonObjectLine $line Line
  3714. * @param string $var Var
  3715. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  3716. * @param string $defaulttpldir Directory where to find the template
  3717. * @param array $selectedLines Array of lines id for selected lines
  3718. * @return void
  3719. */
  3720. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  3721. {
  3722. global $langs, $conf;
  3723. //var_dump($line);
  3724. if (!empty($line->date_start))
  3725. {
  3726. $date_start = $line->date_start;
  3727. } else {
  3728. $date_start = $line->date_debut_prevue;
  3729. if ($line->date_debut_reel) $date_start = $line->date_debut_reel;
  3730. }
  3731. if (!empty($line->date_end))
  3732. {
  3733. $date_end = $line->date_end;
  3734. } else {
  3735. $date_end = $line->date_fin_prevue;
  3736. if ($line->date_fin_reel) $date_end = $line->date_fin_reel;
  3737. }
  3738. $this->tpl['id'] = $line->id;
  3739. $this->tpl['label'] = '';
  3740. if (!empty($line->fk_parent_line)) $this->tpl['label'] .= img_picto('', 'rightarrow');
  3741. if (($line->info_bits & 2) == 2) // TODO Not sure this is used for source object
  3742. {
  3743. $discount = new DiscountAbsolute($this->db);
  3744. $discount->fk_soc = $this->socid;
  3745. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  3746. } elseif (!empty($line->fk_product))
  3747. {
  3748. $productstatic = new Product($this->db);
  3749. $productstatic->id = $line->fk_product;
  3750. $productstatic->ref = $line->ref;
  3751. $productstatic->type = $line->fk_product_type;
  3752. if (empty($productstatic->ref)) {
  3753. $line->fetch_product();
  3754. $productstatic = $line->product;
  3755. }
  3756. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  3757. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  3758. // Dates
  3759. if ($line->product_type == 1 && ($date_start || $date_end))
  3760. {
  3761. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  3762. }
  3763. } else {
  3764. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  3765. if (!empty($line->desc)) {
  3766. $this->tpl['label'] .= $line->desc;
  3767. } else {
  3768. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  3769. }
  3770. // Dates
  3771. if ($line->product_type == 1 && ($date_start || $date_end))
  3772. {
  3773. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  3774. }
  3775. }
  3776. if (!empty($line->desc))
  3777. {
  3778. if ($line->desc == '(CREDIT_NOTE)') // TODO Not sure this is used for source object
  3779. {
  3780. $discount = new DiscountAbsolute($this->db);
  3781. $discount->fetch($line->fk_remise_except);
  3782. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  3783. } elseif ($line->desc == '(DEPOSIT)') // TODO Not sure this is used for source object
  3784. {
  3785. $discount = new DiscountAbsolute($this->db);
  3786. $discount->fetch($line->fk_remise_except);
  3787. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  3788. } elseif ($line->desc == '(EXCESS RECEIVED)')
  3789. {
  3790. $discount = new DiscountAbsolute($this->db);
  3791. $discount->fetch($line->fk_remise_except);
  3792. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  3793. } elseif ($line->desc == '(EXCESS PAID)')
  3794. {
  3795. $discount = new DiscountAbsolute($this->db);
  3796. $discount->fetch($line->fk_remise_except);
  3797. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  3798. } else {
  3799. $this->tpl['description'] = dol_trunc($line->desc, 60);
  3800. }
  3801. } else {
  3802. $this->tpl['description'] = '&nbsp;';
  3803. }
  3804. // VAT Rate
  3805. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  3806. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  3807. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  3808. $this->tpl['price'] = price($line->subprice);
  3809. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  3810. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  3811. if ($conf->global->PRODUCT_USE_UNITS) $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  3812. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  3813. // Is the line strike or not
  3814. $this->tpl['strike'] = 0;
  3815. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) $this->tpl['strike'] = 1;
  3816. // Output template part (modules that overwrite templates must declare this into descriptor)
  3817. // Use global variables + $dateSelector + $seller and $buyer
  3818. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  3819. foreach ($dirtpls as $module => $reldir)
  3820. {
  3821. if (!empty($module))
  3822. {
  3823. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  3824. } else {
  3825. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  3826. }
  3827. if (empty($conf->file->strict_mode)) {
  3828. $res = @include $tpl;
  3829. } else {
  3830. $res = include $tpl; // for debug
  3831. }
  3832. if ($res) break;
  3833. }
  3834. }
  3835. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3836. /**
  3837. * Add resources to the current object : add entry into llx_element_resources
  3838. * Need $this->element & $this->id
  3839. *
  3840. * @param int $resource_id Resource id
  3841. * @param string $resource_type 'resource'
  3842. * @param int $busy Busy or not
  3843. * @param int $mandatory Mandatory or not
  3844. * @return int <=0 if KO, >0 if OK
  3845. */
  3846. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  3847. {
  3848. // phpcs:enable
  3849. $this->db->begin();
  3850. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources (";
  3851. $sql .= "resource_id";
  3852. $sql .= ", resource_type";
  3853. $sql .= ", element_id";
  3854. $sql .= ", element_type";
  3855. $sql .= ", busy";
  3856. $sql .= ", mandatory";
  3857. $sql .= ") VALUES (";
  3858. $sql .= $resource_id;
  3859. $sql .= ", '".$this->db->escape($resource_type)."'";
  3860. $sql .= ", '".$this->db->escape($this->id)."'";
  3861. $sql .= ", '".$this->db->escape($this->element)."'";
  3862. $sql .= ", '".$this->db->escape($busy)."'";
  3863. $sql .= ", '".$this->db->escape($mandatory)."'";
  3864. $sql .= ")";
  3865. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  3866. if ($this->db->query($sql))
  3867. {
  3868. $this->db->commit();
  3869. return 1;
  3870. } else {
  3871. $this->error = $this->db->lasterror();
  3872. $this->db->rollback();
  3873. return 0;
  3874. }
  3875. }
  3876. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3877. /**
  3878. * Delete a link to resource line
  3879. *
  3880. * @param int $rowid Id of resource line to delete
  3881. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  3882. * @param int $notrigger Disable all triggers
  3883. * @return int >0 if OK, <0 if KO
  3884. */
  3885. public function delete_resource($rowid, $element, $notrigger = 0)
  3886. {
  3887. // phpcs:enable
  3888. global $user;
  3889. $this->db->begin();
  3890. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
  3891. $sql .= " WHERE rowid=".$rowid;
  3892. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  3893. $resql = $this->db->query($sql);
  3894. if (!$resql)
  3895. {
  3896. $this->error = $this->db->lasterror();
  3897. $this->db->rollback();
  3898. return -1;
  3899. } else {
  3900. if (!$notrigger)
  3901. {
  3902. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  3903. if ($result < 0) { $this->db->rollback(); return -1; }
  3904. }
  3905. $this->db->commit();
  3906. return 1;
  3907. }
  3908. }
  3909. /**
  3910. * Overwrite magic function to solve problem of cloning object that are kept as references
  3911. *
  3912. * @return void
  3913. */
  3914. public function __clone()
  3915. {
  3916. // Force a copy of this->lines, otherwise it will point to same object.
  3917. if (isset($this->lines) && is_array($this->lines))
  3918. {
  3919. $nboflines = count($this->lines);
  3920. for ($i = 0; $i < $nboflines; $i++)
  3921. {
  3922. $this->lines[$i] = clone $this->lines[$i];
  3923. }
  3924. }
  3925. }
  3926. /**
  3927. * Common function for all objects extending CommonObject for generating documents
  3928. *
  3929. * @param string $modelspath Relative folder where generators are placed
  3930. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  3931. * @param Translate $outputlangs Output language to use
  3932. * @param int $hidedetails 1 to hide details. 0 by default
  3933. * @param int $hidedesc 1 to hide product description. 0 by default
  3934. * @param int $hideref 1 to hide product reference. 0 by default
  3935. * @param null|array $moreparams Array to provide more information
  3936. * @return int >0 if OK, <0 if KO
  3937. * @see addFileIntoDatabaseIndex()
  3938. */
  3939. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  3940. {
  3941. global $conf, $langs, $user, $hookmanager, $action;
  3942. $srctemplatepath = '';
  3943. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  3944. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3945. if (empty($reshook))
  3946. {
  3947. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  3948. // Increase limit for PDF build
  3949. $err = error_reporting();
  3950. error_reporting(0);
  3951. @set_time_limit(120);
  3952. error_reporting($err);
  3953. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  3954. $tmp = explode(':', $modele, 2);
  3955. if (!empty($tmp[1]))
  3956. {
  3957. $modele = $tmp[0];
  3958. $srctemplatepath = $tmp[1];
  3959. }
  3960. // Search template files
  3961. $file = '';
  3962. $classname = '';
  3963. $filefound = '';
  3964. $dirmodels = array('/');
  3965. if (is_array($conf->modules_parts['models'])) $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  3966. foreach ($dirmodels as $reldir)
  3967. {
  3968. foreach (array('doc', 'pdf') as $prefix)
  3969. {
  3970. if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php"; // Member module use prefix_module.class.php
  3971. else $file = $prefix."_".$modele.".modules.php";
  3972. // On verifie l'emplacement du modele
  3973. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  3974. if (file_exists($file))
  3975. {
  3976. $filefound = $file;
  3977. $classname = $prefix.'_'.$modele;
  3978. break;
  3979. }
  3980. }
  3981. if ($filefound) break;
  3982. }
  3983. // If generator was found
  3984. if ($filefound)
  3985. {
  3986. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  3987. require_once $file;
  3988. $obj = new $classname($this->db);
  3989. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  3990. if ($obj->type == 'odt' && empty($srctemplatepath))
  3991. {
  3992. $varfortemplatedir = $obj->scandir;
  3993. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir))
  3994. {
  3995. $dirtoscan = $conf->global->$varfortemplatedir;
  3996. $listoffiles = array();
  3997. // Now we add first model found in directories scanned
  3998. $listofdir = explode(',', $dirtoscan);
  3999. foreach ($listofdir as $key => $tmpdir)
  4000. {
  4001. $tmpdir = trim($tmpdir);
  4002. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4003. if (!$tmpdir) { unset($listofdir[$key]); continue; }
  4004. if (is_dir($tmpdir))
  4005. {
  4006. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4007. if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles);
  4008. }
  4009. }
  4010. if (count($listoffiles))
  4011. {
  4012. foreach ($listoffiles as $record)
  4013. {
  4014. $srctemplatepath = $record['fullname'];
  4015. break;
  4016. }
  4017. }
  4018. }
  4019. if (empty($srctemplatepath))
  4020. {
  4021. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4022. return -1;
  4023. }
  4024. }
  4025. if ($obj->type == 'odt' && !empty($srctemplatepath))
  4026. {
  4027. if (!dol_is_file($srctemplatepath))
  4028. {
  4029. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  4030. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4031. return -1;
  4032. }
  4033. }
  4034. // We save charset_output to restore it because write_file can change it if needed for
  4035. // output format that does not support UTF8.
  4036. $sav_charset_output = $outputlangs->charset_output;
  4037. if (in_array(get_class($this), array('Adherent')))
  4038. {
  4039. $arrayofrecords = array(); // The write_file of templates of adherent class need this var
  4040. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams);
  4041. } else {
  4042. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4043. }
  4044. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4045. if ($resultwritefile > 0)
  4046. {
  4047. $outputlangs->charset_output = $sav_charset_output;
  4048. // We delete old preview
  4049. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4050. dol_delete_preview($this);
  4051. // Index file in database
  4052. if (!empty($obj->result['fullpath']))
  4053. {
  4054. $destfull = $obj->result['fullpath'];
  4055. $upload_dir = dirname($destfull);
  4056. $destfile = basename($destfull);
  4057. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  4058. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) // If not a tmp dir
  4059. {
  4060. $filename = basename($destfile);
  4061. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4062. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4063. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4064. $ecmfile = new EcmFiles($this->db);
  4065. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  4066. // Set the public "share" key
  4067. $setsharekey = false;
  4068. if ($this->element == 'propal')
  4069. {
  4070. $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok
  4071. if ($useonlinesignature) $setsharekey = true;
  4072. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey = true;
  4073. }
  4074. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  4075. $setsharekey = true;
  4076. }
  4077. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  4078. $setsharekey = true;
  4079. }
  4080. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4081. $setsharekey = true;
  4082. }
  4083. if ($setsharekey) {
  4084. if (empty($ecmfile->share)) // Because object not found or share not set yet
  4085. {
  4086. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  4087. $ecmfile->share = getRandomPassword(true);
  4088. }
  4089. }
  4090. if ($result > 0)
  4091. {
  4092. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4093. $ecmfile->fullpath_orig = '';
  4094. $ecmfile->gen_or_uploaded = 'generated';
  4095. $ecmfile->description = ''; // indexed content
  4096. $ecmfile->keyword = ''; // keyword content
  4097. $result = $ecmfile->update($user);
  4098. if ($result < 0) {
  4099. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4100. }
  4101. } else {
  4102. $ecmfile->entity = $conf->entity;
  4103. $ecmfile->filepath = $rel_dir;
  4104. $ecmfile->filename = $filename;
  4105. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4106. $ecmfile->fullpath_orig = '';
  4107. $ecmfile->gen_or_uploaded = 'generated';
  4108. $ecmfile->description = ''; // indexed content
  4109. $ecmfile->keyword = ''; // keyword content
  4110. $ecmfile->src_object_type = $this->table_element;
  4111. $ecmfile->src_object_id = $this->id;
  4112. $result = $ecmfile->create($user);
  4113. if ($result < 0) {
  4114. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4115. }
  4116. }
  4117. /*$this->result['fullname']=$destfull;
  4118. $this->result['filepath']=$ecmfile->filepath;
  4119. $this->result['filename']=$ecmfile->filename;*/
  4120. //var_dump($obj->update_main_doc_field);exit;
  4121. // Update the last_main_doc field into main object (if documenent generator has property ->update_main_doc_field set)
  4122. $update_main_doc_field = 0;
  4123. if (!empty($obj->update_main_doc_field)) $update_main_doc_field = 1;
  4124. if ($update_main_doc_field && !empty($this->table_element))
  4125. {
  4126. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath.'/'.$ecmfile->filename)."'";
  4127. $sql .= ' WHERE rowid = '.$this->id;
  4128. $resql = $this->db->query($sql);
  4129. if (!$resql) {
  4130. dol_print_error($this->db);
  4131. } else {
  4132. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  4133. }
  4134. }
  4135. }
  4136. } else {
  4137. 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);
  4138. }
  4139. // Success in building document. We build meta file.
  4140. dol_meta_create($this);
  4141. return 1;
  4142. } else {
  4143. $outputlangs->charset_output = $sav_charset_output;
  4144. dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
  4145. return -1;
  4146. }
  4147. } else {
  4148. if (!$filefound) {
  4149. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4150. dol_print_error('', $this->error);
  4151. } else {
  4152. $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
  4153. dol_print_error('', $this->error);
  4154. }
  4155. return -1;
  4156. }
  4157. } else return $reshook;
  4158. }
  4159. /**
  4160. * Build thumb
  4161. * @todo Move this into files.lib.php
  4162. *
  4163. * @param string $file Path file in UTF8 to original file to create thumbs from.
  4164. * @return void
  4165. */
  4166. public function addThumbs($file)
  4167. {
  4168. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  4169. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  4170. $file_osencoded = dol_osencode($file);
  4171. if (file_exists($file_osencoded))
  4172. {
  4173. // Create small thumbs for company (Ratio is near 16/9)
  4174. // Used on logon for example
  4175. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  4176. // Create mini thumbs for company (Ratio is near 16/9)
  4177. // Used on menu or for setup page for example
  4178. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  4179. }
  4180. }
  4181. /* Functions common to commonobject and commonobjectline */
  4182. /* For default values */
  4183. /**
  4184. * Return the default value to use for a field when showing the create form of object.
  4185. * Return values in this order:
  4186. * 1) If parameter is available into POST, we return it first.
  4187. * 2) If not but an alternate value was provided as parameter of function, we return it.
  4188. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  4189. * 4) Return value found into database (TODO No yet implemented)
  4190. *
  4191. * @param string $fieldname Name of field
  4192. * @param string $alternatevalue Alternate value to use
  4193. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  4194. **/
  4195. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
  4196. {
  4197. global $conf, $_POST;
  4198. // If param here has been posted, we use this value first.
  4199. if (GETPOSTISSET($fieldname)) return GETPOST($fieldname, 'alphanohtml', 3);
  4200. if (isset($alternatevalue)) return $alternatevalue;
  4201. $newelement = $this->element;
  4202. if ($newelement == 'facture') $newelement = 'invoice';
  4203. if ($newelement == 'commande') $newelement = 'order';
  4204. if (empty($newelement))
  4205. {
  4206. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  4207. return '';
  4208. }
  4209. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  4210. //var_dump($keyforfieldname);
  4211. if (isset($conf->global->$keyforfieldname)) return $conf->global->$keyforfieldname;
  4212. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  4213. }
  4214. /* For triggers */
  4215. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4216. /**
  4217. * Call trigger based on this instance.
  4218. * Some context information may also be provided into array property this->context.
  4219. * NB: Error from trigger are stacked in interface->errors
  4220. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  4221. *
  4222. * @param string $triggerName trigger's name to execute
  4223. * @param User $user Object user
  4224. * @return int Result of run_triggers
  4225. */
  4226. public function call_trigger($triggerName, $user)
  4227. {
  4228. // phpcs:enable
  4229. global $langs, $conf;
  4230. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  4231. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4232. $langs = new Translate('', $conf);
  4233. }
  4234. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  4235. $interface = new Interfaces($this->db);
  4236. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  4237. if ($result < 0)
  4238. {
  4239. if (!empty($this->errors))
  4240. {
  4241. $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.
  4242. } else {
  4243. $this->errors = $interface->errors;
  4244. }
  4245. }
  4246. return $result;
  4247. }
  4248. /* Functions for data in other language */
  4249. /**
  4250. * Function to get alternative languages of a data into $this->array_languages
  4251. * This method is NOT called by method fetch of objects but must be called separately.
  4252. *
  4253. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  4254. * @see fetch_optionnals()
  4255. */
  4256. public function fetchValuesForExtraLanguages()
  4257. {
  4258. // To avoid SQL errors. Probably not the better solution though
  4259. if (!$this->element) {
  4260. return 0;
  4261. }
  4262. if (!($this->id > 0)) {
  4263. return 0;
  4264. }
  4265. if (is_array($this->array_languages)) {
  4266. return 1;
  4267. }
  4268. $this->array_languages = array();
  4269. $element = $this->element;
  4270. if ($element == 'categorie') $element = 'categories'; // For compatibility
  4271. // Request to get translation values for object
  4272. $sql = "SELECT rowid, property, lang , value";
  4273. $sql .= " FROM ".MAIN_DB_PREFIX."object_lang";
  4274. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  4275. $sql .= " AND fk_object = ".$this->id;
  4276. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  4277. $resql = $this->db->query($sql);
  4278. if ($resql)
  4279. {
  4280. $numrows = $this->db->num_rows($resql);
  4281. if ($numrows)
  4282. {
  4283. $i = 0;
  4284. while ($i < $numrows) {
  4285. $obj = $this->db->fetch_object($resql);
  4286. $key = $obj->property;
  4287. $value = $obj->value;
  4288. $codelang = $obj->lang;
  4289. $type = $this->fields[$key]['type'];
  4290. // we can add this attribute to object
  4291. if (preg_match('/date/', $type))
  4292. {
  4293. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  4294. } else {
  4295. $this->array_languages[$key][$codelang] = $value;
  4296. }
  4297. $i++;
  4298. }
  4299. }
  4300. $this->db->free($resql);
  4301. if ($numrows) return $numrows;
  4302. else return 0;
  4303. } else {
  4304. dol_print_error($this->db);
  4305. return -1;
  4306. }
  4307. }
  4308. /**
  4309. * Fill array_options property of object by extrafields value (using for data sent by forms)
  4310. *
  4311. * @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.
  4312. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  4313. */
  4314. public function setValuesForExtraLanguages($onlykey = '')
  4315. {
  4316. global $_POST, $langs;
  4317. // Get extra fields
  4318. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  4319. $tmparray = explode('-', $postfieldkey);
  4320. if ($tmparray[0] != 'field') continue;
  4321. $element = $tmparray[1];
  4322. $key = $tmparray[2];
  4323. $codelang = $tmparray[3];
  4324. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  4325. if (!empty($onlykey) && $key != $onlykey) continue;
  4326. if ($element != $this->element) continue;
  4327. $key_type = $this->fields[$key]['type'];
  4328. $enabled = 1;
  4329. if (isset($this->fields[$key]['enabled']))
  4330. {
  4331. $enabled = dol_eval($this->fields[$key]['enabled'], 1);
  4332. }
  4333. /*$perms = 1;
  4334. if (isset($this->fields[$key]['perms']))
  4335. {
  4336. $perms = dol_eval($this->fields[$key]['perms'], 1);
  4337. }*/
  4338. if (empty($enabled)) continue;
  4339. //if (empty($perms)) continue;
  4340. if (in_array($key_type, array('date')))
  4341. {
  4342. // Clean parameters
  4343. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  4344. $value_key = dol_mktime(0, 0, 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]);
  4345. } elseif (in_array($key_type, array('datetime')))
  4346. {
  4347. // Clean parameters
  4348. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  4349. $value_key = dol_mktime($_POST[$postfieldkey."hour"], $_POST[$postfieldkey."min"], 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]);
  4350. } elseif (in_array($key_type, array('checkbox', 'chkbxlst')))
  4351. {
  4352. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  4353. if (!empty($value_arr)) {
  4354. $value_key = implode($value_arr, ',');
  4355. } else {
  4356. $value_key = '';
  4357. }
  4358. } elseif (in_array($key_type, array('price', 'double')))
  4359. {
  4360. $value_arr = GETPOST($postfieldkey, 'alpha');
  4361. $value_key = price2num($value_arr);
  4362. } else {
  4363. $value_key = GETPOST($postfieldkey);
  4364. if (in_array($key_type, array('link')) && $value_key == '-1') $value_key = '';
  4365. }
  4366. $this->array_languages[$key][$codelang] = $value_key;
  4367. /*if ($nofillrequired) {
  4368. $langs->load('errors');
  4369. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  4370. return -1;
  4371. }*/
  4372. }
  4373. return 1;
  4374. }
  4375. /* Functions for extrafields */
  4376. /**
  4377. * Function to make a fetch but set environment to avoid to load computed values before.
  4378. *
  4379. * @param int $id ID of object
  4380. * @return int >0 if OK, 0 if not found, <0 if KO
  4381. */
  4382. public function fetchNoCompute($id)
  4383. {
  4384. global $conf;
  4385. $savDisableCompute = $conf->disable_compute;
  4386. $conf->disable_compute = 1;
  4387. $ret = $this->fetch($id);
  4388. $conf->disable_compute = $savDisableCompute;
  4389. return $ret;
  4390. }
  4391. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4392. /**
  4393. * Function to get extra fields of an object into $this->array_options
  4394. * This method is in most cases called by method fetch of objects but you can call it separately.
  4395. *
  4396. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  4397. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  4398. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  4399. * @see fetchValuesForExtraLanguages()
  4400. */
  4401. public function fetch_optionals($rowid = null, $optionsArray = null)
  4402. {
  4403. // phpcs:enable
  4404. global $conf, $extrafields;
  4405. if (empty($rowid)) $rowid = $this->id;
  4406. if (empty($rowid)) $rowid = $this->rowid;
  4407. // To avoid SQL errors. Probably not the better solution though
  4408. if (!$this->table_element) {
  4409. return 0;
  4410. }
  4411. $this->array_options = array();
  4412. if (!is_array($optionsArray))
  4413. {
  4414. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  4415. if (!isset($extrafields) || !is_object($extrafields))
  4416. {
  4417. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4418. $extrafields = new ExtraFields($this->db);
  4419. }
  4420. // Load array of extrafields for elementype = $this->table_element
  4421. if (empty($extrafields->attributes[$this->table_element]['loaded']))
  4422. {
  4423. $extrafields->fetch_name_optionals_label($this->table_element);
  4424. }
  4425. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  4426. } else {
  4427. global $extrafields;
  4428. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  4429. }
  4430. $table_element = $this->table_element;
  4431. if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
  4432. // Request to get complementary values
  4433. if (is_array($optionsArray) && count($optionsArray) > 0)
  4434. {
  4435. $sql = "SELECT rowid";
  4436. foreach ($optionsArray as $name => $label)
  4437. {
  4438. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate')
  4439. {
  4440. $sql .= ", ".$name;
  4441. }
  4442. }
  4443. $sql .= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
  4444. $sql .= " WHERE fk_object = ".((int) $rowid);
  4445. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  4446. $resql = $this->db->query($sql);
  4447. if ($resql)
  4448. {
  4449. $numrows = $this->db->num_rows($resql);
  4450. if ($numrows)
  4451. {
  4452. $tab = $this->db->fetch_array($resql);
  4453. foreach ($tab as $key => $value)
  4454. {
  4455. // 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)
  4456. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key))
  4457. {
  4458. // we can add this attribute to object
  4459. if (!empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime')))
  4460. {
  4461. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  4462. $this->array_options["options_".$key] = $this->db->jdate($value);
  4463. } else {
  4464. $this->array_options["options_".$key] = $value;
  4465. }
  4466. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  4467. }
  4468. }
  4469. // If field is a computed field, value must become result of compute
  4470. foreach ($tab as $key => $value) {
  4471. if (!empty($extrafields) && !empty($extrafields->attributes[$this->table_element]['computed'][$key]))
  4472. {
  4473. //var_dump($conf->disable_compute);
  4474. if (empty($conf->disable_compute)) {
  4475. $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0);
  4476. }
  4477. }
  4478. }
  4479. }
  4480. $this->db->free($resql);
  4481. if ($numrows) return $numrows;
  4482. else return 0;
  4483. } else {
  4484. dol_print_error($this->db);
  4485. return -1;
  4486. }
  4487. }
  4488. return 0;
  4489. }
  4490. /**
  4491. * Delete all extra fields values for the current object.
  4492. *
  4493. * @return int <0 if KO, >0 if OK
  4494. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  4495. */
  4496. public function deleteExtraFields()
  4497. {
  4498. global $conf;
  4499. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0;
  4500. $this->db->begin();
  4501. $table_element = $this->table_element;
  4502. if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
  4503. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
  4504. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  4505. $resql = $this->db->query($sql_del);
  4506. if (!$resql)
  4507. {
  4508. $this->error = $this->db->lasterror();
  4509. $this->db->rollback();
  4510. return -1;
  4511. } else {
  4512. $this->db->commit();
  4513. return 1;
  4514. }
  4515. }
  4516. /**
  4517. * Add/Update all extra fields values for the current object.
  4518. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  4519. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  4520. *
  4521. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  4522. * @param User $userused Object user
  4523. * @return int -1=error, O=did nothing, 1=OK
  4524. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  4525. */
  4526. public function insertExtraFields($trigger = '', $userused = null)
  4527. {
  4528. global $conf, $langs, $user;
  4529. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0;
  4530. if (empty($userused)) $userused = $user;
  4531. $error = 0;
  4532. if (!empty($this->array_options))
  4533. {
  4534. // Check parameters
  4535. $langs->load('admin');
  4536. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4537. $extrafields = new ExtraFields($this->db);
  4538. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  4539. //Eliminate copied source object extra_fields that do not exist in target object
  4540. $new_array_options = array();
  4541. foreach ($this->array_options as $key => $value) {
  4542. if (in_array(substr($key, 8), array_keys($target_extrafields))) // We remove the 'options_' from $key for test
  4543. $new_array_options[$key] = $value;
  4544. elseif (in_array($key, array_keys($target_extrafields))) // We test on $key that does not contains the 'options_' prefix
  4545. $new_array_options['options_'.$key] = $value;
  4546. }
  4547. foreach ($new_array_options as $key => $value)
  4548. {
  4549. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  4550. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  4551. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  4552. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  4553. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  4554. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  4555. if ($attributeRequired)
  4556. {
  4557. $mandatorypb = false;
  4558. if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb = true;
  4559. if ($this->array_options[$key] === '') $mandatorypb = true;
  4560. if ($mandatorypb)
  4561. {
  4562. dol_syslog("Mandatory extra field ".$key." is empty");
  4563. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  4564. return -1;
  4565. }
  4566. }
  4567. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  4568. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  4569. if (!empty($attrfieldcomputed))
  4570. {
  4571. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS))
  4572. {
  4573. $value = dol_eval($attrfieldcomputed, 1, 0);
  4574. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  4575. $new_array_options[$key] = $value;
  4576. } else {
  4577. $new_array_options[$key] = null;
  4578. }
  4579. }
  4580. switch ($attributeType)
  4581. {
  4582. case 'int':
  4583. if (!is_numeric($value) && $value != '')
  4584. {
  4585. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  4586. return -1;
  4587. } elseif ($value == '')
  4588. {
  4589. $new_array_options[$key] = null;
  4590. }
  4591. break;
  4592. case 'price':
  4593. case 'double':
  4594. $value = price2num($value);
  4595. if (!is_numeric($value) && $value != '')
  4596. {
  4597. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  4598. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  4599. return -1;
  4600. } elseif ($value == '')
  4601. {
  4602. $new_array_options[$key] = null;
  4603. }
  4604. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  4605. $new_array_options[$key] = $value;
  4606. break;
  4607. /*case 'select': // Not required, we chosed value='0' for undefined values
  4608. if ($value=='-1')
  4609. {
  4610. $this->array_options[$key] = null;
  4611. }
  4612. break;*/
  4613. case 'password':
  4614. $algo = '';
  4615. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']))
  4616. {
  4617. // If there is an encryption choice, we use it to crypt data before insert
  4618. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  4619. $algo = reset($tmparrays);
  4620. if ($algo != '')
  4621. {
  4622. //global $action; // $action may be 'create', 'update', 'update_extras'...
  4623. //var_dump($action);
  4624. //var_dump($this->oldcopy);exit;
  4625. 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
  4626. {
  4627. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  4628. 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.
  4629. {
  4630. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  4631. } else {
  4632. // var_dump($algo);
  4633. $newvalue = dol_hash($this->array_options[$key], $algo);
  4634. $new_array_options[$key] = $newvalue;
  4635. }
  4636. } else {
  4637. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  4638. }
  4639. }
  4640. } else // Common usage
  4641. {
  4642. $new_array_options[$key] = $this->array_options[$key];
  4643. }
  4644. break;
  4645. case 'date':
  4646. case 'datetime':
  4647. // If data is a string instead of a timestamp, we convert it
  4648. if (!is_int($this->array_options[$key])) {
  4649. $this->array_options[$key] = strtotime($this->array_options[$key]);
  4650. }
  4651. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  4652. break;
  4653. case 'link':
  4654. $param_list = array_keys($attributeParam['options']);
  4655. // 0 : ObjectName
  4656. // 1 : classPath
  4657. $InfoFieldList = explode(":", $param_list[0]);
  4658. dol_include_once($InfoFieldList[1]);
  4659. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  4660. {
  4661. if ($value == '-1') // -1 is key for no defined in combo list of objects
  4662. {
  4663. $new_array_options[$key] = '';
  4664. } elseif ($value)
  4665. {
  4666. $object = new $InfoFieldList[0]($this->db);
  4667. if (is_numeric($value)) $res = $object->fetch($value);
  4668. else $res = $object->fetch('', $value);
  4669. if ($res > 0) $new_array_options[$key] = $object->id;
  4670. else {
  4671. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  4672. $this->db->rollback();
  4673. return -1;
  4674. }
  4675. }
  4676. } else {
  4677. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  4678. }
  4679. break;
  4680. }
  4681. }
  4682. $this->db->begin();
  4683. $table_element = $this->table_element;
  4684. if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
  4685. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  4686. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
  4687. $this->db->query($sql_del);
  4688. $sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object";
  4689. foreach ($new_array_options as $key => $value)
  4690. {
  4691. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  4692. // Add field of attribut
  4693. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator
  4694. $sql .= ",".$attributeKey;
  4695. }
  4696. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  4697. if (is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']))
  4698. {
  4699. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval)
  4700. {
  4701. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) // If field not already added previously
  4702. {
  4703. $sql .= ",".$tmpkey;
  4704. }
  4705. }
  4706. }
  4707. $sql .= ") VALUES (".$this->id;
  4708. foreach ($new_array_options as $key => $value)
  4709. {
  4710. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  4711. // Add field of attribute
  4712. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator)
  4713. {
  4714. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0')
  4715. {
  4716. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  4717. } else {
  4718. $sql .= ",null";
  4719. }
  4720. }
  4721. }
  4722. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  4723. if (is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']))
  4724. {
  4725. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval)
  4726. {
  4727. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) // If field not already added previously
  4728. {
  4729. if (in_array($tmpval, array('int', 'double', 'price'))) $sql .= ", 0";
  4730. else $sql .= ", ''";
  4731. }
  4732. }
  4733. }
  4734. $sql .= ")";
  4735. $resql = $this->db->query($sql);
  4736. if (!$resql)
  4737. {
  4738. $this->error = $this->db->lasterror();
  4739. $error++;
  4740. }
  4741. if (!$error && $trigger)
  4742. {
  4743. // Call trigger
  4744. $this->context = array('extrafieldaddupdate'=>1);
  4745. $result = $this->call_trigger($trigger, $userused);
  4746. if ($result < 0) $error++;
  4747. // End call trigger
  4748. }
  4749. if ($error)
  4750. {
  4751. $this->db->rollback();
  4752. return -1;
  4753. } else {
  4754. $this->db->commit();
  4755. return 1;
  4756. }
  4757. } else return 0;
  4758. }
  4759. /**
  4760. * Add/Update all extra fields values for the current object.
  4761. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  4762. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  4763. *
  4764. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  4765. * @param User $userused Object user
  4766. * @return int -1=error, O=did nothing, 1=OK
  4767. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  4768. */
  4769. public function insertExtraLanguages($trigger = '', $userused = null)
  4770. {
  4771. global $conf, $langs, $user;
  4772. if (empty($userused)) $userused = $user;
  4773. $error = 0;
  4774. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) return 0; // For avoid conflicts if trigger used
  4775. if (is_array($this->array_languages))
  4776. {
  4777. $new_array_languages = $this->array_languages;
  4778. foreach ($new_array_languages as $key => $value)
  4779. {
  4780. $attributeKey = $key;
  4781. $attributeType = $this->fields[$attributeKey]['type'];
  4782. $attributeLabel = $this->fields[$attributeKey]['label'];
  4783. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  4784. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  4785. switch ($attributeType)
  4786. {
  4787. case 'int':
  4788. if (!is_numeric($value) && $value != '')
  4789. {
  4790. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  4791. return -1;
  4792. } elseif ($value == '')
  4793. {
  4794. $new_array_languages[$key] = null;
  4795. }
  4796. break;
  4797. case 'double':
  4798. $value = price2num($value);
  4799. if (!is_numeric($value) && $value != '')
  4800. {
  4801. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  4802. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  4803. return -1;
  4804. } elseif ($value == '')
  4805. {
  4806. $new_array_languages[$key] = null;
  4807. }
  4808. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  4809. $new_array_languages[$key] = $value;
  4810. break;
  4811. /*case 'select': // Not required, we chosed value='0' for undefined values
  4812. if ($value=='-1')
  4813. {
  4814. $this->array_options[$key] = null;
  4815. }
  4816. break;*/
  4817. }
  4818. }
  4819. $this->db->begin();
  4820. $table_element = $this->table_element;
  4821. if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
  4822. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  4823. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  4824. foreach ($langcodearray as $langcode => $value) {
  4825. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX."object_lang";
  4826. $sql_del .= " WHERE fk_object = ".$this->id." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  4827. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  4828. $this->db->query($sql_del);
  4829. if ($value !== '') {
  4830. $sql = "INSERT INTO ".MAIN_DB_PREFIX."object_lang (fk_object, property, type_object, lang, value";
  4831. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  4832. $sql .= ")";
  4833. $resql = $this->db->query($sql);
  4834. if (!$resql)
  4835. {
  4836. $this->error = $this->db->lasterror();
  4837. $error++;
  4838. break;
  4839. }
  4840. }
  4841. }
  4842. }
  4843. if (!$error && $trigger)
  4844. {
  4845. // Call trigger
  4846. $this->context = array('extralanguagesaddupdate'=>1);
  4847. $result = $this->call_trigger($trigger, $userused);
  4848. if ($result < 0) $error++;
  4849. // End call trigger
  4850. }
  4851. if ($error)
  4852. {
  4853. $this->db->rollback();
  4854. return -1;
  4855. } else {
  4856. $this->db->commit();
  4857. return 1;
  4858. }
  4859. } else return 0;
  4860. }
  4861. /**
  4862. * Update an extra field value for the current object.
  4863. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  4864. *
  4865. * @param string $key Key of the extrafield to update (without starting 'options_')
  4866. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  4867. * @param User $userused Object user
  4868. * @return int -1=error, O=did nothing, 1=OK
  4869. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  4870. */
  4871. public function updateExtraField($key, $trigger = null, $userused = null)
  4872. {
  4873. global $conf, $langs, $user;
  4874. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0;
  4875. if (empty($userused)) $userused = $user;
  4876. $error = 0;
  4877. if (!empty($this->array_options) && isset($this->array_options["options_".$key]))
  4878. {
  4879. // Check parameters
  4880. $langs->load('admin');
  4881. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4882. $extrafields = new ExtraFields($this->db);
  4883. $extrafields->fetch_name_optionals_label($this->table_element);
  4884. $value = $this->array_options["options_".$key];
  4885. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  4886. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  4887. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  4888. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  4889. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  4890. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  4891. switch ($attributeType)
  4892. {
  4893. case 'int':
  4894. if (!is_numeric($value) && $value != '')
  4895. {
  4896. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  4897. return -1;
  4898. } elseif ($value === '')
  4899. {
  4900. $this->array_options["options_".$key] = null;
  4901. }
  4902. break;
  4903. case 'double':
  4904. $value = price2num($value);
  4905. if (!is_numeric($value) && $value != '')
  4906. {
  4907. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  4908. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  4909. return -1;
  4910. } elseif ($value === '')
  4911. {
  4912. $this->array_options["options_".$key] = null;
  4913. }
  4914. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  4915. $this->array_options["options_".$key] = $value;
  4916. break;
  4917. /*case 'select': // Not required, we chosed value='0' for undefined values
  4918. if ($value=='-1')
  4919. {
  4920. $this->array_options[$key] = null;
  4921. }
  4922. break;*/
  4923. case 'price':
  4924. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  4925. break;
  4926. case 'date':
  4927. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  4928. break;
  4929. case 'datetime':
  4930. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  4931. break;
  4932. case 'link':
  4933. $param_list = array_keys($attributeParam['options']);
  4934. // 0 : ObjectName
  4935. // 1 : classPath
  4936. $InfoFieldList = explode(":", $param_list[0]);
  4937. dol_include_once($InfoFieldList[1]);
  4938. if ($value)
  4939. {
  4940. $object = new $InfoFieldList[0]($this->db);
  4941. $object->fetch(0, $value);
  4942. $this->array_options["options_".$key] = $object->id;
  4943. }
  4944. break;
  4945. }
  4946. $this->db->begin();
  4947. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key."='".$this->db->escape($this->array_options["options_".$key])."'";
  4948. $sql .= " WHERE fk_object = ".$this->id;
  4949. $resql = $this->db->query($sql);
  4950. if (!$resql)
  4951. {
  4952. $error++;
  4953. $this->error = $this->db->lasterror();
  4954. }
  4955. if (!$error && $trigger)
  4956. {
  4957. // Call trigger
  4958. $this->context = array('extrafieldupdate'=>1);
  4959. $result = $this->call_trigger($trigger, $userused);
  4960. if ($result < 0) $error++;
  4961. // End call trigger
  4962. }
  4963. if ($error)
  4964. {
  4965. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  4966. $this->db->rollback();
  4967. return -1;
  4968. } else {
  4969. $this->db->commit();
  4970. return 1;
  4971. }
  4972. } else return 0;
  4973. }
  4974. /**
  4975. * Update an extra language value for the current object.
  4976. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  4977. *
  4978. * @param string $key Key of the extrafield (without starting 'options_')
  4979. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  4980. * @param User $userused Object user
  4981. * @return int -1=error, O=did nothing, 1=OK
  4982. * @see updateExtraFields(), insertExtraLanguages()
  4983. */
  4984. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  4985. {
  4986. global $conf, $langs, $user;
  4987. if (empty($userused)) $userused = $user;
  4988. $error = 0;
  4989. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) return 0; // For avoid conflicts if trigger used
  4990. return 0;
  4991. }
  4992. /**
  4993. * Return HTML string to put an input field into a page
  4994. * Code very similar with showInputField of extra fields
  4995. *
  4996. * @param array $val Array of properties for field to show (used only if ->fields not defined)
  4997. * @param string $key Key of attribute
  4998. * @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)
  4999. * @param string $moreparam To add more parameters on html input tag
  5000. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5001. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5002. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  5003. * @param int $nonewbutton Force to not show the new button on field that are links to object
  5004. * @return string
  5005. */
  5006. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  5007. {
  5008. global $conf, $langs, $form;
  5009. if (!is_object($form))
  5010. {
  5011. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  5012. $form = new Form($this->db);
  5013. }
  5014. if (!empty($this->fields)) {
  5015. $val = $this->fields[$key];
  5016. }
  5017. $out = '';
  5018. $type = '';
  5019. $param = array();
  5020. $param['options'] = array();
  5021. $reg = array();
  5022. $size = $this->fields[$key]['size'];
  5023. // Because we work on extrafields
  5024. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5025. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5026. $type = 'link';
  5027. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5028. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5029. $type = 'link';
  5030. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  5031. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5032. $type = 'link';
  5033. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5034. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5035. $type = 'sellist';
  5036. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  5037. $param['options'] = array();
  5038. $type = 'varchar';
  5039. $size = $reg[1];
  5040. } elseif (preg_match('/varchar/', $val['type'])) {
  5041. $param['options'] = array();
  5042. $type = 'varchar';
  5043. } elseif (is_array($this->fields[$key]['arrayofkeyval'])) {
  5044. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  5045. $type = 'select';
  5046. } else {
  5047. $param['options'] = array();
  5048. $type = $this->fields[$key]['type'];
  5049. }
  5050. $label = $this->fields[$key]['label'];
  5051. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  5052. $default = $this->fields[$key]['default'];
  5053. $computed = $this->fields[$key]['computed'];
  5054. $unique = $this->fields[$key]['unique'];
  5055. $required = $this->fields[$key]['required'];
  5056. $autofocusoncreate = $this->fields[$key]['autofocusoncreate'];
  5057. $langfile = $this->fields[$key]['langfile'];
  5058. $list = $this->fields[$key]['list'];
  5059. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  5060. $objectid = $this->id;
  5061. if ($computed)
  5062. {
  5063. if (!preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  5064. else return '';
  5065. }
  5066. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  5067. if (empty($morecss) && !empty($val['css'])) {
  5068. $morecss = $val['css'];
  5069. } elseif (empty($morecss)) {
  5070. if ($type == 'date')
  5071. {
  5072. $morecss = 'minwidth100imp';
  5073. } elseif ($type == 'datetime' || $type == 'link') // link means an foreign key to another primary id
  5074. {
  5075. $morecss = 'minwidth200imp';
  5076. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type))
  5077. {
  5078. $morecss = 'maxwidth75';
  5079. } elseif ($type == 'url') {
  5080. $morecss = 'minwidth400';
  5081. } elseif ($type == 'boolean')
  5082. {
  5083. $morecss = '';
  5084. } else {
  5085. if (round($size) < 12)
  5086. {
  5087. $morecss = 'minwidth100';
  5088. } elseif (round($size) <= 48)
  5089. {
  5090. $morecss = 'minwidth200';
  5091. } else {
  5092. $morecss = 'minwidth400';
  5093. }
  5094. }
  5095. }
  5096. if (in_array($type, array('date', 'datetime')))
  5097. {
  5098. $tmp = explode(',', $size);
  5099. $newsize = $tmp[0];
  5100. $showtime = in_array($type, array('datetime')) ? 1 : 0;
  5101. // Do not show current date when field not required (see selectDate() method)
  5102. if (!$required && $value == '') $value = '-1';
  5103. // TODO Must also support $moreparam
  5104. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  5105. } elseif (in_array($type, array('duration')))
  5106. {
  5107. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  5108. } elseif (in_array($type, array('int', 'integer')))
  5109. {
  5110. $tmp = explode(',', $size);
  5111. $newsize = $tmp[0];
  5112. $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' : '').'>';
  5113. } elseif (in_array($type, array('real')))
  5114. {
  5115. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5116. } elseif (preg_match('/varchar/', $type))
  5117. {
  5118. $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' : '').'>';
  5119. } elseif (in_array($type, array('mail', 'phone', 'url')))
  5120. {
  5121. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5122. } elseif (preg_match('/^text/', $type))
  5123. {
  5124. if (!preg_match('/search_/', $keyprefix)) // If keyprefix is search_ or search_options_, we must just use a simple text field
  5125. {
  5126. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5127. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  5128. $out = $doleditor->Create(1);
  5129. } else {
  5130. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5131. }
  5132. } elseif (preg_match('/^html/', $type))
  5133. {
  5134. if (!preg_match('/search_/', $keyprefix)) // If keyprefix is search_ or search_options_, we must just use a simple text field
  5135. {
  5136. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5137. $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%');
  5138. $out = $doleditor->Create(1);
  5139. } else {
  5140. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5141. }
  5142. } elseif ($type == 'boolean')
  5143. {
  5144. $checked = '';
  5145. if (!empty($value)) {
  5146. $checked = ' checked value="1" ';
  5147. } else {
  5148. $checked = ' value="1" ';
  5149. }
  5150. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  5151. } elseif ($type == 'price')
  5152. {
  5153. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5154. $value = price($value);
  5155. }
  5156. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  5157. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type))
  5158. {
  5159. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5160. $value = price($value);
  5161. }
  5162. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  5163. } elseif ($type == 'select')
  5164. {
  5165. $out = '';
  5166. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
  5167. {
  5168. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5169. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  5170. }
  5171. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  5172. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1))$out .= '<option value="0">&nbsp;</option>';
  5173. foreach ($param['options'] as $key => $val)
  5174. {
  5175. if ((string) $key == '') continue;
  5176. list($val, $parent) = explode('|', $val);
  5177. $out .= '<option value="'.$key.'"';
  5178. $out .= (((string) $value == (string) $key) ? ' selected' : '');
  5179. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  5180. $out .= '>'.$val.'</option>';
  5181. }
  5182. $out .= '</select>';
  5183. } elseif ($type == 'sellist')
  5184. {
  5185. $out = '';
  5186. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
  5187. {
  5188. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5189. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  5190. }
  5191. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  5192. if (is_array($param['options']))
  5193. {
  5194. $param_list = array_keys($param['options']);
  5195. $InfoFieldList = explode(":", $param_list[0]);
  5196. $parentName = '';
  5197. $parentField = '';
  5198. // 0 : tableName
  5199. // 1 : label field name
  5200. // 2 : key fields name (if differ of rowid)
  5201. // 3 : key field parent (for dependent lists)
  5202. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  5203. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  5204. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4]))
  5205. {
  5206. if (strpos($InfoFieldList[4], 'extra.') !== false)
  5207. {
  5208. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  5209. } else {
  5210. $keyList = $InfoFieldList[2].' as rowid';
  5211. }
  5212. }
  5213. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3]))
  5214. {
  5215. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  5216. $keyList .= ', '.$parentField;
  5217. }
  5218. $fields_label = explode('|', $InfoFieldList[1]);
  5219. if (is_array($fields_label))
  5220. {
  5221. $keyList .= ', ';
  5222. $keyList .= implode(', ', $fields_label);
  5223. }
  5224. $sqlwhere = '';
  5225. $sql = 'SELECT '.$keyList;
  5226. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  5227. if (!empty($InfoFieldList[4]))
  5228. {
  5229. // can use SELECT request
  5230. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  5231. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  5232. }
  5233. // current object id can be use into filter
  5234. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  5235. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  5236. } else {
  5237. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  5238. }
  5239. //We have to join on extrafield table
  5240. if (strpos($InfoFieldList[4], 'extra') !== false)
  5241. {
  5242. $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
  5243. $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
  5244. } else {
  5245. $sqlwhere .= ' WHERE '.$InfoFieldList[4];
  5246. }
  5247. } else {
  5248. $sqlwhere .= ' WHERE 1=1';
  5249. }
  5250. // Some tables may have field, some other not. For the moment we disable it.
  5251. if (in_array($InfoFieldList[0], array('tablewithentity')))
  5252. {
  5253. $sqlwhere .= ' AND entity = '.$conf->entity;
  5254. }
  5255. $sql .= $sqlwhere;
  5256. //print $sql;
  5257. $sql .= ' ORDER BY '.implode(', ', $fields_label);
  5258. dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
  5259. $resql = $this->db->query($sql);
  5260. if ($resql)
  5261. {
  5262. $out .= '<option value="0">&nbsp;</option>';
  5263. $num = $this->db->num_rows($resql);
  5264. $i = 0;
  5265. while ($i < $num)
  5266. {
  5267. $labeltoshow = '';
  5268. $obj = $this->db->fetch_object($resql);
  5269. // Several field into label (eq table:code|libelle:rowid)
  5270. $notrans = false;
  5271. $fields_label = explode('|', $InfoFieldList[1]);
  5272. if (count($fields_label) > 1)
  5273. {
  5274. $notrans = true;
  5275. foreach ($fields_label as $field_toshow)
  5276. {
  5277. $labeltoshow .= $obj->$field_toshow.' ';
  5278. }
  5279. } else {
  5280. $labeltoshow = $obj->{$InfoFieldList[1]};
  5281. }
  5282. $labeltoshow = dol_trunc($labeltoshow, 45);
  5283. if ($value == $obj->rowid)
  5284. {
  5285. foreach ($fields_label as $field_toshow)
  5286. {
  5287. $translabel = $langs->trans($obj->$field_toshow);
  5288. if ($translabel != $obj->$field_toshow) {
  5289. $labeltoshow = dol_trunc($translabel, 18).' ';
  5290. } else {
  5291. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  5292. }
  5293. }
  5294. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  5295. } else {
  5296. if (!$notrans)
  5297. {
  5298. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  5299. if ($translabel != $obj->{$InfoFieldList[1]}) {
  5300. $labeltoshow = dol_trunc($translabel, 18);
  5301. } else {
  5302. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  5303. }
  5304. }
  5305. if (empty($labeltoshow)) $labeltoshow = '(not defined)';
  5306. if ($value == $obj->rowid)
  5307. {
  5308. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  5309. }
  5310. if (!empty($InfoFieldList[3]) && $parentField)
  5311. {
  5312. $parent = $parentName.':'.$obj->{$parentField};
  5313. }
  5314. $out .= '<option value="'.$obj->rowid.'"';
  5315. $out .= ($value == $obj->rowid ? ' selected' : '');
  5316. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  5317. $out .= '>'.$labeltoshow.'</option>';
  5318. }
  5319. $i++;
  5320. }
  5321. $this->db->free($resql);
  5322. } else {
  5323. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  5324. }
  5325. }
  5326. $out .= '</select>';
  5327. } elseif ($type == 'checkbox')
  5328. {
  5329. $value_arr = explode(',', $value);
  5330. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
  5331. } elseif ($type == 'radio')
  5332. {
  5333. $out = '';
  5334. foreach ($param['options'] as $keyopt => $val)
  5335. {
  5336. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  5337. $out .= ' value="'.$keyopt.'"';
  5338. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  5339. $out .= ($value == $keyopt ? 'checked' : '');
  5340. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
  5341. }
  5342. } elseif ($type == 'chkbxlst')
  5343. {
  5344. if (is_array($value)) {
  5345. $value_arr = $value;
  5346. } else {
  5347. $value_arr = explode(',', $value);
  5348. }
  5349. if (is_array($param['options'])) {
  5350. $param_list = array_keys($param['options']);
  5351. $InfoFieldList = explode(":", $param_list[0]);
  5352. $parentName = '';
  5353. $parentField = '';
  5354. // 0 : tableName
  5355. // 1 : label field name
  5356. // 2 : key fields name (if differ of rowid)
  5357. // 3 : key field parent (for dependent lists)
  5358. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  5359. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  5360. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  5361. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  5362. $keyList .= ', '.$parentField;
  5363. }
  5364. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  5365. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  5366. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  5367. } else {
  5368. $keyList = $InfoFieldList[2].' as rowid';
  5369. }
  5370. }
  5371. $fields_label = explode('|', $InfoFieldList[1]);
  5372. if (is_array($fields_label)) {
  5373. $keyList .= ', ';
  5374. $keyList .= implode(', ', $fields_label);
  5375. }
  5376. $sqlwhere = '';
  5377. $sql = 'SELECT '.$keyList;
  5378. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  5379. if (!empty($InfoFieldList[4])) {
  5380. // can use SELECT request
  5381. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  5382. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  5383. }
  5384. // current object id can be use into filter
  5385. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  5386. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  5387. } else {
  5388. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  5389. }
  5390. // We have to join on extrafield table
  5391. if (strpos($InfoFieldList[4], 'extra') !== false) {
  5392. $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
  5393. $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
  5394. } else {
  5395. $sqlwhere .= ' WHERE '.$InfoFieldList[4];
  5396. }
  5397. } else {
  5398. $sqlwhere .= ' WHERE 1=1';
  5399. }
  5400. // Some tables may have field, some other not. For the moment we disable it.
  5401. if (in_array($InfoFieldList[0], array('tablewithentity')))
  5402. {
  5403. $sqlwhere .= ' AND entity = '.$conf->entity;
  5404. }
  5405. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  5406. // print $sql;
  5407. $sql .= $sqlwhere;
  5408. dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
  5409. $resql = $this->db->query($sql);
  5410. if ($resql) {
  5411. $num = $this->db->num_rows($resql);
  5412. $i = 0;
  5413. $data = array();
  5414. while ($i < $num) {
  5415. $labeltoshow = '';
  5416. $obj = $this->db->fetch_object($resql);
  5417. $notrans = false;
  5418. // Several field into label (eq table:code|libelle:rowid)
  5419. $fields_label = explode('|', $InfoFieldList[1]);
  5420. if (count($fields_label) > 1) {
  5421. $notrans = true;
  5422. foreach ($fields_label as $field_toshow) {
  5423. $labeltoshow .= $obj->$field_toshow.' ';
  5424. }
  5425. } else {
  5426. $labeltoshow = $obj->{$InfoFieldList[1]};
  5427. }
  5428. $labeltoshow = dol_trunc($labeltoshow, 45);
  5429. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  5430. foreach ($fields_label as $field_toshow) {
  5431. $translabel = $langs->trans($obj->$field_toshow);
  5432. if ($translabel != $obj->$field_toshow) {
  5433. $labeltoshow = dol_trunc($translabel, 18).' ';
  5434. } else {
  5435. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  5436. }
  5437. }
  5438. $data[$obj->rowid] = $labeltoshow;
  5439. } else {
  5440. if (!$notrans) {
  5441. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  5442. if ($translabel != $obj->{$InfoFieldList[1]}) {
  5443. $labeltoshow = dol_trunc($translabel, 18);
  5444. } else {
  5445. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  5446. }
  5447. }
  5448. if (empty($labeltoshow)) {
  5449. $labeltoshow = '(not defined)';
  5450. }
  5451. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  5452. $data[$obj->rowid] = $labeltoshow;
  5453. }
  5454. if (!empty($InfoFieldList[3]) && $parentField) {
  5455. $parent = $parentName.':'.$obj->{$parentField};
  5456. }
  5457. $data[$obj->rowid] = $labeltoshow;
  5458. }
  5459. $i++;
  5460. }
  5461. $this->db->free($resql);
  5462. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
  5463. } else {
  5464. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  5465. }
  5466. }
  5467. } elseif ($type == 'link')
  5468. {
  5469. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter]]'
  5470. $param_list_array = explode(':', $param_list[0]);
  5471. $showempty = (($required && $default != '') ? 0 : 1);
  5472. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  5473. $morecss .= ' widthcentpercentminusx';
  5474. }
  5475. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  5476. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  5477. 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".
  5478. {
  5479. list($class, $classfile) = explode(':', $param_list[0]);
  5480. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  5481. else $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  5482. $paramforthenewlink = '';
  5483. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  5484. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  5485. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  5486. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  5487. $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>';
  5488. }
  5489. }
  5490. } elseif ($type == 'password')
  5491. {
  5492. // If prefix is 'search_', field is used as a filter, we use a common text field.
  5493. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  5494. } elseif ($type == 'array')
  5495. {
  5496. $newval = $val;
  5497. $newval['type'] = 'varchar(256)';
  5498. $out = '';
  5499. $inputs = array();
  5500. if (!empty($value)) {
  5501. foreach ($value as $option) {
  5502. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  5503. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  5504. }
  5505. }
  5506. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  5507. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  5508. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  5509. if (!empty($conf->use_javascript_ajax)) {
  5510. $out .= '
  5511. <script>
  5512. $(document).ready(function() {
  5513. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  5514. $("'.dol_escape_js($newInput).'").insertBefore(this);
  5515. });
  5516. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  5517. $(this).parent().remove();
  5518. });
  5519. });
  5520. </script>';
  5521. }
  5522. }
  5523. if (!empty($hidden)) {
  5524. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  5525. }
  5526. /* Add comments
  5527. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  5528. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  5529. */
  5530. return $out;
  5531. }
  5532. /**
  5533. * Return HTML string to show a field into a page
  5534. * Code very similar with showOutputField of extra fields
  5535. *
  5536. * @param array $val Array of properties of field to show
  5537. * @param string $key Key of attribute
  5538. * @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)
  5539. * @param string $moreparam To add more parametes on html input tag
  5540. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5541. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5542. * @param mixed $morecss Value for css to define size. May also be a numeric.
  5543. * @return string
  5544. */
  5545. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  5546. {
  5547. global $conf, $langs, $form;
  5548. if (!is_object($form))
  5549. {
  5550. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  5551. $form = new Form($this->db);
  5552. }
  5553. $objectid = $this->id;
  5554. $label = $val['label'];
  5555. $type = $val['type'];
  5556. $size = $val['css'];
  5557. $reg = array();
  5558. // Convert var to be able to share same code than showOutputField of extrafields
  5559. if (preg_match('/varchar\((\d+)\)/', $type, $reg))
  5560. {
  5561. $type = 'varchar'; // convert varchar(xx) int varchar
  5562. $size = $reg[1];
  5563. } elseif (preg_match('/varchar/', $type)) $type = 'varchar'; // convert varchar(xx) int varchar
  5564. if (is_array($val['arrayofkeyval'])) $type = 'select';
  5565. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type = 'link';
  5566. $default = $val['default'];
  5567. $computed = $val['computed'];
  5568. $unique = $val['unique'];
  5569. $required = $val['required'];
  5570. $param = array();
  5571. $param['options'] = array();
  5572. if (is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval'];
  5573. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg))
  5574. {
  5575. $type = 'link';
  5576. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  5577. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5578. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5579. $type = 'sellist';
  5580. }
  5581. $langfile = $val['langfile'];
  5582. $list = $val['list'];
  5583. $help = $val['help'];
  5584. $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)
  5585. if ($hidden) return '';
  5586. // If field is a computed field, value must become result of compute
  5587. if ($computed)
  5588. {
  5589. // Make the eval of compute string
  5590. //var_dump($computed);
  5591. $value = dol_eval($computed, 1, 0);
  5592. }
  5593. if (empty($morecss))
  5594. {
  5595. if ($type == 'date')
  5596. {
  5597. $morecss = 'minwidth100imp';
  5598. } elseif ($type == 'datetime' || $type == 'timestamp')
  5599. {
  5600. $morecss = 'minwidth200imp';
  5601. } elseif (in_array($type, array('int', 'double', 'price')))
  5602. {
  5603. $morecss = 'maxwidth75';
  5604. } elseif ($type == 'url')
  5605. {
  5606. $morecss = 'minwidth400';
  5607. } elseif ($type == 'boolean')
  5608. {
  5609. $morecss = '';
  5610. } else {
  5611. if (round($size) < 12)
  5612. {
  5613. $morecss = 'minwidth100';
  5614. } elseif (round($size) <= 48)
  5615. {
  5616. $morecss = 'minwidth200';
  5617. } else {
  5618. $morecss = 'minwidth400';
  5619. }
  5620. }
  5621. }
  5622. // Format output value differently according to properties of field
  5623. if ($key == 'ref' && method_exists($this, 'getNomUrl')) $value = $this->getNomUrl(1, '', 0, '', 1);
  5624. elseif ($key == 'status' && method_exists($this, 'getLibStatut')) $value = $this->getLibStatut(3);
  5625. elseif ($type == 'date')
  5626. {
  5627. if (!empty($value)) {
  5628. $value = dol_print_date($value, 'day');
  5629. } else {
  5630. $value = '';
  5631. }
  5632. } elseif ($type == 'datetime' || $type == 'timestamp')
  5633. {
  5634. if (!empty($value)) {
  5635. $value = dol_print_date($value, 'dayhour');
  5636. } else {
  5637. $value = '';
  5638. }
  5639. } elseif ($type == 'duration')
  5640. {
  5641. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5642. if (!is_null($value) && $value !== '') {
  5643. $value = convertSecondToTime($value, 'allhourmin');
  5644. }
  5645. } elseif ($type == 'double' || $type == 'real')
  5646. {
  5647. if (!is_null($value) && $value !== '') {
  5648. $value = price($value);
  5649. }
  5650. } elseif ($type == 'boolean')
  5651. {
  5652. $checked = '';
  5653. if (!empty($value)) {
  5654. $checked = ' checked ';
  5655. }
  5656. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  5657. } elseif ($type == 'mail')
  5658. {
  5659. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  5660. } elseif ($type == 'url')
  5661. {
  5662. $value = dol_print_url($value, '_blank', 32, 1);
  5663. } elseif ($type == 'phone')
  5664. {
  5665. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
  5666. } elseif ($type == 'price')
  5667. {
  5668. if (!is_null($value) && $value !== '') {
  5669. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  5670. }
  5671. } elseif ($type == 'select')
  5672. {
  5673. $value = $param['options'][$value];
  5674. } elseif ($type == 'sellist')
  5675. {
  5676. $param_list = array_keys($param['options']);
  5677. $InfoFieldList = explode(":", $param_list[0]);
  5678. $selectkey = "rowid";
  5679. $keyList = 'rowid';
  5680. if (count($InfoFieldList) >= 3)
  5681. {
  5682. $selectkey = $InfoFieldList[2];
  5683. $keyList = $InfoFieldList[2].' as rowid';
  5684. }
  5685. $fields_label = explode('|', $InfoFieldList[1]);
  5686. if (is_array($fields_label)) {
  5687. $keyList .= ', ';
  5688. $keyList .= implode(', ', $fields_label);
  5689. }
  5690. $sql = 'SELECT '.$keyList;
  5691. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  5692. if (strpos($InfoFieldList[4], 'extra') !== false)
  5693. {
  5694. $sql .= ' as main';
  5695. }
  5696. if ($selectkey == 'rowid' && empty($value)) {
  5697. $sql .= " WHERE ".$selectkey."=0";
  5698. } elseif ($selectkey == 'rowid') {
  5699. $sql .= " WHERE ".$selectkey."=".$this->db->escape($value);
  5700. } else {
  5701. $sql .= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  5702. }
  5703. //$sql.= ' AND entity = '.$conf->entity;
  5704. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  5705. $resql = $this->db->query($sql);
  5706. if ($resql)
  5707. {
  5708. $value = ''; // value was used, so now we reste it to use it to build final output
  5709. $obj = $this->db->fetch_object($resql);
  5710. // Several field into label (eq table:code|libelle:rowid)
  5711. $fields_label = explode('|', $InfoFieldList[1]);
  5712. if (is_array($fields_label) && count($fields_label) > 1)
  5713. {
  5714. foreach ($fields_label as $field_toshow)
  5715. {
  5716. $translabel = '';
  5717. if (!empty($obj->$field_toshow)) {
  5718. $translabel = $langs->trans($obj->$field_toshow);
  5719. }
  5720. if ($translabel != $field_toshow) {
  5721. $value .= dol_trunc($translabel, 18).' ';
  5722. } else {
  5723. $value .= $obj->$field_toshow.' ';
  5724. }
  5725. }
  5726. } else {
  5727. $translabel = '';
  5728. if (!empty($obj->{$InfoFieldList[1]})) {
  5729. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  5730. }
  5731. if ($translabel != $obj->{$InfoFieldList[1]}) {
  5732. $value = dol_trunc($translabel, 18);
  5733. } else {
  5734. $value = $obj->{$InfoFieldList[1]};
  5735. }
  5736. }
  5737. } else dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  5738. } elseif ($type == 'radio')
  5739. {
  5740. $value = $param['options'][$value];
  5741. } elseif ($type == 'checkbox')
  5742. {
  5743. $value_arr = explode(',', $value);
  5744. $value = '';
  5745. if (is_array($value_arr) && count($value_arr) > 0)
  5746. {
  5747. $toprint = array();
  5748. foreach ($value_arr as $keyval=>$valueval) {
  5749. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$param['options'][$valueval].'</li>';
  5750. }
  5751. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  5752. }
  5753. } elseif ($type == 'chkbxlst')
  5754. {
  5755. $value_arr = explode(',', $value);
  5756. $param_list = array_keys($param['options']);
  5757. $InfoFieldList = explode(":", $param_list[0]);
  5758. $selectkey = "rowid";
  5759. $keyList = 'rowid';
  5760. if (count($InfoFieldList) >= 3) {
  5761. $selectkey = $InfoFieldList[2];
  5762. $keyList = $InfoFieldList[2].' as rowid';
  5763. }
  5764. $fields_label = explode('|', $InfoFieldList[1]);
  5765. if (is_array($fields_label)) {
  5766. $keyList .= ', ';
  5767. $keyList .= implode(', ', $fields_label);
  5768. }
  5769. $sql = 'SELECT '.$keyList;
  5770. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  5771. if (strpos($InfoFieldList[4], 'extra') !== false) {
  5772. $sql .= ' as main';
  5773. }
  5774. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  5775. // $sql.= ' AND entity = '.$conf->entity;
  5776. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  5777. $resql = $this->db->query($sql);
  5778. if ($resql) {
  5779. $value = ''; // value was used, so now we reste it to use it to build final output
  5780. $toprint = array();
  5781. while ($obj = $this->db->fetch_object($resql)) {
  5782. // Several field into label (eq table:code|libelle:rowid)
  5783. $fields_label = explode('|', $InfoFieldList[1]);
  5784. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  5785. if (is_array($fields_label) && count($fields_label) > 1) {
  5786. foreach ($fields_label as $field_toshow) {
  5787. $translabel = '';
  5788. if (!empty($obj->$field_toshow)) {
  5789. $translabel = $langs->trans($obj->$field_toshow);
  5790. }
  5791. if ($translabel != $field_toshow) {
  5792. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
  5793. } else {
  5794. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->$field_toshow.'</li>';
  5795. }
  5796. }
  5797. } else {
  5798. $translabel = '';
  5799. if (!empty($obj->{$InfoFieldList[1]})) {
  5800. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  5801. }
  5802. if ($translabel != $obj->{$InfoFieldList[1]}) {
  5803. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
  5804. } else {
  5805. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->{$InfoFieldList[1]}.'</li>';
  5806. }
  5807. }
  5808. }
  5809. }
  5810. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  5811. } else {
  5812. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  5813. }
  5814. } elseif ($type == 'link')
  5815. {
  5816. $out = '';
  5817. // only if something to display (perf)
  5818. if ($value)
  5819. {
  5820. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  5821. $InfoFieldList = explode(":", $param_list[0]);
  5822. $classname = $InfoFieldList[0];
  5823. $classpath = $InfoFieldList[1];
  5824. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  5825. if (!empty($classpath))
  5826. {
  5827. dol_include_once($InfoFieldList[1]);
  5828. if ($classname && class_exists($classname))
  5829. {
  5830. $object = new $classname($this->db);
  5831. $object->fetch($value);
  5832. $value = $object->getNomUrl($getnomurlparam);
  5833. }
  5834. } else {
  5835. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5836. return 'Error bad setup of extrafield';
  5837. }
  5838. } else $value = '';
  5839. } elseif (preg_match('/^(text|html)/', $type))
  5840. {
  5841. $value = dol_htmlentitiesbr($value);
  5842. } elseif ($type == 'password')
  5843. {
  5844. $value = preg_replace('/./i', '*', $value);
  5845. } elseif ($type == 'array')
  5846. {
  5847. $value = implode('<br>', $value);
  5848. }
  5849. //print $type.'-'.$size.'-'.$value;
  5850. $out = $value;
  5851. return $out;
  5852. }
  5853. /**
  5854. * Function to show lines of extrafields with output datas.
  5855. * This function is responsible to output the <tr> and <td> according to correct number of columns received into $params['colspan']
  5856. *
  5857. * @param Extrafields $extrafields Extrafield Object
  5858. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  5859. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  5860. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  5861. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  5862. * @param string $onetrtd All fields in same tr td (TODO field not used ?)
  5863. * @return string
  5864. */
  5865. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0)
  5866. {
  5867. global $db, $conf, $langs, $action, $form, $hookmanager;
  5868. if (!is_object($form)) $form = new Form($db);
  5869. $out = '';
  5870. $parameters = array();
  5871. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  5872. if (empty($reshook))
  5873. {
  5874. if (is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0)
  5875. {
  5876. $out .= "\n";
  5877. $out .= '<!-- showOptionals --> ';
  5878. $out .= "\n";
  5879. $extrafields_collapse_num = '';
  5880. $e = 0;
  5881. foreach ($extrafields->attributes[$this->table_element]['label'] as $key=>$label)
  5882. {
  5883. // Show only the key field in params
  5884. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) continue;
  5885. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  5886. $enabled = 1;
  5887. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key]))
  5888. {
  5889. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1);
  5890. }
  5891. if (empty($enabled)) continue;
  5892. $visibility = 1;
  5893. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key]))
  5894. {
  5895. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1);
  5896. }
  5897. $perms = 1;
  5898. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key]))
  5899. {
  5900. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1);
  5901. }
  5902. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  5903. 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
  5904. elseif ($mode == 'view' && empty($visibility)) continue;
  5905. if (empty($perms)) continue;
  5906. // Load language if required
  5907. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  5908. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  5909. }
  5910. $colspan = '';
  5911. if (is_array($params) && count($params) > 0) {
  5912. if (array_key_exists('cols', $params)) {
  5913. $colspan = $params['cols'];
  5914. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  5915. $reg = array();
  5916. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  5917. $colspan = $reg[1];
  5918. } else {
  5919. $colspan = $params['colspan'];
  5920. }
  5921. }
  5922. }
  5923. switch ($mode) {
  5924. case "view":
  5925. $value = $this->array_options["options_".$key.$keysuffix]; // Value may be clean or formated later
  5926. break;
  5927. case "create":
  5928. case "edit":
  5929. // We get the value of property found with GETPOST so it takes into account:
  5930. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  5931. $check = 'alphanohtml';
  5932. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  5933. $check = 'restricthtml';
  5934. }
  5935. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  5936. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  5937. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix))
  5938. {
  5939. if (is_array($getposttemp)) {
  5940. // $getposttemp is an array but following code expects a comma separated string
  5941. $value = implode(",", $getposttemp);
  5942. } else {
  5943. $value = $getposttemp;
  5944. }
  5945. } else {
  5946. $value = $this->array_options["options_".$key]; // No GET, no POST, no default value, so we take value of object.
  5947. }
  5948. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  5949. break;
  5950. }
  5951. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate')
  5952. {
  5953. $extrafields_collapse_num = '';
  5954. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  5955. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  5956. $extrafield_param_list = array_keys($extrafield_param['options']);
  5957. if (count($extrafield_param_list) > 0) {
  5958. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  5959. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  5960. $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  5961. }
  5962. }
  5963. }
  5964. $out .= $extrafields->showSeparator($key, $this, ($colspan + 1));
  5965. } else {
  5966. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  5967. $csstyle = '';
  5968. if (is_array($params) && count($params) > 0) {
  5969. if (array_key_exists('class', $params)) {
  5970. $class .= $params['class'].' ';
  5971. }
  5972. if (array_key_exists('style', $params)) {
  5973. $csstyle = $params['style'];
  5974. }
  5975. }
  5976. // add html5 elements
  5977. $domData = ' data-element="extrafield"';
  5978. $domData .= ' data-targetelement="'.$this->element.'"';
  5979. $domData .= ' data-targetid="'.$this->id.'"';
  5980. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  5981. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) { $colspan = '0'; }
  5982. if ($action == 'selectlines') { $colspan++; }
  5983. // Convert date into timestamp format (value in memory must be a timestamp)
  5984. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime')))
  5985. {
  5986. $datenotinstring = $this->array_options['options_'.$key];
  5987. if (!is_numeric($this->array_options['options_'.$key])) // For backward compatibility
  5988. {
  5989. $datenotinstring = $this->db->jdate($datenotinstring);
  5990. }
  5991. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? 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;
  5992. }
  5993. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  5994. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double')))
  5995. {
  5996. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? price2num($value) : $this->array_options['options_'.$key];
  5997. }
  5998. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  5999. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int')))
  6000. {
  6001. if ($action == 'create') $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  6002. }
  6003. $labeltoshow = $langs->trans($label);
  6004. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  6005. $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="'.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.'" '.$domData.' >';
  6006. $out .= '<td class="';
  6007. //$out .= "titlefield";
  6008. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  6009. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  6010. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  6011. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  6012. $out .= '">';
  6013. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  6014. else $out .= $labeltoshow;
  6015. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= '&nbsp;<font color="red">*</font>';
  6016. } else {
  6017. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= ' fieldrequired';
  6018. $out .= '">';
  6019. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  6020. else $out .= $labeltoshow;
  6021. }
  6022. $out .= '</td>';
  6023. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  6024. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').'class="'.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  6025. switch ($mode) {
  6026. case "view":
  6027. $out .= $extrafields->showOutputField($key, $value);
  6028. break;
  6029. case "create":
  6030. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  6031. break;
  6032. case "edit":
  6033. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  6034. break;
  6035. }
  6036. $out .= '</td>';
  6037. /*for($ii = 0; $ii < ($colspan - 1); $ii++)
  6038. {
  6039. $out .='<td class="'.$this->element.'_extras_'.$key.'"></td>';
  6040. }*/
  6041. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) $out .= '</tr>';
  6042. else $out .= '</tr>';
  6043. $e++;
  6044. }
  6045. }
  6046. $out .= "\n";
  6047. // Add code to manage list depending on others
  6048. if (!empty($conf->use_javascript_ajax)) {
  6049. $out .= '
  6050. <script>
  6051. jQuery(document).ready(function() {
  6052. function showOptions(child_list, parent_list)
  6053. {
  6054. var val = $("select[name=\""+parent_list+"\"]").val();
  6055. var parentVal = parent_list + ":" + val;
  6056. if(val > 0) {
  6057. $("select[name=\""+child_list+"\"] option[parent]").hide();
  6058. $("select[name=\""+child_list+"\"] option[parent=\""+parentVal+"\"]").show();
  6059. } else {
  6060. $("select[name=\""+child_list+"\"] option").show();
  6061. }
  6062. }
  6063. function setListDependencies() {
  6064. jQuery("select option[parent]").parent().each(function() {
  6065. var child_list = $(this).attr("name");
  6066. var parent = $(this).find("option[parent]:first").attr("parent");
  6067. var infos = parent.split(":");
  6068. var parent_list = infos[0];
  6069. $("select[name=\""+parent_list+"\"]").change(function() {
  6070. showOptions(child_list, parent_list);
  6071. });
  6072. });
  6073. }
  6074. setListDependencies();
  6075. });
  6076. </script>'."\n";
  6077. }
  6078. $out .= '<!-- /showOptionals --> '."\n";
  6079. }
  6080. }
  6081. $out .= $hookmanager->resPrint;
  6082. return $out;
  6083. }
  6084. /**
  6085. * Returns the rights used for this class
  6086. * @return stdClass
  6087. */
  6088. public function getRights()
  6089. {
  6090. global $user;
  6091. $element = $this->element;
  6092. if ($element == 'facturerec') $element = 'facture';
  6093. return $user->rights->{$element};
  6094. }
  6095. /**
  6096. * Function used to replace a thirdparty id with another one.
  6097. * This function is meant to be called from replaceThirdparty with the appropiate tables
  6098. * Column name fk_soc MUST be used to identify thirdparties
  6099. *
  6100. * @param DoliDB $db Database handler
  6101. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  6102. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  6103. * @param string[] $tables Tables that need to be changed
  6104. * @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)
  6105. * @return bool True if success, False if error
  6106. */
  6107. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  6108. {
  6109. foreach ($tables as $table)
  6110. {
  6111. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.$dest_id.' WHERE fk_soc = '.$origin_id;
  6112. if (!$db->query($sql))
  6113. {
  6114. 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.
  6115. //$this->errors = $db->lasterror();
  6116. return false;
  6117. }
  6118. }
  6119. return true;
  6120. }
  6121. /**
  6122. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  6123. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  6124. * else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  6125. * else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  6126. * else set min buy price as buy price
  6127. *
  6128. * @param float $unitPrice Product unit price
  6129. * @param float $discountPercent Line discount percent
  6130. * @param int $fk_product Product id
  6131. * @return float <0 if KO, buyprice if OK
  6132. */
  6133. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  6134. {
  6135. global $conf;
  6136. $buyPrice = 0;
  6137. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) // In most cases, test here is false
  6138. {
  6139. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  6140. } else {
  6141. // Get cost price for margin calculation
  6142. if (!empty($fk_product))
  6143. {
  6144. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice')
  6145. {
  6146. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6147. $product = new Product($this->db);
  6148. $result = $product->fetch($fk_product);
  6149. if ($result <= 0)
  6150. {
  6151. $this->errors[] = 'ErrorProductIdDoesNotExists';
  6152. return -1;
  6153. }
  6154. if ($product->cost_price > 0)
  6155. {
  6156. $buyPrice = $product->cost_price;
  6157. } elseif ($product->pmp > 0)
  6158. {
  6159. $buyPrice = $product->pmp;
  6160. }
  6161. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp')
  6162. {
  6163. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6164. $product = new Product($this->db);
  6165. $result = $product->fetch($fk_product);
  6166. if ($result <= 0)
  6167. {
  6168. $this->errors[] = 'ErrorProductIdDoesNotExists';
  6169. return -1;
  6170. }
  6171. if ($product->pmp > 0)
  6172. {
  6173. $buyPrice = $product->pmp;
  6174. }
  6175. }
  6176. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice')))
  6177. {
  6178. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  6179. $productFournisseur = new ProductFournisseur($this->db);
  6180. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0)
  6181. {
  6182. $buyPrice = $productFournisseur->fourn_unitprice;
  6183. } elseif ($result < 0)
  6184. {
  6185. $this->errors[] = $productFournisseur->error;
  6186. return -2;
  6187. }
  6188. }
  6189. }
  6190. }
  6191. return $buyPrice;
  6192. }
  6193. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6194. /**
  6195. * Show photos of an object (nbmax maximum), into several columns
  6196. *
  6197. * @param string $modulepart 'product', 'ticket', ...
  6198. * @param string $sdir Directory to scan (full absolute path)
  6199. * @param int $size 0=original size, 1='small' use thumbnail if possible
  6200. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  6201. * @param int $nbbyrow Number of image per line or -1 to use div. Used only if size=1.
  6202. * @param int $showfilename 1=Show filename
  6203. * @param int $showaction 1=Show icon with action links (resize, delete)
  6204. * @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.
  6205. * @param int $maxWidth Max width of original image when size='small'
  6206. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  6207. * @param int $notitle Do not add title tag on image
  6208. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  6209. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  6210. */
  6211. 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)
  6212. {
  6213. // phpcs:enable
  6214. global $conf, $user, $langs;
  6215. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  6216. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  6217. $sortfield = 'position_name';
  6218. $sortorder = 'asc';
  6219. $dir = $sdir.'/';
  6220. $pdir = '/';
  6221. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/';
  6222. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/';
  6223. // For backward compatibility
  6224. if ($modulepart == 'product' && !empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
  6225. {
  6226. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  6227. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  6228. }
  6229. // Defined relative dir to DOL_DATA_ROOT
  6230. $relativedir = '';
  6231. if ($dir)
  6232. {
  6233. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  6234. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  6235. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  6236. }
  6237. $dirthumb = $dir.'thumbs/';
  6238. $pdirthumb = $pdir.'thumbs/';
  6239. $return = '<!-- Photo -->'."\n";
  6240. $nbphoto = 0;
  6241. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  6242. /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
  6243. {
  6244. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  6245. $filearray=array_merge($filearray, $filearrayold);
  6246. }*/
  6247. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  6248. if (count($filearray))
  6249. {
  6250. if ($sortfield && $sortorder)
  6251. {
  6252. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  6253. }
  6254. foreach ($filearray as $key => $val)
  6255. {
  6256. $photo = '';
  6257. $file = $val['name'];
  6258. //if (! utf8_check($file)) $file=utf8_encode($file); // To be sure file is stored in UTF8 in memory
  6259. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  6260. if (image_format_supported($file) >= 0)
  6261. {
  6262. $nbphoto++;
  6263. $photo = $file;
  6264. $viewfilename = $file;
  6265. if ($size == 1 || $size == 'small') { // Format vignette
  6266. // Find name of thumb file
  6267. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  6268. if (!dol_is_file($dirthumb.$photo_vignette)) $photo_vignette = '';
  6269. // Get filesize of original file
  6270. $imgarray = dol_getImageSize($dir.$photo);
  6271. if ($nbbyrow > 0)
  6272. {
  6273. if ($nbphoto == 1) $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  6274. if ($nbphoto % $nbbyrow == 1) $return .= '<tr class="center valignmiddle" style="border: 1px">';
  6275. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
  6276. } elseif ($nbbyrow < 0) $return .= '<div class="inline-block">';
  6277. $return .= "\n";
  6278. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  6279. if (empty($nolink))
  6280. {
  6281. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  6282. if ($urladvanced) $return .= '<a href="'.$urladvanced.'">';
  6283. else $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
  6284. }
  6285. // Show image (width height=$maxHeight)
  6286. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  6287. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  6288. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  6289. if ($notitle) $alt = '';
  6290. if ($usesharelink)
  6291. {
  6292. if ($val['share'])
  6293. {
  6294. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
  6295. {
  6296. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  6297. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  6298. } else {
  6299. $return .= '<!-- Show original file -->';
  6300. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  6301. }
  6302. } else {
  6303. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  6304. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  6305. }
  6306. } else {
  6307. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
  6308. {
  6309. $return .= '<!-- Show thumb -->';
  6310. $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).'">';
  6311. } else {
  6312. $return .= '<!-- Show original file -->';
  6313. $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).'">';
  6314. }
  6315. }
  6316. if (empty($nolink)) $return .= '</a>';
  6317. $return .= "\n";
  6318. if ($showfilename) $return .= '<br>'.$viewfilename;
  6319. if ($showaction)
  6320. {
  6321. $return .= '<br>';
  6322. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  6323. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight))
  6324. {
  6325. $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>';
  6326. }
  6327. // Special cas for product
  6328. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
  6329. {
  6330. // Link to resize
  6331. $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; ';
  6332. // Link to delete
  6333. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;token='.newToken().'&amp;file='.urlencode($pdir.$viewfilename).'">';
  6334. $return .= img_delete().'</a>';
  6335. }
  6336. }
  6337. $return .= "\n";
  6338. if ($nbbyrow > 0)
  6339. {
  6340. $return .= '</td>';
  6341. if (($nbphoto % $nbbyrow) == 0) $return .= '</tr>';
  6342. } elseif ($nbbyrow < 0) $return .= '</div>';
  6343. }
  6344. if (empty($size)) { // Format origine
  6345. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  6346. if ($showfilename) $return .= '<br>'.$viewfilename;
  6347. if ($showaction)
  6348. {
  6349. // Special case for product
  6350. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
  6351. {
  6352. // Link to resize
  6353. $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; ';
  6354. // Link to delete
  6355. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;token='.newToken().'&amp;file='.urlencode($pdir.$viewfilename).'">';
  6356. $return .= img_delete().'</a>';
  6357. }
  6358. }
  6359. }
  6360. // On continue ou on arrete de boucler ?
  6361. if ($nbmax && $nbphoto >= $nbmax) break;
  6362. }
  6363. }
  6364. if ($size == 1 || $size == 'small')
  6365. {
  6366. if ($nbbyrow > 0)
  6367. {
  6368. // Ferme tableau
  6369. while ($nbphoto % $nbbyrow)
  6370. {
  6371. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  6372. $nbphoto++;
  6373. }
  6374. if ($nbphoto) $return .= '</table>';
  6375. }
  6376. }
  6377. }
  6378. $this->nbphoto = $nbphoto;
  6379. return $return;
  6380. }
  6381. /**
  6382. * Function test if type is array
  6383. *
  6384. * @param array $info content informations of field
  6385. * @return bool true if array
  6386. */
  6387. protected function isArray($info)
  6388. {
  6389. if (is_array($info))
  6390. {
  6391. if (isset($info['type']) && $info['type'] == 'array') return true;
  6392. else return false;
  6393. }
  6394. return false;
  6395. }
  6396. /**
  6397. * Function test if type is date
  6398. *
  6399. * @param array $info content informations of field
  6400. * @return bool true if date
  6401. */
  6402. public function isDate($info)
  6403. {
  6404. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) return true;
  6405. return false;
  6406. }
  6407. /**
  6408. * Function test if type is duration
  6409. *
  6410. * @param array $info content informations of field
  6411. * @return bool true if field of type duration
  6412. */
  6413. public function isDuration($info)
  6414. {
  6415. if (is_array($info))
  6416. {
  6417. if (isset($info['type']) && ($info['type'] == 'duration')) return true;
  6418. else return false;
  6419. } else return false;
  6420. }
  6421. /**
  6422. * Function test if type is integer
  6423. *
  6424. * @param array $info content informations of field
  6425. * @return bool true if integer
  6426. */
  6427. public function isInt($info)
  6428. {
  6429. if (is_array($info))
  6430. {
  6431. if (isset($info['type']) && ($info['type'] == 'int' || preg_match('/^integer/i', $info['type']))) return true;
  6432. else return false;
  6433. } else return false;
  6434. }
  6435. /**
  6436. * Function test if type is float
  6437. *
  6438. * @param array $info content informations of field
  6439. * @return bool true if float
  6440. */
  6441. public function isFloat($info)
  6442. {
  6443. if (is_array($info))
  6444. {
  6445. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) return true;
  6446. else return false;
  6447. }
  6448. return false;
  6449. }
  6450. /**
  6451. * Function test if type is text
  6452. *
  6453. * @param array $info content informations of field
  6454. * @return bool true if type text
  6455. */
  6456. public function isText($info)
  6457. {
  6458. if (is_array($info))
  6459. {
  6460. if (isset($info['type']) && $info['type'] == 'text') return true;
  6461. else return false;
  6462. }
  6463. return false;
  6464. }
  6465. /**
  6466. * Function test if field can be null
  6467. *
  6468. * @param array $info content informations of field
  6469. * @return bool true if it can be null
  6470. */
  6471. protected function canBeNull($info)
  6472. {
  6473. if (is_array($info))
  6474. {
  6475. if (isset($info['notnull']) && $info['notnull'] != '1') return true;
  6476. else return false;
  6477. }
  6478. return true;
  6479. }
  6480. /**
  6481. * Function test if field is forced to null if zero or empty
  6482. *
  6483. * @param array $info content informations of field
  6484. * @return bool true if forced to null
  6485. */
  6486. protected function isForcedToNullIfZero($info)
  6487. {
  6488. if (is_array($info))
  6489. {
  6490. if (isset($info['notnull']) && $info['notnull'] == '-1') return true;
  6491. else return false;
  6492. }
  6493. return false;
  6494. }
  6495. /**
  6496. * Function test if is indexed
  6497. *
  6498. * @param array $info content informations of field
  6499. * @return bool
  6500. */
  6501. protected function isIndex($info)
  6502. {
  6503. if (is_array($info))
  6504. {
  6505. if (isset($info['index']) && $info['index'] == true) return true;
  6506. else return false;
  6507. }
  6508. return false;
  6509. }
  6510. /**
  6511. * Function to prepare a part of the query for insert.
  6512. * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
  6513. * $this->${field} should be a clean value. The page can run
  6514. *
  6515. * @return array
  6516. */
  6517. protected function setSaveQuery()
  6518. {
  6519. global $conf;
  6520. $queryarray = array();
  6521. foreach ($this->fields as $field => $info) // Loop on definition of fields
  6522. {
  6523. // Depending on field type ('datetime', ...)
  6524. if ($this->isDate($info))
  6525. {
  6526. if (empty($this->{$field}))
  6527. {
  6528. $queryarray[$field] = null;
  6529. } else {
  6530. $queryarray[$field] = $this->db->idate($this->{$field});
  6531. }
  6532. } elseif ($this->isArray($info))
  6533. {
  6534. if (!empty($this->{$field})) {
  6535. if (!is_array($this->{$field})) {
  6536. $this->{$field} = array($this->{$field});
  6537. }
  6538. $queryarray[$field] = serialize($this->{$field});
  6539. } else {
  6540. $queryarray[$field] = null;
  6541. }
  6542. } elseif ($this->isDuration($info))
  6543. {
  6544. // $this->{$field} may be null, '', 0, '0', 123, '123'
  6545. if ($this->{$field} != '' || !empty($info['notnull'])) $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  6546. else $queryarray[$field] = null;
  6547. } elseif ($this->isInt($info) || $this->isFloat($info))
  6548. {
  6549. if ($field == 'entity' && is_null($this->{$field})) $queryarray[$field] = $conf->entity;
  6550. else {
  6551. // $this->{$field} may be null, '', 0, '0', 123, '123'
  6552. if ($this->{$field} != '' || !empty($info['notnull'])) {
  6553. if ($this->isInt($info)) $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  6554. if ($this->isFloat($info)) $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  6555. } else $queryarray[$field] = null;
  6556. }
  6557. } else {
  6558. $queryarray[$field] = $this->{$field};
  6559. }
  6560. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) unset($queryarray[$field]);
  6561. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) $queryarray[$field] = null; // May force 0 to null
  6562. }
  6563. return $queryarray;
  6564. }
  6565. /**
  6566. * Function to load data from a SQL pointer into properties of current object $this
  6567. *
  6568. * @param stdClass $obj Contain data of object from database
  6569. * @return void
  6570. */
  6571. public function setVarsFromFetchObj(&$obj)
  6572. {
  6573. foreach ($this->fields as $field => $info)
  6574. {
  6575. if ($this->isDate($info))
  6576. {
  6577. if (empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0;
  6578. else $this->{$field} = strtotime($obj->{$field});
  6579. } elseif ($this->isArray($info))
  6580. {
  6581. if (!empty($obj->{$field})) {
  6582. $this->{$field} = @unserialize($obj->{$field});
  6583. // Hack for data not in UTF8
  6584. if ($this->{$field } === false) @unserialize(utf8_decode($obj->{$field}));
  6585. } else {
  6586. $this->{$field} = array();
  6587. }
  6588. } elseif ($this->isInt($info))
  6589. {
  6590. if ($field == 'rowid') $this->id = (int) $obj->{$field};
  6591. else {
  6592. if ($this->isForcedToNullIfZero($info))
  6593. {
  6594. if (empty($obj->{$field})) $this->{$field} = null;
  6595. else $this->{$field} = (double) $obj->{$field};
  6596. } else {
  6597. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  6598. $this->{$field} = (int) $obj->{$field};
  6599. } else {
  6600. $this->{$field} = null;
  6601. }
  6602. }
  6603. }
  6604. } elseif ($this->isFloat($info))
  6605. {
  6606. if ($this->isForcedToNullIfZero($info))
  6607. {
  6608. if (empty($obj->{$field})) $this->{$field} = null;
  6609. else $this->{$field} = (double) $obj->{$field};
  6610. } else {
  6611. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  6612. $this->{$field} = (double) $obj->{$field};
  6613. } else {
  6614. $this->{$field} = null;
  6615. }
  6616. }
  6617. } else {
  6618. $this->{$field} = $obj->{$field};
  6619. }
  6620. }
  6621. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  6622. if (!isset($this->fields['ref']) && isset($this->id)) $this->ref = $this->id;
  6623. }
  6624. /**
  6625. * Function to concat keys of fields
  6626. *
  6627. * @return string
  6628. */
  6629. protected function getFieldList()
  6630. {
  6631. $keys = array_keys($this->fields);
  6632. return implode(',', $keys);
  6633. }
  6634. /**
  6635. * Add quote to field value if necessary
  6636. *
  6637. * @param string|int $value Value to protect
  6638. * @param array $fieldsentry Properties of field
  6639. * @return string
  6640. */
  6641. protected function quote($value, $fieldsentry)
  6642. {
  6643. if (is_null($value)) return 'NULL';
  6644. elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) return $this->db->escape("$value");
  6645. elseif ($fieldsentry['type'] == 'boolean') {
  6646. if ($value) return 'true';
  6647. else return 'false';
  6648. }
  6649. else return "'".$this->db->escape($value)."'";
  6650. }
  6651. /**
  6652. * Create object into database
  6653. *
  6654. * @param User $user User that creates
  6655. * @param bool $notrigger false=launch triggers after, true=disable triggers
  6656. * @return int <0 if KO, Id of created object if OK
  6657. */
  6658. public function createCommon(User $user, $notrigger = false)
  6659. {
  6660. global $langs;
  6661. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  6662. $error = 0;
  6663. $now = dol_now();
  6664. $fieldvalues = $this->setSaveQuery();
  6665. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) $fieldvalues['date_creation'] = $this->db->idate($now);
  6666. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) $fieldvalues['fk_user_creat'] = $user->id;
  6667. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  6668. if (array_key_exists('ref', $fieldvalues)) $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  6669. $keys = array();
  6670. $values = array(); // Array to store string forged for SQL syntax
  6671. foreach ($fieldvalues as $k => $v) {
  6672. $keys[$k] = $k;
  6673. $value = $this->fields[$k];
  6674. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  6675. }
  6676. // Clean and check mandatory
  6677. foreach ($keys as $key)
  6678. {
  6679. // If field is an implicit foreign key field
  6680. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key] = '';
  6681. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key] = '';
  6682. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default']))
  6683. {
  6684. $error++;
  6685. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  6686. }
  6687. // If value is null and there is a default value for field
  6688. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default']))
  6689. {
  6690. $values[$key] = $this->fields[$key]['default'];
  6691. }
  6692. // If field is an implicit foreign key field
  6693. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  6694. if (isset($this->fields[$key]['default'])) $values[$key] = $this->fields[$key]['default'];
  6695. else $values[$key] = 'null';
  6696. }
  6697. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) $values[$key] = 'null';
  6698. }
  6699. if ($error) return -1;
  6700. $this->db->begin();
  6701. if (!$error)
  6702. {
  6703. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
  6704. $sql .= ' ('.implode(", ", $keys).')';
  6705. $sql .= ' VALUES ('.implode(", ", $values).')';
  6706. $res = $this->db->query($sql);
  6707. if ($res === false) {
  6708. $error++;
  6709. $this->errors[] = $this->db->lasterror();
  6710. }
  6711. }
  6712. if (!$error)
  6713. {
  6714. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
  6715. }
  6716. // If we have a field ref with a default value of (PROV)
  6717. if (!$error)
  6718. {
  6719. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && !is_null($this->fields['ref']['default']) && $this->fields['ref']['default'] == '(PROV)')
  6720. {
  6721. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ref = '(PROV".$this->id.")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".$this->id;
  6722. $resqlupdate = $this->db->query($sql);
  6723. if ($resqlupdate === false)
  6724. {
  6725. $error++;
  6726. $this->errors[] = $this->db->lasterror();
  6727. } else {
  6728. $this->ref = '(PROV'.$this->id.')';
  6729. }
  6730. }
  6731. }
  6732. // Create extrafields
  6733. if (!$error)
  6734. {
  6735. $result = $this->insertExtraFields();
  6736. if ($result < 0) $error++;
  6737. }
  6738. // Create lines
  6739. if (!empty($this->table_element_line) && !empty($this->fk_element))
  6740. {
  6741. $num = (is_array($this->lines) ? count($this->lines) : 0);
  6742. for ($i = 0; $i < $num; $i++)
  6743. {
  6744. $line = $this->lines[$i];
  6745. $keyforparent = $this->fk_element;
  6746. $line->$keyforparent = $this->id;
  6747. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  6748. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  6749. if (!is_object($line)) $line = (object) $line;
  6750. $result = $line->create($user, 1);
  6751. if ($result < 0)
  6752. {
  6753. $this->error = $this->db->lasterror();
  6754. $this->db->rollback();
  6755. return -1;
  6756. }
  6757. }
  6758. }
  6759. // Triggers
  6760. if (!$error && !$notrigger)
  6761. {
  6762. // Call triggers
  6763. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  6764. if ($result < 0) { $error++; }
  6765. // End call triggers
  6766. }
  6767. // Commit or rollback
  6768. if ($error) {
  6769. $this->db->rollback();
  6770. return -1;
  6771. } else {
  6772. $this->db->commit();
  6773. return $this->id;
  6774. }
  6775. }
  6776. /**
  6777. * Load object in memory from the database
  6778. *
  6779. * @param int $id Id object
  6780. * @param string $ref Ref
  6781. * @param string $morewhere More SQL filters (' AND ...')
  6782. * @return int <0 if KO, 0 if not found, >0 if OK
  6783. */
  6784. public function fetchCommon($id, $ref = null, $morewhere = '')
  6785. {
  6786. if (empty($id) && empty($ref) && empty($morewhere)) return -1;
  6787. $fieldlist = $this->getFieldList();
  6788. if (empty($fieldlist)) return 0;
  6789. $sql = 'SELECT '.$fieldlist;
  6790. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
  6791. if (!empty($id)) $sql .= ' WHERE rowid = '.$id;
  6792. elseif (!empty($ref)) $sql .= " WHERE ref = ".$this->quote($ref, $this->fields['ref']);
  6793. else $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  6794. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' AND entity IN ('.getEntity($this->table_element).')';
  6795. if ($morewhere) $sql .= $morewhere;
  6796. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  6797. $res = $this->db->query($sql);
  6798. if ($res)
  6799. {
  6800. $obj = $this->db->fetch_object($res);
  6801. if ($obj)
  6802. {
  6803. $this->setVarsFromFetchObj($obj);
  6804. // Retreive all extrafield
  6805. // fetch optionals attributes and labels
  6806. $this->fetch_optionals();
  6807. return $this->id;
  6808. } else {
  6809. return 0;
  6810. }
  6811. } else {
  6812. $this->error = $this->db->lasterror();
  6813. $this->errors[] = $this->error;
  6814. return -1;
  6815. }
  6816. }
  6817. /**
  6818. * Load object in memory from the database
  6819. *
  6820. * @param string $morewhere More SQL filters (' AND ...')
  6821. * @return int <0 if KO, 0 if not found, >0 if OK
  6822. */
  6823. public function fetchLinesCommon($morewhere = '')
  6824. {
  6825. $objectlineclassname = get_class($this).'Line';
  6826. if (!class_exists($objectlineclassname))
  6827. {
  6828. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  6829. return -1;
  6830. }
  6831. $objectline = new $objectlineclassname($this->db);
  6832. $sql = 'SELECT '.$objectline->getFieldList();
  6833. $sql .= ' FROM '.MAIN_DB_PREFIX.$objectline->table_element;
  6834. $sql .= ' WHERE fk_'.$this->element.' = '.$this->id;
  6835. if ($morewhere) $sql .= $morewhere;
  6836. if (isset($objectline->fields['position'])) {
  6837. $sql .= $this->db->order('position', 'ASC');
  6838. }
  6839. $resql = $this->db->query($sql);
  6840. if ($resql)
  6841. {
  6842. $num_rows = $this->db->num_rows($resql);
  6843. $i = 0;
  6844. while ($i < $num_rows)
  6845. {
  6846. $obj = $this->db->fetch_object($resql);
  6847. if ($obj)
  6848. {
  6849. $newline = new $objectlineclassname($this->db);
  6850. $newline->setVarsFromFetchObj($obj);
  6851. $this->lines[] = $newline;
  6852. }
  6853. $i++;
  6854. }
  6855. return 1;
  6856. } else {
  6857. $this->error = $this->db->lasterror();
  6858. $this->errors[] = $this->error;
  6859. return -1;
  6860. }
  6861. }
  6862. /**
  6863. * Update object into database
  6864. *
  6865. * @param User $user User that modifies
  6866. * @param bool $notrigger false=launch triggers after, true=disable triggers
  6867. * @return int <0 if KO, >0 if OK
  6868. */
  6869. public function updateCommon(User $user, $notrigger = false)
  6870. {
  6871. global $conf, $langs;
  6872. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  6873. $error = 0;
  6874. $now = dol_now();
  6875. $fieldvalues = $this->setSaveQuery();
  6876. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) $fieldvalues['date_modification'] = $this->db->idate($now);
  6877. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) $fieldvalues['fk_user_modif'] = $user->id;
  6878. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  6879. if (array_key_exists('ref', $fieldvalues)) $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  6880. $keys = array();
  6881. $values = array();
  6882. $tmp = array();
  6883. foreach ($fieldvalues as $k => $v) {
  6884. $keys[$k] = $k;
  6885. $value = $this->fields[$k];
  6886. $values[$k] = $this->quote($v, $value);
  6887. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  6888. }
  6889. // Clean and check mandatory
  6890. foreach ($keys as $key)
  6891. {
  6892. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key] = ''; // This is an implicit foreign key field
  6893. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key] = ''; // This is an explicit foreign key field
  6894. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  6895. /*
  6896. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  6897. {
  6898. $error++;
  6899. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  6900. }*/
  6901. }
  6902. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode(',', $tmp).' WHERE rowid='.$this->id;
  6903. $this->db->begin();
  6904. if (!$error)
  6905. {
  6906. $res = $this->db->query($sql);
  6907. if ($res === false)
  6908. {
  6909. $error++;
  6910. $this->errors[] = $this->db->lasterror();
  6911. }
  6912. }
  6913. // Update extrafield
  6914. if (!$error)
  6915. {
  6916. $result = $this->insertExtraFields();
  6917. if ($result < 0)
  6918. {
  6919. $error++;
  6920. }
  6921. }
  6922. // Triggers
  6923. if (!$error && !$notrigger)
  6924. {
  6925. // Call triggers
  6926. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  6927. if ($result < 0) { $error++; } //Do also here what you must do to rollback action if trigger fail
  6928. // End call triggers
  6929. }
  6930. // Commit or rollback
  6931. if ($error) {
  6932. $this->db->rollback();
  6933. return -1;
  6934. } else {
  6935. $this->db->commit();
  6936. return $this->id;
  6937. }
  6938. }
  6939. /**
  6940. * Delete object in database
  6941. *
  6942. * @param User $user User that deletes
  6943. * @param bool $notrigger false=launch triggers after, true=disable triggers
  6944. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  6945. * @return int <=0 if KO, >0 if OK
  6946. */
  6947. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  6948. {
  6949. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  6950. $error = 0;
  6951. $this->db->begin();
  6952. if ($forcechilddeletion) // Force also delete of childtables that should lock deletion in standard case when option force is off
  6953. {
  6954. foreach ($this->childtables as $table)
  6955. {
  6956. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
  6957. $resql = $this->db->query($sql);
  6958. if (!$resql)
  6959. {
  6960. $this->error = $this->db->lasterror();
  6961. $this->errors[] = $this->error;
  6962. $this->db->rollback();
  6963. return -1;
  6964. }
  6965. }
  6966. } elseif (!empty($this->fk_element) && !empty($this->childtables)) // If object has childs linked with a foreign key field, we check all child tables.
  6967. {
  6968. $objectisused = $this->isObjectUsed($this->id);
  6969. if (!empty($objectisused))
  6970. {
  6971. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  6972. $this->error = 'ErrorRecordHasChildren';
  6973. $this->errors[] = $this->error;
  6974. $this->db->rollback();
  6975. return 0;
  6976. }
  6977. }
  6978. // Delete cascade first
  6979. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  6980. foreach ($this->childtablesoncascade as $table)
  6981. {
  6982. $deleteFromObject = explode(':', $table);
  6983. if (count($deleteFromObject) >= 2) {
  6984. $className = str_replace('@', '', $deleteFromObject[0]);
  6985. $filePath = $deleteFromObject[1];
  6986. $columnName = $deleteFromObject[2];
  6987. if (dol_include_once($filePath)) {
  6988. $childObject = new $className($this->db);
  6989. if (method_exists($childObject, 'deleteByParentField')) {
  6990. $result = $childObject->deleteByParentField($this->id, $columnName);
  6991. if ($result < 0) {
  6992. $error++;
  6993. $this->errors[] = $childObject->error;
  6994. break;
  6995. }
  6996. } else {
  6997. $error++;
  6998. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  6999. break;
  7000. }
  7001. } else {
  7002. $error++;
  7003. $this->errors[] = 'Cannot include child class file '.$filePath;
  7004. break;
  7005. }
  7006. } else {
  7007. // Delete record in child table
  7008. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
  7009. $resql = $this->db->query($sql);
  7010. if (!$resql) {
  7011. $error++;
  7012. $this->error = $this->db->lasterror();
  7013. $this->errors[] = $this->error;
  7014. break;
  7015. }
  7016. }
  7017. }
  7018. }
  7019. if (!$error) {
  7020. if (!$notrigger) {
  7021. // Call triggers
  7022. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  7023. if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail
  7024. // End call triggers
  7025. }
  7026. }
  7027. if (!$error && !empty($this->isextrafieldmanaged))
  7028. {
  7029. $result = $this->deleteExtraFields();
  7030. if ($result < 0) { $error++; }
  7031. }
  7032. if (!$error)
  7033. {
  7034. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id;
  7035. $res = $this->db->query($sql);
  7036. if ($res === false) {
  7037. $error++;
  7038. $this->errors[] = $this->db->lasterror();
  7039. }
  7040. }
  7041. // Commit or rollback
  7042. if ($error) {
  7043. $this->db->rollback();
  7044. return -1;
  7045. } else {
  7046. $this->db->commit();
  7047. return 1;
  7048. }
  7049. }
  7050. /**
  7051. * Delete all child object from a parent ID
  7052. *
  7053. * @param int $parentId Parent Id
  7054. * @param string $parentField Name of Foreign key parent column
  7055. * @return int <0 if KO, >0 if OK
  7056. * @throws Exception
  7057. */
  7058. public function deleteByParentField($parentId = 0, $parentField = '')
  7059. {
  7060. global $user;
  7061. $error = 0;
  7062. $deleted = 0;
  7063. if (!empty($parentId) && !empty($parentField)) {
  7064. $this->db->begin();
  7065. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$this->table_element;
  7066. $sql .= ' WHERE '.$parentField.' = '.(int) $parentId;
  7067. $resql = $this->db->query($sql);
  7068. if (!$resql) {
  7069. $this->errors[] = $this->db->lasterror();
  7070. $error++;
  7071. } else {
  7072. while ($obj = $this->db->fetch_object($resql)) {
  7073. $result = $this->fetch($obj->rowid);
  7074. if ($result < 0) {
  7075. $error++;
  7076. $this->errors[] = $this->error;
  7077. } else {
  7078. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  7079. $result = $this->delete();
  7080. } else {
  7081. $result = $this->delete($user);
  7082. }
  7083. if ($result < 0) {
  7084. $error++;
  7085. $this->errors[] = $this->error;
  7086. } else {
  7087. $deleted++;
  7088. }
  7089. }
  7090. }
  7091. }
  7092. if (empty($error)) {
  7093. $this->db->commit();
  7094. return $deleted;
  7095. } else {
  7096. $this->error = implode(', ', $this->errors);
  7097. $this->db->rollback();
  7098. return $error * -1;
  7099. }
  7100. }
  7101. return $deleted;
  7102. }
  7103. /**
  7104. * Delete a line of object in database
  7105. *
  7106. * @param User $user User that delete
  7107. * @param int $idline Id of line to delete
  7108. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7109. * @return int >0 if OK, <0 if KO
  7110. */
  7111. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  7112. {
  7113. global $conf;
  7114. $error = 0;
  7115. $tmpforobjectclass = get_class($this);
  7116. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  7117. // Call trigger
  7118. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  7119. if ($result < 0) return -1;
  7120. // End call triggers
  7121. $this->db->begin();
  7122. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  7123. $sql .= " WHERE rowid=".$idline;
  7124. dol_syslog(get_class($this)."::deleteLineCommon", LOG_DEBUG);
  7125. $resql = $this->db->query($sql);
  7126. if (!$resql)
  7127. {
  7128. $this->error = "Error ".$this->db->lasterror();
  7129. $error++;
  7130. }
  7131. if (empty($error)) {
  7132. // Remove extrafields
  7133. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  7134. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  7135. $tmpobjectline->id = $idline;
  7136. $result = $tmpobjectline->deleteExtraFields();
  7137. if ($result < 0)
  7138. {
  7139. $error++;
  7140. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  7141. }
  7142. }
  7143. }
  7144. if (empty($error)) {
  7145. $this->db->commit();
  7146. return 1;
  7147. } else {
  7148. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  7149. $this->db->rollback();
  7150. return -1;
  7151. }
  7152. }
  7153. /**
  7154. * Set to a status
  7155. *
  7156. * @param User $user Object user that modify
  7157. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  7158. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  7159. * @param string $triggercode Trigger code to use
  7160. * @return int <0 if KO, >0 if OK
  7161. */
  7162. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  7163. {
  7164. $error = 0;
  7165. $this->db->begin();
  7166. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  7167. $sql .= " SET status = ".$status;
  7168. $sql .= " WHERE rowid = ".$this->id;
  7169. if ($this->db->query($sql))
  7170. {
  7171. if (!$error)
  7172. {
  7173. $this->oldcopy = clone $this;
  7174. }
  7175. if (!$error && !$notrigger) {
  7176. // Call trigger
  7177. $result = $this->call_trigger($triggercode, $user);
  7178. if ($result < 0) $error++;
  7179. }
  7180. if (!$error) {
  7181. $this->status = $status;
  7182. $this->db->commit();
  7183. return 1;
  7184. } else {
  7185. $this->db->rollback();
  7186. return -1;
  7187. }
  7188. } else {
  7189. $this->error = $this->db->error();
  7190. $this->db->rollback();
  7191. return -1;
  7192. }
  7193. }
  7194. /**
  7195. * Initialise object with example values
  7196. * Id must be 0 if object instance is a specimen
  7197. *
  7198. * @return void
  7199. */
  7200. public function initAsSpecimenCommon()
  7201. {
  7202. global $user;
  7203. $this->id = 0;
  7204. if (array_key_exists('label', $this->fields)) $this->label = 'This is label';
  7205. if (array_key_exists('note_public', $this->fields)) $this->note_public = 'Public note';
  7206. if (array_key_exists('note_private', $this->fields)) $this->note_private = 'Private note';
  7207. if (array_key_exists('date_creation', $this->fields)) $this->date_creation = (dol_now() - 3600 * 24);
  7208. if (array_key_exists('date_modification', $this->fields)) $this->date_modification = (dol_now() - 3600 * 24);
  7209. if (array_key_exists('fk_user_creat', $this->fields)) $this->fk_user_creat = $user->id;
  7210. if (array_key_exists('fk_user_modif', $this->fields)) $this->fk_user_modif = $user->id;
  7211. if (array_key_exists('date', $this->fields)) $this->date = dol_now();
  7212. // ...
  7213. }
  7214. /* Part for comments */
  7215. /**
  7216. * Load comments linked with current task
  7217. * @return boolean 1 if ok
  7218. */
  7219. public function fetchComments()
  7220. {
  7221. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  7222. $comment = new Comment($this->db);
  7223. $result = $comment->fetchAllFor($this->element, $this->id);
  7224. if ($result < 0) {
  7225. $this->errors = array_merge($this->errors, $comment->errors);
  7226. return -1;
  7227. } else {
  7228. $this->comments = $comment->comments;
  7229. }
  7230. return count($this->comments);
  7231. }
  7232. /**
  7233. * Return nb comments already posted
  7234. *
  7235. * @return int
  7236. */
  7237. public function getNbComments()
  7238. {
  7239. return count($this->comments);
  7240. }
  7241. /**
  7242. * Trim object parameters
  7243. * @param string[] $parameters array of parameters to trim
  7244. *
  7245. * @return void
  7246. */
  7247. public function trimParameters($parameters)
  7248. {
  7249. if (!is_array($parameters)) return;
  7250. foreach ($parameters as $parameter) {
  7251. if (isset($this->$parameter)) {
  7252. $this->$parameter = trim($this->$parameter);
  7253. }
  7254. }
  7255. }
  7256. /* Part for categories/tags */
  7257. /**
  7258. * Sets object to given categories.
  7259. *
  7260. * Deletes object from existing categories not supplied.
  7261. * Adds it to non existing supplied categories.
  7262. * Existing categories are left untouch.
  7263. *
  7264. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  7265. * @return int Array of category objects or < 0 if KO
  7266. */
  7267. public function getCategoriesCommon($type_categ)
  7268. {
  7269. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  7270. // Get current categories
  7271. $c = new Categorie($this->db);
  7272. $existing = $c->containing($this->id, $type_categ, 'id');
  7273. return $existing;
  7274. }
  7275. /**
  7276. * Sets object to given categories.
  7277. *
  7278. * Deletes object from existing categories not supplied.
  7279. * Adds it to non existing supplied categories.
  7280. * Existing categories are left untouch.
  7281. *
  7282. * @param int[]|int $categories Category ID or array of Categories IDs
  7283. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  7284. * @return int <0 if KO, >0 if OK
  7285. */
  7286. public function setCategoriesCommon($categories, $type_categ)
  7287. {
  7288. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  7289. // Handle single category
  7290. if (!is_array($categories)) {
  7291. $categories = array($categories);
  7292. }
  7293. // Get current categories
  7294. $c = new Categorie($this->db);
  7295. $existing = $c->containing($this->id, $type_categ, 'id');
  7296. // Diff
  7297. if (is_array($existing)) {
  7298. $to_del = array_diff($existing, $categories);
  7299. $to_add = array_diff($categories, $existing);
  7300. } else {
  7301. $to_del = array(); // Nothing to delete
  7302. $to_add = $categories;
  7303. }
  7304. $error = 0;
  7305. // Process
  7306. foreach ($to_del as $del) {
  7307. if ($c->fetch($del) > 0) {
  7308. $c->del_type($this, $type_categ);
  7309. }
  7310. }
  7311. foreach ($to_add as $add) {
  7312. if ($c->fetch($add) > 0)
  7313. {
  7314. $result = $c->add_type($this, $type_categ);
  7315. if ($result < 0)
  7316. {
  7317. $error++;
  7318. $this->error = $c->error;
  7319. $this->errors = $c->errors;
  7320. break;
  7321. }
  7322. }
  7323. }
  7324. return $error ? -1 : 1;
  7325. }
  7326. /**
  7327. * Copy related categories to another object
  7328. *
  7329. * @param int $fromId Id object source
  7330. * @param int $toId Id object cible
  7331. * @param string $type Type of category ('product', ...)
  7332. * @return int < 0 si erreur, > 0 si ok
  7333. */
  7334. public function cloneCategories($fromId, $toId, $type = '')
  7335. {
  7336. $this->db->begin();
  7337. if (empty($type)) $type = $this->table_element;
  7338. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  7339. $categorystatic = new Categorie($this->db);
  7340. $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  7341. $sql .= " SELECT fk_categorie, $toId FROM ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  7342. $sql .= " WHERE fk_product = ".((int) $fromId);
  7343. if (!$this->db->query($sql))
  7344. {
  7345. $this->error = $this->db->lasterror();
  7346. $this->db->rollback();
  7347. return -1;
  7348. }
  7349. $this->db->commit();
  7350. return 1;
  7351. }
  7352. /**
  7353. * Delete related files of object in database
  7354. *
  7355. * @return bool
  7356. */
  7357. public function deleteEcmFiles()
  7358. {
  7359. global $conf;
  7360. $this->db->begin();
  7361. switch ($this->element){
  7362. case 'propal':
  7363. $element = 'propale';
  7364. break;
  7365. case 'product':
  7366. $element = 'produit';
  7367. break;
  7368. case 'order_supplier':
  7369. $element ='fournisseur/commande';
  7370. break;
  7371. case 'invoice_supplier':
  7372. $element = 'fournisseur/facture/' . get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  7373. break;
  7374. case 'shipping':
  7375. $element = 'expedition/sending';
  7376. break;
  7377. default:
  7378. $element = $this->element;
  7379. }
  7380. $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files";
  7381. $sql.= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  7382. $sql.= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".$conf->entity;
  7383. if (!$this->db->query($sql)) {
  7384. $this->error = $this->db->lasterror();
  7385. $this->db->rollback();
  7386. return false;
  7387. }
  7388. $this->db->commit();
  7389. return true;
  7390. }
  7391. }