commonobject.class.php 333 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713
  1. <?php
  2. /* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
  5. * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
  6. * Copyright (C) 2011-2019 Philippe Grand <philippe.grand@atoo-net.com>
  7. * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
  8. * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  9. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  10. * Copyright (C) 2015-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
  11. * Copyright (C) 2016 Bahfir abbes <dolipar@dolipar.org>
  12. * Copyright (C) 2017 ATM Consulting <support@atm-consulting.fr>
  13. * Copyright (C) 2017-2019 Nicolas ZABOURI <info@inovea-conseil.com>
  14. * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
  15. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  16. * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
  17. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  18. *
  19. * This program is free software; you can redistribute it and/or modify
  20. * it under the terms of the GNU General Public License as published by
  21. * the Free Software Foundation; either version 3 of the License, or
  22. * (at your option) any later version.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU General Public License
  30. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  31. */
  32. /**
  33. * \file htdocs/core/class/commonobject.class.php
  34. * \ingroup core
  35. * \brief File of parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  36. */
  37. /**
  38. * Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  39. */
  40. abstract class CommonObject
  41. {
  42. /**
  43. * @var DoliDb Database handler (result of a new DoliDB)
  44. */
  45. public $db;
  46. /**
  47. * @var int The object identifier
  48. */
  49. public $id;
  50. /**
  51. * @var int The environment ID when using a multicompany module
  52. */
  53. public $entity;
  54. /**
  55. * @var string Error string
  56. * @see $errors
  57. */
  58. public $error;
  59. /**
  60. * @var string Error string that is hidden but can be used to store complementatry technical code.
  61. */
  62. public $errorhidden;
  63. /**
  64. * @var string[] Array of error strings
  65. */
  66. public $errors = array();
  67. /**
  68. * @var array To store error results of ->validateField()
  69. */
  70. public $validateFieldsErrors = array();
  71. /**
  72. * @var string ID to identify managed object
  73. */
  74. public $element;
  75. /**
  76. * @var string Name to use for 'features' parameter to check module permissions with restrictedArea(). Undefined means same value than $element.
  77. */
  78. public $element_for_permission;
  79. /**
  80. * @var string Name of table without prefix where object is stored
  81. */
  82. public $table_element;
  83. /**
  84. * @var string Name of subtable line
  85. */
  86. public $table_element_line = '';
  87. /**
  88. * @var string Key value used to track if data is coming from import wizard
  89. */
  90. public $import_key;
  91. /**
  92. * @var mixed Contains data to manage extrafields
  93. */
  94. public $array_options = array();
  95. /**
  96. * @var mixed Array to store alternative languages values of object
  97. */
  98. public $array_languages = null; // Value is array() when load already tried
  99. /**
  100. * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked
  101. */
  102. public $linkedObjectsIds;
  103. /**
  104. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  105. */
  106. public $linkedObjects;
  107. /**
  108. * @var Object To store a cloned copy of object before to edit it and keep track of old properties
  109. */
  110. public $oldcopy;
  111. /**
  112. * @var string Column name of the ref field.
  113. */
  114. protected $table_ref_field = '';
  115. /**
  116. * @var integer 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user
  117. */
  118. public $restrictiononfksoc = 0;
  119. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  120. /**
  121. * @var array<string,mixed> Can be used to pass information when only object is provided to method
  122. */
  123. public $context = array();
  124. /**
  125. * @var string Contains canvas name if record is an alternative canvas record
  126. */
  127. public $canvas;
  128. /**
  129. * @var Project The related project
  130. * @see fetch_projet()
  131. */
  132. public $project;
  133. /**
  134. * @var int The related project ID
  135. * @see setProject(), project
  136. */
  137. public $fk_project;
  138. /**
  139. * @deprecated
  140. * @see project
  141. */
  142. public $projet;
  143. /**
  144. * @var Contact a related contact
  145. * @see fetch_contact()
  146. */
  147. public $contact;
  148. /**
  149. * @var int The related contact ID
  150. * @see fetch_contact()
  151. */
  152. public $contact_id;
  153. /**
  154. * @var Societe A related thirdparty
  155. * @see fetch_thirdparty()
  156. */
  157. public $thirdparty;
  158. /**
  159. * @var User A related user
  160. * @see fetch_user()
  161. */
  162. public $user;
  163. /**
  164. * @var string The type of originating object ('commande', 'facture', ...)
  165. * @see fetch_origin()
  166. */
  167. public $origin;
  168. /**
  169. * @var int The id of originating object
  170. * @see fetch_origin()
  171. */
  172. public $origin_id;
  173. /**
  174. * @var string The object's reference
  175. */
  176. public $ref;
  177. /**
  178. * @var string An external reference for the object
  179. */
  180. public $ref_ext;
  181. /**
  182. * @var string The object's previous reference
  183. */
  184. public $ref_previous;
  185. /**
  186. * @var string The object's next reference
  187. */
  188. public $ref_next;
  189. /**
  190. * @var string Ref to store on object to save the new ref to use for example when making a validate() of an object
  191. */
  192. public $newref;
  193. /**
  194. * @var int The object's status
  195. * @see setStatut()
  196. */
  197. public $statut;
  198. /**
  199. * @var int The object's status
  200. * @see setStatut()
  201. */
  202. public $status;
  203. /**
  204. * @var string
  205. * @see getFullAddress()
  206. */
  207. public $country;
  208. /**
  209. * @var int
  210. * @see getFullAddress(), country
  211. */
  212. public $country_id;
  213. /**
  214. * @var string
  215. * @see getFullAddress(), isInEEC(), country
  216. */
  217. public $country_code;
  218. /**
  219. * @var string
  220. * @see getFullAddress()
  221. */
  222. public $state;
  223. /**
  224. * @var int
  225. * @see getFullAddress(), state
  226. */
  227. public $state_id;
  228. /**
  229. * @var string
  230. * @see getFullAddress(), $state
  231. */
  232. public $state_code;
  233. /**
  234. * @var int
  235. * @see getFullAddress(), $region_code, $region
  236. */
  237. public $region_id;
  238. /**
  239. * @var string
  240. * @see getFullAddress(), $region_id, $region
  241. */
  242. public $region_code;
  243. /**
  244. * @var string
  245. * @see getFullAddress(), $region_id, $region_code
  246. */
  247. public $region;
  248. /**
  249. * @var int
  250. * @see fetch_barcode()
  251. */
  252. public $barcode_type;
  253. /**
  254. * @var string
  255. * @see fetch_barcode(), barcode_type
  256. */
  257. public $barcode_type_code;
  258. /**
  259. * @var string
  260. * @see fetch_barcode(), barcode_type
  261. */
  262. public $barcode_type_label;
  263. /**
  264. * @var string
  265. * @see fetch_barcode(), barcode_type
  266. */
  267. public $barcode_type_coder;
  268. /**
  269. * @var int Payment method ID (cheque, cash, ...)
  270. * @see setPaymentMethods()
  271. */
  272. public $mode_reglement_id;
  273. /**
  274. * @var int Payment terms ID
  275. * @see setPaymentTerms()
  276. */
  277. public $cond_reglement_id;
  278. /**
  279. * @var int Demand reason ID
  280. */
  281. public $demand_reason_id;
  282. /**
  283. * @var int Transport mode ID (For module intracomm report)
  284. * @see setTransportMode()
  285. */
  286. public $transport_mode_id;
  287. /**
  288. * @var int Payment terms ID
  289. * @deprecated Kept for compatibility
  290. * @see cond_reglement_id;
  291. */
  292. public $cond_reglement;
  293. /**
  294. * @var int Delivery address ID
  295. * @see setDeliveryAddress()
  296. * @deprecated
  297. */
  298. public $fk_delivery_address;
  299. /**
  300. * @var int Shipping method ID
  301. * @see setShippingMethod()
  302. */
  303. public $shipping_method_id;
  304. /**
  305. * @var string
  306. * @see SetDocModel()
  307. */
  308. public $model_pdf;
  309. /**
  310. * @var string
  311. * @deprecated
  312. * @see $model_pdf
  313. */
  314. public $modelpdf;
  315. /**
  316. * @var string
  317. * Contains relative path of last generated main file
  318. */
  319. public $last_main_doc;
  320. /**
  321. * @var int Bank account ID sometimes, ID of record into llx_bank sometimes
  322. * @deprecated
  323. * @see $fk_account
  324. */
  325. public $fk_bank;
  326. /**
  327. * @var int Bank account ID
  328. * @see SetBankAccount()
  329. */
  330. public $fk_account;
  331. /**
  332. * @var string Open ID
  333. */
  334. public $openid;
  335. /**
  336. * @var string Public note
  337. * @see update_note()
  338. */
  339. public $note_public;
  340. /**
  341. * @var string Private note
  342. * @see update_note()
  343. */
  344. public $note_private;
  345. /**
  346. * @deprecated
  347. * @see $note_private
  348. */
  349. public $note;
  350. /**
  351. * @var float Total amount before taxes
  352. * @see update_price()
  353. */
  354. public $total_ht;
  355. /**
  356. * @var float Total VAT amount
  357. * @see update_price()
  358. */
  359. public $total_tva;
  360. /**
  361. * @var float Total local tax 1 amount
  362. * @see update_price()
  363. */
  364. public $total_localtax1;
  365. /**
  366. * @var float Total local tax 2 amount
  367. * @see update_price()
  368. */
  369. public $total_localtax2;
  370. /**
  371. * @var float Total amount with taxes
  372. * @see update_price()
  373. */
  374. public $total_ttc;
  375. /**
  376. * @var CommonObjectLine[]
  377. */
  378. public $lines;
  379. /**
  380. * @var mixed Contains comments
  381. * @see fetchComments()
  382. */
  383. public $comments = array();
  384. /**
  385. * @var string The name
  386. */
  387. public $name;
  388. /**
  389. * @var string The lastname
  390. */
  391. public $lastname;
  392. /**
  393. * @var string The firstname
  394. */
  395. public $firstname;
  396. /**
  397. * @var string The civility code, not an integer
  398. */
  399. public $civility_id;
  400. // Dates
  401. /**
  402. * @var integer|string date_creation
  403. */
  404. public $date_creation;
  405. /**
  406. * @var integer|string $date_validation;
  407. */
  408. public $date_validation; // Date validation
  409. /**
  410. * @var integer|string $date_modification;
  411. */
  412. public $date_modification; // Date last change (tms field)
  413. public $next_prev_filter;
  414. /**
  415. * @var int 1 if object is specimen
  416. */
  417. public $specimen = 0;
  418. /**
  419. * @var int Id of contact to send object (used by the trigger of module Agenda)
  420. */
  421. public $sendtoid;
  422. /**
  423. * @var float Amount already paid (used to show correct status)
  424. */
  425. public $alreadypaid;
  426. /**
  427. * @var array List of child tables. To test if we can delete object.
  428. */
  429. protected $childtables = array();
  430. /**
  431. * @var array List of child tables. To know object to delete on cascade.
  432. * If name is like '@ClassName:FilePathClass:ParentFkFieldName', it will
  433. * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object.
  434. */
  435. protected $childtablesoncascade = array();
  436. // No constructor as it is an abstract class
  437. /**
  438. * Check an object id/ref exists
  439. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  440. *
  441. * @param string $element String of element ('product', 'facture', ...)
  442. * @param int $id Id of object
  443. * @param string $ref Ref of object to check
  444. * @param string $ref_ext Ref ext of object to check
  445. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  446. */
  447. public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
  448. {
  449. global $db, $conf;
  450. $sql = "SELECT rowid, ref, ref_ext";
  451. $sql .= " FROM ".$db->prefix().$element;
  452. $sql .= " WHERE entity IN (".getEntity($element).")";
  453. if ($id > 0) {
  454. $sql .= " AND rowid = ".((int) $id);
  455. } elseif ($ref) {
  456. $sql .= " AND ref = '".$db->escape($ref)."'";
  457. } elseif ($ref_ext) {
  458. $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
  459. } else {
  460. $error = 'ErrorWrongParameters';
  461. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  462. return -1;
  463. }
  464. if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
  465. $sql .= " AND entity = ".((int) $conf->entity);
  466. }
  467. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  468. $resql = $db->query($sql);
  469. if ($resql) {
  470. $num = $db->num_rows($resql);
  471. if ($num > 0) {
  472. return 1;
  473. } else {
  474. return 0;
  475. }
  476. }
  477. return -1;
  478. }
  479. /**
  480. * Method to output saved errors
  481. *
  482. * @return string String with errors
  483. */
  484. public function errorsToString()
  485. {
  486. return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
  487. }
  488. /**
  489. * Return customer ref for screen output.
  490. *
  491. * @param string $objref Customer ref
  492. * @return string Customer ref formated
  493. */
  494. public function getFormatedCustomerRef($objref)
  495. {
  496. global $hookmanager;
  497. $parameters = array('objref'=>$objref);
  498. $action = '';
  499. $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  500. if ($reshook > 0) {
  501. return $hookmanager->resArray['objref'];
  502. }
  503. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  504. }
  505. /**
  506. * Return supplier ref for screen output.
  507. *
  508. * @param string $objref Supplier ref
  509. * @return string Supplier ref formated
  510. */
  511. public function getFormatedSupplierRef($objref)
  512. {
  513. global $hookmanager;
  514. $parameters = array('objref'=>$objref);
  515. $action = '';
  516. $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  517. if ($reshook > 0) {
  518. return $hookmanager->resArray['objref'];
  519. }
  520. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  521. }
  522. /**
  523. * Return full name (civility+' '+name+' '+lastname)
  524. *
  525. * @param Translate $langs Language object for translation of civility (used only if option is 1)
  526. * @param int $option 0=No option, 1=Add civility
  527. * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname, 3=Firstname if defined else lastname, 4=Lastname, 5=Lastname if defined else firstname
  528. * @param int $maxlen Maximum length
  529. * @return string String with full name
  530. */
  531. public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
  532. {
  533. //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
  534. $lastname = $this->lastname;
  535. $firstname = $this->firstname;
  536. if (empty($lastname)) {
  537. $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 : '')))));
  538. }
  539. $ret = '';
  540. if (!empty($option) && !empty($this->civility_code)) {
  541. if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) {
  542. $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
  543. } else {
  544. $ret .= $this->civility_code.' ';
  545. }
  546. }
  547. $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
  548. return dol_trunc($ret, $maxlen);
  549. }
  550. /**
  551. * Set to upper or ucwords/lower if needed
  552. *
  553. * @return void;
  554. */
  555. public function setUpperOrLowerCase()
  556. {
  557. global $conf;
  558. if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
  559. $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
  560. $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
  561. $this->name = dol_ucwords(dol_strtolower($this->name));
  562. $this->name_alias = dol_ucwords(dol_strtolower($this->name_alias));
  563. }
  564. if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
  565. $this->lastname = dol_strtoupper($this->lastname);
  566. $this->name = dol_strtoupper($this->name);
  567. $this->name_alias = dol_strtoupper($this->name_alias);
  568. }
  569. if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
  570. $this->address = dol_strtoupper($this->address);
  571. $this->town = dol_strtoupper($this->town);
  572. }
  573. }
  574. /**
  575. * Return clicable link of object (with eventually picto)
  576. *
  577. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  578. * @return string HTML Code for Kanban thumb.
  579. */
  580. public function getKanbanView($option = '')
  581. {
  582. $return = '<div class="box-flex-item box-flex-grow-zero">';
  583. $return .= '<div class="info-box info-box-sm">';
  584. $return .= '<span class="info-box-icon bg-infobox-action">';
  585. $return .= img_picto('', $this->picto);
  586. //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
  587. $return .= '</span>';
  588. $return .= '<div class="info-box-content">';
  589. $return .= '<span class="info-box-ref">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  590. if (property_exists($this, 'label')) {
  591. $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
  592. }
  593. if (method_exists($this, 'getLibStatut')) {
  594. $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(5).'</div>';
  595. }
  596. $return .= '</div>';
  597. $return .= '</div>';
  598. $return .= '</div>';
  599. return $return;
  600. }
  601. /**
  602. * Return full address of contact
  603. *
  604. * @param int $withcountry 1=Add country into address string
  605. * @param string $sep Separator to use to build string
  606. * @param int $withregion 1=Add region into address string
  607. * @param string $extralangcode User extralanguages as value
  608. * @return string Full address string
  609. */
  610. public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
  611. {
  612. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
  613. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  614. $tmparray = getCountry($this->country_id, 'all');
  615. $this->country_code = $tmparray['code'];
  616. $this->country = $tmparray['label'];
  617. }
  618. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
  619. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  620. $tmparray = getState($this->state_id, 'all', 0, 1);
  621. $this->state_code = $tmparray['code'];
  622. $this->state = $tmparray['label'];
  623. $this->region_code = $tmparray['region_code'];
  624. $this->region = $tmparray['region'];
  625. }
  626. return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
  627. }
  628. /**
  629. * Return full address for banner
  630. *
  631. * @param string $htmlkey HTML id to make banner content unique
  632. * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member)
  633. * @return string Full address string
  634. */
  635. public function getBannerAddress($htmlkey, $object)
  636. {
  637. global $conf, $langs, $form, $extralanguages;
  638. $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
  639. $contactid = 0;
  640. $thirdpartyid = 0;
  641. $elementforaltlanguage = $this->element;
  642. if ($this->element == 'societe') {
  643. $thirdpartyid = $this->id;
  644. }
  645. if ($this->element == 'contact') {
  646. $contactid = $this->id;
  647. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  648. }
  649. if ($this->element == 'user') {
  650. $contactid = $this->contact_id;
  651. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  652. }
  653. $out = '';
  654. $outdone = 0;
  655. $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
  656. if ($coords) {
  657. if (!empty($conf->use_javascript_ajax)) {
  658. // Add picto with tooltip on map
  659. $namecoords = '';
  660. if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
  661. $namecoords .= $object->name.'<br>';
  662. }
  663. $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
  664. // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
  665. $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
  666. $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
  667. $out .= '</a> ';
  668. }
  669. $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  670. $outdone++;
  671. $outdone++;
  672. // List of extra languages
  673. $arrayoflangcode = array();
  674. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  675. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  676. }
  677. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  678. if (!is_object($extralanguages)) {
  679. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  680. $extralanguages = new ExtraLanguages($this->db);
  681. }
  682. $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
  683. if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
  684. $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
  685. $this->fetchValuesForExtraLanguages();
  686. if (!is_object($form)) {
  687. $form = new Form($this->db);
  688. }
  689. $htmltext = '';
  690. // If there is extra languages
  691. foreach ($arrayoflangcode as $extralangcode) {
  692. $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  693. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
  694. $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  695. }
  696. $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  697. }
  698. }
  699. }
  700. 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
  701. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
  702. if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
  703. $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
  704. } else {
  705. $out .= ($outdone ? ' - ' : '').$this->state;
  706. }
  707. $outdone++;
  708. }
  709. 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)) {
  710. $out .= ($outdone ? '<br>' : '');
  711. }
  712. if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  713. $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  714. $outdone++;
  715. }
  716. if (!empty($this->phone_pro)) {
  717. $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  718. $outdone++;
  719. }
  720. if (!empty($this->phone_mobile)) {
  721. $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  722. $outdone++;
  723. }
  724. if (!empty($this->phone_perso)) {
  725. $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
  726. $outdone++;
  727. }
  728. if (!empty($this->office_phone)) {
  729. $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  730. $outdone++;
  731. }
  732. if (!empty($this->user_mobile)) {
  733. $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  734. $outdone++;
  735. }
  736. if (!empty($this->fax)) {
  737. $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  738. $outdone++;
  739. }
  740. if (!empty($this->office_fax)) {
  741. $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  742. $outdone++;
  743. }
  744. if ($out) {
  745. $out .= '<div style="clear: both;"></div>';
  746. }
  747. $outdone = 0;
  748. if (!empty($this->email)) {
  749. $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
  750. $outdone++;
  751. }
  752. if (!empty($this->url)) {
  753. //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
  754. $out .= dol_print_url($this->url, '_blank', 0, 1);
  755. $outdone++;
  756. }
  757. if (!empty($conf->socialnetworks->enabled)) {
  758. $outsocialnetwork = '';
  759. if (!empty($this->socialnetworks) && is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
  760. $socialnetworksdict = getArrayOfSocialNetworks();
  761. foreach ($this->socialnetworks as $key => $value) {
  762. if ($value) {
  763. $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
  764. }
  765. $outdone++;
  766. }
  767. } else { // Old code to remove
  768. if (!empty($this->skype)) {
  769. $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
  770. }
  771. $outdone++;
  772. if (!empty($this->jabberid)) {
  773. $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
  774. }
  775. $outdone++;
  776. if (!empty($this->twitter)) {
  777. $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
  778. }
  779. $outdone++;
  780. if (!empty($this->facebook)) {
  781. $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
  782. }
  783. $outdone++;
  784. if (!empty($this->linkedin)) {
  785. $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
  786. }
  787. $outdone++;
  788. }
  789. if ($outsocialnetwork) {
  790. $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
  791. }
  792. }
  793. if ($out) {
  794. return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
  795. } else {
  796. return '';
  797. }
  798. }
  799. /**
  800. * Return the link of last main doc file for direct public download.
  801. *
  802. * @param string $modulepart Module related to document
  803. * @param int $initsharekey Init the share key if it was not yet defined
  804. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  805. * @return string Link or empty string if there is no download link
  806. */
  807. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  808. {
  809. global $user, $dolibarr_main_url_root;
  810. if (empty($this->last_main_doc)) {
  811. return ''; // No way to known which document name to use
  812. }
  813. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  814. $ecmfile = new EcmFiles($this->db);
  815. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  816. if ($result < 0) {
  817. $this->error = $ecmfile->error;
  818. $this->errors = $ecmfile->errors;
  819. return -1;
  820. }
  821. if (empty($ecmfile->id)) {
  822. // Add entry into index
  823. if ($initsharekey) {
  824. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  825. // TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first
  826. /*
  827. $ecmfile->filepath = $rel_dir;
  828. $ecmfile->filename = $filename;
  829. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  830. $ecmfile->fullpath_orig = '';
  831. $ecmfile->gen_or_uploaded = 'generated';
  832. $ecmfile->description = ''; // indexed content
  833. $ecmfile->keywords = ''; // keyword content
  834. $ecmfile->share = getRandomPassword(true);
  835. $result = $ecmfile->create($user);
  836. if ($result < 0)
  837. {
  838. $this->error = $ecmfile->error;
  839. $this->errors = $ecmfile->errors;
  840. }
  841. */
  842. } else {
  843. return '';
  844. }
  845. } elseif (empty($ecmfile->share)) {
  846. // Add entry into index
  847. if ($initsharekey) {
  848. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  849. $ecmfile->share = getRandomPassword(true);
  850. $ecmfile->update($user);
  851. } else {
  852. return '';
  853. }
  854. }
  855. // Define $urlwithroot
  856. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  857. // This is to use external domain name found into config file
  858. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  859. //else
  860. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  861. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  862. $forcedownload = 0;
  863. $paramlink = '';
  864. //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  865. //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  866. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  867. if (!empty($ecmfile->share)) {
  868. $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
  869. }
  870. if ($forcedownload) {
  871. $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  872. }
  873. if ($relativelink) {
  874. $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
  875. } else {
  876. $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  877. }
  878. // Here $ecmfile->share is defined
  879. return $linktoreturn;
  880. }
  881. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  882. /**
  883. * Add a link between element $this->element and a contact
  884. *
  885. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  886. * @param int|string $type_contact Type of contact (code or id). Must be id or code found into table llx_c_type_contact. For example: SALESREPFOLL
  887. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  888. * @param int $notrigger Disable all triggers
  889. * @return int <0 if KO, 0 if already added, >0 if OK
  890. */
  891. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  892. {
  893. // phpcs:enable
  894. global $user, $langs;
  895. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  896. // Check parameters
  897. if ($fk_socpeople <= 0) {
  898. $langs->load("errors");
  899. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  900. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  901. return -1;
  902. }
  903. if (!$type_contact) {
  904. $langs->load("errors");
  905. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  906. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  907. return -2;
  908. }
  909. $id_type_contact = 0;
  910. if (is_numeric($type_contact)) {
  911. $id_type_contact = $type_contact;
  912. } else {
  913. // We look for id type_contact
  914. $sql = "SELECT tc.rowid";
  915. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  916. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  917. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  918. $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  919. //print $sql;
  920. $resql = $this->db->query($sql);
  921. if ($resql) {
  922. $obj = $this->db->fetch_object($resql);
  923. if ($obj) {
  924. $id_type_contact = $obj->rowid;
  925. }
  926. }
  927. }
  928. if ($id_type_contact == 0) {
  929. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  930. 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");
  931. return -3;
  932. }
  933. $datecreate = dol_now();
  934. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  935. $TListeContacts = $this->liste_contact(-1, $source);
  936. $already_added = false;
  937. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  938. foreach ($TListeContacts as $array_contact) {
  939. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  940. $already_added = true;
  941. break;
  942. }
  943. }
  944. }
  945. if (!$already_added) {
  946. $this->db->begin();
  947. // Insert into database
  948. $sql = "INSERT INTO ".$this->db->prefix()."element_contact";
  949. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  950. $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
  951. $sql .= "'".$this->db->idate($datecreate)."'";
  952. $sql .= ", 4, ".((int) $id_type_contact);
  953. $sql .= ")";
  954. $resql = $this->db->query($sql);
  955. if ($resql) {
  956. if (!$notrigger) {
  957. $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  958. if ($result < 0) {
  959. $this->db->rollback();
  960. return -1;
  961. }
  962. }
  963. $this->db->commit();
  964. return 1;
  965. } else {
  966. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  967. $this->error = $this->db->errno();
  968. $this->db->rollback();
  969. return -2;
  970. } else {
  971. $this->error = $this->db->lasterror();
  972. $this->db->rollback();
  973. return -1;
  974. }
  975. }
  976. } else {
  977. return 0;
  978. }
  979. }
  980. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  981. /**
  982. * Copy contact from one element to current
  983. *
  984. * @param CommonObject $objFrom Source element
  985. * @param string $source Nature of contact ('internal' or 'external')
  986. * @return int >0 if OK, <0 if KO
  987. */
  988. public function copy_linked_contact($objFrom, $source = 'internal')
  989. {
  990. // phpcs:enable
  991. $contacts = $objFrom->liste_contact(-1, $source);
  992. foreach ($contacts as $contact) {
  993. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
  994. return -1;
  995. }
  996. }
  997. return 1;
  998. }
  999. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1000. /**
  1001. * Update a link to contact line
  1002. *
  1003. * @param int $rowid Id of line contact-element
  1004. * @param int $statut New status of link
  1005. * @param int $type_contact_id Id of contact type (not modified if 0)
  1006. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  1007. * @return int <0 if KO, >= 0 if OK
  1008. */
  1009. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  1010. {
  1011. // phpcs:enable
  1012. // Insert into database
  1013. $sql = "UPDATE ".$this->db->prefix()."element_contact set";
  1014. $sql .= " statut = ".$statut;
  1015. if ($type_contact_id) {
  1016. $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
  1017. }
  1018. if ($fk_socpeople) {
  1019. $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
  1020. }
  1021. $sql .= " where rowid = ".((int) $rowid);
  1022. $resql = $this->db->query($sql);
  1023. if ($resql) {
  1024. return 0;
  1025. } else {
  1026. $this->error = $this->db->lasterror();
  1027. return -1;
  1028. }
  1029. }
  1030. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1031. /**
  1032. * Delete a link to contact line
  1033. *
  1034. * @param int $rowid Id of contact link line to delete
  1035. * @param int $notrigger Disable all triggers
  1036. * @return int >0 if OK, <0 if KO
  1037. */
  1038. public function delete_contact($rowid, $notrigger = 0)
  1039. {
  1040. // phpcs:enable
  1041. global $user;
  1042. $this->db->begin();
  1043. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1044. $sql .= " WHERE rowid = ".((int) $rowid);
  1045. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  1046. if ($this->db->query($sql)) {
  1047. if (!$notrigger) {
  1048. $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  1049. if ($result < 0) {
  1050. $this->db->rollback();
  1051. return -1;
  1052. }
  1053. }
  1054. $this->db->commit();
  1055. return 1;
  1056. } else {
  1057. $this->error = $this->db->lasterror();
  1058. $this->db->rollback();
  1059. return -1;
  1060. }
  1061. }
  1062. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1063. /**
  1064. * Delete all links between an object $this and all its contacts
  1065. *
  1066. * @param string $source '' or 'internal' or 'external'
  1067. * @param string $code Type of contact (code or id)
  1068. * @return int >0 if OK, <0 if KO
  1069. */
  1070. public function delete_linked_contact($source = '', $code = '')
  1071. {
  1072. // phpcs:enable
  1073. $listId = '';
  1074. $temp = array();
  1075. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  1076. if (!empty($typeContact)) {
  1077. foreach ($typeContact as $key => $value) {
  1078. array_push($temp, $key);
  1079. }
  1080. $listId = implode(",", $temp);
  1081. }
  1082. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1083. $sql .= " WHERE element_id = ".((int) $this->id);
  1084. if (!empty($listId)) {
  1085. $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
  1086. }
  1087. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  1088. if ($this->db->query($sql)) {
  1089. return 1;
  1090. } else {
  1091. $this->error = $this->db->lasterror();
  1092. return -1;
  1093. }
  1094. }
  1095. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1096. /**
  1097. * Get array of all contacts for an object
  1098. *
  1099. * @param int $status Status of links to get (-1=all)
  1100. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  1101. * @param int $list 0:Return array contains all properties, 1:Return array contains just id
  1102. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1103. * @return array|int Array of contacts, -1 if error
  1104. */
  1105. public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
  1106. {
  1107. // phpcs:enable
  1108. global $langs;
  1109. $tab = array();
  1110. $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
  1111. if ($source == 'internal') {
  1112. $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  1113. }
  1114. if ($source == 'external' || $source == 'thirdparty') {
  1115. $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1116. }
  1117. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  1118. $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
  1119. $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
  1120. $sql .= ", ".$this->db->prefix()."element_contact ec";
  1121. if ($source == 'internal') {
  1122. $sql .= " LEFT JOIN ".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid";
  1123. }
  1124. if ($source == 'external' || $source == 'thirdparty') {
  1125. $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid";
  1126. }
  1127. $sql .= " WHERE ec.element_id = ".((int) $this->id);
  1128. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1129. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1130. if ($code) {
  1131. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1132. }
  1133. if ($source == 'internal') {
  1134. $sql .= " AND tc.source = 'internal'";
  1135. }
  1136. if ($source == 'external' || $source == 'thirdparty') {
  1137. $sql .= " AND tc.source = 'external'";
  1138. }
  1139. $sql .= " AND tc.active=1";
  1140. if ($status >= 0) {
  1141. $sql .= " AND ec.statut = ".((int) $status);
  1142. }
  1143. $sql .= " ORDER BY t.lastname ASC";
  1144. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  1145. $resql = $this->db->query($sql);
  1146. if ($resql) {
  1147. $num = $this->db->num_rows($resql);
  1148. $i = 0;
  1149. while ($i < $num) {
  1150. $obj = $this->db->fetch_object($resql);
  1151. if (!$list) {
  1152. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1153. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1154. $tab[$i] = array(
  1155. 'source' => $obj->source,
  1156. 'socid' => $obj->socid,
  1157. 'id' => $obj->id,
  1158. 'nom' => $obj->lastname, // For backward compatibility
  1159. 'civility' => $obj->civility,
  1160. 'lastname' => $obj->lastname,
  1161. 'firstname' => $obj->firstname,
  1162. 'email'=>$obj->email,
  1163. 'login'=> (empty($obj->login) ? '' : $obj->login),
  1164. 'photo' => (empty($obj->photo) ? '' : $obj->photo),
  1165. 'statuscontact' => $obj->statuscontact,
  1166. 'rowid' => $obj->rowid,
  1167. 'code' => $obj->code,
  1168. 'libelle' => $libelle_type,
  1169. 'status' => $obj->statuslink,
  1170. 'fk_c_type_contact' => $obj->fk_c_type_contact
  1171. );
  1172. } else {
  1173. $tab[$i] = $obj->id;
  1174. }
  1175. $i++;
  1176. }
  1177. return $tab;
  1178. } else {
  1179. $this->error = $this->db->lasterror();
  1180. dol_print_error($this->db);
  1181. return -1;
  1182. }
  1183. }
  1184. /**
  1185. * Update status of a contact linked to object
  1186. *
  1187. * @param int $rowid Id of link between object and contact
  1188. * @return int <0 if KO, >=0 if OK
  1189. */
  1190. public function swapContactStatus($rowid)
  1191. {
  1192. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1193. $sql .= " tc.code, tc.libelle";
  1194. $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
  1195. $sql .= " WHERE ec.rowid =".((int) $rowid);
  1196. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1197. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1198. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  1199. $resql = $this->db->query($sql);
  1200. if ($resql) {
  1201. $obj = $this->db->fetch_object($resql);
  1202. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1203. $result = $this->update_contact($rowid, $newstatut);
  1204. $this->db->free($resql);
  1205. return $result;
  1206. } else {
  1207. $this->error = $this->db->error();
  1208. dol_print_error($this->db);
  1209. return -1;
  1210. }
  1211. }
  1212. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1213. /**
  1214. * Return array with list of possible values for type of contacts
  1215. *
  1216. * @param string $source 'internal', 'external' or 'all'
  1217. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  1218. * @param int $option 0=Return array id->label, 1=Return array code->label
  1219. * @param int $activeonly 0=all status of contact, 1=only the active
  1220. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1221. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1222. */
  1223. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1224. {
  1225. // phpcs:enable
  1226. global $langs;
  1227. if (empty($order)) {
  1228. $order = 'position';
  1229. }
  1230. if ($order == 'position') {
  1231. $order .= ',code';
  1232. }
  1233. $tab = array();
  1234. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  1235. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1236. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1237. if ($activeonly == 1) {
  1238. $sql .= " AND tc.active=1"; // only the active types
  1239. }
  1240. if (!empty($source) && $source != 'all') {
  1241. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1242. }
  1243. if (!empty($code)) {
  1244. $sql .= " AND tc.code='".$this->db->escape($code)."'";
  1245. }
  1246. $sql .= $this->db->order($order, 'ASC');
  1247. //print "sql=".$sql;
  1248. $resql = $this->db->query($sql);
  1249. if ($resql) {
  1250. $num = $this->db->num_rows($resql);
  1251. $i = 0;
  1252. while ($i < $num) {
  1253. $obj = $this->db->fetch_object($resql);
  1254. $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
  1255. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1256. if (empty($option)) {
  1257. $tab[$obj->rowid] = $libelle_type;
  1258. } else {
  1259. $tab[$obj->code] = $libelle_type;
  1260. }
  1261. $i++;
  1262. }
  1263. return $tab;
  1264. } else {
  1265. $this->error = $this->db->lasterror();
  1266. //dol_print_error($this->db);
  1267. return null;
  1268. }
  1269. }
  1270. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1271. /**
  1272. * Return array with list of possible values for type of contacts
  1273. *
  1274. * @param string $source 'internal', 'external' or 'all'
  1275. * @param int $option 0=Return array id->label, 1=Return array code->label
  1276. * @param int $activeonly 0=all status of contact, 1=only the active
  1277. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1278. * @param string $element Filter on 1 element type
  1279. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1280. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1281. */
  1282. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1283. {
  1284. // phpcs:enable
  1285. global $langs, $conf;
  1286. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1287. $tab = array();
  1288. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
  1289. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1290. $sqlWhere = array();
  1291. if (!empty($element)) {
  1292. $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
  1293. }
  1294. if (!empty($excludeelement)) {
  1295. $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
  1296. }
  1297. if ($activeonly == 1) {
  1298. $sqlWhere[] = " tc.active=1"; // only the active types
  1299. }
  1300. if (!empty($source) && $source != 'all') {
  1301. $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
  1302. }
  1303. if (!empty($code)) {
  1304. $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
  1305. }
  1306. if (count($sqlWhere) > 0) {
  1307. $sql .= " WHERE ".implode(' AND ', $sqlWhere);
  1308. }
  1309. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1310. dol_syslog(__METHOD__, LOG_DEBUG);
  1311. $resql = $this->db->query($sql);
  1312. if ($resql) {
  1313. $num = $this->db->num_rows($resql);
  1314. if ($num > 0) {
  1315. $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
  1316. while ($obj = $this->db->fetch_object($resql)) {
  1317. $modulename = $obj->element;
  1318. if (strpos($obj->element, 'project') !== false) {
  1319. $modulename = 'projet';
  1320. } elseif ($obj->element == 'contrat') {
  1321. $element = 'contract';
  1322. } elseif ($obj->element == 'action') {
  1323. $modulename = 'agenda';
  1324. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1325. $modulename = 'fournisseur';
  1326. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1327. $modulename = 'fournisseur';
  1328. }
  1329. if (!empty($conf->{$modulename}->enabled)) {
  1330. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1331. $tmpelement = $obj->element;
  1332. $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
  1333. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1334. if (empty($option)) {
  1335. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1336. } else {
  1337. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1338. }
  1339. }
  1340. }
  1341. }
  1342. return $tab;
  1343. } else {
  1344. $this->error = $this->db->lasterror();
  1345. return null;
  1346. }
  1347. }
  1348. /**
  1349. * Return id of contacts for a source and a contact code.
  1350. * Example: contact client de facturation ('external', 'BILLING')
  1351. * Example: contact client de livraison ('external', 'SHIPPING')
  1352. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1353. *
  1354. * @param string $source 'external' or 'internal'
  1355. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1356. * @param int $status limited to a certain status
  1357. * @return array List of id for such contacts
  1358. */
  1359. public function getIdContact($source, $code, $status = 0)
  1360. {
  1361. global $conf;
  1362. $result = array();
  1363. $i = 0;
  1364. //cas particulier pour les expeditions
  1365. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1366. $id = $this->origin_id;
  1367. $element = 'commande';
  1368. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1369. $id = $this->origin_id;
  1370. $element = 'order_supplier';
  1371. } else {
  1372. $id = $this->id;
  1373. $element = $this->element;
  1374. }
  1375. $sql = "SELECT ec.fk_socpeople";
  1376. $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
  1377. if ($source == 'internal') {
  1378. $sql .= " ".$this->db->prefix()."user as c,";
  1379. }
  1380. if ($source == 'external') {
  1381. $sql .= " ".$this->db->prefix()."socpeople as c,";
  1382. }
  1383. $sql .= " ".$this->db->prefix()."c_type_contact as tc";
  1384. $sql .= " WHERE ec.element_id = ".((int) $id);
  1385. $sql .= " AND ec.fk_socpeople = c.rowid";
  1386. if ($source == 'internal') {
  1387. $sql .= " AND c.entity IN (".getEntity('user').")";
  1388. }
  1389. if ($source == 'external') {
  1390. $sql .= " AND c.entity IN (".getEntity('societe').")";
  1391. }
  1392. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1393. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1394. $sql .= " AND tc.source = '".$this->db->escape($source)."'";
  1395. if ($code) {
  1396. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1397. }
  1398. $sql .= " AND tc.active = 1";
  1399. if ($status) {
  1400. $sql .= " AND ec.statut = ".((int) $status);
  1401. }
  1402. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1403. $resql = $this->db->query($sql);
  1404. if ($resql) {
  1405. while ($obj = $this->db->fetch_object($resql)) {
  1406. $result[$i] = $obj->fk_socpeople;
  1407. $i++;
  1408. }
  1409. } else {
  1410. $this->error = $this->db->error();
  1411. return null;
  1412. }
  1413. return $result;
  1414. }
  1415. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1416. /**
  1417. * Load object contact with id=$this->contact_id into $this->contact
  1418. *
  1419. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1420. * @return int <0 if KO, >0 if OK
  1421. */
  1422. public function fetch_contact($contactid = null)
  1423. {
  1424. // phpcs:enable
  1425. if (empty($contactid)) {
  1426. $contactid = $this->contact_id;
  1427. }
  1428. if (empty($contactid)) {
  1429. return 0;
  1430. }
  1431. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1432. $contact = new Contact($this->db);
  1433. $result = $contact->fetch($contactid);
  1434. $this->contact = $contact;
  1435. return $result;
  1436. }
  1437. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1438. /**
  1439. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1440. *
  1441. * @param int $force_thirdparty_id Force thirdparty id
  1442. * @return int <0 if KO, >0 if OK
  1443. */
  1444. public function fetch_thirdparty($force_thirdparty_id = 0)
  1445. {
  1446. // phpcs:enable
  1447. global $conf;
  1448. if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) {
  1449. return 0;
  1450. }
  1451. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1452. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
  1453. if ($force_thirdparty_id) {
  1454. $idtofetch = $force_thirdparty_id;
  1455. }
  1456. if ($idtofetch) {
  1457. $thirdparty = new Societe($this->db);
  1458. $result = $thirdparty->fetch($idtofetch);
  1459. if ($result<0) {
  1460. $this->errors=array_merge($this->errors, $thirdparty->errors);
  1461. }
  1462. $this->thirdparty = $thirdparty;
  1463. // Use first price level if level not defined for third party
  1464. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1465. $this->thirdparty->price_level = 1;
  1466. }
  1467. return $result;
  1468. } else {
  1469. return -1;
  1470. }
  1471. }
  1472. /**
  1473. * Looks for an object with ref matching the wildcard provided
  1474. * It does only work when $this->table_ref_field is set
  1475. *
  1476. * @param string $ref Wildcard
  1477. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1478. */
  1479. public function fetchOneLike($ref)
  1480. {
  1481. if (!$this->table_ref_field) {
  1482. return 0;
  1483. }
  1484. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element." WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."' LIMIT 1";
  1485. $query = $this->db->query($sql);
  1486. if (!$this->db->num_rows($query)) {
  1487. return 0;
  1488. }
  1489. $result = $this->db->fetch_object($query);
  1490. return $this->fetch($result->rowid);
  1491. }
  1492. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1493. /**
  1494. * Load data for barcode into properties ->barcode_type*
  1495. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1496. * if it is not defined, ->element must be defined to know default barcode type.
  1497. *
  1498. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1499. */
  1500. public function fetch_barcode()
  1501. {
  1502. // phpcs:enable
  1503. global $conf;
  1504. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1505. $idtype = $this->barcode_type;
  1506. 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
  1507. if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
  1508. $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1509. } elseif ($this->element == 'societe') {
  1510. $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1511. } else {
  1512. dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1513. }
  1514. }
  1515. if ($idtype > 0) {
  1516. 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
  1517. $sql = "SELECT rowid, code, libelle as label, coder";
  1518. $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
  1519. $sql .= " WHERE rowid = ".((int) $idtype);
  1520. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1521. $resql = $this->db->query($sql);
  1522. if ($resql) {
  1523. $obj = $this->db->fetch_object($resql);
  1524. $this->barcode_type = $obj->rowid;
  1525. $this->barcode_type_code = $obj->code;
  1526. $this->barcode_type_label = $obj->label;
  1527. $this->barcode_type_coder = $obj->coder;
  1528. return 1;
  1529. } else {
  1530. dol_print_error($this->db);
  1531. return -1;
  1532. }
  1533. }
  1534. }
  1535. return 0;
  1536. }
  1537. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1538. /**
  1539. * Load the project with id $this->fk_project into this->project
  1540. *
  1541. * @return int <0 if KO, >=0 if OK
  1542. */
  1543. public function fetch_project()
  1544. {
  1545. // phpcs:enable
  1546. return $this->fetch_projet();
  1547. }
  1548. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1549. /**
  1550. * Load the project with id $this->fk_project into this->project
  1551. *
  1552. * @return int <0 if KO, >=0 if OK
  1553. */
  1554. public function fetch_projet()
  1555. {
  1556. // phpcs:enable
  1557. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1558. if (empty($this->fk_project) && !empty($this->fk_projet)) {
  1559. $this->fk_project = $this->fk_projet; // For backward compatibility
  1560. }
  1561. if (empty($this->fk_project)) {
  1562. return 0;
  1563. }
  1564. $project = new Project($this->db);
  1565. $result = $project->fetch($this->fk_project);
  1566. $this->projet = $project; // deprecated
  1567. $this->project = $project;
  1568. return $result;
  1569. }
  1570. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1571. /**
  1572. * Load the product with id $this->fk_product into this->product
  1573. *
  1574. * @return int <0 if KO, >=0 if OK
  1575. */
  1576. public function fetch_product()
  1577. {
  1578. // phpcs:enable
  1579. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1580. if (empty($this->fk_product)) {
  1581. return 0;
  1582. }
  1583. $product = new Product($this->db);
  1584. $result = $product->fetch($this->fk_product);
  1585. $this->product = $product;
  1586. return $result;
  1587. }
  1588. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1589. /**
  1590. * Load the user with id $userid into this->user
  1591. *
  1592. * @param int $userid Id du contact
  1593. * @return int <0 if KO, >0 if OK
  1594. */
  1595. public function fetch_user($userid)
  1596. {
  1597. // phpcs:enable
  1598. $user = new User($this->db);
  1599. $result = $user->fetch($userid);
  1600. $this->user = $user;
  1601. return $result;
  1602. }
  1603. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1604. /**
  1605. * Read linked origin object
  1606. *
  1607. * @return void
  1608. */
  1609. public function fetch_origin()
  1610. {
  1611. // phpcs:enable
  1612. if ($this->origin == 'shipping') {
  1613. $this->origin = 'expedition';
  1614. }
  1615. if ($this->origin == 'delivery') {
  1616. $this->origin = 'livraison';
  1617. }
  1618. if ($this->origin == 'order_supplier') {
  1619. $this->origin = 'commandeFournisseur';
  1620. }
  1621. $origin = $this->origin;
  1622. $classname = ucfirst($origin);
  1623. $this->$origin = new $classname($this->db);
  1624. $this->$origin->fetch($this->origin_id);
  1625. }
  1626. /**
  1627. * Load object from specific field
  1628. *
  1629. * @param string $table Table element or element line
  1630. * @param string $field Field selected
  1631. * @param string $key Import key
  1632. * @param string $element Element name
  1633. * @return int <0 if KO, >0 if OK
  1634. */
  1635. public function fetchObjectFrom($table, $field, $key, $element = null)
  1636. {
  1637. global $conf;
  1638. $result = false;
  1639. $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
  1640. $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
  1641. if (!empty($element)) {
  1642. $sql .= " AND entity IN (".getEntity($element).")";
  1643. } else {
  1644. $sql .= " AND entity = ".((int) $conf->entity);
  1645. }
  1646. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1647. $resql = $this->db->query($sql);
  1648. if ($resql) {
  1649. $row = $this->db->fetch_row($resql);
  1650. // Test for avoid error -1
  1651. if ($row[0] > 0) {
  1652. $result = $this->fetch($row[0]);
  1653. }
  1654. }
  1655. return $result;
  1656. }
  1657. /**
  1658. * Getter generic. Load value from a specific field
  1659. *
  1660. * @param string $table Table of element or element line
  1661. * @param int $id Element id
  1662. * @param string $field Field selected
  1663. * @return int <0 if KO, >0 if OK
  1664. */
  1665. public function getValueFrom($table, $id, $field)
  1666. {
  1667. $result = false;
  1668. if (!empty($id) && !empty($field) && !empty($table)) {
  1669. $sql = "SELECT ".$field." FROM ".$this->db->prefix().$table;
  1670. $sql .= " WHERE rowid = ".((int) $id);
  1671. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1672. $resql = $this->db->query($sql);
  1673. if ($resql) {
  1674. $row = $this->db->fetch_row($resql);
  1675. $result = $row[0];
  1676. }
  1677. }
  1678. return $result;
  1679. }
  1680. /**
  1681. * Setter generic. Update a specific field into database.
  1682. * Warning: Trigger is run only if param trigkey is provided.
  1683. *
  1684. * @param string $field Field to update
  1685. * @param mixed $value New value
  1686. * @param string $table To force other table element or element line (should not be used)
  1687. * @param int $id To force other object id (should not be used)
  1688. * @param string $format Data format ('text', 'date'). 'text' is used if not defined
  1689. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1690. * @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'
  1691. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1692. * @param string $fk_user_field Name of field to save user id making change
  1693. * @return int <0 if KO, >0 if OK
  1694. * @see updateExtraField()
  1695. */
  1696. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1697. {
  1698. global $user, $langs, $conf;
  1699. if (empty($table)) {
  1700. $table = $this->table_element;
  1701. }
  1702. if (empty($id)) {
  1703. $id = $this->id;
  1704. }
  1705. if (empty($format)) {
  1706. $format = 'text';
  1707. }
  1708. if (empty($id_field)) {
  1709. $id_field = 'rowid';
  1710. }
  1711. $error = 0;
  1712. $this->db->begin();
  1713. // Special case
  1714. if ($table == 'product' && $field == 'note_private') {
  1715. $field = 'note';
  1716. }
  1717. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  1718. $fk_user_field = 'fk_user_mod';
  1719. }
  1720. $sql = "UPDATE ".$this->db->prefix().$table." SET ";
  1721. if ($format == 'text') {
  1722. $sql .= $field." = '".$this->db->escape($value)."'";
  1723. } elseif ($format == 'int') {
  1724. $sql .= $field." = ".((int) $value);
  1725. } elseif ($format == 'date') {
  1726. $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1727. }
  1728. if ($fk_user_field) {
  1729. if (!empty($fuser) && is_object($fuser)) {
  1730. $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
  1731. } elseif (empty($fuser) || $fuser != 'none') {
  1732. $sql .= ", ".$fk_user_field." = ".((int) $user->id);
  1733. }
  1734. }
  1735. $sql .= " WHERE ".$id_field." = ".((int) $id);
  1736. dol_syslog(__METHOD__."", LOG_DEBUG);
  1737. $resql = $this->db->query($sql);
  1738. if ($resql) {
  1739. if ($trigkey) {
  1740. // call trigger with updated object values
  1741. if (empty($this->fields) && method_exists($this, 'fetch')) {
  1742. $result = $this->fetch($id);
  1743. } else {
  1744. $result = $this->fetchCommon($id);
  1745. }
  1746. if ($result >= 0) {
  1747. $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1748. }
  1749. if ($result < 0) {
  1750. $error++;
  1751. }
  1752. }
  1753. if (!$error) {
  1754. if (property_exists($this, $field)) {
  1755. $this->$field = $value;
  1756. }
  1757. $this->db->commit();
  1758. return 1;
  1759. } else {
  1760. $this->db->rollback();
  1761. return -2;
  1762. }
  1763. } else {
  1764. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1765. $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
  1766. } else {
  1767. $this->error = $this->db->lasterror();
  1768. }
  1769. $this->db->rollback();
  1770. return -1;
  1771. }
  1772. }
  1773. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1774. /**
  1775. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1776. *
  1777. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')". Do not allow user input data here.
  1778. * @param string $fieldid Name of field to use for the select MAX and MIN
  1779. * @param int $nodbprefix Do not include DB prefix to forge table name
  1780. * @return int <0 if KO, >0 if OK
  1781. */
  1782. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1783. {
  1784. // phpcs:enable
  1785. global $conf, $user;
  1786. if (!$this->table_element) {
  1787. dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1788. return -1;
  1789. }
  1790. if ($fieldid == 'none') {
  1791. return 1;
  1792. }
  1793. // For backward compatibility
  1794. if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
  1795. $fieldid = 'titre';
  1796. }
  1797. // Security on socid
  1798. $socid = 0;
  1799. if ($user->socid > 0) {
  1800. $socid = $user->socid;
  1801. }
  1802. // this->ismultientitymanaged contains
  1803. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1804. $aliastablesociete = 's';
  1805. if ($this->element == 'societe') {
  1806. $aliastablesociete = 'te'; // te as table_element
  1807. }
  1808. $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
  1809. $sql = "SELECT MAX(te.".$fieldid.")";
  1810. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1811. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1812. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1813. }
  1814. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1815. $tmparray = explode('@', $this->ismultientitymanaged);
  1816. $sql .= ", ".$this->db->prefix().$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1817. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1818. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1819. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1820. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1821. }
  1822. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1823. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1824. }
  1825. $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)
  1826. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1827. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1828. }
  1829. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1830. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1831. }
  1832. if (!empty($filter)) {
  1833. if (!preg_match('/^\s*AND/i', $filter)) {
  1834. $sql .= " AND "; // For backward compatibility
  1835. }
  1836. $sql .= $filter;
  1837. }
  1838. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1839. $tmparray = explode('@', $this->ismultientitymanaged);
  1840. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1841. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1842. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1843. }
  1844. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1845. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1846. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1847. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1848. } else {
  1849. $sql .= " AND ug.fk_user = te.rowid";
  1850. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1851. }
  1852. } else {
  1853. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1854. }
  1855. }
  1856. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1857. $tmparray = explode('@', $this->ismultientitymanaged);
  1858. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1859. }
  1860. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1861. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1862. }
  1863. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1864. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1865. }
  1866. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1867. $sql .= ' AND te.rowid = '.((int) $socid);
  1868. }
  1869. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1870. $result = $this->db->query($sql);
  1871. if (!$result) {
  1872. $this->error = $this->db->lasterror();
  1873. return -1;
  1874. }
  1875. $row = $this->db->fetch_row($result);
  1876. $this->ref_previous = $row[0];
  1877. $sql = "SELECT MIN(te.".$fieldid.")";
  1878. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1879. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1880. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1881. }
  1882. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1883. $tmparray = explode('@', $this->ismultientitymanaged);
  1884. $sql .= ", ".$this->db->prefix().$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1885. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1886. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1887. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1888. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1889. }
  1890. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1891. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1892. }
  1893. $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)
  1894. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1895. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1896. }
  1897. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1898. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1899. }
  1900. if (!empty($filter)) {
  1901. if (!preg_match('/^\s*AND/i', $filter)) {
  1902. $sql .= " AND "; // For backward compatibility
  1903. }
  1904. $sql .= $filter;
  1905. }
  1906. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1907. $tmparray = explode('@', $this->ismultientitymanaged);
  1908. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1909. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1910. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1911. }
  1912. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1913. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1914. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1915. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1916. } else {
  1917. $sql .= " AND ug.fk_user = te.rowid";
  1918. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1919. }
  1920. } else {
  1921. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1922. }
  1923. }
  1924. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1925. $tmparray = explode('@', $this->ismultientitymanaged);
  1926. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1927. }
  1928. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1929. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1930. }
  1931. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1932. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1933. }
  1934. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1935. $sql .= ' AND te.rowid = '.((int) $socid);
  1936. }
  1937. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1938. // 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
  1939. $result = $this->db->query($sql);
  1940. if (!$result) {
  1941. $this->error = $this->db->lasterror();
  1942. return -2;
  1943. }
  1944. $row = $this->db->fetch_row($result);
  1945. $this->ref_next = $row[0];
  1946. return 1;
  1947. }
  1948. /**
  1949. * Return list of id of contacts of object
  1950. *
  1951. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  1952. * @return array Array of id of contacts (if source=external or internal)
  1953. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  1954. */
  1955. public function getListContactId($source = 'external')
  1956. {
  1957. $contactAlreadySelected = array();
  1958. $tab = $this->liste_contact(-1, $source);
  1959. $num = count($tab);
  1960. $i = 0;
  1961. while ($i < $num) {
  1962. if ($source == 'thirdparty') {
  1963. $contactAlreadySelected[$i] = $tab[$i]['socid'];
  1964. } else {
  1965. $contactAlreadySelected[$i] = $tab[$i]['id'];
  1966. }
  1967. $i++;
  1968. }
  1969. return $contactAlreadySelected;
  1970. }
  1971. /**
  1972. * Link element with a project
  1973. *
  1974. * @param int $projectid Project id to link element to
  1975. * @return int <0 if KO, >0 if OK
  1976. */
  1977. public function setProject($projectid)
  1978. {
  1979. if (!$this->table_element) {
  1980. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  1981. return -1;
  1982. }
  1983. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  1984. if (!empty($this->fields['fk_project'])) { // Common case
  1985. if ($projectid) {
  1986. $sql .= " SET fk_project = ".((int) $projectid);
  1987. } else {
  1988. $sql .= " SET fk_project = NULL";
  1989. }
  1990. $sql .= ' WHERE rowid = '.((int) $this->id);
  1991. } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
  1992. if ($projectid) {
  1993. $sql .= " SET fk_project = ".((int) $projectid);
  1994. } else {
  1995. $sql .= " SET fk_project = NULL";
  1996. }
  1997. $sql .= ' WHERE id = '.((int) $this->id);
  1998. } else // Special case for old architecture objects
  1999. {
  2000. if ($projectid) {
  2001. $sql .= ' SET fk_projet = '.((int) $projectid);
  2002. } else {
  2003. $sql .= ' SET fk_projet = NULL';
  2004. }
  2005. $sql .= " WHERE rowid = ".((int) $this->id);
  2006. }
  2007. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  2008. if ($this->db->query($sql)) {
  2009. $this->fk_project = ((int) $projectid);
  2010. return 1;
  2011. } else {
  2012. dol_print_error($this->db);
  2013. return -1;
  2014. }
  2015. }
  2016. /**
  2017. * Change the payments methods
  2018. *
  2019. * @param int $id Id of new payment method
  2020. * @return int >0 if OK, <0 if KO
  2021. */
  2022. public function setPaymentMethods($id)
  2023. {
  2024. global $user;
  2025. $error = 0; $notrigger = 0;
  2026. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  2027. if ($this->statut >= 0 || $this->element == 'societe') {
  2028. // TODO uniformize field name
  2029. $fieldname = 'fk_mode_reglement';
  2030. if ($this->element == 'societe') {
  2031. $fieldname = 'mode_reglement';
  2032. }
  2033. if (get_class($this) == 'Fournisseur') {
  2034. $fieldname = 'mode_reglement_supplier';
  2035. }
  2036. if (get_class($this) == 'Tva') {
  2037. $fieldname = 'fk_typepayment';
  2038. }
  2039. if (get_class($this) == 'Salary') {
  2040. $fieldname = 'fk_typepayment';
  2041. }
  2042. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2043. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2044. $sql .= ' WHERE rowid='.((int) $this->id);
  2045. if ($this->db->query($sql)) {
  2046. $this->mode_reglement_id = $id;
  2047. // for supplier
  2048. if (get_class($this) == 'Fournisseur') {
  2049. $this->mode_reglement_supplier_id = $id;
  2050. }
  2051. // Triggers
  2052. if (!$error && !$notrigger) {
  2053. // Call triggers
  2054. if (get_class($this) == 'Commande') {
  2055. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2056. } else {
  2057. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  2058. }
  2059. if ($result < 0) {
  2060. $error++;
  2061. }
  2062. // End call triggers
  2063. }
  2064. return 1;
  2065. } else {
  2066. dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
  2067. $this->error = $this->db->error();
  2068. return -1;
  2069. }
  2070. } else {
  2071. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  2072. $this->error = 'Status of the object is incompatible '.$this->statut;
  2073. return -2;
  2074. }
  2075. }
  2076. /**
  2077. * Change the multicurrency code
  2078. *
  2079. * @param string $code multicurrency code
  2080. * @return int >0 if OK, <0 if KO
  2081. */
  2082. public function setMulticurrencyCode($code)
  2083. {
  2084. dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
  2085. if ($this->statut >= 0 || $this->element == 'societe') {
  2086. $fieldname = 'multicurrency_code';
  2087. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2088. $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
  2089. $sql .= ' WHERE rowid='.((int) $this->id);
  2090. if ($this->db->query($sql)) {
  2091. $this->multicurrency_code = $code;
  2092. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  2093. if ($rate) {
  2094. $this->setMulticurrencyRate($rate, 2);
  2095. }
  2096. return 1;
  2097. } else {
  2098. dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
  2099. $this->error = $this->db->error();
  2100. return -1;
  2101. }
  2102. } else {
  2103. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  2104. $this->error = 'Status of the object is incompatible '.$this->statut;
  2105. return -2;
  2106. }
  2107. }
  2108. /**
  2109. * Change the multicurrency rate
  2110. *
  2111. * @param double $rate multicurrency rate
  2112. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  2113. * @return int >0 if OK, <0 if KO
  2114. */
  2115. public function setMulticurrencyRate($rate, $mode = 1)
  2116. {
  2117. dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
  2118. if ($this->statut >= 0 || $this->element == 'societe') {
  2119. $fieldname = 'multicurrency_tx';
  2120. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2121. $sql .= " SET ".$fieldname." = ".((float) $rate);
  2122. $sql .= ' WHERE rowid='.((int) $this->id);
  2123. if ($this->db->query($sql)) {
  2124. $this->multicurrency_tx = $rate;
  2125. // Update line price
  2126. if (!empty($this->lines)) {
  2127. foreach ($this->lines as &$line) {
  2128. // Amounts in company currency will be recalculated
  2129. if ($mode == 1) {
  2130. $line->subprice = 0;
  2131. }
  2132. // Amounts in foreign currency will be recalculated
  2133. if ($mode == 2) {
  2134. $line->multicurrency_subprice = 0;
  2135. }
  2136. switch ($this->element) {
  2137. case 'propal':
  2138. $this->updateline(
  2139. $line->id,
  2140. $line->subprice,
  2141. $line->qty,
  2142. $line->remise_percent,
  2143. $line->tva_tx,
  2144. $line->localtax1_tx,
  2145. $line->localtax2_tx,
  2146. ($line->description ? $line->description : $line->desc),
  2147. 'HT',
  2148. $line->info_bits,
  2149. $line->special_code,
  2150. $line->fk_parent_line,
  2151. $line->skip_update_total,
  2152. $line->fk_fournprice,
  2153. $line->pa_ht,
  2154. $line->label,
  2155. $line->product_type,
  2156. $line->date_start,
  2157. $line->date_end,
  2158. $line->array_options,
  2159. $line->fk_unit,
  2160. $line->multicurrency_subprice
  2161. );
  2162. break;
  2163. case 'commande':
  2164. $this->updateline(
  2165. $line->id,
  2166. ($line->description ? $line->description : $line->desc),
  2167. $line->subprice,
  2168. $line->qty,
  2169. $line->remise_percent,
  2170. $line->tva_tx,
  2171. $line->localtax1_tx,
  2172. $line->localtax2_tx,
  2173. 'HT',
  2174. $line->info_bits,
  2175. $line->date_start,
  2176. $line->date_end,
  2177. $line->product_type,
  2178. $line->fk_parent_line,
  2179. $line->skip_update_total,
  2180. $line->fk_fournprice,
  2181. $line->pa_ht,
  2182. $line->label,
  2183. $line->special_code,
  2184. $line->array_options,
  2185. $line->fk_unit,
  2186. $line->multicurrency_subprice
  2187. );
  2188. break;
  2189. case 'facture':
  2190. $this->updateline(
  2191. $line->id,
  2192. ($line->description ? $line->description : $line->desc),
  2193. $line->subprice,
  2194. $line->qty,
  2195. $line->remise_percent,
  2196. $line->date_start,
  2197. $line->date_end,
  2198. $line->tva_tx,
  2199. $line->localtax1_tx,
  2200. $line->localtax2_tx,
  2201. 'HT',
  2202. $line->info_bits,
  2203. $line->product_type,
  2204. $line->fk_parent_line,
  2205. $line->skip_update_total,
  2206. $line->fk_fournprice,
  2207. $line->pa_ht,
  2208. $line->label,
  2209. $line->special_code,
  2210. $line->array_options,
  2211. $line->situation_percent,
  2212. $line->fk_unit,
  2213. $line->multicurrency_subprice
  2214. );
  2215. break;
  2216. case 'supplier_proposal':
  2217. $this->updateline(
  2218. $line->id,
  2219. $line->subprice,
  2220. $line->qty,
  2221. $line->remise_percent,
  2222. $line->tva_tx,
  2223. $line->localtax1_tx,
  2224. $line->localtax2_tx,
  2225. ($line->description ? $line->description : $line->desc),
  2226. 'HT',
  2227. $line->info_bits,
  2228. $line->special_code,
  2229. $line->fk_parent_line,
  2230. $line->skip_update_total,
  2231. $line->fk_fournprice,
  2232. $line->pa_ht,
  2233. $line->label,
  2234. $line->product_type,
  2235. $line->array_options,
  2236. $line->ref_fourn,
  2237. $line->multicurrency_subprice
  2238. );
  2239. break;
  2240. case 'order_supplier':
  2241. $this->updateline(
  2242. $line->id,
  2243. ($line->description ? $line->description : $line->desc),
  2244. $line->subprice,
  2245. $line->qty,
  2246. $line->remise_percent,
  2247. $line->tva_tx,
  2248. $line->localtax1_tx,
  2249. $line->localtax2_tx,
  2250. 'HT',
  2251. $line->info_bits,
  2252. $line->product_type,
  2253. false,
  2254. $line->date_start,
  2255. $line->date_end,
  2256. $line->array_options,
  2257. $line->fk_unit,
  2258. $line->multicurrency_subprice,
  2259. $line->ref_supplier
  2260. );
  2261. break;
  2262. case 'invoice_supplier':
  2263. $this->updateline(
  2264. $line->id,
  2265. ($line->description ? $line->description : $line->desc),
  2266. $line->subprice,
  2267. $line->tva_tx,
  2268. $line->localtax1_tx,
  2269. $line->localtax2_tx,
  2270. $line->qty,
  2271. 0,
  2272. 'HT',
  2273. $line->info_bits,
  2274. $line->product_type,
  2275. $line->remise_percent,
  2276. false,
  2277. $line->date_start,
  2278. $line->date_end,
  2279. $line->array_options,
  2280. $line->fk_unit,
  2281. $line->multicurrency_subprice,
  2282. $line->ref_supplier
  2283. );
  2284. break;
  2285. default:
  2286. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  2287. break;
  2288. }
  2289. }
  2290. }
  2291. return 1;
  2292. } else {
  2293. dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
  2294. $this->error = $this->db->error();
  2295. return -1;
  2296. }
  2297. } else {
  2298. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  2299. $this->error = 'Status of the object is incompatible '.$this->statut;
  2300. return -2;
  2301. }
  2302. }
  2303. /**
  2304. * Change the payments terms
  2305. *
  2306. * @param int $id Id of new payment terms
  2307. * @return int >0 if OK, <0 if KO
  2308. */
  2309. public function setPaymentTerms($id)
  2310. {
  2311. dol_syslog(get_class($this).'::setPaymentTerms('.$id.')');
  2312. if ($this->statut >= 0 || $this->element == 'societe') {
  2313. // TODO uniformize field name
  2314. $fieldname = 'fk_cond_reglement';
  2315. if ($this->element == 'societe') {
  2316. $fieldname = 'cond_reglement';
  2317. }
  2318. if (get_class($this) == 'Fournisseur') {
  2319. $fieldname = 'cond_reglement_supplier';
  2320. }
  2321. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2322. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2323. $sql .= ' WHERE rowid='.((int) $this->id);
  2324. if ($this->db->query($sql)) {
  2325. $this->cond_reglement_id = $id;
  2326. // for supplier
  2327. if (get_class($this) == 'Fournisseur') {
  2328. $this->cond_reglement_supplier_id = $id;
  2329. }
  2330. $this->cond_reglement = $id; // for compatibility
  2331. return 1;
  2332. } else {
  2333. dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
  2334. $this->error = $this->db->error();
  2335. return -1;
  2336. }
  2337. } else {
  2338. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  2339. $this->error = 'Status of the object is incompatible '.$this->statut;
  2340. return -2;
  2341. }
  2342. }
  2343. /**
  2344. * Change the transport mode methods
  2345. *
  2346. * @param int $id Id of transport mode
  2347. * @return int >0 if OK, <0 if KO
  2348. */
  2349. public function setTransportMode($id)
  2350. {
  2351. dol_syslog(get_class($this).'::setTransportMode('.$id.')');
  2352. if ($this->statut >= 0 || $this->element == 'societe') {
  2353. $fieldname = 'fk_transport_mode';
  2354. if ($this->element == 'societe') {
  2355. $fieldname = 'transport_mode';
  2356. }
  2357. if (get_class($this) == 'Fournisseur') {
  2358. $fieldname = 'transport_mode_supplier';
  2359. }
  2360. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2361. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2362. $sql .= ' WHERE rowid='.((int) $this->id);
  2363. if ($this->db->query($sql)) {
  2364. $this->transport_mode_id = $id;
  2365. // for supplier
  2366. if (get_class($this) == 'Fournisseur') {
  2367. $this->transport_mode_supplier_id = $id;
  2368. }
  2369. return 1;
  2370. } else {
  2371. dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
  2372. $this->error = $this->db->error();
  2373. return -1;
  2374. }
  2375. } else {
  2376. dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
  2377. $this->error = 'Status of the object is incompatible '.$this->statut;
  2378. return -2;
  2379. }
  2380. }
  2381. /**
  2382. * Change the retained warranty payments terms
  2383. *
  2384. * @param int $id Id of new payment terms
  2385. * @return int >0 if OK, <0 if KO
  2386. */
  2387. public function setRetainedWarrantyPaymentTerms($id)
  2388. {
  2389. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
  2390. if ($this->statut >= 0 || $this->element == 'societe') {
  2391. $fieldname = 'retained_warranty_fk_cond_reglement';
  2392. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2393. $sql .= " SET ".$fieldname." = ".((int) $id);
  2394. $sql .= ' WHERE rowid='.((int) $this->id);
  2395. if ($this->db->query($sql)) {
  2396. $this->retained_warranty_fk_cond_reglement = $id;
  2397. return 1;
  2398. } else {
  2399. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
  2400. $this->error = $this->db->error();
  2401. return -1;
  2402. }
  2403. } else {
  2404. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  2405. $this->error = 'Status of the object is incompatible '.$this->statut;
  2406. return -2;
  2407. }
  2408. }
  2409. /**
  2410. * Define delivery address
  2411. * @deprecated
  2412. *
  2413. * @param int $id Address id
  2414. * @return int <0 si ko, >0 si ok
  2415. */
  2416. public function setDeliveryAddress($id)
  2417. {
  2418. $fieldname = 'fk_delivery_address';
  2419. if ($this->element == 'delivery' || $this->element == 'shipping') {
  2420. $fieldname = 'fk_address';
  2421. }
  2422. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$fieldname." = ".((int) $id);
  2423. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
  2424. if ($this->db->query($sql)) {
  2425. $this->fk_delivery_address = $id;
  2426. return 1;
  2427. } else {
  2428. $this->error = $this->db->error();
  2429. dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
  2430. return -1;
  2431. }
  2432. }
  2433. /**
  2434. * Change the shipping method
  2435. *
  2436. * @param int $shipping_method_id Id of shipping method
  2437. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2438. * @param User $userused Object user
  2439. *
  2440. * @return int 1 if OK, 0 if KO
  2441. */
  2442. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  2443. {
  2444. global $user;
  2445. if (empty($userused)) {
  2446. $userused = $user;
  2447. }
  2448. $error = 0;
  2449. if (!$this->table_element) {
  2450. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2451. return -1;
  2452. }
  2453. $this->db->begin();
  2454. if ($shipping_method_id < 0) {
  2455. $shipping_method_id = 'NULL';
  2456. }
  2457. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  2458. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2459. $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
  2460. $sql .= " WHERE rowid=".((int) $this->id);
  2461. $resql = $this->db->query($sql);
  2462. if (!$resql) {
  2463. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  2464. $this->error = $this->db->lasterror();
  2465. $error++;
  2466. } else {
  2467. if (!$notrigger) {
  2468. // Call trigger
  2469. $this->context = array('shippingmethodupdate'=>1);
  2470. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2471. if ($result < 0) {
  2472. $error++;
  2473. }
  2474. // End call trigger
  2475. }
  2476. }
  2477. if ($error) {
  2478. $this->db->rollback();
  2479. return -1;
  2480. } else {
  2481. $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
  2482. $this->db->commit();
  2483. return 1;
  2484. }
  2485. }
  2486. /**
  2487. * Change the warehouse
  2488. *
  2489. * @param int $warehouse_id Id of warehouse
  2490. * @return int 1 if OK, 0 if KO
  2491. */
  2492. public function setWarehouse($warehouse_id)
  2493. {
  2494. if (!$this->table_element) {
  2495. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2496. return -1;
  2497. }
  2498. if ($warehouse_id < 0) {
  2499. $warehouse_id = 'NULL';
  2500. }
  2501. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  2502. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2503. $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
  2504. $sql .= " WHERE rowid=".((int) $this->id);
  2505. if ($this->db->query($sql)) {
  2506. $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
  2507. return 1;
  2508. } else {
  2509. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  2510. $this->error = $this->db->error();
  2511. return 0;
  2512. }
  2513. }
  2514. /**
  2515. * Set last model used by doc generator
  2516. *
  2517. * @param User $user User object that make change
  2518. * @param string $modelpdf Modele name
  2519. * @return int <0 if KO, >0 if OK
  2520. */
  2521. public function setDocModel($user, $modelpdf)
  2522. {
  2523. if (!$this->table_element) {
  2524. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2525. return -1;
  2526. }
  2527. $newmodelpdf = dol_trunc($modelpdf, 255);
  2528. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2529. $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  2530. $sql .= " WHERE rowid = ".((int) $this->id);
  2531. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  2532. $resql = $this->db->query($sql);
  2533. if ($resql) {
  2534. $this->model_pdf = $modelpdf;
  2535. $this->modelpdf = $modelpdf; // For bakward compatibility
  2536. return 1;
  2537. } else {
  2538. dol_print_error($this->db);
  2539. return 0;
  2540. }
  2541. }
  2542. /**
  2543. * Change the bank account
  2544. *
  2545. * @param int $fk_account Id of bank account
  2546. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2547. * @param User $userused Object user
  2548. * @return int 1 if OK, 0 if KO
  2549. */
  2550. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2551. {
  2552. global $user;
  2553. if (empty($userused)) {
  2554. $userused = $user;
  2555. }
  2556. $error = 0;
  2557. if (!$this->table_element) {
  2558. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2559. return -1;
  2560. }
  2561. $this->db->begin();
  2562. if ($fk_account < 0) {
  2563. $fk_account = 'NULL';
  2564. }
  2565. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  2566. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2567. $sql .= " SET fk_account = ".((int) $fk_account);
  2568. $sql .= " WHERE rowid=".((int) $this->id);
  2569. $resql = $this->db->query($sql);
  2570. if (!$resql) {
  2571. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  2572. $this->error = $this->db->lasterror();
  2573. $error++;
  2574. } else {
  2575. if (!$notrigger) {
  2576. // Call trigger
  2577. $this->context = array('bankaccountupdate'=>1);
  2578. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2579. if ($result < 0) {
  2580. $error++;
  2581. }
  2582. // End call trigger
  2583. }
  2584. }
  2585. if ($error) {
  2586. $this->db->rollback();
  2587. return -1;
  2588. } else {
  2589. $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
  2590. $this->db->commit();
  2591. return 1;
  2592. }
  2593. }
  2594. // TODO: Move line related operations to CommonObjectLine?
  2595. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2596. /**
  2597. * Save a new position (field rang) for details lines.
  2598. * You can choose to set position for lines with already a position or lines without any position defined.
  2599. *
  2600. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2601. * @param string $rowidorder ASC or DESC
  2602. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2603. * @return int <0 if KO, >0 if OK
  2604. */
  2605. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2606. {
  2607. // phpcs:enable
  2608. if (!$this->table_element_line) {
  2609. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2610. return -1;
  2611. }
  2612. if (!$this->fk_element) {
  2613. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2614. return -1;
  2615. }
  2616. // Count number of lines to reorder (according to choice $renum)
  2617. $nl = 0;
  2618. $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
  2619. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2620. if (!$renum) {
  2621. $sql .= ' AND rang = 0';
  2622. }
  2623. if ($renum) {
  2624. $sql .= ' AND rang <> 0';
  2625. }
  2626. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  2627. $resql = $this->db->query($sql);
  2628. if ($resql) {
  2629. $row = $this->db->fetch_row($resql);
  2630. $nl = $row[0];
  2631. } else {
  2632. dol_print_error($this->db);
  2633. }
  2634. if ($nl > 0) {
  2635. // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
  2636. $rows = array();
  2637. // We first search all lines that are parent lines (for multilevel details lines)
  2638. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2639. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2640. if ($fk_parent_line) {
  2641. $sql .= ' AND fk_parent_line IS NULL';
  2642. }
  2643. $sql .= " ORDER BY rang ASC, rowid ".$rowidorder;
  2644. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  2645. $resql = $this->db->query($sql);
  2646. if ($resql) {
  2647. $i = 0;
  2648. $num = $this->db->num_rows($resql);
  2649. while ($i < $num) {
  2650. $row = $this->db->fetch_row($resql);
  2651. $rows[] = $row[0]; // Add parent line into array rows
  2652. $childrens = $this->getChildrenOfLine($row[0]);
  2653. if (!empty($childrens)) {
  2654. foreach ($childrens as $child) {
  2655. array_push($rows, $child);
  2656. }
  2657. }
  2658. $i++;
  2659. }
  2660. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2661. if (!empty($rows)) {
  2662. foreach ($rows as $key => $row) {
  2663. $this->updateRangOfLine($row, ($key + 1));
  2664. }
  2665. }
  2666. } else {
  2667. dol_print_error($this->db);
  2668. }
  2669. }
  2670. return 1;
  2671. }
  2672. /**
  2673. * Get children of line
  2674. *
  2675. * @param int $id Id of parent line
  2676. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2677. * @return array Array with list of children lines id
  2678. */
  2679. public function getChildrenOfLine($id, $includealltree = 0)
  2680. {
  2681. $rows = array();
  2682. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2683. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2684. $sql .= ' AND fk_parent_line = '.((int) $id);
  2685. $sql .= ' ORDER BY rang ASC';
  2686. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
  2687. $resql = $this->db->query($sql);
  2688. if ($resql) {
  2689. if ($this->db->num_rows($resql) > 0) {
  2690. while ($row = $this->db->fetch_row($resql)) {
  2691. $rows[] = $row[0];
  2692. if (!empty($includealltree)) {
  2693. $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2694. }
  2695. }
  2696. }
  2697. }
  2698. return $rows;
  2699. }
  2700. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2701. /**
  2702. * Update a line to have a lower rank
  2703. *
  2704. * @param int $rowid Id of line
  2705. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2706. * @return void
  2707. */
  2708. public function line_up($rowid, $fk_parent_line = true)
  2709. {
  2710. // phpcs:enable
  2711. $this->line_order(false, 'ASC', $fk_parent_line);
  2712. // Get rang of line
  2713. $rang = $this->getRangOfLine($rowid);
  2714. // Update position of line
  2715. $this->updateLineUp($rowid, $rang);
  2716. }
  2717. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2718. /**
  2719. * Update a line to have a higher rank
  2720. *
  2721. * @param int $rowid Id of line
  2722. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2723. * @return void
  2724. */
  2725. public function line_down($rowid, $fk_parent_line = true)
  2726. {
  2727. // phpcs:enable
  2728. $this->line_order(false, 'ASC', $fk_parent_line);
  2729. // Get rang of line
  2730. $rang = $this->getRangOfLine($rowid);
  2731. // Get max value for rang
  2732. $max = $this->line_max();
  2733. // Update position of line
  2734. $this->updateLineDown($rowid, $rang, $max);
  2735. }
  2736. /**
  2737. * Update position of line (rang)
  2738. *
  2739. * @param int $rowid Id of line
  2740. * @param int $rang Position
  2741. * @return int <0 if KO, >0 if OK
  2742. */
  2743. public function updateRangOfLine($rowid, $rang)
  2744. {
  2745. global $hookmanager;
  2746. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2747. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction'))) {
  2748. $fieldposition = 'position';
  2749. }
  2750. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2751. $sql .= ' WHERE rowid = '.((int) $rowid);
  2752. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2753. if (!$this->db->query($sql)) {
  2754. dol_print_error($this->db);
  2755. return -1;
  2756. } else {
  2757. $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
  2758. $action='';
  2759. $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
  2760. return 1;
  2761. }
  2762. }
  2763. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2764. /**
  2765. * Update position of line with ajax (rang)
  2766. *
  2767. * @param array $rows Array of rows
  2768. * @return void
  2769. */
  2770. public function line_ajaxorder($rows)
  2771. {
  2772. // phpcs:enable
  2773. $num = count($rows);
  2774. for ($i = 0; $i < $num; $i++) {
  2775. $this->updateRangOfLine($rows[$i], ($i + 1));
  2776. }
  2777. }
  2778. /**
  2779. * Update position of line up (rang)
  2780. *
  2781. * @param int $rowid Id of line
  2782. * @param int $rang Position
  2783. * @return void
  2784. */
  2785. public function updateLineUp($rowid, $rang)
  2786. {
  2787. if ($rang > 1) {
  2788. $fieldposition = 'rang';
  2789. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
  2790. $fieldposition = 'position';
  2791. }
  2792. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2793. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2794. $sql .= ' AND rang = '.((int) ($rang - 1));
  2795. if ($this->db->query($sql)) {
  2796. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
  2797. $sql .= ' WHERE rowid = '.((int) $rowid);
  2798. if (!$this->db->query($sql)) {
  2799. dol_print_error($this->db);
  2800. }
  2801. } else {
  2802. dol_print_error($this->db);
  2803. }
  2804. }
  2805. }
  2806. /**
  2807. * Update position of line down (rang)
  2808. *
  2809. * @param int $rowid Id of line
  2810. * @param int $rang Position
  2811. * @param int $max Max
  2812. * @return void
  2813. */
  2814. public function updateLineDown($rowid, $rang, $max)
  2815. {
  2816. if ($rang < $max) {
  2817. $fieldposition = 'rang';
  2818. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
  2819. $fieldposition = 'position';
  2820. }
  2821. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2822. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2823. $sql .= ' AND rang = '.((int) ($rang + 1));
  2824. if ($this->db->query($sql)) {
  2825. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
  2826. $sql .= ' WHERE rowid = '.((int) $rowid);
  2827. if (!$this->db->query($sql)) {
  2828. dol_print_error($this->db);
  2829. }
  2830. } else {
  2831. dol_print_error($this->db);
  2832. }
  2833. }
  2834. }
  2835. /**
  2836. * Get position of line (rang)
  2837. *
  2838. * @param int $rowid Id of line
  2839. * @return int Value of rang in table of lines
  2840. */
  2841. public function getRangOfLine($rowid)
  2842. {
  2843. $sql = "SELECT rang FROM ".$this->db->prefix().$this->table_element_line;
  2844. $sql .= " WHERE rowid = ".((int) $rowid);
  2845. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  2846. $resql = $this->db->query($sql);
  2847. if ($resql) {
  2848. $row = $this->db->fetch_row($resql);
  2849. return $row[0];
  2850. }
  2851. }
  2852. /**
  2853. * Get rowid of the line relative to its position
  2854. *
  2855. * @param int $rang Rang value
  2856. * @return int Rowid of the line
  2857. */
  2858. public function getIdOfLine($rang)
  2859. {
  2860. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2861. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2862. $sql .= " AND rang = ".((int) $rang);
  2863. $resql = $this->db->query($sql);
  2864. if ($resql) {
  2865. $row = $this->db->fetch_row($resql);
  2866. return $row[0];
  2867. }
  2868. }
  2869. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2870. /**
  2871. * Get max value used for position of line (rang)
  2872. *
  2873. * @param int $fk_parent_line Parent line id
  2874. * @return int Max value of rang in table of lines
  2875. */
  2876. public function line_max($fk_parent_line = 0)
  2877. {
  2878. // phpcs:enable
  2879. $positionfield = 'rang';
  2880. if ($this->table_element == 'bom_bom') {
  2881. $positionfield = 'position';
  2882. }
  2883. // Search the last rang with fk_parent_line
  2884. if ($fk_parent_line) {
  2885. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  2886. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2887. $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
  2888. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2889. $resql = $this->db->query($sql);
  2890. if ($resql) {
  2891. $row = $this->db->fetch_row($resql);
  2892. if (!empty($row[0])) {
  2893. return $row[0];
  2894. } else {
  2895. return $this->getRangOfLine($fk_parent_line);
  2896. }
  2897. }
  2898. } else {
  2899. // If not, search the last rang of element
  2900. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  2901. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2902. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2903. $resql = $this->db->query($sql);
  2904. if ($resql) {
  2905. $row = $this->db->fetch_row($resql);
  2906. return $row[0];
  2907. }
  2908. }
  2909. }
  2910. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2911. /**
  2912. * Update external ref of element
  2913. *
  2914. * @param string $ref_ext Update field ref_ext
  2915. * @return int <0 if KO, >0 if OK
  2916. */
  2917. public function update_ref_ext($ref_ext)
  2918. {
  2919. // phpcs:enable
  2920. if (!$this->table_element) {
  2921. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  2922. return -1;
  2923. }
  2924. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2925. $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  2926. $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
  2927. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  2928. if ($this->db->query($sql)) {
  2929. $this->ref_ext = $ref_ext;
  2930. return 1;
  2931. } else {
  2932. $this->error = $this->db->error();
  2933. return -1;
  2934. }
  2935. }
  2936. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2937. /**
  2938. * Update note of element
  2939. *
  2940. * @param string $note New value for note
  2941. * @param string $suffix '', '_public' or '_private'
  2942. * @return int <0 if KO, >0 if OK
  2943. */
  2944. public function update_note($note, $suffix = '')
  2945. {
  2946. // phpcs:enable
  2947. global $user;
  2948. if (!$this->table_element) {
  2949. $this->error = 'update_note was called on objet with property table_element not defined';
  2950. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  2951. return -1;
  2952. }
  2953. if (!in_array($suffix, array('', '_public', '_private'))) {
  2954. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  2955. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  2956. return -2;
  2957. }
  2958. $newsuffix = $suffix;
  2959. // Special cas
  2960. if ($this->table_element == 'product' && $newsuffix == '_private') {
  2961. $newsuffix = '';
  2962. }
  2963. if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  2964. $fieldusermod = "fk_user_mod";
  2965. } elseif ($this->table_element == 'ecm_files') {
  2966. $fieldusermod = "fk_user_m";
  2967. } else {
  2968. $fieldusermod = "fk_user_modif";
  2969. }
  2970. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2971. $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
  2972. $sql .= ", ".$fieldusermod." = ".((int) $user->id);
  2973. $sql .= " WHERE rowid = ".((int) $this->id);
  2974. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  2975. if ($this->db->query($sql)) {
  2976. if ($suffix == '_public') {
  2977. $this->note_public = $note;
  2978. } elseif ($suffix == '_private') {
  2979. $this->note_private = $note;
  2980. } else {
  2981. $this->note = $note; // deprecated
  2982. $this->note_private = $note;
  2983. }
  2984. return 1;
  2985. } else {
  2986. $this->error = $this->db->lasterror();
  2987. return -1;
  2988. }
  2989. }
  2990. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2991. /**
  2992. * Update public note (kept for backward compatibility)
  2993. *
  2994. * @param string $note New value for note
  2995. * @return int <0 if KO, >0 if OK
  2996. * @deprecated
  2997. * @see update_note()
  2998. */
  2999. public function update_note_public($note)
  3000. {
  3001. // phpcs:enable
  3002. return $this->update_note($note, '_public');
  3003. }
  3004. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3005. /**
  3006. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  3007. * Must be called at end of methods addline or updateline.
  3008. *
  3009. * @param int $exclspec >0 = Exclude special product (product_type=9)
  3010. * @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
  3011. * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object.
  3012. * @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.
  3013. * @return int <0 if KO, >0 if OK
  3014. */
  3015. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  3016. {
  3017. // phpcs:enable
  3018. global $conf, $hookmanager, $action;
  3019. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  3020. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3021. if ($reshook > 0) {
  3022. return 1; // replacement code
  3023. } elseif ($reshook < 0) {
  3024. return -1; // failure
  3025. } // reshook = 0 => execute normal code
  3026. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  3027. $MODULE = "";
  3028. if ($this->element == 'propal') {
  3029. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  3030. } elseif ($this->element == 'commande' || $this->element == 'order') {
  3031. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  3032. } elseif ($this->element == 'facture' || $this->element == 'invoice') {
  3033. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  3034. } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
  3035. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  3036. } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
  3037. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  3038. } elseif ($this->element == 'supplier_proposal') {
  3039. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  3040. }
  3041. if (!empty($MODULE)) {
  3042. if (!empty($conf->global->$MODULE)) {
  3043. $modsactivated = explode(',', $conf->global->$MODULE);
  3044. foreach ($modsactivated as $mod) {
  3045. if ($conf->$mod->enabled) {
  3046. return 1; // update was disabled by specific setup
  3047. }
  3048. }
  3049. }
  3050. }
  3051. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  3052. if ($roundingadjust == '-1') {
  3053. $roundingadjust = 'auto'; // For backward compatibility
  3054. }
  3055. $forcedroundingmode = $roundingadjust;
  3056. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
  3057. $forcedroundingmode = $conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
  3058. } elseif ($forcedroundingmode == 'auto') {
  3059. $forcedroundingmode = '0';
  3060. }
  3061. $error = 0;
  3062. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  3063. // Define constants to find lines to sum
  3064. $fieldtva = 'total_tva';
  3065. $fieldlocaltax1 = 'total_localtax1';
  3066. $fieldlocaltax2 = 'total_localtax2';
  3067. $fieldup = 'subprice';
  3068. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3069. $fieldtva = 'tva';
  3070. $fieldup = 'pu_ht';
  3071. }
  3072. if ($this->element == 'invoice_supplier_rec') {
  3073. $fieldup = 'pu_ht';
  3074. }
  3075. if ($this->element == 'expensereport') {
  3076. $fieldup = 'value_unit';
  3077. }
  3078. $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,";
  3079. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  3080. if ($this->table_element_line == 'facturedet') {
  3081. $sql .= ', situation_percent';
  3082. }
  3083. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3084. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  3085. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3086. if ($exclspec) {
  3087. $product_field = 'product_type';
  3088. if ($this->table_element_line == 'contratdet') {
  3089. $product_field = ''; // contratdet table has no product_type field
  3090. }
  3091. if ($product_field) {
  3092. $sql .= " AND ".$product_field." <> 9";
  3093. }
  3094. }
  3095. $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
  3096. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3097. $resql = $this->db->query($sql);
  3098. if ($resql) {
  3099. $this->total_ht = 0;
  3100. $this->total_tva = 0;
  3101. $this->total_localtax1 = 0;
  3102. $this->total_localtax2 = 0;
  3103. $this->total_ttc = 0;
  3104. $total_ht_by_vats = array();
  3105. $total_tva_by_vats = array();
  3106. $total_ttc_by_vats = array();
  3107. $this->multicurrency_total_ht = 0;
  3108. $this->multicurrency_total_tva = 0;
  3109. $this->multicurrency_total_ttc = 0;
  3110. $num = $this->db->num_rows($resql);
  3111. $i = 0;
  3112. while ($i < $num) {
  3113. $obj = $this->db->fetch_object($resql);
  3114. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  3115. $parameters = array('fk_element' => $obj->rowid);
  3116. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3117. 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'
  3118. // This part of code is to fix data. We should not call it too often.
  3119. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  3120. $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);
  3121. $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.
  3122. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  3123. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
  3124. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  3125. if ($diff_when_using_price_ht && $diff_on_current_total) {
  3126. $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2])." WHERE rowid = ".((int) $obj->rowid);
  3127. 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);
  3128. $resqlfix = $this->db->query($sqlfix);
  3129. if (!$resqlfix) {
  3130. dol_print_error($this->db, 'Failed to update line');
  3131. }
  3132. $obj->total_tva = $tmpcal[1];
  3133. $obj->total_ttc = $tmpcal[2];
  3134. }
  3135. }
  3136. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  3137. $this->total_tva += $obj->total_tva;
  3138. $this->total_localtax1 += $obj->total_localtax1;
  3139. $this->total_localtax2 += $obj->total_localtax2;
  3140. $this->total_ttc += $obj->total_ttc;
  3141. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  3142. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  3143. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  3144. if (!isset($total_ht_by_vats[$obj->vatrate])) {
  3145. $total_ht_by_vats[$obj->vatrate] = 0;
  3146. }
  3147. if (!isset($total_tva_by_vats[$obj->vatrate])) {
  3148. $total_tva_by_vats[$obj->vatrate] = 0;
  3149. }
  3150. if (!isset($total_ttc_by_vats[$obj->vatrate])) {
  3151. $total_ttc_by_vats[$obj->vatrate] = 0;
  3152. }
  3153. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  3154. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  3155. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  3156. if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  3157. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  3158. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  3159. //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";
  3160. if ($diff) {
  3161. if (abs($diff) > 0.1) {
  3162. $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.';
  3163. dol_syslog($errmsg, LOG_WARNING);
  3164. dol_print_error('', $errmsg);
  3165. exit;
  3166. }
  3167. $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num($obj->total_tva - $diff).", total_ttc = ".price2num($obj->total_ttc - $diff)." WHERE rowid = ".((int) $obj->rowid);
  3168. 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);
  3169. $resqlfix = $this->db->query($sqlfix);
  3170. if (!$resqlfix) {
  3171. dol_print_error($this->db, 'Failed to update line');
  3172. }
  3173. $this->total_tva -= $diff;
  3174. $this->total_ttc -= $diff;
  3175. $total_tva_by_vats[$obj->vatrate] -= $diff;
  3176. $total_ttc_by_vats[$obj->vatrate] -= $diff;
  3177. }
  3178. }
  3179. $i++;
  3180. }
  3181. // Add revenue stamp to total
  3182. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  3183. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  3184. // Situations totals
  3185. if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
  3186. $prev_sits = $this->get_prev_sits();
  3187. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  3188. $this->total_ht -= $sit->total_ht;
  3189. $this->total_tva -= $sit->total_tva;
  3190. $this->total_localtax1 -= $sit->total_localtax1;
  3191. $this->total_localtax2 -= $sit->total_localtax2;
  3192. $this->total_ttc -= $sit->total_ttc;
  3193. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  3194. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  3195. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  3196. }
  3197. }
  3198. $this->db->free($resql);
  3199. // Now update global field total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_*
  3200. $fieldht = 'total_ht';
  3201. $fieldtva = 'tva';
  3202. $fieldlocaltax1 = 'localtax1';
  3203. $fieldlocaltax2 = 'localtax2';
  3204. $fieldttc = 'total_ttc';
  3205. // Specific code for backward compatibility with old field names
  3206. if ($this->element == 'facture' || $this->element == 'facturerec') {
  3207. $fieldtva = 'total_tva';
  3208. }
  3209. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
  3210. $fieldtva = 'total_tva';
  3211. }
  3212. if ($this->element == 'propal') {
  3213. $fieldtva = 'total_tva';
  3214. }
  3215. if ($this->element == 'expensereport') {
  3216. $fieldtva = 'total_tva';
  3217. }
  3218. if ($this->element == 'supplier_proposal') {
  3219. $fieldtva = 'total_tva';
  3220. }
  3221. if ($this->element == 'commande') {
  3222. $fieldtva = 'total_tva';
  3223. }
  3224. if ($this->element == 'order_supplier') {
  3225. $fieldtva = 'total_tva';
  3226. }
  3227. if (empty($nodatabaseupdate)) {
  3228. $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
  3229. $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht)).",";
  3230. $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva)).",";
  3231. $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1)).",";
  3232. $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2)).",";
  3233. $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc));
  3234. $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
  3235. $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
  3236. $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
  3237. $sql .= " WHERE rowid = ".((int) $this->id);
  3238. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3239. $resql = $this->db->query($sql);
  3240. if (!$resql) {
  3241. $error++;
  3242. $this->error = $this->db->lasterror();
  3243. $this->errors[] = $this->db->lasterror();
  3244. }
  3245. }
  3246. if (!$error) {
  3247. return 1;
  3248. } else {
  3249. return -1;
  3250. }
  3251. } else {
  3252. dol_print_error($this->db, 'Bad request in update_price');
  3253. return -1;
  3254. }
  3255. }
  3256. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3257. /**
  3258. * Add objects linked in llx_element_element.
  3259. *
  3260. * @param string $origin Linked element type
  3261. * @param int $origin_id Linked element id
  3262. * @param User $f_user User that create
  3263. * @param int $notrigger 1=Does not execute triggers, 0=execute triggers
  3264. * @return int <=0 if KO, >0 if OK
  3265. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  3266. */
  3267. public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
  3268. {
  3269. // phpcs:enable
  3270. global $user, $hookmanager, $action;
  3271. $origin = (!empty($origin) ? $origin : $this->origin);
  3272. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  3273. $f_user = isset($f_user) ? $f_user : $user;
  3274. // Special case
  3275. if ($origin == 'order') {
  3276. $origin = 'commande';
  3277. }
  3278. if ($origin == 'invoice') {
  3279. $origin = 'facture';
  3280. }
  3281. if ($origin == 'invoice_template') {
  3282. $origin = 'facturerec';
  3283. }
  3284. if ($origin == 'supplierorder') {
  3285. $origin = 'order_supplier';
  3286. }
  3287. // Elements of the core modules which have `$module` property but may to which we don't want to prefix module part to the element name for finding the linked object in llx_element_element.
  3288. // It's because an entry for this element may be exist in llx_element_element before this modification (version <=14.2) and ave named only with their element name in fk_source or fk_target.
  3289. $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization');
  3290. // Add module part to target type if object has $module property and isn't in core modules.
  3291. $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
  3292. $parameters = array('targettype'=>$targettype);
  3293. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3294. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3295. if ($reshook > 0) {
  3296. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3297. }
  3298. $this->db->begin();
  3299. $error = 0;
  3300. $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
  3301. $sql .= "fk_source";
  3302. $sql .= ", sourcetype";
  3303. $sql .= ", fk_target";
  3304. $sql .= ", targettype";
  3305. $sql .= ") VALUES (";
  3306. $sql .= ((int) $origin_id);
  3307. $sql .= ", '" . $this->db->escape($origin) . "'";
  3308. $sql .= ", " . ((int) $this->id);
  3309. $sql .= ", '" . $this->db->escape($targettype) . "'";
  3310. $sql .= ")";
  3311. dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
  3312. if ($this->db->query($sql)) {
  3313. if (!$notrigger) {
  3314. // Call trigger
  3315. $this->context['link_origin'] = $origin;
  3316. $this->context['link_origin_id'] = $origin_id;
  3317. $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
  3318. if ($result < 0) {
  3319. $error++;
  3320. }
  3321. // End call triggers
  3322. }
  3323. } else {
  3324. $this->error = $this->db->lasterror();
  3325. $error++;
  3326. }
  3327. if (!$error) {
  3328. $this->db->commit();
  3329. return 1;
  3330. } else {
  3331. $this->db->rollback();
  3332. return 0;
  3333. }
  3334. }
  3335. /**
  3336. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  3337. * this->linkedObjectsIds array +
  3338. * this->linkedObjects array if $loadalsoobjects = 1 or $loadalsoobjects = type
  3339. * Possible usage for parameters:
  3340. * - all parameters empty -> we look all link to current object (current object can be source or target)
  3341. * - source id+type -> will get list of targets linked to source
  3342. * - target id+type -> will get list of sources linked to target
  3343. * - source id+type + target type -> will get list of targets of the type linked to source
  3344. * - target id+type + source type -> will get list of sources of the type linked to target
  3345. *
  3346. * @param int $sourceid Object source id (if not defined, id of object)
  3347. * @param string $sourcetype Object source type (if not defined, element name of object)
  3348. * @param int $targetid Object target id (if not defined, id of object)
  3349. * @param string $targettype Object target type (if not defined, element name of object)
  3350. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  3351. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  3352. * @param string $orderby SQL 'ORDER BY' clause
  3353. * @param int|string $loadalsoobjects Load also array this->linkedObjects. Use 0 to increase performances, Use 1 to load all, Use value of type ('facture', 'facturerec', ...) to load only a type of object.
  3354. * @return int <0 if KO, >0 if OK
  3355. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  3356. */
  3357. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  3358. {
  3359. global $conf, $hookmanager, $action;
  3360. $this->linkedObjectsIds = array();
  3361. $this->linkedObjects = array();
  3362. $justsource = false;
  3363. $justtarget = false;
  3364. $withtargettype = false;
  3365. $withsourcetype = false;
  3366. $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
  3367. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3368. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3369. if ($reshook > 0) {
  3370. if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
  3371. if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
  3372. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3373. if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
  3374. }
  3375. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
  3376. $justsource = true; // the source (id and type) is a search criteria
  3377. if (!empty($targettype)) {
  3378. $withtargettype = true;
  3379. }
  3380. }
  3381. if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
  3382. $justtarget = true; // the target (id and type) is a search criteria
  3383. if (!empty($sourcetype)) {
  3384. $withsourcetype = true;
  3385. }
  3386. }
  3387. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3388. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3389. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3390. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3391. /*if (empty($sourceid) && empty($targetid))
  3392. {
  3393. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  3394. return -1;
  3395. }*/
  3396. // Links between objects are stored in table element_element
  3397. $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
  3398. $sql .= " FROM ".$this->db->prefix()."element_element";
  3399. $sql .= " WHERE ";
  3400. if ($justsource || $justtarget) {
  3401. if ($justsource) {
  3402. $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3403. if ($withtargettype) {
  3404. $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
  3405. }
  3406. } elseif ($justtarget) {
  3407. $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
  3408. if ($withsourcetype) {
  3409. $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3410. }
  3411. }
  3412. } else {
  3413. $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
  3414. $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
  3415. }
  3416. $sql .= " ORDER BY ".$orderby;
  3417. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  3418. $resql = $this->db->query($sql);
  3419. if ($resql) {
  3420. $num = $this->db->num_rows($resql);
  3421. $i = 0;
  3422. while ($i < $num) {
  3423. $obj = $this->db->fetch_object($resql);
  3424. if ($justsource || $justtarget) {
  3425. if ($justsource) {
  3426. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3427. } elseif ($justtarget) {
  3428. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3429. }
  3430. } else {
  3431. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
  3432. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3433. }
  3434. if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
  3435. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3436. }
  3437. }
  3438. $i++;
  3439. }
  3440. if (!empty($this->linkedObjectsIds)) {
  3441. $tmparray = $this->linkedObjectsIds;
  3442. foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  3443. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  3444. $module = $element = $subelement = $objecttype;
  3445. $regs = array();
  3446. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  3447. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  3448. $module = $element = $regs[1];
  3449. $subelement = $regs[2];
  3450. }
  3451. $classpath = $element.'/class';
  3452. // To work with non standard classpath or module name
  3453. if ($objecttype == 'facture') {
  3454. $classpath = 'compta/facture/class';
  3455. } elseif ($objecttype == 'facturerec') {
  3456. $classpath = 'compta/facture/class';
  3457. $module = 'facture';
  3458. } elseif ($objecttype == 'propal') {
  3459. $classpath = 'comm/propal/class';
  3460. } elseif ($objecttype == 'supplier_proposal') {
  3461. $classpath = 'supplier_proposal/class';
  3462. } elseif ($objecttype == 'shipping') {
  3463. $classpath = 'expedition/class';
  3464. $subelement = 'expedition';
  3465. $module = 'expedition_bon';
  3466. } elseif ($objecttype == 'delivery') {
  3467. $classpath = 'delivery/class';
  3468. $subelement = 'delivery';
  3469. $module = 'delivery_note';
  3470. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  3471. $classpath = 'fourn/class';
  3472. $module = 'fournisseur';
  3473. } elseif ($objecttype == 'fichinter') {
  3474. $classpath = 'fichinter/class';
  3475. $subelement = 'fichinter';
  3476. $module = 'ficheinter';
  3477. } elseif ($objecttype == 'subscription') {
  3478. $classpath = 'adherents/class';
  3479. $module = 'adherent';
  3480. } elseif ($objecttype == 'contact') {
  3481. $module = 'societe';
  3482. }
  3483. // Set classfile
  3484. $classfile = strtolower($subelement);
  3485. $classname = ucfirst($subelement);
  3486. if ($objecttype == 'order') {
  3487. $classfile = 'commande';
  3488. $classname = 'Commande';
  3489. } elseif ($objecttype == 'invoice_supplier') {
  3490. $classfile = 'fournisseur.facture';
  3491. $classname = 'FactureFournisseur';
  3492. } elseif ($objecttype == 'order_supplier') {
  3493. $classfile = 'fournisseur.commande';
  3494. $classname = 'CommandeFournisseur';
  3495. } elseif ($objecttype == 'supplier_proposal') {
  3496. $classfile = 'supplier_proposal';
  3497. $classname = 'SupplierProposal';
  3498. } elseif ($objecttype == 'facturerec') {
  3499. $classfile = 'facture-rec';
  3500. $classname = 'FactureRec';
  3501. } elseif ($objecttype == 'subscription') {
  3502. $classfile = 'subscription';
  3503. $classname = 'Subscription';
  3504. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  3505. $classpath = 'projet/class';
  3506. $classfile = 'project';
  3507. $classname = 'Project';
  3508. } elseif ($objecttype == 'conferenceorboothattendee') {
  3509. $classpath = 'eventorganization/class';
  3510. $classfile = 'conferenceorboothattendee';
  3511. $classname = 'ConferenceOrBoothAttendee';
  3512. $module = 'eventorganization';
  3513. } elseif ($objecttype == 'conferenceorbooth') {
  3514. $classpath = 'eventorganization/class';
  3515. $classfile = 'conferenceorbooth';
  3516. $classname = 'ConferenceOrBooth';
  3517. $module = 'eventorganization';
  3518. } elseif ($objecttype == 'mo') {
  3519. $classpath = 'mrp/class';
  3520. $classfile = 'mo';
  3521. $classname = 'Mo';
  3522. $module = 'mrp';
  3523. }
  3524. // Here $module, $classfile and $classname are set, we can use them.
  3525. if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
  3526. if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
  3527. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  3528. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  3529. if (class_exists($classname)) {
  3530. foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
  3531. $object = new $classname($this->db);
  3532. $ret = $object->fetch($objectid);
  3533. if ($ret >= 0) {
  3534. $this->linkedObjects[$objecttype][$i] = $object;
  3535. }
  3536. }
  3537. }
  3538. }
  3539. } else {
  3540. unset($this->linkedObjectsIds[$objecttype]);
  3541. }
  3542. }
  3543. }
  3544. return 1;
  3545. } else {
  3546. dol_print_error($this->db);
  3547. return -1;
  3548. }
  3549. }
  3550. /**
  3551. * Update object linked of a current object
  3552. *
  3553. * @param int $sourceid Object source id
  3554. * @param string $sourcetype Object source type
  3555. * @param int $targetid Object target id
  3556. * @param string $targettype Object target type
  3557. * @param User $f_user User that create
  3558. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3559. * @return int >0 if OK, <0 if KO
  3560. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3561. */
  3562. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
  3563. {
  3564. global $user;
  3565. $updatesource = false;
  3566. $updatetarget = false;
  3567. $f_user = isset($f_user) ? $f_user : $user;
  3568. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3569. $updatesource = true;
  3570. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3571. $updatetarget = true;
  3572. }
  3573. $this->db->begin();
  3574. $error = 0;
  3575. $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
  3576. if ($updatesource) {
  3577. $sql .= "fk_source = " . ((int) $sourceid);
  3578. $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3579. $sql .= " WHERE fk_target = " . ((int) $this->id);
  3580. $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
  3581. } elseif ($updatetarget) {
  3582. $sql .= "fk_target = " . ((int) $targetid);
  3583. $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
  3584. $sql .= " WHERE fk_source = " . ((int) $this->id);
  3585. $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3586. }
  3587. dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
  3588. if ($this->db->query($sql)) {
  3589. if (!$notrigger) {
  3590. // Call trigger
  3591. $this->context['link_source_id'] = $sourceid;
  3592. $this->context['link_source_type'] = $sourcetype;
  3593. $this->context['link_target_id'] = $targetid;
  3594. $this->context['link_target_type'] = $targettype;
  3595. $result = $this->call_trigger('OBJECT_LINK_UPDATE', $f_user);
  3596. if ($result < 0) {
  3597. $error++;
  3598. }
  3599. // End call triggers
  3600. }
  3601. } else {
  3602. $this->error = $this->db->lasterror();
  3603. $error++;
  3604. }
  3605. if (!$error) {
  3606. $this->db->commit();
  3607. return 1;
  3608. } else {
  3609. $this->db->rollback();
  3610. return -1;
  3611. }
  3612. }
  3613. /**
  3614. * Delete all links between an object $this
  3615. *
  3616. * @param int $sourceid Object source id
  3617. * @param string $sourcetype Object source type
  3618. * @param int $targetid Object target id
  3619. * @param string $targettype Object target type
  3620. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3621. * @param User $f_user User that create
  3622. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3623. * @return int >0 if OK, <0 if KO
  3624. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3625. */
  3626. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
  3627. {
  3628. global $user;
  3629. $deletesource = false;
  3630. $deletetarget = false;
  3631. $f_user = isset($f_user) ? $f_user : $user;
  3632. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3633. $deletesource = true;
  3634. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3635. $deletetarget = true;
  3636. }
  3637. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3638. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3639. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3640. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3641. $this->db->begin();
  3642. $error = 0;
  3643. if (!$notrigger) {
  3644. // Call trigger
  3645. $this->context['link_id'] = $rowid;
  3646. $this->context['link_source_id'] = $sourceid;
  3647. $this->context['link_source_type'] = $sourcetype;
  3648. $this->context['link_target_id'] = $targetid;
  3649. $this->context['link_target_type'] = $targettype;
  3650. $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
  3651. if ($result < 0) {
  3652. $error++;
  3653. }
  3654. // End call triggers
  3655. }
  3656. if (!$error) {
  3657. $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
  3658. $sql .= " WHERE";
  3659. if ($rowid > 0) {
  3660. $sql .= " rowid = " . ((int) $rowid);
  3661. } else {
  3662. if ($deletesource) {
  3663. $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3664. $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
  3665. } elseif ($deletetarget) {
  3666. $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
  3667. $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3668. } else {
  3669. $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
  3670. $sql .= " OR";
  3671. $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
  3672. }
  3673. }
  3674. dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
  3675. if (!$this->db->query($sql)) {
  3676. $this->error = $this->db->lasterror();
  3677. $this->errors[] = $this->error;
  3678. $error++;
  3679. }
  3680. }
  3681. if (!$error) {
  3682. $this->db->commit();
  3683. return 1;
  3684. } else {
  3685. $this->db->rollback();
  3686. return 0;
  3687. }
  3688. }
  3689. /**
  3690. * Function used to get an array with all items linked to an object id in association table
  3691. *
  3692. * @param int $fk_object_where id of object we need to get linked items
  3693. * @param string $field_select name of field we need to get a list
  3694. * @param string $field_where name of field of object we need to get linked items
  3695. * @param string $table_element name of association table
  3696. * @return array Array of record
  3697. */
  3698. public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
  3699. {
  3700. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3701. return -1;
  3702. }
  3703. global $db;
  3704. $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3705. $resql = $db->query($sql);
  3706. $TRes = array();
  3707. if (!empty($resql)) {
  3708. while ($res = $db->fetch_object($resql)) {
  3709. $TRes[] = $res->{$field_select};
  3710. }
  3711. }
  3712. return $TRes;
  3713. }
  3714. /**
  3715. * Function used to remove all items linked to an object id in association table
  3716. *
  3717. * @param int $fk_object_where id of object we need to remove linked items
  3718. * @param string $field_where name of field of object we need to delete linked items
  3719. * @param string $table_element name of association table
  3720. * @return int <0 if KO, 0 if nothing done, >0 if OK and something done
  3721. */
  3722. public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
  3723. {
  3724. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3725. return -1;
  3726. }
  3727. global $db;
  3728. $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3729. $resql = $db->query($sql);
  3730. if (empty($resql)) {
  3731. return 0;
  3732. }
  3733. return 1;
  3734. }
  3735. /**
  3736. * Set status of an object
  3737. *
  3738. * @param int $status Status to set
  3739. * @param int $elementId Id of element to force (use this->id by default if null)
  3740. * @param string $elementType Type of element to force (use this->table_element by default)
  3741. * @param string $trigkey Trigger key to use for trigger. Use '' means automatic but it not recommended and is deprecated.
  3742. * @param string $fieldstatus Name of status field in this->table_element
  3743. * @return int <0 if KO, >0 if OK
  3744. */
  3745. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
  3746. {
  3747. global $user, $langs, $conf;
  3748. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3749. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3750. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3751. $this->db->begin();
  3752. if ($elementTable == 'facture_rec') {
  3753. $fieldstatus = "suspended";
  3754. }
  3755. if ($elementTable == 'mailing') {
  3756. $fieldstatus = "statut";
  3757. }
  3758. if ($elementTable == 'cronjob') {
  3759. $fieldstatus = "status";
  3760. }
  3761. if ($elementTable == 'user') {
  3762. $fieldstatus = "statut";
  3763. }
  3764. if ($elementTable == 'expensereport') {
  3765. $fieldstatus = "fk_statut";
  3766. }
  3767. if ($elementTable == 'commande_fournisseur_dispatch') {
  3768. $fieldstatus = "status";
  3769. }
  3770. if (is_array($this->fields) && array_key_exists('status', $this->fields)) {
  3771. $fieldstatus = 'status';
  3772. }
  3773. $sql = "UPDATE ".$this->db->prefix().$elementTable;
  3774. $sql .= " SET ".$fieldstatus." = ".((int) $status);
  3775. // If status = 1 = validated, update also fk_user_valid
  3776. // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
  3777. if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
  3778. $sql .= ", fk_user_valid = ".((int) $user->id);
  3779. }
  3780. if ($status == 1 && in_array($elementTable, array('expensereport'))) {
  3781. $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
  3782. }
  3783. if ($status == 1 && in_array($elementTable, array('inventory'))) {
  3784. $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
  3785. }
  3786. $sql .= " WHERE rowid=".((int) $elementId);
  3787. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  3788. if ($this->db->query($sql)) {
  3789. $error = 0;
  3790. // Try autoset of trigkey
  3791. if (empty($trigkey)) {
  3792. if ($this->element == 'supplier_proposal' && $status == 2) {
  3793. $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3794. }
  3795. if ($this->element == 'supplier_proposal' && $status == 3) {
  3796. $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3797. }
  3798. if ($this->element == 'supplier_proposal' && $status == 4) {
  3799. $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3800. }
  3801. if ($this->element == 'fichinter' && $status == 3) {
  3802. $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3803. }
  3804. if ($this->element == 'fichinter' && $status == 2) {
  3805. $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3806. }
  3807. if ($this->element == 'fichinter' && $status == 1) {
  3808. $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3809. }
  3810. }
  3811. if ($trigkey) {
  3812. // Call trigger
  3813. $result = $this->call_trigger($trigkey, $user);
  3814. if ($result < 0) {
  3815. $error++;
  3816. }
  3817. // End call triggers
  3818. }
  3819. if (!$error) {
  3820. $this->db->commit();
  3821. if (empty($savElementId)) {
  3822. // If the element we update is $this (so $elementId was provided as null)
  3823. if ($fieldstatus == 'tosell') {
  3824. $this->status = $status;
  3825. } elseif ($fieldstatus == 'tobuy') {
  3826. $this->status_buy = $status;
  3827. } else {
  3828. $this->statut = $status;
  3829. $this->status = $status;
  3830. }
  3831. }
  3832. return 1;
  3833. } else {
  3834. $this->db->rollback();
  3835. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  3836. return -1;
  3837. }
  3838. } else {
  3839. $this->error = $this->db->lasterror();
  3840. $this->db->rollback();
  3841. return -1;
  3842. }
  3843. }
  3844. /**
  3845. * Load type of canvas of an object if it exists
  3846. *
  3847. * @param int $id Record id
  3848. * @param string $ref Record ref
  3849. * @return int <0 if KO, 0 if nothing done, >0 if OK
  3850. */
  3851. public function getCanvas($id = 0, $ref = '')
  3852. {
  3853. global $conf;
  3854. if (empty($id) && empty($ref)) {
  3855. return 0;
  3856. }
  3857. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
  3858. return 0; // To increase speed. Not enabled by default.
  3859. }
  3860. // Clean parameters
  3861. $ref = trim($ref);
  3862. $sql = "SELECT rowid, canvas";
  3863. $sql .= " FROM ".$this->db->prefix().$this->table_element;
  3864. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  3865. if (!empty($id)) {
  3866. $sql .= " AND rowid = ".((int) $id);
  3867. }
  3868. if (!empty($ref)) {
  3869. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  3870. }
  3871. $resql = $this->db->query($sql);
  3872. if ($resql) {
  3873. $obj = $this->db->fetch_object($resql);
  3874. if ($obj) {
  3875. $this->canvas = $obj->canvas;
  3876. return 1;
  3877. } else {
  3878. return 0;
  3879. }
  3880. } else {
  3881. dol_print_error($this->db);
  3882. return -1;
  3883. }
  3884. }
  3885. /**
  3886. * Get special code of a line
  3887. *
  3888. * @param int $lineid Id of line
  3889. * @return int Special code
  3890. */
  3891. public function getSpecialCode($lineid)
  3892. {
  3893. $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
  3894. $sql .= " WHERE rowid = ".((int) $lineid);
  3895. $resql = $this->db->query($sql);
  3896. if ($resql) {
  3897. $row = $this->db->fetch_row($resql);
  3898. return $row[0];
  3899. }
  3900. }
  3901. /**
  3902. * Function to check if an object is used by others.
  3903. * Check is done into this->childtables. There is no check into llx_element_element.
  3904. *
  3905. * @param int $id Force id of object
  3906. * @return int <0 if KO, 0 if not used, >0 if already used
  3907. */
  3908. public function isObjectUsed($id = 0)
  3909. {
  3910. global $langs;
  3911. if (empty($id)) {
  3912. $id = $this->id;
  3913. }
  3914. // Check parameters
  3915. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
  3916. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  3917. return -1;
  3918. }
  3919. $arraytoscan = $this->childtables;
  3920. // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
  3921. $tmparray = array_keys($this->childtables);
  3922. if (is_numeric($tmparray[0])) {
  3923. $arraytoscan = array_flip($this->childtables);
  3924. }
  3925. // Test if child exists
  3926. $haschild = 0;
  3927. foreach ($arraytoscan as $table => $elementname) {
  3928. //print $id.'-'.$table.'-'.$elementname.'<br>';
  3929. // Check if third party can be deleted
  3930. $sql = "SELECT COUNT(*) as nb from ".$this->db->prefix().$table;
  3931. $sql .= " WHERE ".$this->fk_element." = ".((int) $id);
  3932. $resql = $this->db->query($sql);
  3933. if ($resql) {
  3934. $obj = $this->db->fetch_object($resql);
  3935. if ($obj->nb > 0) {
  3936. $langs->load("errors");
  3937. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  3938. $haschild += $obj->nb;
  3939. if (is_numeric($elementname)) { // old usage
  3940. $this->errors[] = $langs->transnoentities("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
  3941. } else // new usage: $elementname=Translation key
  3942. {
  3943. $this->errors[] = $langs->transnoentities("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($elementname));
  3944. }
  3945. break; // We found at least one, we stop here
  3946. }
  3947. } else {
  3948. $this->errors[] = $this->db->lasterror();
  3949. return -1;
  3950. }
  3951. }
  3952. if ($haschild > 0) {
  3953. $this->errors[] = "ErrorRecordHasChildren";
  3954. return $haschild;
  3955. } else {
  3956. return 0;
  3957. }
  3958. }
  3959. /**
  3960. * Function to say how many lines object contains
  3961. *
  3962. * @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
  3963. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  3964. */
  3965. public function hasProductsOrServices($predefined = -1)
  3966. {
  3967. $nb = 0;
  3968. foreach ($this->lines as $key => $val) {
  3969. $qualified = 0;
  3970. if ($predefined == -1) {
  3971. $qualified = 1;
  3972. }
  3973. if ($predefined == 1 && $val->fk_product > 0) {
  3974. $qualified = 1;
  3975. }
  3976. if ($predefined == 0 && $val->fk_product <= 0) {
  3977. $qualified = 1;
  3978. }
  3979. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
  3980. $qualified = 1;
  3981. }
  3982. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
  3983. $qualified = 1;
  3984. }
  3985. if ($qualified) {
  3986. $nb++;
  3987. }
  3988. }
  3989. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  3990. return $nb;
  3991. }
  3992. /**
  3993. * Function that returns the total amount HT of discounts applied for all lines.
  3994. *
  3995. * @return float|string Total amout of discount
  3996. */
  3997. public function getTotalDiscount()
  3998. {
  3999. if (!empty($this->table_element_line) ) {
  4000. $total_discount = 0.00;
  4001. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  4002. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  4003. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  4004. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  4005. $resql = $this->db->query($sql);
  4006. if ($resql) {
  4007. $num = $this->db->num_rows($resql);
  4008. $i = 0;
  4009. while ($i < $num) {
  4010. $obj = $this->db->fetch_object($resql);
  4011. $pu_ht = $obj->pu_ht;
  4012. $qty = $obj->qty;
  4013. $total_ht = $obj->total_ht;
  4014. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  4015. $total_discount += $total_discount_line;
  4016. $i++;
  4017. }
  4018. }
  4019. //print $total_discount; exit;
  4020. return price2num($total_discount);
  4021. }
  4022. return null;
  4023. }
  4024. /**
  4025. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  4026. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  4027. *
  4028. * @return array array('weight'=>...,'volume'=>...)
  4029. */
  4030. public function getTotalWeightVolume()
  4031. {
  4032. $totalWeight = 0;
  4033. $totalVolume = 0;
  4034. // defined for shipment only
  4035. $totalOrdered = '';
  4036. // defined for shipment only
  4037. $totalToShip = '';
  4038. foreach ($this->lines as $line) {
  4039. if (isset($line->qty_asked)) {
  4040. if (empty($totalOrdered)) {
  4041. $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  4042. }
  4043. $totalOrdered += $line->qty_asked; // defined for shipment only
  4044. }
  4045. if (isset($line->qty_shipped)) {
  4046. if (empty($totalToShip)) {
  4047. $totalToShip = 0; // Avoid warning because $totalToShip is ''
  4048. }
  4049. $totalToShip += $line->qty_shipped; // defined for shipment only
  4050. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
  4051. if (empty($totalToShip)) {
  4052. $totalToShip = 0;
  4053. }
  4054. $totalToShip += $line->qty; // defined for reception only
  4055. }
  4056. // Define qty, weight, volume, weight_units, volume_units
  4057. if ($this->element == 'shipping') {
  4058. // for shipments
  4059. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  4060. } else {
  4061. $qty = $line->qty ? $line->qty : 0;
  4062. }
  4063. $weight = !empty($line->weight) ? $line->weight : 0;
  4064. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  4065. $volume = !empty($line->volume) ? $line->volume : 0;
  4066. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  4067. $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
  4068. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  4069. $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
  4070. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  4071. $weightUnit = 0;
  4072. $volumeUnit = 0;
  4073. if (!empty($weight_units)) {
  4074. $weightUnit = $weight_units;
  4075. }
  4076. if (!empty($volume_units)) {
  4077. $volumeUnit = $volume_units;
  4078. }
  4079. if (empty($totalWeight)) {
  4080. $totalWeight = 0; // Avoid warning because $totalWeight is ''
  4081. }
  4082. if (empty($totalVolume)) {
  4083. $totalVolume = 0; // Avoid warning because $totalVolume is ''
  4084. }
  4085. //var_dump($line->volume_units);
  4086. if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4087. $trueWeightUnit = pow(10, $weightUnit);
  4088. $totalWeight += $weight * $qty * $trueWeightUnit;
  4089. } else {
  4090. if ($weight_units == 99) {
  4091. // conversion 1 Pound = 0.45359237 KG
  4092. $trueWeightUnit = 0.45359237;
  4093. $totalWeight += $weight * $qty * $trueWeightUnit;
  4094. } elseif ($weight_units == 98) {
  4095. // conversion 1 Ounce = 0.0283495 KG
  4096. $trueWeightUnit = 0.0283495;
  4097. $totalWeight += $weight * $qty * $trueWeightUnit;
  4098. } else {
  4099. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  4100. }
  4101. }
  4102. if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4103. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  4104. $trueVolumeUnit = pow(10, $volumeUnit);
  4105. //print $line->volume;
  4106. $totalVolume += $volume * $qty * $trueVolumeUnit;
  4107. } else {
  4108. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  4109. }
  4110. }
  4111. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  4112. }
  4113. /**
  4114. * Set extra parameters
  4115. *
  4116. * @return int <0 if KO, >0 if OK
  4117. */
  4118. public function setExtraParameters()
  4119. {
  4120. $this->db->begin();
  4121. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  4122. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  4123. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  4124. $sql .= " WHERE rowid = ".((int) $this->id);
  4125. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  4126. $resql = $this->db->query($sql);
  4127. if (!$resql) {
  4128. $this->error = $this->db->lasterror();
  4129. $this->db->rollback();
  4130. return -1;
  4131. } else {
  4132. $this->db->commit();
  4133. return 1;
  4134. }
  4135. }
  4136. // --------------------
  4137. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  4138. // --------------------
  4139. /* This is to show add lines */
  4140. /**
  4141. * Show add free and predefined products/services form
  4142. *
  4143. * @param int $dateSelector 1=Show also date range input fields
  4144. * @param Societe $seller Object thirdparty who sell
  4145. * @param Societe $buyer Object thirdparty who buy
  4146. * @param string $defaulttpldir Directory where to find the template
  4147. * @return void
  4148. */
  4149. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  4150. {
  4151. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  4152. global $form;
  4153. // Line extrafield
  4154. if (!is_object($extrafields)) {
  4155. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4156. $extrafields = new ExtraFields($this->db);
  4157. }
  4158. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4159. // Output template part (modules that overwrite templates must declare this into descriptor)
  4160. // Use global variables + $dateSelector + $seller and $buyer
  4161. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  4162. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4163. foreach ($dirtpls as $module => $reldir) {
  4164. if (!empty($module)) {
  4165. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  4166. } else {
  4167. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  4168. }
  4169. if (empty($conf->file->strict_mode)) {
  4170. $res = @include $tpl;
  4171. } else {
  4172. $res = include $tpl; // for debug
  4173. }
  4174. if ($res) {
  4175. break;
  4176. }
  4177. }
  4178. }
  4179. /* This is to show array of line of details */
  4180. /**
  4181. * Return HTML table for object lines
  4182. * TODO Move this into an output class file (htmlline.class.php)
  4183. * If lines are into a template, title must also be into a template
  4184. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4185. *
  4186. * @param string $action Action code
  4187. * @param string $seller Object of seller third party
  4188. * @param string $buyer Object of buyer third party
  4189. * @param int $selected Object line selected
  4190. * @param int $dateSelector 1=Show also date range input fields
  4191. * @param string $defaulttpldir Directory where to find the template
  4192. * @return void
  4193. */
  4194. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  4195. {
  4196. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  4197. // TODO We should not use global var for this
  4198. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  4199. // Define usemargins
  4200. $usemargins = 0;
  4201. if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
  4202. $usemargins = 1;
  4203. }
  4204. $num = count($this->lines);
  4205. // Line extrafield
  4206. if (!is_object($extrafields)) {
  4207. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4208. $extrafields = new ExtraFields($this->db);
  4209. }
  4210. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4211. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  4212. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4213. if (empty($reshook)) {
  4214. // Output template part (modules that overwrite templates must declare this into descriptor)
  4215. // Use global variables + $dateSelector + $seller and $buyer
  4216. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  4217. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4218. foreach ($dirtpls as $module => $reldir) {
  4219. if (!empty($module)) {
  4220. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  4221. } else {
  4222. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  4223. }
  4224. if (empty($conf->file->strict_mode)) {
  4225. $res = @include $tpl;
  4226. } else {
  4227. $res = include $tpl; // for debug
  4228. }
  4229. if ($res) {
  4230. break;
  4231. }
  4232. }
  4233. }
  4234. $i = 0;
  4235. print "<!-- begin printObjectLines() --><tbody>\n";
  4236. foreach ($this->lines as $line) {
  4237. //Line extrafield
  4238. $line->fetch_optionals();
  4239. //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  4240. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4241. if (empty($line->fk_parent_line)) {
  4242. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  4243. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4244. } else {
  4245. $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);
  4246. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4247. }
  4248. }
  4249. if (empty($reshook)) {
  4250. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  4251. }
  4252. $i++;
  4253. }
  4254. print "</tbody><!-- end printObjectLines() -->\n";
  4255. }
  4256. /**
  4257. * Return HTML content of a detail line
  4258. * TODO Move this into an output class file (htmlline.class.php)
  4259. *
  4260. * @param string $action GET/POST action
  4261. * @param CommonObjectLine $line Selected object line to output
  4262. * @param string $var Is it a an odd line (true)
  4263. * @param int $num Number of line (0)
  4264. * @param int $i I
  4265. * @param int $dateSelector 1=Show also date range input fields
  4266. * @param string $seller Object of seller third party
  4267. * @param string $buyer Object of buyer third party
  4268. * @param int $selected Object line selected
  4269. * @param Extrafields $extrafields Object of extrafields
  4270. * @param string $defaulttpldir Directory where to find the template (deprecated)
  4271. * @return void
  4272. */
  4273. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  4274. {
  4275. global $conf, $langs, $user, $object, $hookmanager;
  4276. global $form;
  4277. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  4278. $object_rights = $this->getRights();
  4279. $element = $this->element;
  4280. $text = '';
  4281. $description = '';
  4282. // Line in view mode
  4283. if ($action != 'editline' || $selected != $line->id) {
  4284. // Product
  4285. if ($line->fk_product > 0) {
  4286. $product_static = new Product($this->db);
  4287. $product_static->fetch($line->fk_product);
  4288. $product_static->ref = $line->ref; //can change ref in hook
  4289. $product_static->label = $line->label; //can change label in hook
  4290. $text = $product_static->getNomUrl(1);
  4291. // Define output language and label
  4292. if (!empty($conf->global->MAIN_MULTILANGS)) {
  4293. if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
  4294. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  4295. return;
  4296. }
  4297. $prod = new Product($this->db);
  4298. $prod->fetch($line->fk_product);
  4299. $outputlangs = $langs;
  4300. $newlang = '';
  4301. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  4302. $newlang = GETPOST('lang_id', 'aZ09');
  4303. }
  4304. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
  4305. $newlang = $this->thirdparty->default_lang; // To use language of customer
  4306. }
  4307. if (!empty($newlang)) {
  4308. $outputlangs = new Translate("", $conf);
  4309. $outputlangs->setDefaultLang($newlang);
  4310. }
  4311. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  4312. } else {
  4313. $label = $line->product_label;
  4314. }
  4315. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  4316. $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.
  4317. }
  4318. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4319. // Output template part (modules that overwrite templates must declare this into descriptor)
  4320. // Use global variables + $dateSelector + $seller and $buyer
  4321. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4322. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4323. foreach ($dirtpls as $module => $reldir) {
  4324. if (!empty($module)) {
  4325. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  4326. } else {
  4327. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  4328. }
  4329. if (empty($conf->file->strict_mode)) {
  4330. $res = @include $tpl;
  4331. } else {
  4332. $res = include $tpl; // for debug
  4333. }
  4334. if ($res) {
  4335. break;
  4336. }
  4337. }
  4338. }
  4339. // Line in update mode
  4340. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
  4341. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  4342. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4343. // Output template part (modules that overwrite templates must declare this into descriptor)
  4344. // Use global variables + $dateSelector + $seller and $buyer
  4345. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4346. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4347. foreach ($dirtpls as $module => $reldir) {
  4348. if (!empty($module)) {
  4349. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  4350. } else {
  4351. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  4352. }
  4353. if (empty($conf->file->strict_mode)) {
  4354. $res = @include $tpl;
  4355. } else {
  4356. $res = include $tpl; // for debug
  4357. }
  4358. if ($res) {
  4359. break;
  4360. }
  4361. }
  4362. }
  4363. }
  4364. /* This is to show array of line of details of source object */
  4365. /**
  4366. * Return HTML table table of source object lines
  4367. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4368. * If lines are into a template, title must also be into a template
  4369. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  4370. *
  4371. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  4372. * @param array $selectedLines Array of lines id for selected lines
  4373. * @return void
  4374. */
  4375. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  4376. {
  4377. global $langs, $hookmanager, $conf, $form, $action;
  4378. print '<tr class="liste_titre">';
  4379. print '<td>'.$langs->trans('Ref').'</td>';
  4380. print '<td>'.$langs->trans('Description').'</td>';
  4381. print '<td class="right">'.$langs->trans('VATRate').'</td>';
  4382. print '<td class="right">'.$langs->trans('PriceUHT').'</td>';
  4383. if (!empty($conf->multicurrency->enabled)) {
  4384. print '<td class="right">'.$langs->trans('PriceUHTCurrency').'</td>';
  4385. }
  4386. print '<td class="right">'.$langs->trans('Qty').'</td>';
  4387. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4388. print '<td class="left">'.$langs->trans('Unit').'</td>';
  4389. }
  4390. print '<td class="right">'.$langs->trans('ReductionShort').'</td>';
  4391. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  4392. print '</tr>';
  4393. $i = 0;
  4394. if (!empty($this->lines)) {
  4395. foreach ($this->lines as $line) {
  4396. $reshook = 0;
  4397. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
  4398. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4399. $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
  4400. if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
  4401. $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4402. }
  4403. if (empty($reshook)) {
  4404. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  4405. }
  4406. $i++;
  4407. }
  4408. }
  4409. }
  4410. /**
  4411. * Return HTML with a line of table array of source object lines
  4412. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4413. * If lines are into a template, title must also be into a template
  4414. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4415. *
  4416. * @param CommonObjectLine $line Line
  4417. * @param string $var Var
  4418. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  4419. * @param string $defaulttpldir Directory where to find the template
  4420. * @param array $selectedLines Array of lines id for selected lines
  4421. * @return void
  4422. */
  4423. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  4424. {
  4425. global $langs, $conf;
  4426. //var_dump($line);
  4427. if (!empty($line->date_start)) {
  4428. $date_start = $line->date_start;
  4429. } else {
  4430. $date_start = $line->date_debut_prevue;
  4431. if ($line->date_debut_reel) {
  4432. $date_start = $line->date_debut_reel;
  4433. }
  4434. }
  4435. if (!empty($line->date_end)) {
  4436. $date_end = $line->date_end;
  4437. } else {
  4438. $date_end = $line->date_fin_prevue;
  4439. if ($line->date_fin_reel) {
  4440. $date_end = $line->date_fin_reel;
  4441. }
  4442. }
  4443. $this->tpl['id'] = $line->id;
  4444. $this->tpl['label'] = '';
  4445. if (!empty($line->fk_parent_line)) {
  4446. $this->tpl['label'] .= img_picto('', 'rightarrow');
  4447. }
  4448. if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
  4449. $discount = new DiscountAbsolute($this->db);
  4450. $discount->fk_soc = $this->socid;
  4451. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  4452. } elseif (!empty($line->fk_product)) {
  4453. $productstatic = new Product($this->db);
  4454. $productstatic->id = $line->fk_product;
  4455. $productstatic->ref = $line->ref;
  4456. $productstatic->type = $line->fk_product_type;
  4457. if (empty($productstatic->ref)) {
  4458. $line->fetch_product();
  4459. $productstatic = $line->product;
  4460. }
  4461. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  4462. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  4463. // Dates
  4464. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4465. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4466. }
  4467. } else {
  4468. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  4469. if (!empty($line->desc)) {
  4470. $this->tpl['label'] .= $line->desc;
  4471. } else {
  4472. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  4473. }
  4474. // Dates
  4475. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4476. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4477. }
  4478. }
  4479. if (!empty($line->desc)) {
  4480. if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
  4481. $discount = new DiscountAbsolute($this->db);
  4482. $discount->fetch($line->fk_remise_except);
  4483. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  4484. } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
  4485. $discount = new DiscountAbsolute($this->db);
  4486. $discount->fetch($line->fk_remise_except);
  4487. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  4488. } elseif ($line->desc == '(EXCESS RECEIVED)') {
  4489. $discount = new DiscountAbsolute($this->db);
  4490. $discount->fetch($line->fk_remise_except);
  4491. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  4492. } elseif ($line->desc == '(EXCESS PAID)') {
  4493. $discount = new DiscountAbsolute($this->db);
  4494. $discount->fetch($line->fk_remise_except);
  4495. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  4496. } else {
  4497. $this->tpl['description'] = dol_trunc($line->desc, 60);
  4498. }
  4499. } else {
  4500. $this->tpl['description'] = '&nbsp;';
  4501. }
  4502. // VAT Rate
  4503. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  4504. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  4505. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
  4506. $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  4507. }
  4508. $this->tpl['price'] = price($line->subprice);
  4509. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  4510. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  4511. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4512. $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  4513. }
  4514. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  4515. // Is the line strike or not
  4516. $this->tpl['strike'] = 0;
  4517. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
  4518. $this->tpl['strike'] = 1;
  4519. }
  4520. // Output template part (modules that overwrite templates must declare this into descriptor)
  4521. // Use global variables + $dateSelector + $seller and $buyer
  4522. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4523. foreach ($dirtpls as $module => $reldir) {
  4524. if (!empty($module)) {
  4525. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  4526. } else {
  4527. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  4528. }
  4529. if (empty($conf->file->strict_mode)) {
  4530. $res = @include $tpl;
  4531. } else {
  4532. $res = include $tpl; // for debug
  4533. }
  4534. if ($res) {
  4535. break;
  4536. }
  4537. }
  4538. }
  4539. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4540. /**
  4541. * Add resources to the current object : add entry into llx_element_resources
  4542. * Need $this->element & $this->id
  4543. *
  4544. * @param int $resource_id Resource id
  4545. * @param string $resource_type 'resource'
  4546. * @param int $busy Busy or not
  4547. * @param int $mandatory Mandatory or not
  4548. * @return int <=0 if KO, >0 if OK
  4549. */
  4550. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  4551. {
  4552. // phpcs:enable
  4553. $this->db->begin();
  4554. $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
  4555. $sql .= "resource_id";
  4556. $sql .= ", resource_type";
  4557. $sql .= ", element_id";
  4558. $sql .= ", element_type";
  4559. $sql .= ", busy";
  4560. $sql .= ", mandatory";
  4561. $sql .= ") VALUES (";
  4562. $sql .= $resource_id;
  4563. $sql .= ", '".$this->db->escape($resource_type)."'";
  4564. $sql .= ", '".$this->db->escape($this->id)."'";
  4565. $sql .= ", '".$this->db->escape($this->element)."'";
  4566. $sql .= ", '".$this->db->escape($busy)."'";
  4567. $sql .= ", '".$this->db->escape($mandatory)."'";
  4568. $sql .= ")";
  4569. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  4570. if ($this->db->query($sql)) {
  4571. $this->db->commit();
  4572. return 1;
  4573. } else {
  4574. $this->error = $this->db->lasterror();
  4575. $this->db->rollback();
  4576. return 0;
  4577. }
  4578. }
  4579. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4580. /**
  4581. * Delete a link to resource line
  4582. *
  4583. * @param int $rowid Id of resource line to delete
  4584. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  4585. * @param int $notrigger Disable all triggers
  4586. * @return int >0 if OK, <0 if KO
  4587. */
  4588. public function delete_resource($rowid, $element, $notrigger = 0)
  4589. {
  4590. // phpcs:enable
  4591. global $user;
  4592. $this->db->begin();
  4593. $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
  4594. $sql .= " WHERE rowid = ".((int) $rowid);
  4595. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  4596. $resql = $this->db->query($sql);
  4597. if (!$resql) {
  4598. $this->error = $this->db->lasterror();
  4599. $this->db->rollback();
  4600. return -1;
  4601. } else {
  4602. if (!$notrigger) {
  4603. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  4604. if ($result < 0) {
  4605. $this->db->rollback();
  4606. return -1;
  4607. }
  4608. }
  4609. $this->db->commit();
  4610. return 1;
  4611. }
  4612. }
  4613. /**
  4614. * Overwrite magic function to solve problem of cloning object that are kept as references
  4615. *
  4616. * @return void
  4617. */
  4618. public function __clone()
  4619. {
  4620. // Force a copy of this->lines, otherwise it will point to same object.
  4621. if (isset($this->lines) && is_array($this->lines)) {
  4622. $nboflines = count($this->lines);
  4623. for ($i = 0; $i < $nboflines; $i++) {
  4624. $this->lines[$i] = clone $this->lines[$i];
  4625. }
  4626. }
  4627. }
  4628. /**
  4629. * Common function for all objects extending CommonObject for generating documents
  4630. *
  4631. * @param string $modelspath Relative folder where generators are placed
  4632. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4633. * @param Translate $outputlangs Output language to use
  4634. * @param int $hidedetails 1 to hide details. 0 by default
  4635. * @param int $hidedesc 1 to hide product description. 0 by default
  4636. * @param int $hideref 1 to hide product reference. 0 by default
  4637. * @param null|array $moreparams Array to provide more information
  4638. * @return int >0 if OK, <0 if KO
  4639. * @see addFileIntoDatabaseIndex()
  4640. */
  4641. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4642. {
  4643. global $conf, $langs, $user, $hookmanager, $action;
  4644. $srctemplatepath = '';
  4645. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  4646. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4647. if (empty($reshook)) {
  4648. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4649. if (empty($modele)) {
  4650. $this->error = 'BadValueForParameterModele';
  4651. return -1;
  4652. }
  4653. // Increase limit for PDF build
  4654. $err = error_reporting();
  4655. error_reporting(0);
  4656. @set_time_limit(120);
  4657. error_reporting($err);
  4658. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4659. $tmp = explode(':', $modele, 2);
  4660. if (!empty($tmp[1])) {
  4661. $modele = $tmp[0];
  4662. $srctemplatepath = $tmp[1];
  4663. }
  4664. // Search template files
  4665. $file = '';
  4666. $classname = '';
  4667. $filefound = '';
  4668. $dirmodels = array('/');
  4669. if (is_array($conf->modules_parts['models'])) {
  4670. $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4671. }
  4672. foreach ($dirmodels as $reldir) {
  4673. foreach (array('doc', 'pdf') as $prefix) {
  4674. if (in_array(get_class($this), array('Adherent'))) {
  4675. // Member module use prefix_modele.class.php
  4676. $file = $prefix."_".$modele.".class.php";
  4677. } else {
  4678. // Other module use prefix_modele.modules.php
  4679. $file = $prefix."_".$modele.".modules.php";
  4680. }
  4681. // On verifie l'emplacement du modele
  4682. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  4683. if (file_exists($file)) {
  4684. $filefound = $file;
  4685. $classname = $prefix.'_'.$modele;
  4686. break;
  4687. }
  4688. }
  4689. if ($filefound) {
  4690. break;
  4691. }
  4692. }
  4693. // If generator was found
  4694. if ($filefound) {
  4695. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4696. require_once $file;
  4697. $obj = new $classname($this->db);
  4698. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4699. if ($obj->type == 'odt' && empty($srctemplatepath)) {
  4700. $varfortemplatedir = $obj->scandir;
  4701. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
  4702. $dirtoscan = $conf->global->$varfortemplatedir;
  4703. $listoffiles = array();
  4704. // Now we add first model found in directories scanned
  4705. $listofdir = explode(',', $dirtoscan);
  4706. foreach ($listofdir as $key => $tmpdir) {
  4707. $tmpdir = trim($tmpdir);
  4708. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4709. if (!$tmpdir) {
  4710. unset($listofdir[$key]);
  4711. continue;
  4712. }
  4713. if (is_dir($tmpdir)) {
  4714. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4715. if (count($tmpfiles)) {
  4716. $listoffiles = array_merge($listoffiles, $tmpfiles);
  4717. }
  4718. }
  4719. }
  4720. if (count($listoffiles)) {
  4721. foreach ($listoffiles as $record) {
  4722. $srctemplatepath = $record['fullname'];
  4723. break;
  4724. }
  4725. }
  4726. }
  4727. if (empty($srctemplatepath)) {
  4728. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4729. return -1;
  4730. }
  4731. }
  4732. if ($obj->type == 'odt' && !empty($srctemplatepath)) {
  4733. if (!dol_is_file($srctemplatepath)) {
  4734. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  4735. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4736. return -1;
  4737. }
  4738. }
  4739. // We save charset_output to restore it because write_file can change it if needed for
  4740. // output format that does not support UTF8.
  4741. $sav_charset_output = $outputlangs->charset_output;
  4742. if (in_array(get_class($this), array('Adherent'))) {
  4743. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
  4744. } else {
  4745. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4746. }
  4747. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4748. if ($resultwritefile > 0) {
  4749. $outputlangs->charset_output = $sav_charset_output;
  4750. // We delete old preview
  4751. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4752. dol_delete_preview($this);
  4753. // Index file in database
  4754. if (!empty($obj->result['fullpath'])) {
  4755. $destfull = $obj->result['fullpath'];
  4756. // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
  4757. $update_main_doc_field = 0;
  4758. if (!empty($obj->update_main_doc_field)) {
  4759. $update_main_doc_field = 1;
  4760. }
  4761. $this->indexFile($destfull, $update_main_doc_field);
  4762. } else {
  4763. 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);
  4764. }
  4765. // Success in building document. We build meta file.
  4766. dol_meta_create($this);
  4767. return 1;
  4768. } else {
  4769. $outputlangs->charset_output = $sav_charset_output;
  4770. dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
  4771. return -1;
  4772. }
  4773. } else {
  4774. if (!$filefound) {
  4775. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4776. dol_print_error('', $this->error);
  4777. } else {
  4778. $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
  4779. dol_print_error('', $this->error);
  4780. }
  4781. return -1;
  4782. }
  4783. } else {
  4784. return $reshook;
  4785. }
  4786. }
  4787. /**
  4788. * Index a file into the ECM database
  4789. *
  4790. * @param string $destfull Full path of file to index
  4791. * @param int $update_main_doc_field Update field main_doc file into table of object
  4792. * @return int <0 if KO, >0 if OK
  4793. */
  4794. public function indexFile($destfull, $update_main_doc_field)
  4795. {
  4796. global $conf, $user;
  4797. $upload_dir = dirname($destfull);
  4798. $destfile = basename($destfull);
  4799. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  4800. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  4801. $filename = basename($destfile);
  4802. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4803. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4804. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4805. $ecmfile = new EcmFiles($this->db);
  4806. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  4807. // Set the public "share" key
  4808. $setsharekey = false;
  4809. if ($this->element == 'propal' || $this->element == 'proposal') {
  4810. if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
  4811. $setsharekey = true; // feature to make online signature is not set or set to on (default)
  4812. }
  4813. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4814. $setsharekey = true;
  4815. }
  4816. }
  4817. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  4818. $setsharekey = true;
  4819. }
  4820. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  4821. $setsharekey = true;
  4822. }
  4823. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4824. $setsharekey = true;
  4825. }
  4826. if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4827. $setsharekey = true;
  4828. }
  4829. if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4830. $setsharekey = true;
  4831. }
  4832. if ($setsharekey) {
  4833. if (empty($ecmfile->share)) { // Because object not found or share not set yet
  4834. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  4835. $ecmfile->share = getRandomPassword(true);
  4836. }
  4837. }
  4838. if ($result > 0) {
  4839. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4840. $ecmfile->fullpath_orig = '';
  4841. $ecmfile->gen_or_uploaded = 'generated';
  4842. $ecmfile->description = ''; // indexed content
  4843. $ecmfile->keywords = ''; // keyword content
  4844. $result = $ecmfile->update($user);
  4845. if ($result < 0) {
  4846. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4847. return -1;
  4848. }
  4849. } else {
  4850. $ecmfile->entity = $conf->entity;
  4851. $ecmfile->filepath = $rel_dir;
  4852. $ecmfile->filename = $filename;
  4853. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4854. $ecmfile->fullpath_orig = '';
  4855. $ecmfile->gen_or_uploaded = 'generated';
  4856. $ecmfile->description = ''; // indexed content
  4857. $ecmfile->keywords = ''; // keyword content
  4858. $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
  4859. $ecmfile->src_object_id = $this->id;
  4860. $result = $ecmfile->create($user);
  4861. if ($result < 0) {
  4862. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4863. return -1;
  4864. }
  4865. }
  4866. /*$this->result['fullname']=$destfull;
  4867. $this->result['filepath']=$ecmfile->filepath;
  4868. $this->result['filename']=$ecmfile->filename;*/
  4869. //var_dump($obj->update_main_doc_field);exit;
  4870. if ($update_main_doc_field && !empty($this->table_element)) {
  4871. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
  4872. $sql .= " WHERE rowid = ".((int) $this->id);
  4873. $resql = $this->db->query($sql);
  4874. if (!$resql) {
  4875. dol_print_error($this->db);
  4876. return -1;
  4877. } else {
  4878. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  4879. }
  4880. }
  4881. }
  4882. return 1;
  4883. }
  4884. /**
  4885. * Build thumb
  4886. * @todo Move this into files.lib.php
  4887. *
  4888. * @param string $file Path file in UTF8 to original file to create thumbs from.
  4889. * @return void
  4890. */
  4891. public function addThumbs($file)
  4892. {
  4893. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  4894. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  4895. $file_osencoded = dol_osencode($file);
  4896. if (file_exists($file_osencoded)) {
  4897. // Create small thumbs for company (Ratio is near 16/9)
  4898. // Used on logon for example
  4899. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  4900. // Create mini thumbs for company (Ratio is near 16/9)
  4901. // Used on menu or for setup page for example
  4902. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  4903. }
  4904. }
  4905. /* Functions common to commonobject and commonobjectline */
  4906. /* For default values */
  4907. /**
  4908. * Return the default value to use for a field when showing the create form of object.
  4909. * Return values in this order:
  4910. * 1) If parameter is available into POST, we return it first.
  4911. * 2) If not but an alternate value was provided as parameter of function, we return it.
  4912. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  4913. * 4) Return value found into database (TODO No yet implemented)
  4914. *
  4915. * @param string $fieldname Name of field
  4916. * @param string $alternatevalue Alternate value to use
  4917. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  4918. **/
  4919. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
  4920. {
  4921. global $conf, $_POST;
  4922. // If param here has been posted, we use this value first.
  4923. if (GETPOSTISSET($fieldname)) {
  4924. return GETPOST($fieldname, 'alphanohtml', 3);
  4925. }
  4926. if (isset($alternatevalue)) {
  4927. return $alternatevalue;
  4928. }
  4929. $newelement = $this->element;
  4930. if ($newelement == 'facture') {
  4931. $newelement = 'invoice';
  4932. }
  4933. if ($newelement == 'commande') {
  4934. $newelement = 'order';
  4935. }
  4936. if (empty($newelement)) {
  4937. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  4938. return '';
  4939. }
  4940. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  4941. //var_dump($keyforfieldname);
  4942. if (isset($conf->global->$keyforfieldname)) {
  4943. return $conf->global->$keyforfieldname;
  4944. }
  4945. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  4946. }
  4947. /* For triggers */
  4948. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4949. /**
  4950. * Call trigger based on this instance.
  4951. * Some context information may also be provided into array property this->context.
  4952. * NB: Error from trigger are stacked in interface->errors
  4953. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  4954. *
  4955. * @param string $triggerName trigger's name to execute
  4956. * @param User $user Object user
  4957. * @return int Result of run_triggers
  4958. */
  4959. public function call_trigger($triggerName, $user)
  4960. {
  4961. // phpcs:enable
  4962. global $langs, $conf;
  4963. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  4964. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4965. $langs = new Translate('', $conf);
  4966. }
  4967. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  4968. $interface = new Interfaces($this->db);
  4969. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  4970. if ($result < 0) {
  4971. if (!empty($this->errors)) {
  4972. $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.
  4973. } else {
  4974. $this->errors = $interface->errors;
  4975. }
  4976. }
  4977. return $result;
  4978. }
  4979. /* Functions for data in other language */
  4980. /**
  4981. * Function to get alternative languages of a data into $this->array_languages
  4982. * This method is NOT called by method fetch of objects but must be called separately.
  4983. *
  4984. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  4985. * @see fetch_optionnals()
  4986. */
  4987. public function fetchValuesForExtraLanguages()
  4988. {
  4989. // To avoid SQL errors. Probably not the better solution though
  4990. if (!$this->element) {
  4991. return 0;
  4992. }
  4993. if (!($this->id > 0)) {
  4994. return 0;
  4995. }
  4996. if (is_array($this->array_languages)) {
  4997. return 1;
  4998. }
  4999. $this->array_languages = array();
  5000. $element = $this->element;
  5001. if ($element == 'categorie') {
  5002. $element = 'categories'; // For compatibility
  5003. }
  5004. // Request to get translation values for object
  5005. $sql = "SELECT rowid, property, lang , value";
  5006. $sql .= " FROM ".$this->db->prefix()."object_lang";
  5007. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  5008. $sql .= " AND fk_object = ".((int) $this->id);
  5009. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5010. $resql = $this->db->query($sql);
  5011. if ($resql) {
  5012. $numrows = $this->db->num_rows($resql);
  5013. if ($numrows) {
  5014. $i = 0;
  5015. while ($i < $numrows) {
  5016. $obj = $this->db->fetch_object($resql);
  5017. $key = $obj->property;
  5018. $value = $obj->value;
  5019. $codelang = $obj->lang;
  5020. $type = $this->fields[$key]['type'];
  5021. // we can add this attribute to object
  5022. if (preg_match('/date/', $type)) {
  5023. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  5024. } else {
  5025. $this->array_languages[$key][$codelang] = $value;
  5026. }
  5027. $i++;
  5028. }
  5029. }
  5030. $this->db->free($resql);
  5031. if ($numrows) {
  5032. return $numrows;
  5033. } else {
  5034. return 0;
  5035. }
  5036. } else {
  5037. dol_print_error($this->db);
  5038. return -1;
  5039. }
  5040. }
  5041. /**
  5042. * Fill array_options property of object by extrafields value (using for data sent by forms)
  5043. *
  5044. * @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.
  5045. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  5046. */
  5047. public function setValuesForExtraLanguages($onlykey = '')
  5048. {
  5049. global $_POST, $langs;
  5050. // Get extra fields
  5051. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  5052. $tmparray = explode('-', $postfieldkey);
  5053. if ($tmparray[0] != 'field') {
  5054. continue;
  5055. }
  5056. $element = $tmparray[1];
  5057. $key = $tmparray[2];
  5058. $codelang = $tmparray[3];
  5059. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  5060. if (!empty($onlykey) && $key != $onlykey) {
  5061. continue;
  5062. }
  5063. if ($element != $this->element) {
  5064. continue;
  5065. }
  5066. $key_type = $this->fields[$key]['type'];
  5067. $enabled = 1;
  5068. if (isset($this->fields[$key]['enabled'])) {
  5069. $enabled = dol_eval($this->fields[$key]['enabled'], 1);
  5070. }
  5071. /*$perms = 1;
  5072. if (isset($this->fields[$key]['perms']))
  5073. {
  5074. $perms = dol_eval($this->fields[$key]['perms'], 1);
  5075. }*/
  5076. if (empty($enabled)) {
  5077. continue;
  5078. }
  5079. //if (empty($perms)) continue;
  5080. if (in_array($key_type, array('date'))) {
  5081. // Clean parameters
  5082. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5083. $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
  5084. } elseif (in_array($key_type, array('datetime'))) {
  5085. // Clean parameters
  5086. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5087. $value_key = dol_mktime(GETPOST($postfieldkey."hour", 'int'), GETPOST($postfieldkey."min", 'int'), 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
  5088. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  5089. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  5090. if (!empty($value_arr)) {
  5091. $value_key = implode(',', $value_arr);
  5092. } else {
  5093. $value_key = '';
  5094. }
  5095. } elseif (in_array($key_type, array('price', 'double'))) {
  5096. $value_arr = GETPOST($postfieldkey, 'alpha');
  5097. $value_key = price2num($value_arr);
  5098. } else {
  5099. $value_key = GETPOST($postfieldkey);
  5100. if (in_array($key_type, array('link')) && $value_key == '-1') {
  5101. $value_key = '';
  5102. }
  5103. }
  5104. $this->array_languages[$key][$codelang] = $value_key;
  5105. /*if ($nofillrequired) {
  5106. $langs->load('errors');
  5107. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  5108. return -1;
  5109. }*/
  5110. }
  5111. return 1;
  5112. }
  5113. /* Functions for extrafields */
  5114. /**
  5115. * Function to make a fetch but set environment to avoid to load computed values before.
  5116. *
  5117. * @param int $id ID of object
  5118. * @return int >0 if OK, 0 if not found, <0 if KO
  5119. */
  5120. public function fetchNoCompute($id)
  5121. {
  5122. global $conf;
  5123. $savDisableCompute = $conf->disable_compute;
  5124. $conf->disable_compute = 1;
  5125. $ret = $this->fetch($id);
  5126. $conf->disable_compute = $savDisableCompute;
  5127. return $ret;
  5128. }
  5129. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5130. /**
  5131. * Function to get extra fields of an object into $this->array_options
  5132. * This method is in most cases called by method fetch of objects but you can call it separately.
  5133. *
  5134. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  5135. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  5136. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  5137. * @see fetchValuesForExtraLanguages()
  5138. */
  5139. public function fetch_optionals($rowid = null, $optionsArray = null)
  5140. {
  5141. // phpcs:enable
  5142. global $conf, $extrafields;
  5143. if (empty($rowid)) {
  5144. $rowid = $this->id;
  5145. }
  5146. if (empty($rowid) && isset($this->rowid)) {
  5147. $rowid = $this->rowid; // deprecated
  5148. }
  5149. // To avoid SQL errors. Probably not the better solution though
  5150. if (!$this->table_element) {
  5151. return 0;
  5152. }
  5153. $this->array_options = array();
  5154. if (!is_array($optionsArray)) {
  5155. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  5156. if (!isset($extrafields) || !is_object($extrafields)) {
  5157. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5158. $extrafields = new ExtraFields($this->db);
  5159. }
  5160. // Load array of extrafields for elementype = $this->table_element
  5161. if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
  5162. $extrafields->fetch_name_optionals_label($this->table_element);
  5163. }
  5164. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  5165. } else {
  5166. global $extrafields;
  5167. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  5168. }
  5169. $table_element = $this->table_element;
  5170. if ($table_element == 'categorie') {
  5171. $table_element = 'categories'; // For compatibility
  5172. }
  5173. // Request to get complementary values
  5174. if (is_array($optionsArray) && count($optionsArray) > 0) {
  5175. $sql = "SELECT rowid";
  5176. foreach ($optionsArray as $name => $label) {
  5177. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
  5178. $sql .= ", ".$name;
  5179. }
  5180. }
  5181. $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
  5182. $sql .= " WHERE fk_object = ".((int) $rowid);
  5183. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5184. $resql = $this->db->query($sql);
  5185. if ($resql) {
  5186. $numrows = $this->db->num_rows($resql);
  5187. if ($numrows) {
  5188. $tab = $this->db->fetch_array($resql);
  5189. foreach ($tab as $key => $value) {
  5190. // 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)
  5191. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
  5192. // we can add this attribute to object
  5193. if (!empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
  5194. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  5195. $this->array_options["options_".$key] = $this->db->jdate($value);
  5196. } else {
  5197. $this->array_options["options_".$key] = $value;
  5198. }
  5199. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  5200. }
  5201. }
  5202. // If field is a computed field, value must become result of compute
  5203. foreach ($tab as $key => $value) {
  5204. if (!empty($extrafields) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
  5205. //var_dump($conf->disable_compute);
  5206. if (empty($conf->disable_compute)) {
  5207. $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0);
  5208. }
  5209. }
  5210. }
  5211. }
  5212. $this->db->free($resql);
  5213. if ($numrows) {
  5214. return $numrows;
  5215. } else {
  5216. return 0;
  5217. }
  5218. } else {
  5219. $this->errors[]=$this->db->lasterror;
  5220. return -1;
  5221. }
  5222. }
  5223. return 0;
  5224. }
  5225. /**
  5226. * Delete all extra fields values for the current object.
  5227. *
  5228. * @return int <0 if KO, >0 if OK
  5229. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  5230. */
  5231. public function deleteExtraFields()
  5232. {
  5233. global $conf;
  5234. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5235. return 0;
  5236. }
  5237. $this->db->begin();
  5238. $table_element = $this->table_element;
  5239. if ($table_element == 'categorie') {
  5240. $table_element = 'categories'; // For compatibility
  5241. }
  5242. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  5243. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5244. $resql = $this->db->query($sql_del);
  5245. if (!$resql) {
  5246. $this->error = $this->db->lasterror();
  5247. $this->db->rollback();
  5248. return -1;
  5249. } else {
  5250. $this->db->commit();
  5251. return 1;
  5252. }
  5253. }
  5254. /**
  5255. * Add/Update all extra fields values for the current object.
  5256. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5257. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5258. *
  5259. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5260. * @param User $userused Object user
  5261. * @return int -1=error, O=did nothing, 1=OK
  5262. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  5263. */
  5264. public function insertExtraFields($trigger = '', $userused = null)
  5265. {
  5266. global $conf, $langs, $user;
  5267. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5268. return 0;
  5269. }
  5270. if (empty($userused)) {
  5271. $userused = $user;
  5272. }
  5273. $error = 0;
  5274. if (!empty($this->array_options)) {
  5275. // Check parameters
  5276. $langs->load('admin');
  5277. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5278. $extrafields = new ExtraFields($this->db);
  5279. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  5280. // Eliminate copied source object extra fields that do not exist in target object
  5281. $new_array_options = array();
  5282. foreach ($this->array_options as $key => $value) {
  5283. if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
  5284. $new_array_options[$key] = $value;
  5285. } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
  5286. $new_array_options['options_'.$key] = $value;
  5287. }
  5288. }
  5289. foreach ($new_array_options as $key => $value) {
  5290. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5291. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  5292. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  5293. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  5294. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  5295. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  5296. // Similar code than into insertExtraFields
  5297. if ($attributeRequired) {
  5298. $mandatorypb = false;
  5299. if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
  5300. $mandatorypb = true;
  5301. }
  5302. if ($this->array_options[$key] === '') {
  5303. $mandatorypb = true;
  5304. }
  5305. if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
  5306. $mandatorypb = true;
  5307. }
  5308. if ($mandatorypb) {
  5309. $langs->load("errors");
  5310. dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
  5311. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5312. return -1;
  5313. }
  5314. }
  5315. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5316. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5317. if (!empty($attrfieldcomputed)) {
  5318. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5319. $value = dol_eval($attrfieldcomputed, 1, 0);
  5320. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5321. $new_array_options[$key] = $value;
  5322. } else {
  5323. $new_array_options[$key] = null;
  5324. }
  5325. }
  5326. switch ($attributeType) {
  5327. case 'int':
  5328. if (!is_numeric($value) && $value != '') {
  5329. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5330. return -1;
  5331. } elseif ($value == '') {
  5332. $new_array_options[$key] = null;
  5333. }
  5334. break;
  5335. case 'price':
  5336. case 'double':
  5337. $value = price2num($value);
  5338. if (!is_numeric($value) && $value != '') {
  5339. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5340. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5341. return -1;
  5342. } elseif ($value == '') {
  5343. $new_array_options[$key] = null;
  5344. }
  5345. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5346. $new_array_options[$key] = $value;
  5347. break;
  5348. /*case 'select': // Not required, we chosed value='0' for undefined values
  5349. if ($value=='-1')
  5350. {
  5351. $this->array_options[$key] = null;
  5352. }
  5353. break;*/
  5354. case 'password':
  5355. $algo = '';
  5356. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
  5357. // If there is an encryption choice, we use it to crypt data before insert
  5358. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  5359. $algo = reset($tmparrays);
  5360. if ($algo != '') {
  5361. //global $action; // $action may be 'create', 'update', 'update_extras'...
  5362. //var_dump($action);
  5363. //var_dump($this->oldcopy);exit;
  5364. 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
  5365. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  5366. 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.
  5367. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5368. } else {
  5369. // var_dump($algo);
  5370. $newvalue = dol_hash($this->array_options[$key], $algo);
  5371. $new_array_options[$key] = $newvalue;
  5372. }
  5373. } else {
  5374. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5375. }
  5376. }
  5377. } else // Common usage
  5378. {
  5379. $new_array_options[$key] = $this->array_options[$key];
  5380. }
  5381. break;
  5382. case 'date':
  5383. case 'datetime':
  5384. // If data is a string instead of a timestamp, we convert it
  5385. if (!is_int($this->array_options[$key])) {
  5386. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5387. }
  5388. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  5389. break;
  5390. case 'link':
  5391. $param_list = array_keys($attributeParam['options']);
  5392. // 0 : ObjectName
  5393. // 1 : classPath
  5394. $InfoFieldList = explode(":", $param_list[0]);
  5395. dol_include_once($InfoFieldList[1]);
  5396. if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
  5397. if ($value == '-1') { // -1 is key for no defined in combo list of objects
  5398. $new_array_options[$key] = '';
  5399. } elseif ($value) {
  5400. $object = new $InfoFieldList[0]($this->db);
  5401. if (is_numeric($value)) {
  5402. $res = $object->fetch($value); // Common case
  5403. } else {
  5404. $res = $object->fetch('', $value); // For compatibility
  5405. }
  5406. if ($res > 0) {
  5407. $new_array_options[$key] = $object->id;
  5408. } else {
  5409. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5410. $this->db->rollback();
  5411. return -1;
  5412. }
  5413. }
  5414. } else {
  5415. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5416. }
  5417. break;
  5418. }
  5419. }
  5420. $this->db->begin();
  5421. $table_element = $this->table_element;
  5422. if ($table_element == 'categorie') {
  5423. $table_element = 'categories'; // For compatibility
  5424. }
  5425. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  5426. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5427. $this->db->query($sql_del);
  5428. $sql = "INSERT INTO ".$this->db->prefix().$table_element."_extrafields (fk_object";
  5429. foreach ($new_array_options as $key => $value) {
  5430. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5431. // Add field of attribut
  5432. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
  5433. $sql .= ",".$attributeKey;
  5434. }
  5435. }
  5436. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5437. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5438. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5439. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5440. $sql .= ",".$tmpkey;
  5441. }
  5442. }
  5443. }
  5444. $sql .= ") VALUES (".$this->id;
  5445. foreach ($new_array_options as $key => $value) {
  5446. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5447. // Add field of attribute
  5448. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
  5449. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
  5450. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  5451. } else {
  5452. $sql .= ",null";
  5453. }
  5454. }
  5455. }
  5456. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5457. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5458. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5459. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5460. if (in_array($tmpval, array('int', 'double', 'price'))) {
  5461. $sql .= ", 0";
  5462. } else {
  5463. $sql .= ", ''";
  5464. }
  5465. }
  5466. }
  5467. }
  5468. $sql .= ")";
  5469. $resql = $this->db->query($sql);
  5470. if (!$resql) {
  5471. $this->error = $this->db->lasterror();
  5472. $error++;
  5473. }
  5474. if (!$error && $trigger) {
  5475. // Call trigger
  5476. $this->context = array('extrafieldaddupdate'=>1);
  5477. $result = $this->call_trigger($trigger, $userused);
  5478. if ($result < 0) {
  5479. $error++;
  5480. }
  5481. // End call trigger
  5482. }
  5483. if ($error) {
  5484. $this->db->rollback();
  5485. return -1;
  5486. } else {
  5487. $this->db->commit();
  5488. return 1;
  5489. }
  5490. } else {
  5491. return 0;
  5492. }
  5493. }
  5494. /**
  5495. * Add/Update all extra fields values for the current object.
  5496. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5497. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5498. *
  5499. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5500. * @param User $userused Object user
  5501. * @return int -1=error, O=did nothing, 1=OK
  5502. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  5503. */
  5504. public function insertExtraLanguages($trigger = '', $userused = null)
  5505. {
  5506. global $conf, $langs, $user;
  5507. if (empty($userused)) {
  5508. $userused = $user;
  5509. }
  5510. $error = 0;
  5511. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5512. return 0; // For avoid conflicts if trigger used
  5513. }
  5514. if (is_array($this->array_languages)) {
  5515. $new_array_languages = $this->array_languages;
  5516. foreach ($new_array_languages as $key => $value) {
  5517. $attributeKey = $key;
  5518. $attributeType = $this->fields[$attributeKey]['type'];
  5519. $attributeLabel = $this->fields[$attributeKey]['label'];
  5520. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5521. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5522. switch ($attributeType) {
  5523. case 'int':
  5524. if (!is_numeric($value) && $value != '') {
  5525. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5526. return -1;
  5527. } elseif ($value == '') {
  5528. $new_array_languages[$key] = null;
  5529. }
  5530. break;
  5531. case 'double':
  5532. $value = price2num($value);
  5533. if (!is_numeric($value) && $value != '') {
  5534. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5535. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5536. return -1;
  5537. } elseif ($value == '') {
  5538. $new_array_languages[$key] = null;
  5539. }
  5540. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5541. $new_array_languages[$key] = $value;
  5542. break;
  5543. /*case 'select': // Not required, we chosed value='0' for undefined values
  5544. if ($value=='-1')
  5545. {
  5546. $this->array_options[$key] = null;
  5547. }
  5548. break;*/
  5549. }
  5550. }
  5551. $this->db->begin();
  5552. $table_element = $this->table_element;
  5553. if ($table_element == 'categorie') {
  5554. $table_element = 'categories'; // For compatibility
  5555. }
  5556. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  5557. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  5558. foreach ($langcodearray as $langcode => $value) {
  5559. $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
  5560. $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  5561. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  5562. $this->db->query($sql_del);
  5563. if ($value !== '') {
  5564. $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
  5565. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  5566. $sql .= ")";
  5567. $resql = $this->db->query($sql);
  5568. if (!$resql) {
  5569. $this->error = $this->db->lasterror();
  5570. $error++;
  5571. break;
  5572. }
  5573. }
  5574. }
  5575. }
  5576. if (!$error && $trigger) {
  5577. // Call trigger
  5578. $this->context = array('extralanguagesaddupdate'=>1);
  5579. $result = $this->call_trigger($trigger, $userused);
  5580. if ($result < 0) {
  5581. $error++;
  5582. }
  5583. // End call trigger
  5584. }
  5585. if ($error) {
  5586. $this->db->rollback();
  5587. return -1;
  5588. } else {
  5589. $this->db->commit();
  5590. return 1;
  5591. }
  5592. } else {
  5593. return 0;
  5594. }
  5595. }
  5596. /**
  5597. * Update 1 extra field value for the current object. Keep other fields unchanged.
  5598. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5599. *
  5600. * @param string $key Key of the extrafield to update (without starting 'options_')
  5601. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5602. * @param User $userused Object user
  5603. * @return int -1=error, O=did nothing, 1=OK
  5604. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  5605. */
  5606. public function updateExtraField($key, $trigger = null, $userused = null)
  5607. {
  5608. global $conf, $langs, $user;
  5609. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5610. return 0;
  5611. }
  5612. if (empty($userused)) {
  5613. $userused = $user;
  5614. }
  5615. $error = 0;
  5616. if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
  5617. // Check parameters
  5618. $langs->load('admin');
  5619. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5620. $extrafields = new ExtraFields($this->db);
  5621. $extrafields->fetch_name_optionals_label($this->table_element);
  5622. $value = $this->array_options["options_".$key];
  5623. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  5624. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  5625. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  5626. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  5627. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  5628. // Similar code than into insertExtraFields
  5629. if ($attributeRequired) {
  5630. $mandatorypb = false;
  5631. if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
  5632. $mandatorypb = true;
  5633. }
  5634. if ($this->array_options["options_".$key] === '') {
  5635. $mandatorypb = true;
  5636. }
  5637. if ($mandatorypb) {
  5638. $langs->load("errors");
  5639. dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
  5640. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5641. return -1;
  5642. }
  5643. }
  5644. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5645. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5646. if (!empty($attrfieldcomputed)) {
  5647. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5648. $value = dol_eval($attrfieldcomputed, 1, 0);
  5649. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5650. $this->array_options["options_".$key] = $value;
  5651. } else {
  5652. $this->array_options["options_".$key] = null;
  5653. }
  5654. }
  5655. switch ($attributeType) {
  5656. case 'int':
  5657. if (!is_numeric($value) && $value != '') {
  5658. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5659. return -1;
  5660. } elseif ($value === '') {
  5661. $this->array_options["options_".$key] = null;
  5662. }
  5663. break;
  5664. case 'double':
  5665. $value = price2num($value);
  5666. if (!is_numeric($value) && $value != '') {
  5667. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5668. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5669. return -1;
  5670. } elseif ($value === '') {
  5671. $this->array_options["options_".$key] = null;
  5672. }
  5673. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5674. $this->array_options["options_".$key] = $value;
  5675. break;
  5676. /*case 'select': // Not required, we chosed value='0' for undefined values
  5677. if ($value=='-1')
  5678. {
  5679. $this->array_options[$key] = null;
  5680. }
  5681. break;*/
  5682. case 'price':
  5683. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  5684. break;
  5685. case 'date':
  5686. case 'datetime':
  5687. if (empty($this->array_options["options_".$key])) {
  5688. $this->array_options["options_".$key] = null;
  5689. } else {
  5690. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5691. }
  5692. break;
  5693. case 'boolean':
  5694. if (empty($this->array_options["options_".$key])) {
  5695. $this->array_options["options_".$key] = null;
  5696. }
  5697. break;
  5698. /*
  5699. case 'link':
  5700. $param_list = array_keys($attributeParam['options']);
  5701. // 0 : ObjectName
  5702. // 1 : classPath
  5703. $InfoFieldList = explode(":", $param_list[0]);
  5704. dol_include_once($InfoFieldList[1]);
  5705. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  5706. {
  5707. if ($value == '-1') // -1 is key for no defined in combo list of objects
  5708. {
  5709. $new_array_options[$key] = '';
  5710. } elseif ($value) {
  5711. $object = new $InfoFieldList[0]($this->db);
  5712. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  5713. else $res = $object->fetch('', $value); // For compatibility
  5714. if ($res > 0) $new_array_options[$key] = $object->id;
  5715. else {
  5716. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5717. $this->db->rollback();
  5718. return -1;
  5719. }
  5720. }
  5721. } else {
  5722. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5723. }
  5724. break;
  5725. */
  5726. }
  5727. $this->db->begin();
  5728. $linealreadyfound = 0;
  5729. // Check if there is already a line for this object (in most cases, it is, but sometimes it is not, for example when extra field has been created after), so we must keep this overload)
  5730. $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5731. $resql = $this->db->query($sql);
  5732. if ($resql) {
  5733. $tmpobj = $this->db->fetch_object($resql);
  5734. if ($tmpobj) {
  5735. $linealreadyfound = $tmpobj->nb;
  5736. }
  5737. }
  5738. if ($linealreadyfound) {
  5739. if ($this->array_options["options_".$key] === null) {
  5740. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = null";
  5741. } else {
  5742. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
  5743. }
  5744. $sql .= " WHERE fk_object = ".((int) $this->id);
  5745. } else {
  5746. $result = $this->insertExtraFields('', $user);
  5747. if ($result < 0) {
  5748. $error++;
  5749. }
  5750. }
  5751. $resql = $this->db->query($sql);
  5752. if (!$resql) {
  5753. $error++;
  5754. $this->error = $this->db->lasterror();
  5755. }
  5756. if (!$error && $trigger) {
  5757. // Call trigger
  5758. $this->context = array('extrafieldupdate'=>1);
  5759. $result = $this->call_trigger($trigger, $userused);
  5760. if ($result < 0) {
  5761. $error++;
  5762. }
  5763. // End call trigger
  5764. }
  5765. if ($error) {
  5766. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  5767. $this->db->rollback();
  5768. return -1;
  5769. } else {
  5770. $this->db->commit();
  5771. return 1;
  5772. }
  5773. } else {
  5774. return 0;
  5775. }
  5776. }
  5777. /**
  5778. * Update an extra language value for the current object.
  5779. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5780. *
  5781. * @param string $key Key of the extrafield (without starting 'options_')
  5782. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5783. * @param User $userused Object user
  5784. * @return int -1=error, O=did nothing, 1=OK
  5785. * @see updateExtraFields(), insertExtraLanguages()
  5786. */
  5787. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  5788. {
  5789. global $conf, $langs, $user;
  5790. if (empty($userused)) {
  5791. $userused = $user;
  5792. }
  5793. $error = 0;
  5794. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5795. return 0; // For avoid conflicts if trigger used
  5796. }
  5797. return 0;
  5798. }
  5799. /**
  5800. * Return HTML string to put an input field into a page
  5801. * Code very similar with showInputField of extra fields
  5802. *
  5803. * @param array $val Array of properties for field to show (used only if ->fields not defined)
  5804. * @param string $key Key of attribute
  5805. * @param string|array $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value, for array type must be array)
  5806. * @param string $moreparam To add more parameters on html input tag
  5807. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5808. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5809. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  5810. * @param int $nonewbutton Force to not show the new button on field that are links to object
  5811. * @return string
  5812. */
  5813. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  5814. {
  5815. global $conf, $langs, $form;
  5816. if (!is_object($form)) {
  5817. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  5818. $form = new Form($this->db);
  5819. }
  5820. if (!empty($this->fields)) {
  5821. $val = $this->fields[$key];
  5822. }
  5823. // Validation tests and output
  5824. $fieldValidationErrorMsg = '';
  5825. $validationClass = '';
  5826. $fieldValidationErrorMsg = $this->getFieldError($key);
  5827. if (!empty($fieldValidationErrorMsg)) {
  5828. $validationClass = ' --error'; // the -- is use as class state in css : .--error can't be be defined alone it must be define with another class like .my-class.--error or input.--error
  5829. } else {
  5830. $validationClass = ' --success'; // the -- is use as class state in css : .--success can't be be defined alone it must be define with another class like .my-class.--success or input.--success
  5831. }
  5832. $out = '';
  5833. $type = '';
  5834. $isDependList = 0;
  5835. $param = array();
  5836. $param['options'] = array();
  5837. $reg = array();
  5838. $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
  5839. // Because we work on extrafields
  5840. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5841. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5842. $type = 'link';
  5843. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5844. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5845. $type = 'link';
  5846. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  5847. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5848. $type = 'link';
  5849. } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5850. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5851. $type = 'sellist';
  5852. } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5853. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5854. $type = 'sellist';
  5855. } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
  5856. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5857. $type = 'sellist';
  5858. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  5859. $param['options'] = array();
  5860. $type = 'varchar';
  5861. $size = $reg[1];
  5862. } elseif (preg_match('/varchar/', $val['type'])) {
  5863. $param['options'] = array();
  5864. $type = 'varchar';
  5865. } else {
  5866. $param['options'] = array();
  5867. $type = $this->fields[$key]['type'];
  5868. }
  5869. // Special case that force options and type ($type can be integer, varchar, ...)
  5870. if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
  5871. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  5872. $type = 'select';
  5873. }
  5874. $label = $this->fields[$key]['label'];
  5875. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  5876. $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
  5877. $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
  5878. $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
  5879. $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
  5880. $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
  5881. $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
  5882. $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
  5883. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  5884. $objectid = $this->id;
  5885. if ($computed) {
  5886. if (!preg_match('/^search_/', $keyprefix)) {
  5887. return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  5888. } else {
  5889. return '';
  5890. }
  5891. }
  5892. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  5893. if (empty($morecss) && !empty($val['css'])) {
  5894. $morecss = $val['css'];
  5895. } elseif (empty($morecss)) {
  5896. if ($type == 'date') {
  5897. $morecss = 'minwidth100imp';
  5898. } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
  5899. $morecss = 'minwidth200imp';
  5900. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  5901. $morecss = 'maxwidth75';
  5902. } elseif ($type == 'url') {
  5903. $morecss = 'minwidth400';
  5904. } elseif ($type == 'boolean') {
  5905. $morecss = '';
  5906. } else {
  5907. if (round($size) < 12) {
  5908. $morecss = 'minwidth100';
  5909. } elseif (round($size) <= 48) {
  5910. $morecss = 'minwidth200';
  5911. } else {
  5912. $morecss = 'minwidth400';
  5913. }
  5914. }
  5915. }
  5916. // Add validation state class
  5917. if (!empty($validationClass)) {
  5918. $morecss.= ' '.$validationClass;
  5919. }
  5920. if (in_array($type, array('date'))) {
  5921. $tmp = explode(',', $size);
  5922. $newsize = $tmp[0];
  5923. $showtime = 0;
  5924. // Do not show current date when field not required (see selectDate() method)
  5925. if (!$required && $value == '') {
  5926. $value = '-1';
  5927. }
  5928. // TODO Must also support $moreparam
  5929. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  5930. } elseif (in_array($type, array('datetime'))) {
  5931. $tmp = explode(',', $size);
  5932. $newsize = $tmp[0];
  5933. $showtime = 1;
  5934. // Do not show current date when field not required (see selectDate() method)
  5935. if (!$required && $value == '') $value = '-1';
  5936. // TODO Must also support $moreparam
  5937. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
  5938. } elseif (in_array($type, array('duration'))) {
  5939. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  5940. } elseif (in_array($type, array('int', 'integer'))) {
  5941. $tmp = explode(',', $size);
  5942. $newsize = $tmp[0];
  5943. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"'.($newsize > 0 ? ' maxlength="'.$newsize.'"' : '').' value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5944. } elseif (in_array($type, array('real'))) {
  5945. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5946. } elseif (preg_match('/varchar/', $type)) {
  5947. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"'.($size > 0 ? ' maxlength="'.$size.'"' : '').' value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5948. } elseif (in_array($type, array('mail', 'phone', 'url'))) {
  5949. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5950. } elseif (preg_match('/^text/', $type)) {
  5951. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  5952. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5953. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  5954. $out = $doleditor->Create(1);
  5955. } else {
  5956. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5957. }
  5958. } elseif (preg_match('/^html/', $type)) {
  5959. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  5960. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5961. $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%');
  5962. $out = $doleditor->Create(1);
  5963. } else {
  5964. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5965. }
  5966. } elseif ($type == 'boolean') {
  5967. $checked = '';
  5968. if (!empty($value)) {
  5969. $checked = ' checked value="1" ';
  5970. } else {
  5971. $checked = ' value="1" ';
  5972. }
  5973. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  5974. } elseif ($type == 'price') {
  5975. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5976. $value = price($value);
  5977. }
  5978. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  5979. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  5980. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5981. $value = price($value);
  5982. }
  5983. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  5984. } elseif ($type == 'select') {
  5985. $out = '';
  5986. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  5987. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5988. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  5989. }
  5990. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  5991. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
  5992. $out .= '<option value="0">&nbsp;</option>';
  5993. }
  5994. foreach ($param['options'] as $key => $val) {
  5995. if ((string) $key == '') {
  5996. continue;
  5997. }
  5998. list($val, $parent) = explode('|', $val);
  5999. $out .= '<option value="'.$key.'"';
  6000. $out .= (((string) $value == (string) $key) ? ' selected' : '');
  6001. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6002. $out .= '>'.$val.'</option>';
  6003. }
  6004. $out .= '</select>';
  6005. } elseif ($type == 'sellist') {
  6006. $out = '';
  6007. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6008. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6009. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6010. }
  6011. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6012. if (is_array($param['options'])) {
  6013. $param_list = array_keys($param['options']);
  6014. $InfoFieldList = explode(":", $param_list[0]);
  6015. $parentName = '';
  6016. $parentField = '';
  6017. // 0 : tableName
  6018. // 1 : label field name
  6019. // 2 : key fields name (if differ of rowid)
  6020. // 3 : key field parent (for dependent lists)
  6021. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6022. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6023. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6024. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6025. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6026. } else {
  6027. $keyList = $InfoFieldList[2].' as rowid';
  6028. }
  6029. }
  6030. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6031. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6032. $keyList .= ', '.$parentField;
  6033. }
  6034. $fields_label = explode('|', $InfoFieldList[1]);
  6035. if (is_array($fields_label)) {
  6036. $keyList .= ', ';
  6037. $keyList .= implode(', ', $fields_label);
  6038. }
  6039. $sqlwhere = '';
  6040. $sql = "SELECT ".$keyList;
  6041. $sql .= " FROM ".$this->db->prefix().$InfoFieldList[0];
  6042. if (!empty($InfoFieldList[4])) {
  6043. // can use SELECT request
  6044. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6045. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6046. }
  6047. // current object id can be use into filter
  6048. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6049. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6050. } else {
  6051. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6052. }
  6053. //We have to join on extrafield table
  6054. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6055. $sql .= " as main, ".$this->db->prefix().$InfoFieldList[0]."_extrafields as extra";
  6056. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  6057. } else {
  6058. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  6059. }
  6060. } else {
  6061. $sqlwhere .= ' WHERE 1=1';
  6062. }
  6063. // Some tables may have field, some other not. For the moment we disable it.
  6064. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6065. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  6066. }
  6067. $sql .= $sqlwhere;
  6068. //print $sql;
  6069. $sql .= ' ORDER BY '.implode(', ', $fields_label);
  6070. dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
  6071. $resql = $this->db->query($sql);
  6072. if ($resql) {
  6073. $out .= '<option value="0">&nbsp;</option>';
  6074. $num = $this->db->num_rows($resql);
  6075. $i = 0;
  6076. while ($i < $num) {
  6077. $labeltoshow = '';
  6078. $obj = $this->db->fetch_object($resql);
  6079. // Several field into label (eq table:code|libelle:rowid)
  6080. $notrans = false;
  6081. $fields_label = explode('|', $InfoFieldList[1]);
  6082. if (count($fields_label) > 1) {
  6083. $notrans = true;
  6084. foreach ($fields_label as $field_toshow) {
  6085. $labeltoshow .= $obj->$field_toshow.' ';
  6086. }
  6087. } else {
  6088. $labeltoshow = $obj->{$InfoFieldList[1]};
  6089. }
  6090. $labeltoshow = dol_trunc($labeltoshow, 45);
  6091. if ($value == $obj->rowid) {
  6092. foreach ($fields_label as $field_toshow) {
  6093. $translabel = $langs->trans($obj->$field_toshow);
  6094. if ($translabel != $obj->$field_toshow) {
  6095. $labeltoshow = dol_trunc($translabel).' ';
  6096. } else {
  6097. $labeltoshow = dol_trunc($obj->$field_toshow).' ';
  6098. }
  6099. }
  6100. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6101. } else {
  6102. if (!$notrans) {
  6103. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6104. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6105. $labeltoshow = dol_trunc($translabel, 18);
  6106. } else {
  6107. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
  6108. }
  6109. }
  6110. if (empty($labeltoshow)) {
  6111. $labeltoshow = '(not defined)';
  6112. }
  6113. if ($value == $obj->rowid) {
  6114. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6115. }
  6116. if (!empty($InfoFieldList[3]) && $parentField) {
  6117. $parent = $parentName.':'.$obj->{$parentField};
  6118. $isDependList = 1;
  6119. }
  6120. $out .= '<option value="'.$obj->rowid.'"';
  6121. $out .= ($value == $obj->rowid ? ' selected' : '');
  6122. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6123. $out .= '>'.$labeltoshow.'</option>';
  6124. }
  6125. $i++;
  6126. }
  6127. $this->db->free($resql);
  6128. } else {
  6129. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6130. }
  6131. }
  6132. $out .= '</select>';
  6133. } elseif ($type == 'checkbox') {
  6134. $value_arr = explode(',', $value);
  6135. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
  6136. } elseif ($type == 'radio') {
  6137. $out = '';
  6138. foreach ($param['options'] as $keyopt => $val) {
  6139. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  6140. $out .= ' value="'.$keyopt.'"';
  6141. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  6142. $out .= ($value == $keyopt ? 'checked' : '');
  6143. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
  6144. }
  6145. } elseif ($type == 'chkbxlst') {
  6146. if (is_array($value)) {
  6147. $value_arr = $value;
  6148. } else {
  6149. $value_arr = explode(',', $value);
  6150. }
  6151. if (is_array($param['options'])) {
  6152. $param_list = array_keys($param['options']);
  6153. $InfoFieldList = explode(":", $param_list[0]);
  6154. $parentName = '';
  6155. $parentField = '';
  6156. // 0 : tableName
  6157. // 1 : label field name
  6158. // 2 : key fields name (if differ of rowid)
  6159. // 3 : key field parent (for dependent lists)
  6160. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6161. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6162. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6163. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6164. $keyList .= ', '.$parentField;
  6165. }
  6166. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6167. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6168. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6169. } else {
  6170. $keyList = $InfoFieldList[2].' as rowid';
  6171. }
  6172. }
  6173. $fields_label = explode('|', $InfoFieldList[1]);
  6174. if (is_array($fields_label)) {
  6175. $keyList .= ', ';
  6176. $keyList .= implode(', ', $fields_label);
  6177. }
  6178. $sqlwhere = '';
  6179. $sql = "SELECT ".$keyList;
  6180. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6181. if (!empty($InfoFieldList[4])) {
  6182. // can use SELECT request
  6183. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6184. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6185. }
  6186. // current object id can be use into filter
  6187. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6188. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6189. } else {
  6190. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6191. }
  6192. // We have to join on extrafield table
  6193. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6194. $sql .= ' as main, '.$this->db->prefix().$InfoFieldList[0].'_extrafields as extra';
  6195. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  6196. } else {
  6197. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  6198. }
  6199. } else {
  6200. $sqlwhere .= ' WHERE 1=1';
  6201. }
  6202. // Some tables may have field, some other not. For the moment we disable it.
  6203. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6204. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  6205. }
  6206. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  6207. // print $sql;
  6208. $sql .= $sqlwhere;
  6209. dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
  6210. $resql = $this->db->query($sql);
  6211. if ($resql) {
  6212. $num = $this->db->num_rows($resql);
  6213. $i = 0;
  6214. $data = array();
  6215. while ($i < $num) {
  6216. $labeltoshow = '';
  6217. $obj = $this->db->fetch_object($resql);
  6218. $notrans = false;
  6219. // Several field into label (eq table:code|libelle:rowid)
  6220. $fields_label = explode('|', $InfoFieldList[1]);
  6221. if (count($fields_label) > 1) {
  6222. $notrans = true;
  6223. foreach ($fields_label as $field_toshow) {
  6224. $labeltoshow .= $obj->$field_toshow.' ';
  6225. }
  6226. } else {
  6227. $labeltoshow = $obj->{$InfoFieldList[1]};
  6228. }
  6229. $labeltoshow = dol_trunc($labeltoshow, 45);
  6230. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6231. foreach ($fields_label as $field_toshow) {
  6232. $translabel = $langs->trans($obj->$field_toshow);
  6233. if ($translabel != $obj->$field_toshow) {
  6234. $labeltoshow = dol_trunc($translabel, 18).' ';
  6235. } else {
  6236. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  6237. }
  6238. }
  6239. $data[$obj->rowid] = $labeltoshow;
  6240. } else {
  6241. if (!$notrans) {
  6242. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6243. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6244. $labeltoshow = dol_trunc($translabel, 18);
  6245. } else {
  6246. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  6247. }
  6248. }
  6249. if (empty($labeltoshow)) {
  6250. $labeltoshow = '(not defined)';
  6251. }
  6252. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6253. $data[$obj->rowid] = $labeltoshow;
  6254. }
  6255. if (!empty($InfoFieldList[3]) && $parentField) {
  6256. $parent = $parentName.':'.$obj->{$parentField};
  6257. $isDependList = 1;
  6258. }
  6259. $data[$obj->rowid] = $labeltoshow;
  6260. }
  6261. $i++;
  6262. }
  6263. $this->db->free($resql);
  6264. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
  6265. } else {
  6266. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6267. }
  6268. }
  6269. } elseif ($type == 'link') {
  6270. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
  6271. $param_list_array = explode(':', $param_list[0]);
  6272. $showempty = (($required && $default != '') ? 0 : 1);
  6273. if (!preg_match('/search_/', $keyprefix)) {
  6274. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6275. if (!empty($this->fields[$key]['picto'])) {
  6276. $morecss .= ' widthcentpercentminusxx';
  6277. } else {
  6278. $morecss .= ' widthcentpercentminusx';
  6279. }
  6280. } else {
  6281. if (!empty($this->fields[$key]['picto'])) {
  6282. $morecss .= ' widthcentpercentminusx';
  6283. }
  6284. }
  6285. }
  6286. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  6287. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6288. 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".
  6289. list($class, $classfile) = explode(':', $param_list[0]);
  6290. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
  6291. $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  6292. } else {
  6293. $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  6294. }
  6295. $paramforthenewlink = '';
  6296. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  6297. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  6298. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  6299. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  6300. $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>';
  6301. }
  6302. }
  6303. } elseif ($type == 'password') {
  6304. // If prefix is 'search_', field is used as a filter, we use a common text field.
  6305. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  6306. } elseif ($type == 'array') {
  6307. $newval = $val;
  6308. $newval['type'] = 'varchar(256)';
  6309. $out = '';
  6310. if (!empty($value)) {
  6311. foreach ($value as $option) {
  6312. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6313. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  6314. }
  6315. }
  6316. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6317. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6318. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  6319. if (!empty($conf->use_javascript_ajax)) {
  6320. $out .= '
  6321. <script>
  6322. $(document).ready(function() {
  6323. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  6324. $("'.dol_escape_js($newInput).'").insertBefore(this);
  6325. });
  6326. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  6327. $(this).parent().remove();
  6328. });
  6329. });
  6330. </script>';
  6331. }
  6332. }
  6333. if (!empty($hidden)) {
  6334. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  6335. }
  6336. if ($isDependList==1) {
  6337. $out .= $this->getJSListDependancies('_common');
  6338. }
  6339. /* Add comments
  6340. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  6341. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  6342. */
  6343. // Display error message for field
  6344. if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
  6345. $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
  6346. }
  6347. return $out;
  6348. }
  6349. /**
  6350. * Return HTML string to show a field into a page
  6351. * Code very similar with showOutputField of extra fields
  6352. *
  6353. * @param array $val Array of properties of field to show
  6354. * @param string $key Key of attribute
  6355. * @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)
  6356. * @param string $moreparam To add more parametes on html input tag
  6357. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6358. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6359. * @param mixed $morecss Value for css to define size. May also be a numeric.
  6360. * @return string
  6361. */
  6362. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  6363. {
  6364. global $conf, $langs, $form;
  6365. if (!is_object($form)) {
  6366. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6367. $form = new Form($this->db);
  6368. }
  6369. $objectid = $this->id; // Not used ???
  6370. $label = empty($val['label']) ? '' : $val['label'];
  6371. $type = empty($val['type']) ? '' : $val['type'];
  6372. $size = empty($val['css']) ? '' : $val['css'];
  6373. $reg = array();
  6374. // Convert var to be able to share same code than showOutputField of extrafields
  6375. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6376. $type = 'varchar'; // convert varchar(xx) int varchar
  6377. $size = $reg[1];
  6378. } elseif (preg_match('/varchar/', $type)) {
  6379. $type = 'varchar'; // convert varchar(xx) int varchar
  6380. }
  6381. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6382. $type = 'select';
  6383. }
  6384. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6385. $type = 'link';
  6386. }
  6387. $default = empty($val['default']) ? '' : $val['default'];
  6388. $computed = empty($val['computed']) ? '' : $val['computed'];
  6389. $unique = empty($val['unique']) ? '' : $val['unique'];
  6390. $required = empty($val['required']) ? '' : $val['required'];
  6391. $param = array();
  6392. $param['options'] = array();
  6393. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6394. $param['options'] = $val['arrayofkeyval'];
  6395. }
  6396. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6397. $type = 'link';
  6398. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6399. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6400. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6401. $type = 'sellist';
  6402. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6403. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6404. $type = 'sellist';
  6405. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6406. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6407. $type = 'sellist';
  6408. }
  6409. $langfile = empty($val['langfile']) ? '' : $val['langfile'];
  6410. $list = (empty($val['list']) ? '' : $val['list']);
  6411. $help = (empty($val['help']) ? '' : $val['help']);
  6412. $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)
  6413. if ($hidden) {
  6414. return '';
  6415. }
  6416. // If field is a computed field, value must become result of compute
  6417. if ($computed) {
  6418. // Make the eval of compute string
  6419. //var_dump($computed);
  6420. $value = dol_eval($computed, 1, 0);
  6421. }
  6422. if (empty($morecss)) {
  6423. if ($type == 'date') {
  6424. $morecss = 'minwidth100imp';
  6425. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6426. $morecss = 'minwidth200imp';
  6427. } elseif (in_array($type, array('int', 'double', 'price'))) {
  6428. $morecss = 'maxwidth75';
  6429. } elseif ($type == 'url') {
  6430. $morecss = 'minwidth400';
  6431. } elseif ($type == 'boolean') {
  6432. $morecss = '';
  6433. } else {
  6434. if (is_numeric($size) && round($size) < 12) {
  6435. $morecss = 'minwidth100';
  6436. } elseif (is_numeric($size) && round($size) <= 48) {
  6437. $morecss = 'minwidth200';
  6438. } else {
  6439. $morecss = 'minwidth400';
  6440. }
  6441. }
  6442. }
  6443. // Format output value differently according to properties of field
  6444. if ($key == 'ref' && method_exists($this, 'getNomUrl')) {
  6445. $value = $this->getNomUrl(1, '', 0, '', 1);
  6446. } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
  6447. $value = $this->getLibStatut(3);
  6448. } elseif ($type == 'date') {
  6449. if (!empty($value)) {
  6450. $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
  6451. } else {
  6452. $value = '';
  6453. }
  6454. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6455. if (!empty($value)) {
  6456. $value = dol_print_date($value, 'dayhour', 'tzuserrel');
  6457. } else {
  6458. $value = '';
  6459. }
  6460. } elseif ($type == 'duration') {
  6461. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6462. if (!is_null($value) && $value !== '') {
  6463. $value = convertSecondToTime($value, 'allhourmin');
  6464. }
  6465. } elseif ($type == 'double' || $type == 'real') {
  6466. if (!is_null($value) && $value !== '') {
  6467. $value = price($value);
  6468. }
  6469. } elseif ($type == 'boolean') {
  6470. $checked = '';
  6471. if (!empty($value)) {
  6472. $checked = ' checked ';
  6473. }
  6474. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  6475. } elseif ($type == 'mail') {
  6476. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  6477. } elseif ($type == 'url') {
  6478. $value = dol_print_url($value, '_blank', 32, 1);
  6479. } elseif ($type == 'phone') {
  6480. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
  6481. } elseif ($type == 'price') {
  6482. if (!is_null($value) && $value !== '') {
  6483. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  6484. }
  6485. } elseif ($type == 'select') {
  6486. $value = $param['options'][$value];
  6487. } elseif ($type == 'sellist') {
  6488. $param_list = array_keys($param['options']);
  6489. $InfoFieldList = explode(":", $param_list[0]);
  6490. $selectkey = "rowid";
  6491. $keyList = 'rowid';
  6492. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6493. $selectkey = $InfoFieldList[2];
  6494. $keyList = $InfoFieldList[2].' as rowid';
  6495. }
  6496. $fields_label = explode('|', $InfoFieldList[1]);
  6497. if (is_array($fields_label)) {
  6498. $keyList .= ', ';
  6499. $keyList .= implode(', ', $fields_label);
  6500. }
  6501. $sql = "SELECT ".$keyList;
  6502. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6503. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6504. $sql .= ' as main';
  6505. }
  6506. if ($selectkey == 'rowid' && empty($value)) {
  6507. $sql .= " WHERE ".$selectkey." = 0";
  6508. } elseif ($selectkey == 'rowid') {
  6509. $sql .= " WHERE ".$selectkey." = ".((int) $value);
  6510. } else {
  6511. $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
  6512. }
  6513. //$sql.= ' AND entity = '.$conf->entity;
  6514. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  6515. $resql = $this->db->query($sql);
  6516. if ($resql) {
  6517. $value = ''; // value was used, so now we reste it to use it to build final output
  6518. $obj = $this->db->fetch_object($resql);
  6519. // Several field into label (eq table:code|libelle:rowid)
  6520. $fields_label = explode('|', $InfoFieldList[1]);
  6521. if (is_array($fields_label) && count($fields_label) > 1) {
  6522. foreach ($fields_label as $field_toshow) {
  6523. $translabel = '';
  6524. if (!empty($obj->$field_toshow)) {
  6525. $translabel = $langs->trans($obj->$field_toshow);
  6526. }
  6527. if ($translabel != $field_toshow) {
  6528. $value .= dol_trunc($translabel, 18).' ';
  6529. } else {
  6530. $value .= $obj->$field_toshow.' ';
  6531. }
  6532. }
  6533. } else {
  6534. $translabel = '';
  6535. if (!empty($obj->{$InfoFieldList[1]})) {
  6536. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6537. }
  6538. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6539. $value = dol_trunc($translabel, 18);
  6540. } else {
  6541. $value = $obj->{$InfoFieldList[1]};
  6542. }
  6543. }
  6544. } else {
  6545. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6546. }
  6547. } elseif ($type == 'radio') {
  6548. $value = $param['options'][$value];
  6549. } elseif ($type == 'checkbox') {
  6550. $value_arr = explode(',', $value);
  6551. $value = '';
  6552. if (is_array($value_arr) && count($value_arr) > 0) {
  6553. $toprint = array();
  6554. foreach ($value_arr as $keyval => $valueval) {
  6555. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  6556. }
  6557. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6558. }
  6559. } elseif ($type == 'chkbxlst') {
  6560. $value_arr = explode(',', $value);
  6561. $param_list = array_keys($param['options']);
  6562. $InfoFieldList = explode(":", $param_list[0]);
  6563. $selectkey = "rowid";
  6564. $keyList = 'rowid';
  6565. if (count($InfoFieldList) >= 3) {
  6566. $selectkey = $InfoFieldList[2];
  6567. $keyList = $InfoFieldList[2].' as rowid';
  6568. }
  6569. $fields_label = explode('|', $InfoFieldList[1]);
  6570. if (is_array($fields_label)) {
  6571. $keyList .= ', ';
  6572. $keyList .= implode(', ', $fields_label);
  6573. }
  6574. $sql = "SELECT ".$keyList;
  6575. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6576. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6577. $sql .= ' as main';
  6578. }
  6579. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  6580. // $sql.= ' AND entity = '.$conf->entity;
  6581. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  6582. $resql = $this->db->query($sql);
  6583. if ($resql) {
  6584. $value = ''; // value was used, so now we reste it to use it to build final output
  6585. $toprint = array();
  6586. while ($obj = $this->db->fetch_object($resql)) {
  6587. // Several field into label (eq table:code|libelle:rowid)
  6588. $fields_label = explode('|', $InfoFieldList[1]);
  6589. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6590. if (is_array($fields_label) && count($fields_label) > 1) {
  6591. foreach ($fields_label as $field_toshow) {
  6592. $translabel = '';
  6593. if (!empty($obj->$field_toshow)) {
  6594. $translabel = $langs->trans($obj->$field_toshow);
  6595. }
  6596. if ($translabel != $field_toshow) {
  6597. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6598. } else {
  6599. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->$field_toshow.'</li>';
  6600. }
  6601. }
  6602. } else {
  6603. $translabel = '';
  6604. if (!empty($obj->{$InfoFieldList[1]})) {
  6605. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6606. }
  6607. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6608. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6609. } else {
  6610. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->{$InfoFieldList[1]}.'</li>';
  6611. }
  6612. }
  6613. }
  6614. }
  6615. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6616. } else {
  6617. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6618. }
  6619. } elseif ($type == 'link') {
  6620. $out = '';
  6621. // only if something to display (perf)
  6622. if ($value) {
  6623. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6624. $InfoFieldList = explode(":", $param_list[0]);
  6625. $classname = $InfoFieldList[0];
  6626. $classpath = $InfoFieldList[1];
  6627. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  6628. $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
  6629. if (!empty($classpath)) {
  6630. dol_include_once($InfoFieldList[1]);
  6631. if ($classname && class_exists($classname)) {
  6632. $object = new $classname($this->db);
  6633. if ($object->element === 'product') { // Special cas for product because default valut of fetch are wrong
  6634. $object->fetch($value, '', '', '', 0, 1, 1);
  6635. } else {
  6636. $object->fetch($value);
  6637. }
  6638. $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
  6639. }
  6640. } else {
  6641. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  6642. return 'Error bad setup of extrafield';
  6643. }
  6644. } else {
  6645. $value = '';
  6646. }
  6647. } elseif (preg_match('/^(text|html)/', $type)) {
  6648. $value = dol_htmlentitiesbr($value);
  6649. } elseif ($type == 'password') {
  6650. $value = preg_replace('/./i', '*', $value);
  6651. } elseif ($type == 'array') {
  6652. $value = implode('<br>', $value);
  6653. }
  6654. //print $type.'-'.$size.'-'.$value;
  6655. $out = $value;
  6656. return $out;
  6657. }
  6658. /**
  6659. * clear validation message result for a field
  6660. *
  6661. * @param string $fieldKey Key of attribute to clear
  6662. * @return null
  6663. */
  6664. public function clearFieldError($fieldKey)
  6665. {
  6666. $this->error = '';
  6667. unset($this->validateFieldsErrors[$fieldKey]);
  6668. }
  6669. /**
  6670. * set validation error message a field
  6671. *
  6672. * @param string $fieldKey Key of attribute
  6673. * @param string $msg the field error message
  6674. * @return null
  6675. */
  6676. public function setFieldError($fieldKey, $msg = '')
  6677. {
  6678. global $langs;
  6679. if (empty($msg)) { $msg = $langs->trans("UnknowError"); }
  6680. $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
  6681. }
  6682. /**
  6683. * get field error message
  6684. *
  6685. * @param string $fieldKey Key of attribute
  6686. * @return string
  6687. */
  6688. public function getFieldError($fieldKey)
  6689. {
  6690. if (!empty($this->validateFieldsErrors[$fieldKey])) {
  6691. return $this->validateFieldsErrors[$fieldKey];
  6692. }
  6693. return '';
  6694. }
  6695. /**
  6696. * Return validation test result for a field
  6697. *
  6698. * @param array $val Array of properties of field to show
  6699. * @param string $fieldKey Key of attribute
  6700. * @param string $fieldValue value of attribute
  6701. * @return bool return false if fail true on success, see $this->error for error message
  6702. */
  6703. public function validateField($val, $fieldKey, $fieldValue)
  6704. {
  6705. global $langs;
  6706. if (!class_exists('Validate')) { require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php'; }
  6707. $this->clearFieldError($fieldKey);
  6708. if (!isset($val[$fieldKey])) {
  6709. $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
  6710. return false;
  6711. }
  6712. $param = array();
  6713. $param['options'] = array();
  6714. $type = $val[$fieldKey]['type'];
  6715. $required = false;
  6716. if (isset($val[$fieldKey]['notnull']) && $val[$fieldKey]['notnull'] === 1) {
  6717. // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  6718. $required = true;
  6719. }
  6720. $maxSize = 0;
  6721. $minSize = 0;
  6722. //
  6723. // PREPARE Elements
  6724. //
  6725. // Convert var to be able to share same code than showOutputField of extrafields
  6726. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6727. $type = 'varchar'; // convert varchar(xx) int varchar
  6728. $maxSize = $reg[1];
  6729. } elseif (preg_match('/varchar/', $type)) {
  6730. $type = 'varchar'; // convert varchar(xx) int varchar
  6731. }
  6732. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6733. $type = 'select';
  6734. }
  6735. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6736. $type = 'link';
  6737. }
  6738. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6739. $param['options'] = $val['arrayofkeyval'];
  6740. }
  6741. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6742. $type = 'link';
  6743. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6744. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6745. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6746. $type = 'sellist';
  6747. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6748. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6749. $type = 'sellist';
  6750. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6751. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6752. $type = 'sellist';
  6753. }
  6754. //
  6755. // TEST Value
  6756. //
  6757. // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
  6758. $validate = new Validate($this->db, $langs);
  6759. // little trick : to perform tests with good performances sort tests by quick to low
  6760. //
  6761. // COMMON TESTS
  6762. //
  6763. // Required test and empty value
  6764. if ($required && !$validate->isNotEmptyString($fieldValue)) {
  6765. $this->setFieldError($fieldKey, $validate->error);
  6766. return false;
  6767. } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
  6768. // if no value sent and the field is not mandatory, no need to perform tests
  6769. return true;
  6770. }
  6771. // MAX Size test
  6772. if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
  6773. $this->setFieldError($fieldKey, $validate->error);
  6774. return false;
  6775. }
  6776. // MIN Size test
  6777. if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
  6778. $this->setFieldError($fieldKey, $validate->error);
  6779. return false;
  6780. }
  6781. //
  6782. // TESTS for TYPE
  6783. //
  6784. if (in_array($type, array('date', 'datetime', 'timestamp'))) {
  6785. if (!$validate->isTimestamp($fieldValue)) {
  6786. $this->setFieldError($fieldKey, $validate->error);
  6787. return false;
  6788. } else { return true; }
  6789. } elseif ($type == 'duration') {
  6790. if (!$validate->isDuration($fieldValue)) {
  6791. $this->setFieldError($fieldKey, $validate->error);
  6792. return false;
  6793. } else { return true; }
  6794. } elseif (in_array($type, array('double', 'real', 'price'))) {
  6795. // is numeric
  6796. if (!$validate->isNumeric($fieldValue)) {
  6797. $this->setFieldError($fieldKey, $validate->error);
  6798. return false;
  6799. } else { return true; }
  6800. } elseif ($type == 'boolean') {
  6801. if (!$validate->isBool($fieldValue)) {
  6802. $this->setFieldError($fieldKey, $validate->error);
  6803. return false;
  6804. } else { return true; }
  6805. } elseif ($type == 'mail') {
  6806. if (!$validate->isEmail($fieldValue)) {
  6807. $this->setFieldError($fieldKey, $validate->error);
  6808. return false;
  6809. }
  6810. } elseif ($type == 'url') {
  6811. if (!$validate->isUrl($fieldValue)) {
  6812. $this->setFieldError($fieldKey, $validate->error);
  6813. return false;
  6814. } else { return true; }
  6815. } elseif ($type == 'phone') {
  6816. if (!$validate->isPhone($fieldValue)) {
  6817. $this->setFieldError($fieldKey, $validate->error);
  6818. return false;
  6819. } else { return true; }
  6820. } elseif ($type == 'select' || $type == 'radio') {
  6821. if (!isset($param['options'][$fieldValue])) {
  6822. $this->error = $langs->trans('RequireValidValue');
  6823. return false;
  6824. } else { return true; }
  6825. } elseif ($type == 'sellist' || $type == 'chkbxlst') {
  6826. $param_list = array_keys($param['options']);
  6827. $InfoFieldList = explode(":", $param_list[0]);
  6828. $value_arr = explode(',', $fieldValue);
  6829. $value_arr = array_map(array($this->db, 'escape'), $value_arr);
  6830. $selectkey = "rowid";
  6831. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6832. $selectkey = $InfoFieldList[2];
  6833. }
  6834. if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
  6835. $this->setFieldError($fieldKey, $validate->error);
  6836. return false;
  6837. } else { return true; }
  6838. } elseif ($type == 'link') {
  6839. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6840. $InfoFieldList = explode(":", $param_list[0]);
  6841. $classname = $InfoFieldList[0];
  6842. $classpath = $InfoFieldList[1];
  6843. if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
  6844. $this->setFieldError($fieldKey, $validate->error);
  6845. return false;
  6846. } else { return true; }
  6847. }
  6848. // if no test failled all is ok
  6849. return true;
  6850. }
  6851. /**
  6852. * Function to show lines of extrafields with output datas.
  6853. * This function is responsible to output the <tr> and <td> according to correct number of columns received into $params['colspan'] or <div> according to $display_type
  6854. *
  6855. * @param Extrafields $extrafields Extrafield Object
  6856. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  6857. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  6858. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  6859. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  6860. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  6861. * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...)
  6862. * @return string
  6863. */
  6864. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
  6865. {
  6866. global $db, $conf, $langs, $action, $form, $hookmanager;
  6867. if (!is_object($form)) {
  6868. $form = new Form($db);
  6869. }
  6870. $out = '';
  6871. $parameters = array();
  6872. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  6873. if (empty($reshook)) {
  6874. if (key_exists('label', $extrafields->attributes[$this->table_element]) && is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0) {
  6875. $out .= "\n";
  6876. $out .= '<!-- showOptionals --> ';
  6877. $out .= "\n";
  6878. $extrafields_collapse_num = '';
  6879. $e = 0;
  6880. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
  6881. // Show only the key field in params
  6882. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
  6883. continue;
  6884. }
  6885. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  6886. $enabled = 1;
  6887. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  6888. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1);
  6889. }
  6890. if (empty($enabled)) {
  6891. continue;
  6892. }
  6893. $visibility = 1;
  6894. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  6895. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1);
  6896. }
  6897. $perms = 1;
  6898. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  6899. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1);
  6900. }
  6901. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
  6902. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  6903. } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
  6904. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  6905. } elseif ($mode == 'view' && empty($visibility)) {
  6906. continue;
  6907. }
  6908. if (empty($perms)) {
  6909. continue;
  6910. }
  6911. // Load language if required
  6912. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  6913. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  6914. }
  6915. $colspan = 0;
  6916. if (is_array($params) && count($params) > 0 && $display_type=='card') {
  6917. if (array_key_exists('cols', $params)) {
  6918. $colspan = $params['cols'];
  6919. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  6920. $reg = array();
  6921. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  6922. $colspan = $reg[1];
  6923. } else {
  6924. $colspan = $params['colspan'];
  6925. }
  6926. }
  6927. }
  6928. $colspan = intval($colspan);
  6929. switch ($mode) {
  6930. case "view":
  6931. $value = $this->array_options["options_".$key.$keysuffix]; // Value may be clean or formated later
  6932. break;
  6933. case "create":
  6934. case "edit":
  6935. // We get the value of property found with GETPOST so it takes into account:
  6936. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  6937. $check = 'alphanohtml';
  6938. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  6939. $check = 'restricthtml';
  6940. }
  6941. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  6942. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  6943. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
  6944. if (is_array($getposttemp)) {
  6945. // $getposttemp is an array but following code expects a comma separated string
  6946. $value = implode(",", $getposttemp);
  6947. } else {
  6948. $value = $getposttemp;
  6949. }
  6950. } else {
  6951. $value = (!empty($this->array_options["options_".$key]) ? $this->array_options["options_".$key] : ''); // No GET, no POST, no default value, so we take value of object.
  6952. }
  6953. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  6954. break;
  6955. }
  6956. // Output value of the current field
  6957. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  6958. $extrafields_collapse_num = '';
  6959. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  6960. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  6961. $extrafield_param_list = array_keys($extrafield_param['options']);
  6962. if (count($extrafield_param_list) > 0) {
  6963. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  6964. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  6965. $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  6966. }
  6967. }
  6968. }
  6969. // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
  6970. $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type);
  6971. } else {
  6972. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  6973. $csstyle = '';
  6974. if (is_array($params) && count($params) > 0) {
  6975. if (array_key_exists('class', $params)) {
  6976. $class .= $params['class'].' ';
  6977. }
  6978. if (array_key_exists('style', $params)) {
  6979. $csstyle = $params['style'];
  6980. }
  6981. }
  6982. // add html5 elements
  6983. $domData = ' data-element="extrafield"';
  6984. $domData .= ' data-targetelement="'.$this->element.'"';
  6985. $domData .= ' data-targetid="'.$this->id.'"';
  6986. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  6987. if ($display_type=='card') {
  6988. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
  6989. $colspan = 0;
  6990. }
  6991. if ($action == 'selectlines') {
  6992. $colspan++;
  6993. }
  6994. }
  6995. // Convert date into timestamp format (value in memory must be a timestamp)
  6996. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
  6997. $datenotinstring = $this->array_options['options_'.$key];
  6998. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  6999. $datenotinstring = $this->db->jdate($datenotinstring);
  7000. }
  7001. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) ? dol_mktime(12, 0, 0, GETPOST($keyprefix.'options_'.$key.$keysuffix."month", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."day", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."year", 'int', 3)) : $datenotinstring;
  7002. }
  7003. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
  7004. $datenotinstring = $this->array_options['options_'.$key];
  7005. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7006. $datenotinstring = $this->db->jdate($datenotinstring);
  7007. }
  7008. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) ? dol_mktime(GETPOST($keyprefix.'options_'.$key.$keysuffix."hour", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."min", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."sec", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."month", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."day", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."year", 'int', 3), 'tzuserrel') : $datenotinstring;
  7009. }
  7010. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  7011. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
  7012. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? price2num($value) : $this->array_options['options_'.$key];
  7013. }
  7014. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  7015. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int'))) {
  7016. if ($action == 'create') {
  7017. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  7018. }
  7019. }
  7020. $labeltoshow = $langs->trans($label);
  7021. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  7022. if ($display_type == 'card') {
  7023. $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="valuefieldcreate '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >';
  7024. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action == 'view' || $action == 'valid' || $action == 'editline')) {
  7025. $out .= '<td></td>';
  7026. }
  7027. $out .= '<td class="wordbreak';
  7028. } elseif ($display_type == 'line') {
  7029. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="valuefieldlinecreate '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >';
  7030. $out .= '<div style="display: inline-block; padding-right:4px" class="wordbreak';
  7031. }
  7032. //$out .= "titlefield";
  7033. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  7034. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  7035. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  7036. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  7037. $out .= '">';
  7038. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7039. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7040. } else {
  7041. $out .= $labeltoshow;
  7042. }
  7043. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7044. $out .= '&nbsp;<span style="color: red">*</span>';
  7045. }
  7046. } else {
  7047. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7048. $out .= ' fieldrequired';
  7049. }
  7050. $out .= '">';
  7051. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7052. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7053. } else {
  7054. $out .= $labeltoshow;
  7055. }
  7056. }
  7057. $out .= ($display_type == 'card' ? '</td>' : '</div>');
  7058. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  7059. if ($display_type == 'card') {
  7060. // a first td column was already output (and may be another on before if MAIN_VIEW_LINE_NUMBER set), so this td is the next one
  7061. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="'.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  7062. } elseif ($display_type == 'line') {
  7063. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').' style="display: inline-block" class="'.$this->element.'_extras_'.$key.'">';
  7064. }
  7065. switch ($mode) {
  7066. case "view":
  7067. $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
  7068. break;
  7069. case "create":
  7070. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7071. break;
  7072. case "edit":
  7073. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7074. break;
  7075. }
  7076. $out .= ($display_type=='card' ? '</td>' : '</div>');
  7077. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
  7078. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7079. } else {
  7080. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7081. }
  7082. $e++;
  7083. }
  7084. }
  7085. $out .= "\n";
  7086. // Add code to manage list depending on others
  7087. if (!empty($conf->use_javascript_ajax)) {
  7088. $out .= $this->getJSListDependancies();
  7089. }
  7090. $out .= '<!-- /showOptionals --> '."\n";
  7091. }
  7092. }
  7093. $out .= $hookmanager->resPrint;
  7094. return $out;
  7095. }
  7096. /**
  7097. * @param string $type Type for prefix
  7098. * @return string Javacript code to manage dependency
  7099. */
  7100. public function getJSListDependancies($type = '_extra')
  7101. {
  7102. $out = '
  7103. <script>
  7104. jQuery(document).ready(function() {
  7105. function showOptions'.$type.'(child_list, parent_list, orig_select)
  7106. {
  7107. var val = $("select[name=\""+parent_list+"\"]").val();
  7108. var parentVal = parent_list + ":" + val;
  7109. if(typeof val == "string"){
  7110. if(val != "") {
  7111. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7112. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7113. $("select[name=\""+child_list+"\"]").append(options);
  7114. } else {
  7115. var options = orig_select.find("option[parent]").clone();
  7116. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7117. $("select[name=\""+child_list+"\"]").append(options);
  7118. }
  7119. } else if(val > 0) {
  7120. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7121. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7122. $("select[name=\""+child_list+"\"]").append(options);
  7123. } else {
  7124. var options = orig_select.find("option[parent]").clone();
  7125. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7126. $("select[name=\""+child_list+"\"]").append(options);
  7127. }
  7128. }
  7129. function setListDependencies'.$type.'() {
  7130. jQuery("select option[parent]").parent().each(function() {
  7131. var orig_select = {};
  7132. var child_list = $(this).attr("name");
  7133. orig_select[child_list] = $(this).clone();
  7134. var parent = $(this).find("option[parent]:first").attr("parent");
  7135. var infos = parent.split(":");
  7136. var parent_list = infos[0];
  7137. //Hide daughters lists
  7138. if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
  7139. $("#"+child_list).hide();
  7140. //Show mother lists
  7141. } else if ($("#"+parent_list).val() != 0){
  7142. $("#"+parent_list).show();
  7143. }
  7144. //Show the child list if the parent list value is selected
  7145. $("select[name=\""+parent_list+"\"]").click(function() {
  7146. if ($(this).val() != 0){
  7147. $("#"+child_list).show()
  7148. }
  7149. });
  7150. //When we change parent list
  7151. $("select[name=\""+parent_list+"\"]").change(function() {
  7152. showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
  7153. //Select the value 0 on child list after a change on the parent list
  7154. $("#"+child_list).val(0).trigger("change");
  7155. //Hide child lists if the parent value is set to 0
  7156. if ($(this).val() == 0){
  7157. $("#"+child_list).hide();
  7158. }
  7159. });
  7160. });
  7161. }
  7162. setListDependencies'.$type.'();
  7163. });
  7164. </script>'."\n";
  7165. return $out;
  7166. }
  7167. /**
  7168. * Returns the rights used for this class
  7169. * @return stdClass
  7170. */
  7171. public function getRights()
  7172. {
  7173. global $user;
  7174. $element = $this->element;
  7175. if ($element == 'facturerec') {
  7176. $element = 'facture';
  7177. } elseif ($element == 'invoice_supplier_rec') {
  7178. return $user->rights->fournisseur->facture;
  7179. }
  7180. return $user->rights->{$element};
  7181. }
  7182. /**
  7183. * Function used to replace a thirdparty id with another one.
  7184. * This function is meant to be called from replaceThirdparty with the appropiate tables
  7185. * Column name fk_soc MUST be used to identify thirdparties
  7186. *
  7187. * @param DoliDB $db Database handler
  7188. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  7189. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  7190. * @param string[] $tables Tables that need to be changed
  7191. * @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)
  7192. * @return bool True if success, False if error
  7193. */
  7194. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7195. {
  7196. foreach ($tables as $table) {
  7197. $sql = 'UPDATE '.$db->prefix().$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
  7198. if (!$db->query($sql)) {
  7199. if ($ignoreerrors) {
  7200. 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.
  7201. }
  7202. //$this->errors = $db->lasterror();
  7203. return false;
  7204. }
  7205. }
  7206. return true;
  7207. }
  7208. /**
  7209. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  7210. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  7211. * else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  7212. * else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  7213. * else set min buy price as buy price
  7214. *
  7215. * @param float $unitPrice Product unit price
  7216. * @param float $discountPercent Line discount percent
  7217. * @param int $fk_product Product id
  7218. * @return float <0 if KO, buyprice if OK
  7219. */
  7220. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  7221. {
  7222. global $conf;
  7223. $buyPrice = 0;
  7224. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
  7225. // When ForceBuyingPriceIfNull is set
  7226. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  7227. } else {
  7228. // Get cost price for margin calculation
  7229. if (!empty($fk_product) && $fk_product > 0) {
  7230. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
  7231. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7232. $product = new Product($this->db);
  7233. $result = $product->fetch($fk_product);
  7234. if ($result <= 0) {
  7235. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7236. return -1;
  7237. }
  7238. if ($product->cost_price > 0) {
  7239. $buyPrice = $product->cost_price;
  7240. } elseif ($product->pmp > 0) {
  7241. $buyPrice = $product->pmp;
  7242. }
  7243. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
  7244. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7245. $product = new Product($this->db);
  7246. $result = $product->fetch($fk_product);
  7247. if ($result <= 0) {
  7248. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7249. return -1;
  7250. }
  7251. if ($product->pmp > 0) {
  7252. $buyPrice = $product->pmp;
  7253. }
  7254. }
  7255. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
  7256. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  7257. $productFournisseur = new ProductFournisseur($this->db);
  7258. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
  7259. $buyPrice = $productFournisseur->fourn_unitprice;
  7260. } elseif ($result < 0) {
  7261. $this->errors[] = $productFournisseur->error;
  7262. return -2;
  7263. }
  7264. }
  7265. }
  7266. }
  7267. return $buyPrice;
  7268. }
  7269. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7270. /**
  7271. * Show photos of an object (nbmax maximum), into several columns
  7272. *
  7273. * @param string $modulepart 'product', 'ticket', ...
  7274. * @param string $sdir Directory to scan (full absolute path)
  7275. * @param int $size 0=original size, 1='small' use thumbnail if possible
  7276. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  7277. * @param int $nbbyrow Number of image per line or -1 to use div separator or 0 to use no separator. Used only if size=1 or 'small'.
  7278. * @param int $showfilename 1=Show filename
  7279. * @param int $showaction 1=Show icon with action links (resize, delete)
  7280. * @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.
  7281. * @param int $maxWidth Max width of original image when size='small'
  7282. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  7283. * @param int $notitle Do not add title tag on image
  7284. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  7285. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  7286. */
  7287. 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)
  7288. {
  7289. // phpcs:enable
  7290. global $conf, $user, $langs;
  7291. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7292. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  7293. $sortfield = 'position_name';
  7294. $sortorder = 'asc';
  7295. $dir = $sdir.'/';
  7296. $pdir = '/';
  7297. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7298. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7299. // For backward compatibility
  7300. if ($modulepart == 'product') {
  7301. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  7302. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7303. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7304. }
  7305. }
  7306. // Defined relative dir to DOL_DATA_ROOT
  7307. $relativedir = '';
  7308. if ($dir) {
  7309. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  7310. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  7311. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  7312. }
  7313. $dirthumb = $dir.'thumbs/';
  7314. $pdirthumb = $pdir.'thumbs/';
  7315. $return = '<!-- Photo -->'."\n";
  7316. $nbphoto = 0;
  7317. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  7318. /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
  7319. {
  7320. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  7321. $filearray=array_merge($filearray, $filearrayold);
  7322. }*/
  7323. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  7324. if (count($filearray)) {
  7325. if ($sortfield && $sortorder) {
  7326. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  7327. }
  7328. foreach ($filearray as $key => $val) {
  7329. $photo = '';
  7330. $file = $val['name'];
  7331. //if (! utf8_check($file)) $file=utf8_encode($file); // To be sure file is stored in UTF8 in memory
  7332. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  7333. if (image_format_supported($file) >= 0) {
  7334. $nbphoto++;
  7335. $photo = $file;
  7336. $viewfilename = $file;
  7337. if ($size == 1 || $size == 'small') { // Format vignette
  7338. // Find name of thumb file
  7339. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  7340. if (!dol_is_file($dirthumb.$photo_vignette)) {
  7341. $photo_vignette = '';
  7342. }
  7343. // Get filesize of original file
  7344. $imgarray = dol_getImageSize($dir.$photo);
  7345. if ($nbbyrow > 0) {
  7346. if ($nbphoto == 1) {
  7347. $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  7348. }
  7349. if ($nbphoto % $nbbyrow == 1) {
  7350. $return .= '<tr class="center valignmiddle" style="border: 1px">';
  7351. }
  7352. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
  7353. } elseif ($nbbyrow < 0) {
  7354. $return .= '<div class="inline-block">';
  7355. }
  7356. $return .= "\n";
  7357. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  7358. if (empty($nolink)) {
  7359. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  7360. if ($urladvanced) {
  7361. $return .= '<a href="'.$urladvanced.'">';
  7362. } else {
  7363. $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
  7364. }
  7365. }
  7366. // Show image (width height=$maxHeight)
  7367. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  7368. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  7369. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  7370. if ($notitle) {
  7371. $alt = '';
  7372. }
  7373. $addphotorefcss = 1;
  7374. if ($usesharelink) {
  7375. if ($val['share']) {
  7376. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7377. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  7378. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7379. } else {
  7380. $return .= '<!-- Show original file -->';
  7381. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7382. }
  7383. } else {
  7384. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  7385. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  7386. }
  7387. } else {
  7388. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7389. $return .= '<!-- Show thumb -->';
  7390. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').' maxwidth150onsmartphone maxwidth200" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdirthumb.$photo_vignette).'" title="'.dol_escape_htmltag($alt).'">';
  7391. } else {
  7392. $return .= '<!-- Show original file -->';
  7393. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" title="'.dol_escape_htmltag($alt).'">';
  7394. }
  7395. }
  7396. if (empty($nolink)) {
  7397. $return .= '</a>';
  7398. }
  7399. $return .= "\n";
  7400. if ($showfilename) {
  7401. $return .= '<br>'.$viewfilename;
  7402. }
  7403. if ($showaction) {
  7404. $return .= '<br>';
  7405. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  7406. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
  7407. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=addthumb&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'), 'refresh').'&nbsp;&nbsp;</a>';
  7408. }
  7409. // Special cas for product
  7410. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7411. // Link to resize
  7412. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  7413. // Link to delete
  7414. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7415. $return .= img_delete().'</a>';
  7416. }
  7417. }
  7418. $return .= "\n";
  7419. if ($nbbyrow > 0) {
  7420. $return .= '</td>';
  7421. if (($nbphoto % $nbbyrow) == 0) {
  7422. $return .= '</tr>';
  7423. }
  7424. } elseif ($nbbyrow < 0) {
  7425. $return .= '</div>';
  7426. }
  7427. }
  7428. if (empty($size)) { // Format origine
  7429. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  7430. if ($showfilename) {
  7431. $return .= '<br>'.$viewfilename;
  7432. }
  7433. if ($showaction) {
  7434. // Special case for product
  7435. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7436. // Link to resize
  7437. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  7438. // Link to delete
  7439. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7440. $return .= img_delete().'</a>';
  7441. }
  7442. }
  7443. }
  7444. // On continue ou on arrete de boucler ?
  7445. if ($nbmax && $nbphoto >= $nbmax) {
  7446. break;
  7447. }
  7448. }
  7449. }
  7450. if ($size == 1 || $size == 'small') {
  7451. if ($nbbyrow > 0) {
  7452. // Ferme tableau
  7453. while ($nbphoto % $nbbyrow) {
  7454. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  7455. $nbphoto++;
  7456. }
  7457. if ($nbphoto) {
  7458. $return .= '</table>';
  7459. }
  7460. }
  7461. }
  7462. }
  7463. $this->nbphoto = $nbphoto;
  7464. return $return;
  7465. }
  7466. /**
  7467. * Function test if type is array
  7468. *
  7469. * @param array $info content informations of field
  7470. * @return bool true if array
  7471. */
  7472. protected function isArray($info)
  7473. {
  7474. if (is_array($info)) {
  7475. if (isset($info['type']) && $info['type'] == 'array') {
  7476. return true;
  7477. } else {
  7478. return false;
  7479. }
  7480. }
  7481. return false;
  7482. }
  7483. /**
  7484. * Function test if type is date
  7485. *
  7486. * @param array $info content informations of field
  7487. * @return bool true if date
  7488. */
  7489. public function isDate($info)
  7490. {
  7491. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
  7492. return true;
  7493. }
  7494. return false;
  7495. }
  7496. /**
  7497. * Function test if type is duration
  7498. *
  7499. * @param array $info content informations of field
  7500. * @return bool true if field of type duration
  7501. */
  7502. public function isDuration($info)
  7503. {
  7504. if (is_array($info)) {
  7505. if (isset($info['type']) && ($info['type'] == 'duration')) {
  7506. return true;
  7507. } else {
  7508. return false;
  7509. }
  7510. } else {
  7511. return false;
  7512. }
  7513. }
  7514. /**
  7515. * Function test if type is integer
  7516. *
  7517. * @param array $info content informations of field
  7518. * @return bool true if integer
  7519. */
  7520. public function isInt($info)
  7521. {
  7522. if (is_array($info)) {
  7523. if (isset($info['type']) && ($info['type'] == 'int' || preg_match('/^integer/i', $info['type']))) {
  7524. return true;
  7525. } else {
  7526. return false;
  7527. }
  7528. } else {
  7529. return false;
  7530. }
  7531. }
  7532. /**
  7533. * Function test if type is float
  7534. *
  7535. * @param array $info content informations of field
  7536. * @return bool true if float
  7537. */
  7538. public function isFloat($info)
  7539. {
  7540. if (is_array($info)) {
  7541. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
  7542. return true;
  7543. } else {
  7544. return false;
  7545. }
  7546. }
  7547. return false;
  7548. }
  7549. /**
  7550. * Function test if type is text
  7551. *
  7552. * @param array $info content informations of field
  7553. * @return bool true if type text
  7554. */
  7555. public function isText($info)
  7556. {
  7557. if (is_array($info)) {
  7558. if (isset($info['type']) && $info['type'] == 'text') {
  7559. return true;
  7560. } else {
  7561. return false;
  7562. }
  7563. }
  7564. return false;
  7565. }
  7566. /**
  7567. * Function test if field can be null
  7568. *
  7569. * @param array $info content informations of field
  7570. * @return bool true if it can be null
  7571. */
  7572. protected function canBeNull($info)
  7573. {
  7574. if (is_array($info)) {
  7575. if (isset($info['notnull']) && $info['notnull'] != '1') {
  7576. return true;
  7577. } else {
  7578. return false;
  7579. }
  7580. }
  7581. return true;
  7582. }
  7583. /**
  7584. * Function test if field is forced to null if zero or empty
  7585. *
  7586. * @param array $info content informations of field
  7587. * @return bool true if forced to null
  7588. */
  7589. protected function isForcedToNullIfZero($info)
  7590. {
  7591. if (is_array($info)) {
  7592. if (isset($info['notnull']) && $info['notnull'] == '-1') {
  7593. return true;
  7594. } else {
  7595. return false;
  7596. }
  7597. }
  7598. return false;
  7599. }
  7600. /**
  7601. * Function test if is indexed
  7602. *
  7603. * @param array $info content informations of field
  7604. * @return bool
  7605. */
  7606. protected function isIndex($info)
  7607. {
  7608. if (is_array($info)) {
  7609. if (isset($info['index']) && $info['index'] == true) {
  7610. return true;
  7611. } else {
  7612. return false;
  7613. }
  7614. }
  7615. return false;
  7616. }
  7617. /**
  7618. * Function to prepare a part of the query for insert.
  7619. * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
  7620. * $this->${field} should be a clean value. The page can run
  7621. *
  7622. * @return array
  7623. */
  7624. protected function setSaveQuery()
  7625. {
  7626. global $conf;
  7627. $queryarray = array();
  7628. foreach ($this->fields as $field => $info) { // Loop on definition of fields
  7629. // Depending on field type ('datetime', ...)
  7630. if ($this->isDate($info)) {
  7631. if (empty($this->{$field})) {
  7632. $queryarray[$field] = null;
  7633. } else {
  7634. $queryarray[$field] = $this->db->idate($this->{$field});
  7635. }
  7636. } elseif ($this->isDuration($info)) {
  7637. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7638. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7639. if (!isset($this->{$field})) {
  7640. $queryarray[$field] = 0;
  7641. } else {
  7642. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7643. }
  7644. } else {
  7645. $queryarray[$field] = null;
  7646. }
  7647. } elseif ($this->isInt($info) || $this->isFloat($info)) {
  7648. if ($field == 'entity' && is_null($this->{$field})) {
  7649. $queryarray[$field] = $conf->entity;
  7650. } else {
  7651. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7652. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7653. if (!isset($this->{$field})) {
  7654. $queryarray[$field] = 0;
  7655. } elseif ($this->isInt($info)) {
  7656. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7657. } elseif ($this->isFloat($info)) {
  7658. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7659. }
  7660. } else {
  7661. $queryarray[$field] = null;
  7662. }
  7663. }
  7664. } else {
  7665. // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
  7666. // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
  7667. $queryarray[$field] = $this->{$field};
  7668. }
  7669. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
  7670. unset($queryarray[$field]);
  7671. }
  7672. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
  7673. $queryarray[$field] = null; // May force 0 to null
  7674. }
  7675. }
  7676. return $queryarray;
  7677. }
  7678. /**
  7679. * Function to load data from a SQL pointer into properties of current object $this
  7680. *
  7681. * @param stdClass $obj Contain data of object from database
  7682. * @return void
  7683. */
  7684. public function setVarsFromFetchObj(&$obj)
  7685. {
  7686. global $db;
  7687. foreach ($this->fields as $field => $info) {
  7688. if ($this->isDate($info)) {
  7689. if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
  7690. $this->{$field} = '';
  7691. } else {
  7692. $this->{$field} = $db->jdate($obj->{$field});
  7693. }
  7694. } elseif ($this->isInt($info)) {
  7695. if ($field == 'rowid') {
  7696. $this->id = (int) $obj->{$field};
  7697. } else {
  7698. if ($this->isForcedToNullIfZero($info)) {
  7699. if (empty($obj->{$field})) {
  7700. $this->{$field} = null;
  7701. } else {
  7702. $this->{$field} = (double) $obj->{$field};
  7703. }
  7704. } else {
  7705. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7706. $this->{$field} = (int) $obj->{$field};
  7707. } else {
  7708. $this->{$field} = null;
  7709. }
  7710. }
  7711. }
  7712. } elseif ($this->isFloat($info)) {
  7713. if ($this->isForcedToNullIfZero($info)) {
  7714. if (empty($obj->{$field})) {
  7715. $this->{$field} = null;
  7716. } else {
  7717. $this->{$field} = (double) $obj->{$field};
  7718. }
  7719. } else {
  7720. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7721. $this->{$field} = (double) $obj->{$field};
  7722. } else {
  7723. $this->{$field} = null;
  7724. }
  7725. }
  7726. } else {
  7727. $this->{$field} = $obj->{$field};
  7728. }
  7729. }
  7730. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  7731. if (!isset($this->fields['ref']) && isset($this->id)) {
  7732. $this->ref = $this->id;
  7733. }
  7734. }
  7735. /**
  7736. * Function to concat keys of fields
  7737. *
  7738. * @param string $alias String of alias of table for fields. For example 't'.
  7739. * @return string list of alias fields
  7740. */
  7741. public function getFieldList($alias = '')
  7742. {
  7743. $keys = array_keys($this->fields);
  7744. if (!empty($alias)) {
  7745. $keys_with_alias = array();
  7746. foreach ($keys as $fieldname) {
  7747. $keys_with_alias[] = $alias . '.' . $fieldname;
  7748. }
  7749. return implode(',', $keys_with_alias);
  7750. } else {
  7751. return implode(',', $keys);
  7752. }
  7753. }
  7754. /**
  7755. * Add quote to field value if necessary
  7756. *
  7757. * @param string|int $value Value to protect
  7758. * @param array $fieldsentry Properties of field
  7759. * @return string
  7760. */
  7761. protected function quote($value, $fieldsentry)
  7762. {
  7763. if (is_null($value)) {
  7764. return 'NULL';
  7765. } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
  7766. return price2num("$value");
  7767. } elseif ($fieldsentry['type'] == 'boolean') {
  7768. if ($value) {
  7769. return 'true';
  7770. } else {
  7771. return 'false';
  7772. }
  7773. } else {
  7774. return "'".$this->db->escape($value)."'";
  7775. }
  7776. }
  7777. /**
  7778. * Create object into database
  7779. *
  7780. * @param User $user User that creates
  7781. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7782. * @return int <0 if KO, Id of created object if OK
  7783. */
  7784. public function createCommon(User $user, $notrigger = false)
  7785. {
  7786. global $langs;
  7787. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  7788. $error = 0;
  7789. $now = dol_now();
  7790. $fieldvalues = $this->setSaveQuery();
  7791. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
  7792. $fieldvalues['date_creation'] = $this->db->idate($now);
  7793. }
  7794. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
  7795. $fieldvalues['fk_user_creat'] = $user->id;
  7796. }
  7797. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  7798. if (array_key_exists('ref', $fieldvalues)) {
  7799. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  7800. }
  7801. $keys = array();
  7802. $values = array(); // Array to store string forged for SQL syntax
  7803. foreach ($fieldvalues as $k => $v) {
  7804. $keys[$k] = $k;
  7805. $value = $this->fields[$k];
  7806. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  7807. }
  7808. // Clean and check mandatory
  7809. foreach ($keys as $key) {
  7810. // If field is an implicit foreign key field
  7811. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  7812. $values[$key] = '';
  7813. }
  7814. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  7815. $values[$key] = '';
  7816. }
  7817. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
  7818. $error++;
  7819. $langs->load("errors");
  7820. dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
  7821. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  7822. }
  7823. // If value is null and there is a default value for field
  7824. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
  7825. $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
  7826. }
  7827. // If field is an implicit foreign key field
  7828. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  7829. if (isset($this->fields[$key]['default'])) {
  7830. $values[$key] = ((int) $this->fields[$key]['default']);
  7831. } else {
  7832. $values[$key] = 'null';
  7833. }
  7834. }
  7835. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
  7836. $values[$key] = 'null';
  7837. }
  7838. }
  7839. if ($error) {
  7840. return -1;
  7841. }
  7842. $this->db->begin();
  7843. if (!$error) {
  7844. $sql = "INSERT INTO ".$this->db->prefix().$this->table_element;
  7845. $sql .= " (".implode(", ", $keys).')';
  7846. $sql .= " VALUES (".implode(", ", $values).")"; // $values can contains 'abc' or 123
  7847. $res = $this->db->query($sql);
  7848. if (!$res) {
  7849. $error++;
  7850. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  7851. $this->errors[] = "ErrorRefAlreadyExists";
  7852. } else {
  7853. $this->errors[] = $this->db->lasterror();
  7854. }
  7855. }
  7856. }
  7857. if (!$error) {
  7858. $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
  7859. }
  7860. // If we have a field ref with a default value of (PROV)
  7861. if (!$error) {
  7862. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
  7863. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
  7864. $resqlupdate = $this->db->query($sql);
  7865. if ($resqlupdate === false) {
  7866. $error++;
  7867. $this->errors[] = $this->db->lasterror();
  7868. } else {
  7869. $this->ref = '(PROV'.$this->id.')';
  7870. }
  7871. }
  7872. }
  7873. // Create extrafields
  7874. if (!$error) {
  7875. $result = $this->insertExtraFields();
  7876. if ($result < 0) {
  7877. $error++;
  7878. }
  7879. }
  7880. // Create lines
  7881. if (!empty($this->table_element_line) && !empty($this->fk_element)) {
  7882. $num = (is_array($this->lines) ? count($this->lines) : 0);
  7883. for ($i = 0; $i < $num; $i++) {
  7884. $line = $this->lines[$i];
  7885. $keyforparent = $this->fk_element;
  7886. $line->$keyforparent = $this->id;
  7887. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  7888. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  7889. if (!is_object($line)) {
  7890. $line = (object) $line;
  7891. }
  7892. $result = $line->create($user, 1);
  7893. if ($result < 0) {
  7894. $this->error = $line->error;
  7895. $this->db->rollback();
  7896. return -1;
  7897. }
  7898. }
  7899. }
  7900. // Triggers
  7901. if (!$error && !$notrigger) {
  7902. // Call triggers
  7903. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  7904. if ($result < 0) {
  7905. $error++;
  7906. }
  7907. // End call triggers
  7908. }
  7909. // Commit or rollback
  7910. if ($error) {
  7911. $this->db->rollback();
  7912. return -1;
  7913. } else {
  7914. $this->db->commit();
  7915. return $this->id;
  7916. }
  7917. }
  7918. /**
  7919. * Load object in memory from the database
  7920. *
  7921. * @param int $id Id object
  7922. * @param string $ref Ref
  7923. * @param string $morewhere More SQL filters (' AND ...')
  7924. * @return int <0 if KO, 0 if not found, >0 if OK
  7925. */
  7926. public function fetchCommon($id, $ref = null, $morewhere = '')
  7927. {
  7928. if (empty($id) && empty($ref) && empty($morewhere)) {
  7929. return -1;
  7930. }
  7931. $fieldlist = $this->getFieldList('t');
  7932. if (empty($fieldlist)) {
  7933. return 0;
  7934. }
  7935. $sql = "SELECT ".$fieldlist;
  7936. $sql .= " FROM ".$this->db->prefix().$this->table_element.' as t';
  7937. if (!empty($id)) {
  7938. $sql .= ' WHERE t.rowid = '.((int) $id);
  7939. } elseif (!empty($ref)) {
  7940. $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
  7941. } else {
  7942. $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  7943. }
  7944. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  7945. $sql .= ' AND t.entity IN ('.getEntity($this->table_element).')';
  7946. }
  7947. if ($morewhere) {
  7948. $sql .= $morewhere;
  7949. }
  7950. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  7951. $res = $this->db->query($sql);
  7952. if ($res) {
  7953. $obj = $this->db->fetch_object($res);
  7954. if ($obj) {
  7955. $this->setVarsFromFetchObj($obj);
  7956. // Retrieve all extrafield
  7957. // fetch optionals attributes and labels
  7958. $this->fetch_optionals();
  7959. return $this->id;
  7960. } else {
  7961. return 0;
  7962. }
  7963. } else {
  7964. $this->error = $this->db->lasterror();
  7965. $this->errors[] = $this->error;
  7966. return -1;
  7967. }
  7968. }
  7969. /**
  7970. * Load object in memory from the database
  7971. *
  7972. * @param string $morewhere More SQL filters (' AND ...')
  7973. * @return int <0 if KO, 0 if not found, >0 if OK
  7974. */
  7975. public function fetchLinesCommon($morewhere = '')
  7976. {
  7977. $objectlineclassname = get_class($this).'Line';
  7978. if (!class_exists($objectlineclassname)) {
  7979. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  7980. return -1;
  7981. }
  7982. $objectline = new $objectlineclassname($this->db);
  7983. $sql = "SELECT ".$objectline->getFieldList('l');
  7984. $sql .= " FROM ".$this->db->prefix().$objectline->table_element." as l";
  7985. $sql .= " WHERE l.fk_".$this->db->escape($this->element)." = ".((int) $this->id);
  7986. if ($morewhere) {
  7987. $sql .= $morewhere;
  7988. }
  7989. if (isset($objectline->fields['position'])) {
  7990. $sql .= $this->db->order('position', 'ASC');
  7991. }
  7992. $resql = $this->db->query($sql);
  7993. if ($resql) {
  7994. $num_rows = $this->db->num_rows($resql);
  7995. $i = 0;
  7996. while ($i < $num_rows) {
  7997. $obj = $this->db->fetch_object($resql);
  7998. if ($obj) {
  7999. $newline = new $objectlineclassname($this->db);
  8000. $newline->setVarsFromFetchObj($obj);
  8001. $this->lines[] = $newline;
  8002. }
  8003. $i++;
  8004. }
  8005. return 1;
  8006. } else {
  8007. $this->error = $this->db->lasterror();
  8008. $this->errors[] = $this->error;
  8009. return -1;
  8010. }
  8011. }
  8012. /**
  8013. * Update object into database
  8014. *
  8015. * @param User $user User that modifies
  8016. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8017. * @return int <0 if KO, >0 if OK
  8018. */
  8019. public function updateCommon(User $user, $notrigger = false)
  8020. {
  8021. global $conf, $langs;
  8022. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  8023. $error = 0;
  8024. $now = dol_now();
  8025. $fieldvalues = $this->setSaveQuery();
  8026. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
  8027. $fieldvalues['date_modification'] = $this->db->idate($now);
  8028. }
  8029. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
  8030. $fieldvalues['fk_user_modif'] = $user->id;
  8031. }
  8032. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  8033. if (array_key_exists('ref', $fieldvalues)) {
  8034. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8035. }
  8036. // Add quotes and escape on fields with type string
  8037. $keys = array();
  8038. $values = array();
  8039. $tmp = array();
  8040. foreach ($fieldvalues as $k => $v) {
  8041. $keys[$k] = $k;
  8042. $value = $this->fields[$k];
  8043. $values[$k] = $this->quote($v, $value);
  8044. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  8045. }
  8046. // Clean and check mandatory fields
  8047. foreach ($keys as $key) {
  8048. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8049. $values[$key] = ''; // This is an implicit foreign key field
  8050. }
  8051. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8052. $values[$key] = ''; // This is an explicit foreign key field
  8053. }
  8054. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  8055. /*
  8056. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  8057. {
  8058. $error++;
  8059. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8060. }*/
  8061. }
  8062. $sql = 'UPDATE '.$this->db->prefix().$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
  8063. $this->db->begin();
  8064. if (!$error) {
  8065. $res = $this->db->query($sql);
  8066. if (!$res) {
  8067. $error++;
  8068. $this->errors[] = $this->db->lasterror();
  8069. }
  8070. }
  8071. // Update extrafield
  8072. if (!$error) {
  8073. $result = $this->insertExtraFields();
  8074. if ($result < 0) {
  8075. $error++;
  8076. }
  8077. }
  8078. // Triggers
  8079. if (!$error && !$notrigger) {
  8080. // Call triggers
  8081. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  8082. if ($result < 0) {
  8083. $error++;
  8084. } //Do also here what you must do to rollback action if trigger fail
  8085. // End call triggers
  8086. }
  8087. // Commit or rollback
  8088. if ($error) {
  8089. $this->db->rollback();
  8090. return -1;
  8091. } else {
  8092. $this->db->commit();
  8093. return $this->id;
  8094. }
  8095. }
  8096. /**
  8097. * Delete object in database
  8098. *
  8099. * @param User $user User that deletes
  8100. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8101. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  8102. * @return int <=0 if KO, 0=Nothing done because object has child, >0 if OK
  8103. */
  8104. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  8105. {
  8106. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  8107. $error = 0;
  8108. $this->db->begin();
  8109. if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
  8110. foreach ($this->childtables as $table) {
  8111. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8112. $resql = $this->db->query($sql);
  8113. if (!$resql) {
  8114. $this->error = $this->db->lasterror();
  8115. $this->errors[] = $this->error;
  8116. $this->db->rollback();
  8117. return -1;
  8118. }
  8119. }
  8120. } elseif (!empty($this->fk_element) && !empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
  8121. $objectisused = $this->isObjectUsed($this->id);
  8122. if (!empty($objectisused)) {
  8123. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  8124. $this->error = 'ErrorRecordHasChildren';
  8125. $this->errors[] = $this->error;
  8126. $this->db->rollback();
  8127. return 0;
  8128. }
  8129. }
  8130. // Delete cascade first
  8131. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  8132. foreach ($this->childtablesoncascade as $table) {
  8133. $deleteFromObject = explode(':', $table);
  8134. if (count($deleteFromObject) >= 2) {
  8135. $className = str_replace('@', '', $deleteFromObject[0]);
  8136. $filePath = $deleteFromObject[1];
  8137. $columnName = $deleteFromObject[2];
  8138. $TMoreSQL = array();
  8139. $more_sql = $deleteFromObject[3];
  8140. if (!empty($more_sql)) {
  8141. $TMoreSQL['customsql'] = $more_sql;
  8142. }
  8143. if (dol_include_once($filePath)) {
  8144. $childObject = new $className($this->db);
  8145. if (method_exists($childObject, 'deleteByParentField')) {
  8146. $result = $childObject->deleteByParentField($this->id, $columnName, $TMoreSQL);
  8147. if ($result < 0) {
  8148. $error++;
  8149. $this->errors[] = $childObject->error;
  8150. break;
  8151. }
  8152. } else {
  8153. $error++;
  8154. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  8155. break;
  8156. }
  8157. } else {
  8158. $error++;
  8159. $this->errors[] = 'Cannot include child class file '.$filePath;
  8160. break;
  8161. }
  8162. } else {
  8163. // Delete record in child table
  8164. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8165. $resql = $this->db->query($sql);
  8166. if (!$resql) {
  8167. $error++;
  8168. $this->error = $this->db->lasterror();
  8169. $this->errors[] = $this->error;
  8170. break;
  8171. }
  8172. }
  8173. }
  8174. }
  8175. if (!$error) {
  8176. if (!$notrigger) {
  8177. // Call triggers
  8178. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  8179. if ($result < 0) {
  8180. $error++;
  8181. } // Do also here what you must do to rollback action if trigger fail
  8182. // End call triggers
  8183. }
  8184. }
  8185. // Delete llx_ecm_files
  8186. if (!$error) {
  8187. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  8188. if (!$res) {
  8189. $error++;
  8190. }
  8191. }
  8192. if (!$error && !empty($this->isextrafieldmanaged)) {
  8193. $result = $this->deleteExtraFields();
  8194. if ($result < 0) {
  8195. $error++;
  8196. }
  8197. }
  8198. if (!$error) {
  8199. $sql = 'DELETE FROM '.$this->db->prefix().$this->table_element.' WHERE rowid='.((int) $this->id);
  8200. $resql = $this->db->query($sql);
  8201. if (!$resql) {
  8202. $error++;
  8203. $this->errors[] = $this->db->lasterror();
  8204. }
  8205. }
  8206. // Commit or rollback
  8207. if ($error) {
  8208. $this->db->rollback();
  8209. return -1;
  8210. } else {
  8211. $this->db->commit();
  8212. return 1;
  8213. }
  8214. }
  8215. /**
  8216. * Delete all child object from a parent ID
  8217. *
  8218. * @param int $parentId Parent Id
  8219. * @param string $parentField Name of Foreign key parent column
  8220. * @param array $filter an array filter
  8221. * @param string $filtermode AND or OR
  8222. * @return int <0 if KO, >0 if OK
  8223. * @throws Exception
  8224. */
  8225. public function deleteByParentField($parentId = 0, $parentField = '', $filter = array(), $filtermode = "AND")
  8226. {
  8227. global $user;
  8228. $error = 0;
  8229. $deleted = 0;
  8230. if (!empty($parentId) && !empty($parentField)) {
  8231. $this->db->begin();
  8232. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
  8233. $sql .= " WHERE ".$parentField." = ".(int) $parentId;
  8234. // Manage filters
  8235. $sqlwhere = array();
  8236. if (count($filter) > 0) {
  8237. foreach ($filter as $key => $value) {
  8238. if ($key == 'customsql') {
  8239. $sqlwhere[] = $value;
  8240. } elseif (strpos($value, '%') === false) {
  8241. $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
  8242. } else {
  8243. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  8244. }
  8245. }
  8246. }
  8247. if (count($sqlwhere) > 0) {
  8248. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  8249. }
  8250. $resql = $this->db->query($sql);
  8251. if (!$resql) {
  8252. $this->errors[] = $this->db->lasterror();
  8253. $error++;
  8254. } else {
  8255. while ($obj = $this->db->fetch_object($resql)) {
  8256. $result = $this->fetch($obj->rowid);
  8257. if ($result < 0) {
  8258. $error++;
  8259. $this->errors[] = $this->error;
  8260. } else {
  8261. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  8262. $result = $this->delete();
  8263. } else {
  8264. $result = $this->delete($user);
  8265. }
  8266. if ($result < 0) {
  8267. $error++;
  8268. $this->errors[] = $this->error;
  8269. } else {
  8270. $deleted++;
  8271. }
  8272. }
  8273. }
  8274. }
  8275. if (empty($error)) {
  8276. $this->db->commit();
  8277. return $deleted;
  8278. } else {
  8279. $this->error = implode(', ', $this->errors);
  8280. $this->db->rollback();
  8281. return $error * -1;
  8282. }
  8283. }
  8284. return $deleted;
  8285. }
  8286. /**
  8287. * Delete a line of object in database
  8288. *
  8289. * @param User $user User that delete
  8290. * @param int $idline Id of line to delete
  8291. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8292. * @return int >0 if OK, <0 if KO
  8293. */
  8294. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  8295. {
  8296. global $conf;
  8297. $error = 0;
  8298. $tmpforobjectclass = get_class($this);
  8299. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  8300. // Call trigger
  8301. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  8302. if ($result < 0) {
  8303. return -1;
  8304. }
  8305. // End call triggers
  8306. $this->db->begin();
  8307. $sql = "DELETE FROM ".$this->db->prefix().$this->table_element_line;
  8308. $sql .= " WHERE rowid = ".((int) $idline);
  8309. dol_syslog(get_class($this)."::deleteLineCommon", LOG_DEBUG);
  8310. $resql = $this->db->query($sql);
  8311. if (!$resql) {
  8312. $this->error = "Error ".$this->db->lasterror();
  8313. $error++;
  8314. }
  8315. if (empty($error)) {
  8316. // Remove extrafields
  8317. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  8318. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  8319. $tmpobjectline->id = $idline;
  8320. $result = $tmpobjectline->deleteExtraFields();
  8321. if ($result < 0) {
  8322. $error++;
  8323. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  8324. }
  8325. }
  8326. }
  8327. if (empty($error)) {
  8328. $this->db->commit();
  8329. return 1;
  8330. } else {
  8331. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  8332. $this->db->rollback();
  8333. return -1;
  8334. }
  8335. }
  8336. /**
  8337. * Set to a status
  8338. *
  8339. * @param User $user Object user that modify
  8340. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  8341. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  8342. * @param string $triggercode Trigger code to use
  8343. * @return int <0 if KO, >0 if OK
  8344. */
  8345. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  8346. {
  8347. $error = 0;
  8348. $this->db->begin();
  8349. $statusfield = 'status';
  8350. if ($this->element == 'don' || $this->element == 'donation') {
  8351. $statusfield = 'fk_statut';
  8352. }
  8353. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  8354. $sql .= " SET ".$statusfield." = ".((int) $status);
  8355. $sql .= " WHERE rowid = ".((int) $this->id);
  8356. if ($this->db->query($sql)) {
  8357. if (!$error) {
  8358. $this->oldcopy = clone $this;
  8359. }
  8360. if (!$error && !$notrigger) {
  8361. // Call trigger
  8362. $result = $this->call_trigger($triggercode, $user);
  8363. if ($result < 0) {
  8364. $error++;
  8365. }
  8366. }
  8367. if (!$error) {
  8368. $this->status = $status;
  8369. $this->db->commit();
  8370. return 1;
  8371. } else {
  8372. $this->db->rollback();
  8373. return -1;
  8374. }
  8375. } else {
  8376. $this->error = $this->db->error();
  8377. $this->db->rollback();
  8378. return -1;
  8379. }
  8380. }
  8381. /**
  8382. * Initialise object with example values
  8383. * Id must be 0 if object instance is a specimen
  8384. *
  8385. * @return int
  8386. */
  8387. public function initAsSpecimenCommon()
  8388. {
  8389. global $user;
  8390. $this->id = 0;
  8391. $this->specimen = 1;
  8392. $fields = array(
  8393. 'label' => 'This is label',
  8394. 'ref' => 'ABCD1234',
  8395. 'description' => 'This is a description',
  8396. 'qty' => 123.12,
  8397. 'note_public' => 'Public note',
  8398. 'note_private' => 'Private note',
  8399. 'date_creation' => (dol_now() - 3600 * 48),
  8400. 'date_modification' => (dol_now() - 3600 * 24),
  8401. 'fk_user_creat' => $user->id,
  8402. 'fk_user_modif' => $user->id,
  8403. 'date' => dol_now(),
  8404. );
  8405. foreach ($fields as $key => $value) {
  8406. if (array_key_exists($key, $this->fields)) {
  8407. $this->{$key} = $value;
  8408. }
  8409. }
  8410. return 1;
  8411. }
  8412. /* Part for comments */
  8413. /**
  8414. * Load comments linked with current task
  8415. * @return boolean 1 if ok
  8416. */
  8417. public function fetchComments()
  8418. {
  8419. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  8420. $comment = new Comment($this->db);
  8421. $result = $comment->fetchAllFor($this->element, $this->id);
  8422. if ($result < 0) {
  8423. $this->errors = array_merge($this->errors, $comment->errors);
  8424. return -1;
  8425. } else {
  8426. $this->comments = $comment->comments;
  8427. }
  8428. return count($this->comments);
  8429. }
  8430. /**
  8431. * Return nb comments already posted
  8432. *
  8433. * @return int
  8434. */
  8435. public function getNbComments()
  8436. {
  8437. return count($this->comments);
  8438. }
  8439. /**
  8440. * Trim object parameters
  8441. *
  8442. * @param string[] $parameters array of parameters to trim
  8443. * @return void
  8444. */
  8445. public function trimParameters($parameters)
  8446. {
  8447. if (!is_array($parameters)) {
  8448. return;
  8449. }
  8450. foreach ($parameters as $parameter) {
  8451. if (isset($this->$parameter)) {
  8452. $this->$parameter = trim($this->$parameter);
  8453. }
  8454. }
  8455. }
  8456. /* Part for categories/tags */
  8457. /**
  8458. * Sets object to given categories.
  8459. *
  8460. * Deletes object from existing categories not supplied.
  8461. * Adds it to non existing supplied categories.
  8462. * Existing categories are left untouch.
  8463. *
  8464. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  8465. * @return int Array of category objects or < 0 if KO
  8466. */
  8467. public function getCategoriesCommon($type_categ)
  8468. {
  8469. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8470. // Get current categories
  8471. $c = new Categorie($this->db);
  8472. $existing = $c->containing($this->id, $type_categ, 'id');
  8473. return $existing;
  8474. }
  8475. /**
  8476. * Sets object to given categories.
  8477. *
  8478. * Adds it to non existing supplied categories.
  8479. * Deletes object from existing categories not supplied (if remove_existing==true).
  8480. * Existing categories are left untouch.
  8481. *
  8482. * @param int[]|int $categories Category ID or array of Categories IDs
  8483. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) definied into const class Categorie type
  8484. * @param boolean $remove_existing True: Remove existings categories from Object if not supplies by $categories, False: let them
  8485. * @return int <0 if KO, >0 if OK
  8486. */
  8487. public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
  8488. {
  8489. // Handle single category
  8490. if (!is_array($categories)) {
  8491. $categories = array($categories);
  8492. }
  8493. dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
  8494. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8495. if (empty($type_categ)) {
  8496. dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
  8497. return -1;
  8498. }
  8499. // Get current categories
  8500. $c = new Categorie($this->db);
  8501. $existing = $c->containing($this->id, $type_categ, 'id');
  8502. if ($remove_existing) {
  8503. // Diff
  8504. if (is_array($existing)) {
  8505. $to_del = array_diff($existing, $categories);
  8506. $to_add = array_diff($categories, $existing);
  8507. } else {
  8508. $to_del = array(); // Nothing to delete
  8509. $to_add = $categories;
  8510. }
  8511. } else {
  8512. $to_del = array(); // Nothing to delete
  8513. $to_add = array_diff($categories, $existing);
  8514. }
  8515. $error = 0;
  8516. $ok = 0;
  8517. // Process
  8518. foreach ($to_del as $del) {
  8519. if ($c->fetch($del) > 0) {
  8520. $result=$c->del_type($this, $type_categ);
  8521. if ($result < 0) {
  8522. $error++;
  8523. $this->error = $c->error;
  8524. $this->errors = $c->errors;
  8525. break;
  8526. } else {
  8527. $ok += $result;
  8528. }
  8529. }
  8530. }
  8531. foreach ($to_add as $add) {
  8532. if ($c->fetch($add) > 0) {
  8533. $result = $c->add_type($this, $type_categ);
  8534. if ($result < 0) {
  8535. $error++;
  8536. $this->error = $c->error;
  8537. $this->errors = $c->errors;
  8538. break;
  8539. } else {
  8540. $ok += $result;
  8541. }
  8542. }
  8543. }
  8544. return $error ? -1 * $error : $ok;
  8545. }
  8546. /**
  8547. * Copy related categories to another object
  8548. *
  8549. * @param int $fromId Id object source
  8550. * @param int $toId Id object cible
  8551. * @param string $type Type of category ('product', ...)
  8552. * @return int < 0 if error, > 0 if ok
  8553. */
  8554. public function cloneCategories($fromId, $toId, $type = '')
  8555. {
  8556. $this->db->begin();
  8557. if (empty($type)) {
  8558. $type = $this->table_element;
  8559. }
  8560. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8561. $categorystatic = new Categorie($this->db);
  8562. $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  8563. $sql .= " SELECT fk_categorie, $toId FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  8564. $sql .= " WHERE fk_product = ".((int) $fromId);
  8565. if (!$this->db->query($sql)) {
  8566. $this->error = $this->db->lasterror();
  8567. $this->db->rollback();
  8568. return -1;
  8569. }
  8570. $this->db->commit();
  8571. return 1;
  8572. }
  8573. /**
  8574. * Delete related files of object in database
  8575. *
  8576. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  8577. * @return bool True if OK, False if KO
  8578. */
  8579. public function deleteEcmFiles($mode = 0)
  8580. {
  8581. global $conf;
  8582. $this->db->begin();
  8583. // Delete in database with mode 0
  8584. if ($mode == 0) {
  8585. switch ($this->element) {
  8586. case 'propal':
  8587. $element = 'propale';
  8588. break;
  8589. case 'product':
  8590. $element = 'produit';
  8591. break;
  8592. case 'order_supplier':
  8593. $element = 'fournisseur/commande';
  8594. break;
  8595. case 'invoice_supplier':
  8596. $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  8597. break;
  8598. case 'shipping':
  8599. $element = 'expedition/sending';
  8600. break;
  8601. default:
  8602. $element = $this->element;
  8603. }
  8604. // Delete ecm_files extrafields
  8605. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files_extrafields WHERE fk_object IN (";
  8606. $sql .= " SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8607. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  8608. $sql .= ")";
  8609. if (!$this->db->query($sql)) {
  8610. $this->error = $this->db->lasterror();
  8611. $this->db->rollback();
  8612. return false;
  8613. }
  8614. // Delete ecm_files
  8615. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files";
  8616. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8617. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  8618. if (!$this->db->query($sql)) {
  8619. $this->error = $this->db->lasterror();
  8620. $this->db->rollback();
  8621. return false;
  8622. }
  8623. }
  8624. // Delete in database with mode 1
  8625. if ($mode == 1) {
  8626. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files_extrafields";
  8627. $sql .= " WHERE fk_object IN (SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id).")";
  8628. $resql = $this->db->query($sql);
  8629. if (!$resql) {
  8630. $this->error = $this->db->lasterror();
  8631. $this->db->rollback();
  8632. return false;
  8633. }
  8634. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files";
  8635. $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
  8636. $resql = $this->db->query($sql);
  8637. if (!$resql) {
  8638. $this->error = $this->db->lasterror();
  8639. $this->db->rollback();
  8640. return false;
  8641. }
  8642. }
  8643. $this->db->commit();
  8644. return true;
  8645. }
  8646. }