commonobject.class.php 324 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557
  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 of table without prefix where object is stored
  77. */
  78. public $table_element;
  79. /**
  80. * @var string Name of subtable line
  81. */
  82. public $table_element_line = '';
  83. /**
  84. * @var string Key value used to track if data is coming from import wizard
  85. */
  86. public $import_key;
  87. /**
  88. * @var mixed Contains data to manage extrafields
  89. */
  90. public $array_options = array();
  91. /**
  92. * @var mixed Array to store alternative languages values of object
  93. */
  94. public $array_languages = null; // Value is array() when load already tried
  95. /**
  96. * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked
  97. */
  98. public $linkedObjectsIds;
  99. /**
  100. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  101. */
  102. public $linkedObjects;
  103. /**
  104. * @var Object To store a cloned copy of object before to edit it and keep track of old properties
  105. */
  106. public $oldcopy;
  107. /**
  108. * @var string Column name of the ref field.
  109. */
  110. protected $table_ref_field = '';
  111. /**
  112. * @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
  113. */
  114. public $restrictiononfksoc = 0;
  115. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  116. /**
  117. * @var array<string,mixed> Can be used to pass information when only object is provided to method
  118. */
  119. public $context = array();
  120. /**
  121. * @var string Contains canvas name if record is an alternative canvas record
  122. */
  123. public $canvas;
  124. /**
  125. * @var Project The related project
  126. * @see fetch_projet()
  127. */
  128. public $project;
  129. /**
  130. * @var int The related project ID
  131. * @see setProject(), project
  132. */
  133. public $fk_project;
  134. /**
  135. * @deprecated
  136. * @see project
  137. */
  138. public $projet;
  139. /**
  140. * @var Contact a related contact
  141. * @see fetch_contact()
  142. */
  143. public $contact;
  144. /**
  145. * @var int The related contact ID
  146. * @see fetch_contact()
  147. */
  148. public $contact_id;
  149. /**
  150. * @var Societe A related thirdparty
  151. * @see fetch_thirdparty()
  152. */
  153. public $thirdparty;
  154. /**
  155. * @var User A related user
  156. * @see fetch_user()
  157. */
  158. public $user;
  159. /**
  160. * @var string The type of originating object ('commande', 'facture', ...)
  161. * @see fetch_origin()
  162. */
  163. public $origin;
  164. /**
  165. * @var int The id of originating object
  166. * @see fetch_origin()
  167. */
  168. public $origin_id;
  169. /**
  170. * @var string The object's reference
  171. */
  172. public $ref;
  173. /**
  174. * @var string An external reference for the object
  175. */
  176. public $ref_ext;
  177. /**
  178. * @var string The object's previous reference
  179. */
  180. public $ref_previous;
  181. /**
  182. * @var string The object's next reference
  183. */
  184. public $ref_next;
  185. /**
  186. * @var string Ref to store on object to save the new ref to use for example when making a validate() of an object
  187. */
  188. public $newref;
  189. /**
  190. * @var int The object's status
  191. * @see setStatut()
  192. */
  193. public $statut;
  194. /**
  195. * @var int The object's status
  196. * @see setStatut()
  197. */
  198. public $status;
  199. /**
  200. * @var string
  201. * @see getFullAddress()
  202. */
  203. public $country;
  204. /**
  205. * @var int
  206. * @see getFullAddress(), country
  207. */
  208. public $country_id;
  209. /**
  210. * @var string
  211. * @see getFullAddress(), isInEEC(), country
  212. */
  213. public $country_code;
  214. /**
  215. * @var string
  216. * @see getFullAddress()
  217. */
  218. public $state;
  219. /**
  220. * @var int
  221. * @see getFullAddress(), state
  222. */
  223. public $state_id;
  224. /**
  225. * @var string
  226. * @see getFullAddress(), $state
  227. */
  228. public $state_code;
  229. /**
  230. * @var int
  231. * @see getFullAddress(), $region_code, $region
  232. */
  233. public $region_id;
  234. /**
  235. * @var string
  236. * @see getFullAddress(), $region_id, $region
  237. */
  238. public $region_code;
  239. /**
  240. * @var string
  241. * @see getFullAddress(), $region_id, $region_code
  242. */
  243. public $region;
  244. /**
  245. * @var int
  246. * @see fetch_barcode()
  247. */
  248. public $barcode_type;
  249. /**
  250. * @var string
  251. * @see fetch_barcode(), barcode_type
  252. */
  253. public $barcode_type_code;
  254. /**
  255. * @var string
  256. * @see fetch_barcode(), barcode_type
  257. */
  258. public $barcode_type_label;
  259. /**
  260. * @var string
  261. * @see fetch_barcode(), barcode_type
  262. */
  263. public $barcode_type_coder;
  264. /**
  265. * @var int Payment method ID (cheque, cash, ...)
  266. * @see setPaymentMethods()
  267. */
  268. public $mode_reglement_id;
  269. /**
  270. * @var int Payment terms ID
  271. * @see setPaymentTerms()
  272. */
  273. public $cond_reglement_id;
  274. /**
  275. * @var int Demand reason ID
  276. */
  277. public $demand_reason_id;
  278. /**
  279. * @var int Transport mode ID (For module intracomm report)
  280. * @see setTransportMode()
  281. */
  282. public $transport_mode_id;
  283. /**
  284. * @var int Payment terms ID
  285. * @deprecated Kept for compatibility
  286. * @see cond_reglement_id;
  287. */
  288. public $cond_reglement;
  289. /**
  290. * @var int Delivery address ID
  291. * @see setDeliveryAddress()
  292. * @deprecated
  293. */
  294. public $fk_delivery_address;
  295. /**
  296. * @var int Shipping method ID
  297. * @see setShippingMethod()
  298. */
  299. public $shipping_method_id;
  300. /**
  301. * @var string
  302. * @see SetDocModel()
  303. */
  304. public $model_pdf;
  305. /**
  306. * @var string
  307. * @deprecated
  308. * @see $model_pdf
  309. */
  310. public $modelpdf;
  311. /**
  312. * @var string
  313. * Contains relative path of last generated main file
  314. */
  315. public $last_main_doc;
  316. /**
  317. * @var int Bank account ID sometimes, ID of record into llx_bank sometimes
  318. * @deprecated
  319. * @see $fk_account
  320. */
  321. public $fk_bank;
  322. /**
  323. * @var int Bank account ID
  324. * @see SetBankAccount()
  325. */
  326. public $fk_account;
  327. /**
  328. * @var string Open ID
  329. */
  330. public $openid;
  331. /**
  332. * @var string Public note
  333. * @see update_note()
  334. */
  335. public $note_public;
  336. /**
  337. * @var string Private note
  338. * @see update_note()
  339. */
  340. public $note_private;
  341. /**
  342. * @deprecated
  343. * @see $note_private
  344. */
  345. public $note;
  346. /**
  347. * @var float Total amount before taxes
  348. * @see update_price()
  349. */
  350. public $total_ht;
  351. /**
  352. * @var float Total VAT amount
  353. * @see update_price()
  354. */
  355. public $total_tva;
  356. /**
  357. * @var float Total local tax 1 amount
  358. * @see update_price()
  359. */
  360. public $total_localtax1;
  361. /**
  362. * @var float Total local tax 2 amount
  363. * @see update_price()
  364. */
  365. public $total_localtax2;
  366. /**
  367. * @var float Total amount with taxes
  368. * @see update_price()
  369. */
  370. public $total_ttc;
  371. /**
  372. * @var CommonObjectLine[]
  373. */
  374. public $lines;
  375. /**
  376. * @var mixed Contains comments
  377. * @see fetchComments()
  378. */
  379. public $comments = array();
  380. /**
  381. * @var string The name
  382. */
  383. public $name;
  384. /**
  385. * @var string The lastname
  386. */
  387. public $lastname;
  388. /**
  389. * @var string The firstname
  390. */
  391. public $firstname;
  392. /**
  393. * @var string The civility code, not an integer
  394. */
  395. public $civility_id;
  396. // Dates
  397. /**
  398. * @var integer|string date_creation
  399. */
  400. public $date_creation;
  401. /**
  402. * @var integer|string $date_validation;
  403. */
  404. public $date_validation; // Date validation
  405. /**
  406. * @var integer|string $date_modification;
  407. */
  408. public $date_modification; // Date last change (tms field)
  409. public $next_prev_filter;
  410. /**
  411. * @var int 1 if object is specimen
  412. */
  413. public $specimen = 0;
  414. /**
  415. * @var int Id of contact to send object (used by the trigger of module Agenda)
  416. */
  417. public $sendtoid;
  418. /**
  419. * @var float Amount already paid (used to show correct status)
  420. */
  421. public $alreadypaid;
  422. /**
  423. * @var array List of child tables. To test if we can delete object.
  424. */
  425. protected $childtables = array();
  426. /**
  427. * @var array List of child tables. To know object to delete on cascade.
  428. * If name is like '@ClassName:FilePathClass:ParentFkFieldName', it will
  429. * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object.
  430. */
  431. protected $childtablesoncascade = array();
  432. // No constructor as it is an abstract class
  433. /**
  434. * Check an object id/ref exists
  435. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  436. *
  437. * @param string $element String of element ('product', 'facture', ...)
  438. * @param int $id Id of object
  439. * @param string $ref Ref of object to check
  440. * @param string $ref_ext Ref ext of object to check
  441. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  442. */
  443. public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
  444. {
  445. global $db, $conf;
  446. $sql = "SELECT rowid, ref, ref_ext";
  447. $sql .= " FROM ".MAIN_DB_PREFIX.$element;
  448. $sql .= " WHERE entity IN (".getEntity($element).")";
  449. if ($id > 0) {
  450. $sql .= " AND rowid = ".((int) $id);
  451. } elseif ($ref) {
  452. $sql .= " AND ref = '".$db->escape($ref)."'";
  453. } elseif ($ref_ext) {
  454. $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
  455. } else {
  456. $error = 'ErrorWrongParameters';
  457. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  458. return -1;
  459. }
  460. if ($ref || $ref_ext) {
  461. $sql .= " AND entity = ".((int) $conf->entity);
  462. }
  463. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  464. $resql = $db->query($sql);
  465. if ($resql) {
  466. $num = $db->num_rows($resql);
  467. if ($num > 0) {
  468. return 1;
  469. } else {
  470. return 0;
  471. }
  472. }
  473. return -1;
  474. }
  475. /**
  476. * Method to output saved errors
  477. *
  478. * @return string String with errors
  479. */
  480. public function errorsToString()
  481. {
  482. return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
  483. }
  484. /**
  485. * Return customer ref for screen output.
  486. *
  487. * @param string $objref Customer ref
  488. * @return string Customer ref formated
  489. */
  490. public function getFormatedCustomerRef($objref)
  491. {
  492. global $hookmanager;
  493. $parameters = array('objref'=>$objref);
  494. $action = '';
  495. $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  496. if ($reshook > 0) {
  497. return $hookmanager->resArray['objref'];
  498. }
  499. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  500. }
  501. /**
  502. * Return supplier ref for screen output.
  503. *
  504. * @param string $objref Supplier ref
  505. * @return string Supplier ref formated
  506. */
  507. public function getFormatedSupplierRef($objref)
  508. {
  509. global $hookmanager;
  510. $parameters = array('objref'=>$objref);
  511. $action = '';
  512. $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  513. if ($reshook > 0) {
  514. return $hookmanager->resArray['objref'];
  515. }
  516. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  517. }
  518. /**
  519. * Return full name (civility+' '+name+' '+lastname)
  520. *
  521. * @param Translate $langs Language object for translation of civility (used only if option is 1)
  522. * @param int $option 0=No option, 1=Add civility
  523. * @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
  524. * @param int $maxlen Maximum length
  525. * @return string String with full name
  526. */
  527. public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
  528. {
  529. //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
  530. $lastname = $this->lastname;
  531. $firstname = $this->firstname;
  532. if (empty($lastname)) {
  533. $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 : '')))));
  534. }
  535. $ret = '';
  536. if (!empty($option) && !empty($this->civility_code)) {
  537. if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) {
  538. $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
  539. } else {
  540. $ret .= $this->civility_code.' ';
  541. }
  542. }
  543. $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
  544. return dol_trunc($ret, $maxlen);
  545. }
  546. /**
  547. * Set to upper or ucwords/lower if needed
  548. *
  549. * @return void;
  550. */
  551. public function setUpperOrLowerCase()
  552. {
  553. global $conf;
  554. if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
  555. $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
  556. $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
  557. $this->name = dol_ucwords(dol_strtolower($this->name));
  558. $this->name_alias = dol_ucwords(dol_strtolower($this->name_alias));
  559. }
  560. if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
  561. $this->lastname = dol_strtoupper($this->lastname);
  562. $this->name = dol_strtoupper($this->name);
  563. $this->name_alias = dol_strtoupper($this->name_alias);
  564. }
  565. if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
  566. $this->address = dol_strtoupper($this->address);
  567. $this->town = dol_strtoupper($this->town);
  568. }
  569. }
  570. /**
  571. * Return clicable link of object (with eventually picto)
  572. *
  573. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  574. * @return string HTML Code for Kanban thumb.
  575. */
  576. public function getKanbanView($option = '')
  577. {
  578. $return = '<div class="box-flex-item">';
  579. $return .= '<div class="info-box info-box-sm">';
  580. $return .= '<span class="info-box-icon bg-infobox-action">';
  581. $return .= '<i class="fa fa-dol-action"></i>'; // Can be image
  582. $return .= '</span>';
  583. $return .= '<div class="info-box-content">';
  584. $return .= '<span class="info-box-title">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  585. $return .= '</div>';
  586. $return .= '</div>';
  587. $return .= '</div>';
  588. return $return;
  589. }
  590. /**
  591. * Return full address of contact
  592. *
  593. * @param int $withcountry 1=Add country into address string
  594. * @param string $sep Separator to use to build string
  595. * @param int $withregion 1=Add region into address string
  596. * @param string $extralangcode User extralanguages as value
  597. * @return string Full address string
  598. */
  599. public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
  600. {
  601. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
  602. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  603. $tmparray = getCountry($this->country_id, 'all');
  604. $this->country_code = $tmparray['code'];
  605. $this->country = $tmparray['label'];
  606. }
  607. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
  608. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  609. $tmparray = getState($this->state_id, 'all', 0, 1);
  610. $this->state_code = $tmparray['code'];
  611. $this->state = $tmparray['label'];
  612. $this->region_code = $tmparray['region_code'];
  613. $this->region = $tmparray['region'];
  614. }
  615. return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
  616. }
  617. /**
  618. * Return full address for banner
  619. *
  620. * @param string $htmlkey HTML id to make banner content unique
  621. * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member)
  622. * @return string Full address string
  623. */
  624. public function getBannerAddress($htmlkey, $object)
  625. {
  626. global $conf, $langs, $form, $extralanguages;
  627. $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
  628. $contactid = 0;
  629. $thirdpartyid = 0;
  630. $elementforaltlanguage = $this->element;
  631. if ($this->element == 'societe') {
  632. $thirdpartyid = $this->id;
  633. }
  634. if ($this->element == 'contact') {
  635. $contactid = $this->id;
  636. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  637. }
  638. if ($this->element == 'user') {
  639. $contactid = $this->contact_id;
  640. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  641. }
  642. $out = '';
  643. $outdone = 0;
  644. $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
  645. if ($coords) {
  646. if (!empty($conf->use_javascript_ajax)) {
  647. // Add picto with tooltip on map
  648. $namecoords = '';
  649. if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
  650. $namecoords .= $object->name.'<br>';
  651. }
  652. $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
  653. // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
  654. $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
  655. $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
  656. $out .= '</a> ';
  657. }
  658. $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  659. $outdone++;
  660. $outdone++;
  661. // List of extra languages
  662. $arrayoflangcode = array();
  663. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  664. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  665. }
  666. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  667. if (!is_object($extralanguages)) {
  668. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  669. $extralanguages = new ExtraLanguages($this->db);
  670. }
  671. $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
  672. if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
  673. $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
  674. $this->fetchValuesForExtraLanguages();
  675. if (!is_object($form)) {
  676. $form = new Form($this->db);
  677. }
  678. $htmltext = '';
  679. // If there is extra languages
  680. foreach ($arrayoflangcode as $extralangcode) {
  681. $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  682. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
  683. $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  684. }
  685. $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  686. }
  687. }
  688. }
  689. 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
  690. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
  691. if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
  692. $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
  693. } else {
  694. $out .= ($outdone ? ' - ' : '').$this->state;
  695. }
  696. $outdone++;
  697. }
  698. 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)) {
  699. $out .= ($outdone ? '<br>' : '');
  700. }
  701. if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  702. $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  703. $outdone++;
  704. }
  705. if (!empty($this->phone_pro)) {
  706. $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  707. $outdone++;
  708. }
  709. if (!empty($this->phone_mobile)) {
  710. $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  711. $outdone++;
  712. }
  713. if (!empty($this->phone_perso)) {
  714. $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
  715. $outdone++;
  716. }
  717. if (!empty($this->office_phone)) {
  718. $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  719. $outdone++;
  720. }
  721. if (!empty($this->user_mobile)) {
  722. $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  723. $outdone++;
  724. }
  725. if (!empty($this->fax)) {
  726. $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  727. $outdone++;
  728. }
  729. if (!empty($this->office_fax)) {
  730. $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  731. $outdone++;
  732. }
  733. if ($out) {
  734. $out .= '<div style="clear: both;"></div>';
  735. }
  736. $outdone = 0;
  737. if (!empty($this->email)) {
  738. $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
  739. $outdone++;
  740. }
  741. if (!empty($this->url)) {
  742. //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
  743. $out .= dol_print_url($this->url, '_blank', 0, 1);
  744. $outdone++;
  745. }
  746. if (!empty($conf->socialnetworks->enabled)) {
  747. $outsocialnetwork = '';
  748. if (!empty($this->socialnetworks) && is_countable($this->socialnetworks) && count($this->socialnetworks) > 0) {
  749. $socialnetworksdict = getArrayOfSocialNetworks();
  750. foreach ($this->socialnetworks as $key => $value) {
  751. if ($value) {
  752. $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
  753. }
  754. $outdone++;
  755. }
  756. } else { // Old code to remove
  757. if (!empty($this->skype)) {
  758. $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
  759. }
  760. $outdone++;
  761. if (!empty($this->jabberid)) {
  762. $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
  763. }
  764. $outdone++;
  765. if (!empty($this->twitter)) {
  766. $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
  767. }
  768. $outdone++;
  769. if (!empty($this->facebook)) {
  770. $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
  771. }
  772. $outdone++;
  773. if (!empty($this->linkedin)) {
  774. $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
  775. }
  776. $outdone++;
  777. }
  778. if ($outsocialnetwork) {
  779. $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
  780. }
  781. }
  782. if ($out) {
  783. return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
  784. } else {
  785. return '';
  786. }
  787. }
  788. /**
  789. * Return the link of last main doc file for direct public download.
  790. *
  791. * @param string $modulepart Module related to document
  792. * @param int $initsharekey Init the share key if it was not yet defined
  793. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  794. * @return string Link or empty string if there is no download link
  795. */
  796. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  797. {
  798. global $user, $dolibarr_main_url_root;
  799. if (empty($this->last_main_doc)) {
  800. return ''; // No way to known which document name to use
  801. }
  802. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  803. $ecmfile = new EcmFiles($this->db);
  804. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  805. if ($result < 0) {
  806. $this->error = $ecmfile->error;
  807. $this->errors = $ecmfile->errors;
  808. return -1;
  809. }
  810. if (empty($ecmfile->id)) {
  811. // Add entry into index
  812. if ($initsharekey) {
  813. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  814. // TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first
  815. /*
  816. $ecmfile->filepath = $rel_dir;
  817. $ecmfile->filename = $filename;
  818. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  819. $ecmfile->fullpath_orig = '';
  820. $ecmfile->gen_or_uploaded = 'generated';
  821. $ecmfile->description = ''; // indexed content
  822. $ecmfile->keywords = ''; // keyword content
  823. $ecmfile->share = getRandomPassword(true);
  824. $result = $ecmfile->create($user);
  825. if ($result < 0)
  826. {
  827. $this->error = $ecmfile->error;
  828. $this->errors = $ecmfile->errors;
  829. }
  830. */
  831. } else {
  832. return '';
  833. }
  834. } elseif (empty($ecmfile->share)) {
  835. // Add entry into index
  836. if ($initsharekey) {
  837. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  838. $ecmfile->share = getRandomPassword(true);
  839. $ecmfile->update($user);
  840. } else {
  841. return '';
  842. }
  843. }
  844. // Define $urlwithroot
  845. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  846. // This is to use external domain name found into config file
  847. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  848. //else
  849. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  850. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  851. $forcedownload = 0;
  852. $paramlink = '';
  853. //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  854. //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  855. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  856. if (!empty($ecmfile->share)) {
  857. $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
  858. }
  859. if ($forcedownload) {
  860. $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  861. }
  862. if ($relativelink) {
  863. $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
  864. } else {
  865. $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  866. }
  867. // Here $ecmfile->share is defined
  868. return $linktoreturn;
  869. }
  870. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  871. /**
  872. * Add a link between element $this->element and a contact
  873. *
  874. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  875. * @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
  876. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  877. * @param int $notrigger Disable all triggers
  878. * @return int <0 if KO, 0 if already added, >0 if OK
  879. */
  880. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  881. {
  882. // phpcs:enable
  883. global $user, $langs;
  884. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  885. // Check parameters
  886. if ($fk_socpeople <= 0) {
  887. $langs->load("errors");
  888. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  889. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  890. return -1;
  891. }
  892. if (!$type_contact) {
  893. $langs->load("errors");
  894. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  895. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  896. return -2;
  897. }
  898. $id_type_contact = 0;
  899. if (is_numeric($type_contact)) {
  900. $id_type_contact = $type_contact;
  901. } else {
  902. // We look for id type_contact
  903. $sql = "SELECT tc.rowid";
  904. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  905. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  906. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  907. $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  908. //print $sql;
  909. $resql = $this->db->query($sql);
  910. if ($resql) {
  911. $obj = $this->db->fetch_object($resql);
  912. if ($obj) {
  913. $id_type_contact = $obj->rowid;
  914. }
  915. }
  916. }
  917. if ($id_type_contact == 0) {
  918. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  919. 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");
  920. return -3;
  921. }
  922. $datecreate = dol_now();
  923. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  924. $TListeContacts = $this->liste_contact(-1, $source);
  925. $already_added = false;
  926. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  927. foreach ($TListeContacts as $array_contact) {
  928. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  929. $already_added = true;
  930. break;
  931. }
  932. }
  933. }
  934. if (!$already_added) {
  935. $this->db->begin();
  936. // Insert into database
  937. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact";
  938. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  939. $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
  940. $sql .= "'".$this->db->idate($datecreate)."'";
  941. $sql .= ", 4, ".((int) $id_type_contact);
  942. $sql .= ")";
  943. $resql = $this->db->query($sql);
  944. if ($resql) {
  945. if (!$notrigger) {
  946. $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  947. if ($result < 0) {
  948. $this->db->rollback();
  949. return -1;
  950. }
  951. }
  952. $this->db->commit();
  953. return 1;
  954. } else {
  955. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  956. $this->error = $this->db->errno();
  957. $this->db->rollback();
  958. return -2;
  959. } else {
  960. $this->error = $this->db->lasterror();
  961. $this->db->rollback();
  962. return -1;
  963. }
  964. }
  965. } else {
  966. return 0;
  967. }
  968. }
  969. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  970. /**
  971. * Copy contact from one element to current
  972. *
  973. * @param CommonObject $objFrom Source element
  974. * @param string $source Nature of contact ('internal' or 'external')
  975. * @return int >0 if OK, <0 if KO
  976. */
  977. public function copy_linked_contact($objFrom, $source = 'internal')
  978. {
  979. // phpcs:enable
  980. $contacts = $objFrom->liste_contact(-1, $source);
  981. foreach ($contacts as $contact) {
  982. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
  983. return -1;
  984. }
  985. }
  986. return 1;
  987. }
  988. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  989. /**
  990. * Update a link to contact line
  991. *
  992. * @param int $rowid Id of line contact-element
  993. * @param int $statut New status of link
  994. * @param int $type_contact_id Id of contact type (not modified if 0)
  995. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  996. * @return int <0 if KO, >= 0 if OK
  997. */
  998. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  999. {
  1000. // phpcs:enable
  1001. // Insert into database
  1002. $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set";
  1003. $sql .= " statut = ".$statut;
  1004. if ($type_contact_id) {
  1005. $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
  1006. }
  1007. if ($fk_socpeople) {
  1008. $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
  1009. }
  1010. $sql .= " where rowid = ".((int) $rowid);
  1011. $resql = $this->db->query($sql);
  1012. if ($resql) {
  1013. return 0;
  1014. } else {
  1015. $this->error = $this->db->lasterror();
  1016. return -1;
  1017. }
  1018. }
  1019. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1020. /**
  1021. * Delete a link to contact line
  1022. *
  1023. * @param int $rowid Id of contact link line to delete
  1024. * @param int $notrigger Disable all triggers
  1025. * @return int >0 if OK, <0 if KO
  1026. */
  1027. public function delete_contact($rowid, $notrigger = 0)
  1028. {
  1029. // phpcs:enable
  1030. global $user;
  1031. $this->db->begin();
  1032. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  1033. $sql .= " WHERE rowid = ".((int) $rowid);
  1034. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  1035. if ($this->db->query($sql)) {
  1036. if (!$notrigger) {
  1037. $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  1038. if ($result < 0) {
  1039. $this->db->rollback();
  1040. return -1;
  1041. }
  1042. }
  1043. $this->db->commit();
  1044. return 1;
  1045. } else {
  1046. $this->error = $this->db->lasterror();
  1047. $this->db->rollback();
  1048. return -1;
  1049. }
  1050. }
  1051. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1052. /**
  1053. * Delete all links between an object $this and all its contacts
  1054. *
  1055. * @param string $source '' or 'internal' or 'external'
  1056. * @param string $code Type of contact (code or id)
  1057. * @return int >0 if OK, <0 if KO
  1058. */
  1059. public function delete_linked_contact($source = '', $code = '')
  1060. {
  1061. // phpcs:enable
  1062. $temp = array();
  1063. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  1064. foreach ($typeContact as $key => $value) {
  1065. array_push($temp, $key);
  1066. }
  1067. $listId = implode(",", $temp);
  1068. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  1069. $sql .= " WHERE element_id = ".$this->id;
  1070. if ($listId) {
  1071. $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
  1072. }
  1073. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  1074. if ($this->db->query($sql)) {
  1075. return 1;
  1076. } else {
  1077. $this->error = $this->db->lasterror();
  1078. return -1;
  1079. }
  1080. }
  1081. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1082. /**
  1083. * Get array of all contacts for an object
  1084. *
  1085. * @param int $status Status of links to get (-1=all)
  1086. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  1087. * @param int $list 0:Return array contains all properties, 1:Return array contains just id
  1088. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1089. * @return array|int Array of contacts, -1 if error
  1090. */
  1091. public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
  1092. {
  1093. // phpcs:enable
  1094. global $langs;
  1095. $tab = array();
  1096. $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
  1097. if ($source == 'internal') {
  1098. $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  1099. }
  1100. if ($source == 'external' || $source == 'thirdparty') {
  1101. $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1102. }
  1103. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  1104. $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
  1105. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
  1106. $sql .= ", ".MAIN_DB_PREFIX."element_contact ec";
  1107. if ($source == 'internal') {
  1108. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
  1109. }
  1110. if ($source == 'external' || $source == 'thirdparty') {
  1111. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
  1112. }
  1113. $sql .= " WHERE ec.element_id =".$this->id;
  1114. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1115. $sql .= " AND tc.element='".$this->db->escape($this->element)."'";
  1116. if ($code) {
  1117. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1118. }
  1119. if ($source == 'internal') {
  1120. $sql .= " AND tc.source = 'internal'";
  1121. }
  1122. if ($source == 'external' || $source == 'thirdparty') {
  1123. $sql .= " AND tc.source = 'external'";
  1124. }
  1125. $sql .= " AND tc.active=1";
  1126. if ($status >= 0) {
  1127. $sql .= " AND ec.statut = ".((int) $status);
  1128. }
  1129. $sql .= " ORDER BY t.lastname ASC";
  1130. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  1131. $resql = $this->db->query($sql);
  1132. if ($resql) {
  1133. $num = $this->db->num_rows($resql);
  1134. $i = 0;
  1135. while ($i < $num) {
  1136. $obj = $this->db->fetch_object($resql);
  1137. if (!$list) {
  1138. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1139. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1140. $tab[$i] = array(
  1141. 'source' => $obj->source,
  1142. 'socid' => $obj->socid,
  1143. 'id' => $obj->id,
  1144. 'nom' => $obj->lastname, // For backward compatibility
  1145. 'civility' => $obj->civility,
  1146. 'lastname' => $obj->lastname,
  1147. 'firstname' => $obj->firstname,
  1148. 'email'=>$obj->email,
  1149. 'login'=> (empty($obj->login) ? '' : $obj->login),
  1150. 'photo' => (empty($obj->photo) ? '' : $obj->photo),
  1151. 'statuscontact' => $obj->statuscontact,
  1152. 'rowid' => $obj->rowid,
  1153. 'code' => $obj->code,
  1154. 'libelle' => $libelle_type,
  1155. 'status' => $obj->statuslink,
  1156. 'fk_c_type_contact' => $obj->fk_c_type_contact
  1157. );
  1158. } else {
  1159. $tab[$i] = $obj->id;
  1160. }
  1161. $i++;
  1162. }
  1163. return $tab;
  1164. } else {
  1165. $this->error = $this->db->lasterror();
  1166. dol_print_error($this->db);
  1167. return -1;
  1168. }
  1169. }
  1170. /**
  1171. * Update status of a contact linked to object
  1172. *
  1173. * @param int $rowid Id of link between object and contact
  1174. * @return int <0 if KO, >=0 if OK
  1175. */
  1176. public function swapContactStatus($rowid)
  1177. {
  1178. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1179. $sql .= " tc.code, tc.libelle";
  1180. $sql .= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)";
  1181. $sql .= " WHERE ec.rowid =".((int) $rowid);
  1182. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1183. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1184. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  1185. $resql = $this->db->query($sql);
  1186. if ($resql) {
  1187. $obj = $this->db->fetch_object($resql);
  1188. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1189. $result = $this->update_contact($rowid, $newstatut);
  1190. $this->db->free($resql);
  1191. return $result;
  1192. } else {
  1193. $this->error = $this->db->error();
  1194. dol_print_error($this->db);
  1195. return -1;
  1196. }
  1197. }
  1198. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1199. /**
  1200. * Return array with list of possible values for type of contacts
  1201. *
  1202. * @param string $source 'internal', 'external' or 'all'
  1203. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  1204. * @param int $option 0=Return array id->label, 1=Return array code->label
  1205. * @param int $activeonly 0=all status of contact, 1=only the active
  1206. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1207. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1208. */
  1209. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1210. {
  1211. // phpcs:enable
  1212. global $langs;
  1213. if (empty($order)) {
  1214. $order = 'position';
  1215. }
  1216. if ($order == 'position') {
  1217. $order .= ',code';
  1218. }
  1219. $tab = array();
  1220. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  1221. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  1222. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1223. if ($activeonly == 1) {
  1224. $sql .= " AND tc.active=1"; // only the active types
  1225. }
  1226. if (!empty($source) && $source != 'all') {
  1227. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1228. }
  1229. if (!empty($code)) {
  1230. $sql .= " AND tc.code='".$this->db->escape($code)."'";
  1231. }
  1232. $sql .= $this->db->order($order, 'ASC');
  1233. //print "sql=".$sql;
  1234. $resql = $this->db->query($sql);
  1235. if ($resql) {
  1236. $num = $this->db->num_rows($resql);
  1237. $i = 0;
  1238. while ($i < $num) {
  1239. $obj = $this->db->fetch_object($resql);
  1240. $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
  1241. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1242. if (empty($option)) {
  1243. $tab[$obj->rowid] = $libelle_type;
  1244. } else {
  1245. $tab[$obj->code] = $libelle_type;
  1246. }
  1247. $i++;
  1248. }
  1249. return $tab;
  1250. } else {
  1251. $this->error = $this->db->lasterror();
  1252. //dol_print_error($this->db);
  1253. return null;
  1254. }
  1255. }
  1256. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1257. /**
  1258. * Return array with list of possible values for type of contacts
  1259. *
  1260. * @param string $source 'internal', 'external' or 'all'
  1261. * @param int $option 0=Return array id->label, 1=Return array code->label
  1262. * @param int $activeonly 0=all status of contact, 1=only the active
  1263. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1264. * @param string $element Filter on 1 element type
  1265. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1266. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1267. */
  1268. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1269. {
  1270. // phpcs:enable
  1271. global $langs, $conf;
  1272. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1273. $tab = array();
  1274. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
  1275. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  1276. $sqlWhere = array();
  1277. if (!empty($element)) {
  1278. $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
  1279. }
  1280. if (!empty($excludeelement)) {
  1281. $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
  1282. }
  1283. if ($activeonly == 1) {
  1284. $sqlWhere[] = " tc.active=1"; // only the active types
  1285. }
  1286. if (!empty($source) && $source != 'all') {
  1287. $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
  1288. }
  1289. if (!empty($code)) {
  1290. $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
  1291. }
  1292. if (count($sqlWhere) > 0) {
  1293. $sql .= " WHERE ".implode(' AND ', $sqlWhere);
  1294. }
  1295. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1296. dol_syslog(__METHOD__, LOG_DEBUG);
  1297. $resql = $this->db->query($sql);
  1298. if ($resql) {
  1299. $num = $this->db->num_rows($resql);
  1300. if ($num > 0) {
  1301. $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
  1302. while ($obj = $this->db->fetch_object($resql)) {
  1303. $modulename = $obj->element;
  1304. if (strpos($obj->element, 'project') !== false) {
  1305. $modulename = 'projet';
  1306. } elseif ($obj->element == 'contrat') {
  1307. $element = 'contract';
  1308. } elseif ($obj->element == 'action') {
  1309. $modulename = 'agenda';
  1310. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1311. $modulename = 'fournisseur';
  1312. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1313. $modulename = 'fournisseur';
  1314. }
  1315. if (!empty($conf->{$modulename}->enabled)) {
  1316. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1317. $tmpelement = $obj->element;
  1318. $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
  1319. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1320. if (empty($option)) {
  1321. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1322. } else {
  1323. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1324. }
  1325. }
  1326. }
  1327. }
  1328. return $tab;
  1329. } else {
  1330. $this->error = $this->db->lasterror();
  1331. return null;
  1332. }
  1333. }
  1334. /**
  1335. * Return id of contacts for a source and a contact code.
  1336. * Example: contact client de facturation ('external', 'BILLING')
  1337. * Example: contact client de livraison ('external', 'SHIPPING')
  1338. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1339. *
  1340. * @param string $source 'external' or 'internal'
  1341. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1342. * @param int $status limited to a certain status
  1343. * @return array List of id for such contacts
  1344. */
  1345. public function getIdContact($source, $code, $status = 0)
  1346. {
  1347. global $conf;
  1348. $result = array();
  1349. $i = 0;
  1350. //cas particulier pour les expeditions
  1351. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1352. $id = $this->origin_id;
  1353. $element = 'commande';
  1354. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1355. $id = $this->origin_id;
  1356. $element = 'order_supplier';
  1357. } else {
  1358. $id = $this->id;
  1359. $element = $this->element;
  1360. }
  1361. $sql = "SELECT ec.fk_socpeople";
  1362. $sql .= " FROM ".MAIN_DB_PREFIX."element_contact as ec,";
  1363. if ($source == 'internal') {
  1364. $sql .= " ".MAIN_DB_PREFIX."user as c,";
  1365. }
  1366. if ($source == 'external') {
  1367. $sql .= " ".MAIN_DB_PREFIX."socpeople as c,";
  1368. }
  1369. $sql .= " ".MAIN_DB_PREFIX."c_type_contact as tc";
  1370. $sql .= " WHERE ec.element_id = ".((int) $id);
  1371. $sql .= " AND ec.fk_socpeople = c.rowid";
  1372. if ($source == 'internal') {
  1373. $sql .= " AND c.entity IN (".getEntity('user').")";
  1374. }
  1375. if ($source == 'external') {
  1376. $sql .= " AND c.entity IN (".getEntity('societe').")";
  1377. }
  1378. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1379. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1380. $sql .= " AND tc.source = '".$this->db->escape($source)."'";
  1381. if ($code) {
  1382. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1383. }
  1384. $sql .= " AND tc.active = 1";
  1385. if ($status) {
  1386. $sql .= " AND ec.statut = ".((int) $status);
  1387. }
  1388. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1389. $resql = $this->db->query($sql);
  1390. if ($resql) {
  1391. while ($obj = $this->db->fetch_object($resql)) {
  1392. $result[$i] = $obj->fk_socpeople;
  1393. $i++;
  1394. }
  1395. } else {
  1396. $this->error = $this->db->error();
  1397. return null;
  1398. }
  1399. return $result;
  1400. }
  1401. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1402. /**
  1403. * Load object contact with id=$this->contact_id into $this->contact
  1404. *
  1405. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1406. * @return int <0 if KO, >0 if OK
  1407. */
  1408. public function fetch_contact($contactid = null)
  1409. {
  1410. // phpcs:enable
  1411. if (empty($contactid)) {
  1412. $contactid = $this->contact_id;
  1413. }
  1414. if (empty($contactid)) {
  1415. return 0;
  1416. }
  1417. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1418. $contact = new Contact($this->db);
  1419. $result = $contact->fetch($contactid);
  1420. $this->contact = $contact;
  1421. return $result;
  1422. }
  1423. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1424. /**
  1425. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1426. *
  1427. * @param int $force_thirdparty_id Force thirdparty id
  1428. * @return int <0 if KO, >0 if OK
  1429. */
  1430. public function fetch_thirdparty($force_thirdparty_id = 0)
  1431. {
  1432. // phpcs:enable
  1433. global $conf;
  1434. if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) {
  1435. return 0;
  1436. }
  1437. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1438. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
  1439. if ($force_thirdparty_id) {
  1440. $idtofetch = $force_thirdparty_id;
  1441. }
  1442. if ($idtofetch) {
  1443. $thirdparty = new Societe($this->db);
  1444. $result = $thirdparty->fetch($idtofetch);
  1445. if ($result<0) {
  1446. $this->errors=array_merge($this->errors, $thirdparty->errors);
  1447. }
  1448. $this->thirdparty = $thirdparty;
  1449. // Use first price level if level not defined for third party
  1450. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1451. $this->thirdparty->price_level = 1;
  1452. }
  1453. return $result;
  1454. } else {
  1455. return -1;
  1456. }
  1457. }
  1458. /**
  1459. * Looks for an object with ref matching the wildcard provided
  1460. * It does only work when $this->table_ref_field is set
  1461. *
  1462. * @param string $ref Wildcard
  1463. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1464. */
  1465. public function fetchOneLike($ref)
  1466. {
  1467. if (!$this->table_ref_field) {
  1468. return 0;
  1469. }
  1470. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE '.$this->table_ref_field.' LIKE "'.$this->db->escape($ref).'" LIMIT 1';
  1471. $query = $this->db->query($sql);
  1472. if (!$this->db->num_rows($query)) {
  1473. return 0;
  1474. }
  1475. $result = $this->db->fetch_object($query);
  1476. return $this->fetch($result->rowid);
  1477. }
  1478. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1479. /**
  1480. * Load data for barcode into properties ->barcode_type*
  1481. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1482. * if it is not defined, ->element must be defined to know default barcode type.
  1483. *
  1484. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1485. */
  1486. public function fetch_barcode()
  1487. {
  1488. // phpcs:enable
  1489. global $conf;
  1490. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1491. $idtype = $this->barcode_type;
  1492. 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
  1493. if ($this->element == 'product') {
  1494. $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1495. } elseif ($this->element == 'societe') {
  1496. $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1497. } else {
  1498. dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1499. }
  1500. }
  1501. if ($idtype > 0) {
  1502. 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
  1503. $sql = "SELECT rowid, code, libelle as label, coder";
  1504. $sql .= " FROM ".MAIN_DB_PREFIX."c_barcode_type";
  1505. $sql .= " WHERE rowid = ".((int) $idtype);
  1506. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1507. $resql = $this->db->query($sql);
  1508. if ($resql) {
  1509. $obj = $this->db->fetch_object($resql);
  1510. $this->barcode_type = $obj->rowid;
  1511. $this->barcode_type_code = $obj->code;
  1512. $this->barcode_type_label = $obj->label;
  1513. $this->barcode_type_coder = $obj->coder;
  1514. return 1;
  1515. } else {
  1516. dol_print_error($this->db);
  1517. return -1;
  1518. }
  1519. }
  1520. }
  1521. return 0;
  1522. }
  1523. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1524. /**
  1525. * Load the project with id $this->fk_project into this->project
  1526. *
  1527. * @return int <0 if KO, >=0 if OK
  1528. */
  1529. public function fetch_projet()
  1530. {
  1531. // phpcs:enable
  1532. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1533. if (empty($this->fk_project) && !empty($this->fk_projet)) {
  1534. $this->fk_project = $this->fk_projet; // For backward compatibility
  1535. }
  1536. if (empty($this->fk_project)) {
  1537. return 0;
  1538. }
  1539. $project = new Project($this->db);
  1540. $result = $project->fetch($this->fk_project);
  1541. $this->projet = $project; // deprecated
  1542. $this->project = $project;
  1543. return $result;
  1544. }
  1545. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1546. /**
  1547. * Load the product with id $this->fk_product into this->product
  1548. *
  1549. * @return int <0 if KO, >=0 if OK
  1550. */
  1551. public function fetch_product()
  1552. {
  1553. // phpcs:enable
  1554. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1555. if (empty($this->fk_product)) {
  1556. return 0;
  1557. }
  1558. $product = new Product($this->db);
  1559. $result = $product->fetch($this->fk_product);
  1560. $this->product = $product;
  1561. return $result;
  1562. }
  1563. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1564. /**
  1565. * Load the user with id $userid into this->user
  1566. *
  1567. * @param int $userid Id du contact
  1568. * @return int <0 if KO, >0 if OK
  1569. */
  1570. public function fetch_user($userid)
  1571. {
  1572. // phpcs:enable
  1573. $user = new User($this->db);
  1574. $result = $user->fetch($userid);
  1575. $this->user = $user;
  1576. return $result;
  1577. }
  1578. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1579. /**
  1580. * Read linked origin object
  1581. *
  1582. * @return void
  1583. */
  1584. public function fetch_origin()
  1585. {
  1586. // phpcs:enable
  1587. if ($this->origin == 'shipping') {
  1588. $this->origin = 'expedition';
  1589. }
  1590. if ($this->origin == 'delivery') {
  1591. $this->origin = 'livraison';
  1592. }
  1593. if ($this->origin == 'order_supplier') {
  1594. $this->origin = 'commandeFournisseur';
  1595. }
  1596. $origin = $this->origin;
  1597. $classname = ucfirst($origin);
  1598. $this->$origin = new $classname($this->db);
  1599. $this->$origin->fetch($this->origin_id);
  1600. }
  1601. /**
  1602. * Load object from specific field
  1603. *
  1604. * @param string $table Table element or element line
  1605. * @param string $field Field selected
  1606. * @param string $key Import key
  1607. * @param string $element Element name
  1608. * @return int <0 if KO, >0 if OK
  1609. */
  1610. public function fetchObjectFrom($table, $field, $key, $element = null)
  1611. {
  1612. global $conf;
  1613. $result = false;
  1614. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$table;
  1615. $sql .= " WHERE ".$field." = '".$key."'";
  1616. if (!empty($element)) {
  1617. $sql .= " AND entity IN (".getEntity($element).")";
  1618. } else {
  1619. $sql .= " AND entity = ".$conf->entity;
  1620. }
  1621. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1622. $resql = $this->db->query($sql);
  1623. if ($resql) {
  1624. $row = $this->db->fetch_row($resql);
  1625. // Test for avoid error -1
  1626. if ($row[0] > 0) {
  1627. $result = $this->fetch($row[0]);
  1628. }
  1629. }
  1630. return $result;
  1631. }
  1632. /**
  1633. * Getter generic. Load value from a specific field
  1634. *
  1635. * @param string $table Table of element or element line
  1636. * @param int $id Element id
  1637. * @param string $field Field selected
  1638. * @return int <0 if KO, >0 if OK
  1639. */
  1640. public function getValueFrom($table, $id, $field)
  1641. {
  1642. $result = false;
  1643. if (!empty($id) && !empty($field) && !empty($table)) {
  1644. $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table;
  1645. $sql .= " WHERE rowid = ".((int) $id);
  1646. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1647. $resql = $this->db->query($sql);
  1648. if ($resql) {
  1649. $row = $this->db->fetch_row($resql);
  1650. $result = $row[0];
  1651. }
  1652. }
  1653. return $result;
  1654. }
  1655. /**
  1656. * Setter generic. Update a specific field into database.
  1657. * Warning: Trigger is run only if param trigkey is provided.
  1658. *
  1659. * @param string $field Field to update
  1660. * @param mixed $value New value
  1661. * @param string $table To force other table element or element line (should not be used)
  1662. * @param int $id To force other object id (should not be used)
  1663. * @param string $format Data format ('text', 'date'). 'text' is used if not defined
  1664. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1665. * @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'
  1666. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1667. * @param string $fk_user_field Name of field to save user id making change
  1668. * @return int <0 if KO, >0 if OK
  1669. * @see updateExtraField()
  1670. */
  1671. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1672. {
  1673. global $user, $langs, $conf;
  1674. if (empty($table)) {
  1675. $table = $this->table_element;
  1676. }
  1677. if (empty($id)) {
  1678. $id = $this->id;
  1679. }
  1680. if (empty($format)) {
  1681. $format = 'text';
  1682. }
  1683. if (empty($id_field)) {
  1684. $id_field = 'rowid';
  1685. }
  1686. $error = 0;
  1687. $this->db->begin();
  1688. // Special case
  1689. if ($table == 'product' && $field == 'note_private') {
  1690. $field = 'note';
  1691. }
  1692. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  1693. $fk_user_field = 'fk_user_mod';
  1694. }
  1695. $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
  1696. if ($format == 'text') {
  1697. $sql .= $field." = '".$this->db->escape($value)."'";
  1698. } elseif ($format == 'int') {
  1699. $sql .= $field." = ".((int) $value);
  1700. } elseif ($format == 'date') {
  1701. $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1702. }
  1703. if ($fk_user_field) {
  1704. if (!empty($fuser) && is_object($fuser)) {
  1705. $sql .= ", ".$fk_user_field." = ".$fuser->id;
  1706. } elseif (empty($fuser) || $fuser != 'none') {
  1707. $sql .= ", ".$fk_user_field." = ".$user->id;
  1708. }
  1709. }
  1710. $sql .= " WHERE ".$id_field." = ".((int) $id);
  1711. dol_syslog(__METHOD__."", LOG_DEBUG);
  1712. $resql = $this->db->query($sql);
  1713. if ($resql) {
  1714. if ($trigkey) {
  1715. // call trigger with updated object values
  1716. if (empty($this->fields) && method_exists($this, 'fetch')) {
  1717. $result = $this->fetch($id);
  1718. } else {
  1719. $result = $this->fetchCommon($id);
  1720. }
  1721. if ($result >= 0) {
  1722. $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1723. }
  1724. if ($result < 0) {
  1725. $error++;
  1726. }
  1727. }
  1728. if (!$error) {
  1729. if (property_exists($this, $field)) {
  1730. $this->$field = $value;
  1731. }
  1732. $this->db->commit();
  1733. return 1;
  1734. } else {
  1735. $this->db->rollback();
  1736. return -2;
  1737. }
  1738. } else {
  1739. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1740. $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
  1741. } else {
  1742. $this->error = $this->db->lasterror();
  1743. }
  1744. $this->db->rollback();
  1745. return -1;
  1746. }
  1747. }
  1748. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1749. /**
  1750. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1751. *
  1752. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')"
  1753. * @param string $fieldid Name of field to use for the select MAX and MIN
  1754. * @param int $nodbprefix Do not include DB prefix to forge table name
  1755. * @return int <0 if KO, >0 if OK
  1756. */
  1757. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1758. {
  1759. // phpcs:enable
  1760. global $conf, $user;
  1761. if (!$this->table_element) {
  1762. dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1763. return -1;
  1764. }
  1765. if ($fieldid == 'none') {
  1766. return 1;
  1767. }
  1768. // Security on socid
  1769. $socid = 0;
  1770. if ($user->socid > 0) {
  1771. $socid = $user->socid;
  1772. }
  1773. // this->ismultientitymanaged contains
  1774. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1775. $aliastablesociete = 's';
  1776. if ($this->element == 'societe') {
  1777. $aliastablesociete = 'te'; // te as table_element
  1778. }
  1779. $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
  1780. $sql = "SELECT MAX(te.".$fieldid.")";
  1781. $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1782. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1783. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  1784. }
  1785. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1786. $tmparray = explode('@', $this->ismultientitymanaged);
  1787. $sql .= ", ".MAIN_DB_PREFIX.$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1788. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1789. $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid
  1790. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1791. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1792. }
  1793. if ($restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) {
  1794. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1795. }
  1796. $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)
  1797. if ($restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) {
  1798. $sql .= " AND sc.fk_user = ".$user->id;
  1799. }
  1800. if ($restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) {
  1801. $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)';
  1802. }
  1803. if (!empty($filter)) {
  1804. if (!preg_match('/^\s*AND/i', $filter)) {
  1805. $sql .= " AND "; // For backward compatibility
  1806. }
  1807. $sql .= $filter;
  1808. }
  1809. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1810. $tmparray = explode('@', $this->ismultientitymanaged);
  1811. $sql .= ' AND te.'.$tmparray[0].' = '.($tmparray[1] == 'societe' ? 's' : 'parenttable').'.rowid'; // If we need to link to this table to limit select to entity
  1812. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1813. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1814. }
  1815. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1816. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1817. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1818. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1819. } else {
  1820. $sql .= " AND ug.fk_user = te.rowid";
  1821. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1822. }
  1823. } else {
  1824. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1825. }
  1826. }
  1827. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1828. $tmparray = explode('@', $this->ismultientitymanaged);
  1829. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1830. }
  1831. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1832. $sql .= ' AND te.fk_soc = '.$socid;
  1833. }
  1834. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1835. $sql .= ' AND (te.fk_soc = '.$socid.' OR te.fk_soc IS NULL)';
  1836. }
  1837. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1838. $sql .= ' AND te.rowid = '.$socid;
  1839. }
  1840. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1841. $result = $this->db->query($sql);
  1842. if (!$result) {
  1843. $this->error = $this->db->lasterror();
  1844. return -1;
  1845. }
  1846. $row = $this->db->fetch_row($result);
  1847. $this->ref_previous = $row[0];
  1848. $sql = "SELECT MIN(te.".$fieldid.")";
  1849. $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1850. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1851. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  1852. }
  1853. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1854. $tmparray = explode('@', $this->ismultientitymanaged);
  1855. $sql .= ", ".MAIN_DB_PREFIX.$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1856. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1857. $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid
  1858. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1859. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1860. }
  1861. if ($restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) {
  1862. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1863. }
  1864. $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)
  1865. if ($restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) {
  1866. $sql .= " AND sc.fk_user = ".$user->id;
  1867. }
  1868. if ($restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) {
  1869. $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)';
  1870. }
  1871. if (!empty($filter)) {
  1872. if (!preg_match('/^\s*AND/i', $filter)) {
  1873. $sql .= " AND "; // For backward compatibility
  1874. }
  1875. $sql .= $filter;
  1876. }
  1877. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1878. $tmparray = explode('@', $this->ismultientitymanaged);
  1879. $sql .= ' AND te.'.$tmparray[0].' = '.($tmparray[1] == 'societe' ? 's' : 'parenttable').'.rowid'; // If we need to link to this table to limit select to entity
  1880. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1881. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1882. }
  1883. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1884. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1885. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1886. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1887. } else {
  1888. $sql .= " AND ug.fk_user = te.rowid";
  1889. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1890. }
  1891. } else {
  1892. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1893. }
  1894. }
  1895. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1896. $tmparray = explode('@', $this->ismultientitymanaged);
  1897. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1898. }
  1899. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1900. $sql .= ' AND te.fk_soc = '.$socid;
  1901. }
  1902. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1903. $sql .= ' AND (te.fk_soc = '.$socid.' OR te.fk_soc IS NULL)';
  1904. }
  1905. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1906. $sql .= ' AND te.rowid = '.$socid;
  1907. }
  1908. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1909. // 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
  1910. $result = $this->db->query($sql);
  1911. if (!$result) {
  1912. $this->error = $this->db->lasterror();
  1913. return -2;
  1914. }
  1915. $row = $this->db->fetch_row($result);
  1916. $this->ref_next = $row[0];
  1917. return 1;
  1918. }
  1919. /**
  1920. * Return list of id of contacts of object
  1921. *
  1922. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  1923. * @return array Array of id of contacts (if source=external or internal)
  1924. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  1925. */
  1926. public function getListContactId($source = 'external')
  1927. {
  1928. $contactAlreadySelected = array();
  1929. $tab = $this->liste_contact(-1, $source);
  1930. $num = count($tab);
  1931. $i = 0;
  1932. while ($i < $num) {
  1933. if ($source == 'thirdparty') {
  1934. $contactAlreadySelected[$i] = $tab[$i]['socid'];
  1935. } else {
  1936. $contactAlreadySelected[$i] = $tab[$i]['id'];
  1937. }
  1938. $i++;
  1939. }
  1940. return $contactAlreadySelected;
  1941. }
  1942. /**
  1943. * Link element with a project
  1944. *
  1945. * @param int $projectid Project id to link element to
  1946. * @return int <0 if KO, >0 if OK
  1947. */
  1948. public function setProject($projectid)
  1949. {
  1950. if (!$this->table_element) {
  1951. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  1952. return -1;
  1953. }
  1954. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1955. if (!empty($this->fields['fk_project'])) { // Common case
  1956. if ($projectid) {
  1957. $sql .= ' SET fk_project = '.((int) $projectid);
  1958. } else {
  1959. $sql .= ' SET fk_project = NULL';
  1960. }
  1961. $sql .= ' WHERE rowid = '.((int) $this->id);
  1962. } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
  1963. if ($projectid) {
  1964. $sql .= ' SET fk_project = '.((int) $projectid);
  1965. } else {
  1966. $sql .= ' SET fk_project = NULL';
  1967. }
  1968. $sql .= ' WHERE id = '.((int) $this->id);
  1969. } else // Special case for old architecture objects
  1970. {
  1971. if ($projectid) {
  1972. $sql .= ' SET fk_projet = '.((int) $projectid);
  1973. } else {
  1974. $sql .= ' SET fk_projet = NULL';
  1975. }
  1976. $sql .= ' WHERE rowid = '.$this->id;
  1977. }
  1978. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  1979. if ($this->db->query($sql)) {
  1980. $this->fk_project = ((int) $projectid);
  1981. return 1;
  1982. } else {
  1983. dol_print_error($this->db);
  1984. return -1;
  1985. }
  1986. }
  1987. /**
  1988. * Change the payments methods
  1989. *
  1990. * @param int $id Id of new payment method
  1991. * @return int >0 if OK, <0 if KO
  1992. */
  1993. public function setPaymentMethods($id)
  1994. {
  1995. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  1996. if ($this->statut >= 0 || $this->element == 'societe') {
  1997. // TODO uniformize field name
  1998. $fieldname = 'fk_mode_reglement';
  1999. if ($this->element == 'societe') {
  2000. $fieldname = 'mode_reglement';
  2001. }
  2002. if (get_class($this) == 'Fournisseur') {
  2003. $fieldname = 'mode_reglement_supplier';
  2004. }
  2005. if (get_class($this) == 'Tva') {
  2006. $fieldname = 'fk_typepayment';
  2007. }
  2008. if (get_class($this) == 'Salary') {
  2009. $fieldname = 'fk_typepayment';
  2010. }
  2011. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2012. $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL');
  2013. $sql .= ' WHERE rowid='.((int) $this->id);
  2014. if ($this->db->query($sql)) {
  2015. $this->mode_reglement_id = $id;
  2016. // for supplier
  2017. if (get_class($this) == 'Fournisseur') {
  2018. $this->mode_reglement_supplier_id = $id;
  2019. }
  2020. return 1;
  2021. } else {
  2022. dol_syslog(get_class($this).'::setPaymentMethods Error '.$sql.' - '.$this->db->error());
  2023. $this->error = $this->db->error();
  2024. return -1;
  2025. }
  2026. } else {
  2027. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  2028. $this->error = 'Status of the object is incompatible '.$this->statut;
  2029. return -2;
  2030. }
  2031. }
  2032. /**
  2033. * Change the multicurrency code
  2034. *
  2035. * @param string $code multicurrency code
  2036. * @return int >0 if OK, <0 if KO
  2037. */
  2038. public function setMulticurrencyCode($code)
  2039. {
  2040. dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
  2041. if ($this->statut >= 0 || $this->element == 'societe') {
  2042. $fieldname = 'multicurrency_code';
  2043. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2044. $sql .= ' SET '.$fieldname." = '".$this->db->escape($code)."'";
  2045. $sql .= ' WHERE rowid='.((int) $this->id);
  2046. if ($this->db->query($sql)) {
  2047. $this->multicurrency_code = $code;
  2048. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  2049. if ($rate) {
  2050. $this->setMulticurrencyRate($rate, 2);
  2051. }
  2052. return 1;
  2053. } else {
  2054. dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
  2055. $this->error = $this->db->error();
  2056. return -1;
  2057. }
  2058. } else {
  2059. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  2060. $this->error = 'Status of the object is incompatible '.$this->statut;
  2061. return -2;
  2062. }
  2063. }
  2064. /**
  2065. * Change the multicurrency rate
  2066. *
  2067. * @param double $rate multicurrency rate
  2068. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  2069. * @return int >0 if OK, <0 if KO
  2070. */
  2071. public function setMulticurrencyRate($rate, $mode = 1)
  2072. {
  2073. dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
  2074. if ($this->statut >= 0 || $this->element == 'societe') {
  2075. $fieldname = 'multicurrency_tx';
  2076. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2077. $sql .= ' SET '.$fieldname.' = '.((float) $rate);
  2078. $sql .= ' WHERE rowid='.((int) $this->id);
  2079. if ($this->db->query($sql)) {
  2080. $this->multicurrency_tx = $rate;
  2081. // Update line price
  2082. if (!empty($this->lines)) {
  2083. foreach ($this->lines as &$line) {
  2084. // Amounts in company currency will be recalculated
  2085. if ($mode == 1) {
  2086. $line->subprice = 0;
  2087. }
  2088. // Amounts in foreign currency will be recalculated
  2089. if ($mode == 2) {
  2090. $line->multicurrency_subprice = 0;
  2091. }
  2092. switch ($this->element) {
  2093. case 'propal':
  2094. $this->updateline(
  2095. $line->id,
  2096. $line->subprice,
  2097. $line->qty,
  2098. $line->remise_percent,
  2099. $line->tva_tx,
  2100. $line->localtax1_tx,
  2101. $line->localtax2_tx,
  2102. ($line->description ? $line->description : $line->desc),
  2103. 'HT',
  2104. $line->info_bits,
  2105. $line->special_code,
  2106. $line->fk_parent_line,
  2107. $line->skip_update_total,
  2108. $line->fk_fournprice,
  2109. $line->pa_ht,
  2110. $line->label,
  2111. $line->product_type,
  2112. $line->date_start,
  2113. $line->date_end,
  2114. $line->array_options,
  2115. $line->fk_unit,
  2116. $line->multicurrency_subprice
  2117. );
  2118. break;
  2119. case 'commande':
  2120. $this->updateline(
  2121. $line->id,
  2122. ($line->description ? $line->description : $line->desc),
  2123. $line->subprice,
  2124. $line->qty,
  2125. $line->remise_percent,
  2126. $line->tva_tx,
  2127. $line->localtax1_tx,
  2128. $line->localtax2_tx,
  2129. 'HT',
  2130. $line->info_bits,
  2131. $line->date_start,
  2132. $line->date_end,
  2133. $line->product_type,
  2134. $line->fk_parent_line,
  2135. $line->skip_update_total,
  2136. $line->fk_fournprice,
  2137. $line->pa_ht,
  2138. $line->label,
  2139. $line->special_code,
  2140. $line->array_options,
  2141. $line->fk_unit,
  2142. $line->multicurrency_subprice
  2143. );
  2144. break;
  2145. case 'facture':
  2146. $this->updateline(
  2147. $line->id,
  2148. ($line->description ? $line->description : $line->desc),
  2149. $line->subprice,
  2150. $line->qty,
  2151. $line->remise_percent,
  2152. $line->date_start,
  2153. $line->date_end,
  2154. $line->tva_tx,
  2155. $line->localtax1_tx,
  2156. $line->localtax2_tx,
  2157. 'HT',
  2158. $line->info_bits,
  2159. $line->product_type,
  2160. $line->fk_parent_line,
  2161. $line->skip_update_total,
  2162. $line->fk_fournprice,
  2163. $line->pa_ht,
  2164. $line->label,
  2165. $line->special_code,
  2166. $line->array_options,
  2167. $line->situation_percent,
  2168. $line->fk_unit,
  2169. $line->multicurrency_subprice
  2170. );
  2171. break;
  2172. case 'supplier_proposal':
  2173. $this->updateline(
  2174. $line->id,
  2175. $line->subprice,
  2176. $line->qty,
  2177. $line->remise_percent,
  2178. $line->tva_tx,
  2179. $line->localtax1_tx,
  2180. $line->localtax2_tx,
  2181. ($line->description ? $line->description : $line->desc),
  2182. 'HT',
  2183. $line->info_bits,
  2184. $line->special_code,
  2185. $line->fk_parent_line,
  2186. $line->skip_update_total,
  2187. $line->fk_fournprice,
  2188. $line->pa_ht,
  2189. $line->label,
  2190. $line->product_type,
  2191. $line->array_options,
  2192. $line->ref_fourn,
  2193. $line->multicurrency_subprice
  2194. );
  2195. break;
  2196. case 'order_supplier':
  2197. $this->updateline(
  2198. $line->id,
  2199. ($line->description ? $line->description : $line->desc),
  2200. $line->subprice,
  2201. $line->qty,
  2202. $line->remise_percent,
  2203. $line->tva_tx,
  2204. $line->localtax1_tx,
  2205. $line->localtax2_tx,
  2206. 'HT',
  2207. $line->info_bits,
  2208. $line->product_type,
  2209. false,
  2210. $line->date_start,
  2211. $line->date_end,
  2212. $line->array_options,
  2213. $line->fk_unit,
  2214. $line->multicurrency_subprice,
  2215. $line->ref_supplier
  2216. );
  2217. break;
  2218. case 'invoice_supplier':
  2219. $this->updateline(
  2220. $line->id,
  2221. ($line->description ? $line->description : $line->desc),
  2222. $line->subprice,
  2223. $line->tva_tx,
  2224. $line->localtax1_tx,
  2225. $line->localtax2_tx,
  2226. $line->qty,
  2227. 0,
  2228. 'HT',
  2229. $line->info_bits,
  2230. $line->product_type,
  2231. $line->remise_percent,
  2232. false,
  2233. $line->date_start,
  2234. $line->date_end,
  2235. $line->array_options,
  2236. $line->fk_unit,
  2237. $line->multicurrency_subprice,
  2238. $line->ref_supplier
  2239. );
  2240. break;
  2241. default:
  2242. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  2243. break;
  2244. }
  2245. }
  2246. }
  2247. return 1;
  2248. } else {
  2249. dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
  2250. $this->error = $this->db->error();
  2251. return -1;
  2252. }
  2253. } else {
  2254. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  2255. $this->error = 'Status of the object is incompatible '.$this->statut;
  2256. return -2;
  2257. }
  2258. }
  2259. /**
  2260. * Change the payments terms
  2261. *
  2262. * @param int $id Id of new payment terms
  2263. * @return int >0 if OK, <0 if KO
  2264. */
  2265. public function setPaymentTerms($id)
  2266. {
  2267. dol_syslog(get_class($this).'::setPaymentTerms('.$id.')');
  2268. if ($this->statut >= 0 || $this->element == 'societe') {
  2269. // TODO uniformize field name
  2270. $fieldname = 'fk_cond_reglement';
  2271. if ($this->element == 'societe') {
  2272. $fieldname = 'cond_reglement';
  2273. }
  2274. if (get_class($this) == 'Fournisseur') {
  2275. $fieldname = 'cond_reglement_supplier';
  2276. }
  2277. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2278. $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL');
  2279. $sql .= ' WHERE rowid='.((int) $this->id);
  2280. if ($this->db->query($sql)) {
  2281. $this->cond_reglement_id = $id;
  2282. // for supplier
  2283. if (get_class($this) == 'Fournisseur') {
  2284. $this->cond_reglement_supplier_id = $id;
  2285. }
  2286. $this->cond_reglement = $id; // for compatibility
  2287. return 1;
  2288. } else {
  2289. dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
  2290. $this->error = $this->db->error();
  2291. return -1;
  2292. }
  2293. } else {
  2294. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  2295. $this->error = 'Status of the object is incompatible '.$this->statut;
  2296. return -2;
  2297. }
  2298. }
  2299. /**
  2300. * Change the transport mode methods
  2301. *
  2302. * @param int $id Id of transport mode
  2303. * @return int >0 if OK, <0 if KO
  2304. */
  2305. public function setTransportMode($id)
  2306. {
  2307. dol_syslog(get_class($this).'::setTransportMode('.$id.')');
  2308. if ($this->statut >= 0 || $this->element == 'societe') {
  2309. $fieldname = 'fk_transport_mode';
  2310. if ($this->element == 'societe') {
  2311. $fieldname = 'transport_mode';
  2312. }
  2313. if (get_class($this) == 'Fournisseur') {
  2314. $fieldname = 'transport_mode_supplier';
  2315. }
  2316. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2317. $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL');
  2318. $sql .= ' WHERE rowid='.((int) $this->id);
  2319. if ($this->db->query($sql)) {
  2320. $this->transport_mode_id = $id;
  2321. // for supplier
  2322. if (get_class($this) == 'Fournisseur') {
  2323. $this->transport_mode_supplier_id = $id;
  2324. }
  2325. return 1;
  2326. } else {
  2327. dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
  2328. $this->error = $this->db->error();
  2329. return -1;
  2330. }
  2331. } else {
  2332. dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
  2333. $this->error = 'Status of the object is incompatible '.$this->statut;
  2334. return -2;
  2335. }
  2336. }
  2337. /**
  2338. * Change the retained warranty payments terms
  2339. *
  2340. * @param int $id Id of new payment terms
  2341. * @return int >0 if OK, <0 if KO
  2342. */
  2343. public function setRetainedWarrantyPaymentTerms($id)
  2344. {
  2345. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
  2346. if ($this->statut >= 0 || $this->element == 'societe') {
  2347. $fieldname = 'retained_warranty_fk_cond_reglement';
  2348. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2349. $sql .= ' SET '.$fieldname.' = '.((int) $id);
  2350. $sql .= ' WHERE rowid='.((int) $this->id);
  2351. if ($this->db->query($sql)) {
  2352. $this->retained_warranty_fk_cond_reglement = $id;
  2353. return 1;
  2354. } else {
  2355. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
  2356. $this->error = $this->db->error();
  2357. return -1;
  2358. }
  2359. } else {
  2360. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  2361. $this->error = 'Status of the object is incompatible '.$this->statut;
  2362. return -2;
  2363. }
  2364. }
  2365. /**
  2366. * Define delivery address
  2367. * @deprecated
  2368. *
  2369. * @param int $id Address id
  2370. * @return int <0 si ko, >0 si ok
  2371. */
  2372. public function setDeliveryAddress($id)
  2373. {
  2374. $fieldname = 'fk_delivery_address';
  2375. if ($this->element == 'delivery' || $this->element == 'shipping') {
  2376. $fieldname = 'fk_address';
  2377. }
  2378. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".((int) $id);
  2379. $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0";
  2380. if ($this->db->query($sql)) {
  2381. $this->fk_delivery_address = $id;
  2382. return 1;
  2383. } else {
  2384. $this->error = $this->db->error();
  2385. dol_syslog(get_class($this).'::setDeliveryAddress Error '.$sql.' - '.$this->error);
  2386. return -1;
  2387. }
  2388. }
  2389. /**
  2390. * Change the shipping method
  2391. *
  2392. * @param int $shipping_method_id Id of shipping method
  2393. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2394. * @param User $userused Object user
  2395. *
  2396. * @return int 1 if OK, 0 if KO
  2397. */
  2398. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  2399. {
  2400. global $user;
  2401. if (empty($userused)) {
  2402. $userused = $user;
  2403. }
  2404. $error = 0;
  2405. if (!$this->table_element) {
  2406. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2407. return -1;
  2408. }
  2409. $this->db->begin();
  2410. if ($shipping_method_id < 0) {
  2411. $shipping_method_id = 'NULL';
  2412. }
  2413. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  2414. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2415. $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
  2416. $sql .= " WHERE rowid=".((int) $this->id);
  2417. $resql = $this->db->query($sql);
  2418. if (!$resql) {
  2419. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  2420. $this->error = $this->db->lasterror();
  2421. $error++;
  2422. } else {
  2423. if (!$notrigger) {
  2424. // Call trigger
  2425. $this->context = array('shippingmethodupdate'=>1);
  2426. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2427. if ($result < 0) {
  2428. $error++;
  2429. }
  2430. // End call trigger
  2431. }
  2432. }
  2433. if ($error) {
  2434. $this->db->rollback();
  2435. return -1;
  2436. } else {
  2437. $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
  2438. $this->db->commit();
  2439. return 1;
  2440. }
  2441. }
  2442. /**
  2443. * Change the warehouse
  2444. *
  2445. * @param int $warehouse_id Id of warehouse
  2446. * @return int 1 if OK, 0 if KO
  2447. */
  2448. public function setWarehouse($warehouse_id)
  2449. {
  2450. if (!$this->table_element) {
  2451. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2452. return -1;
  2453. }
  2454. if ($warehouse_id < 0) {
  2455. $warehouse_id = 'NULL';
  2456. }
  2457. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  2458. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2459. $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
  2460. $sql .= " WHERE rowid=".((int) $this->id);
  2461. if ($this->db->query($sql)) {
  2462. $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
  2463. return 1;
  2464. } else {
  2465. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  2466. $this->error = $this->db->error();
  2467. return 0;
  2468. }
  2469. }
  2470. /**
  2471. * Set last model used by doc generator
  2472. *
  2473. * @param User $user User object that make change
  2474. * @param string $modelpdf Modele name
  2475. * @return int <0 if KO, >0 if OK
  2476. */
  2477. public function setDocModel($user, $modelpdf)
  2478. {
  2479. if (!$this->table_element) {
  2480. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2481. return -1;
  2482. }
  2483. $newmodelpdf = dol_trunc($modelpdf, 255);
  2484. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2485. $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  2486. $sql .= " WHERE rowid = ".$this->id;
  2487. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  2488. $resql = $this->db->query($sql);
  2489. if ($resql) {
  2490. $this->model_pdf = $modelpdf;
  2491. $this->modelpdf = $modelpdf; // For bakward compatibility
  2492. return 1;
  2493. } else {
  2494. dol_print_error($this->db);
  2495. return 0;
  2496. }
  2497. }
  2498. /**
  2499. * Change the bank account
  2500. *
  2501. * @param int $fk_account Id of bank account
  2502. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2503. * @param User $userused Object user
  2504. * @return int 1 if OK, 0 if KO
  2505. */
  2506. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2507. {
  2508. global $user;
  2509. if (empty($userused)) {
  2510. $userused = $user;
  2511. }
  2512. $error = 0;
  2513. if (!$this->table_element) {
  2514. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2515. return -1;
  2516. }
  2517. $this->db->begin();
  2518. if ($fk_account < 0) {
  2519. $fk_account = 'NULL';
  2520. }
  2521. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  2522. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2523. $sql .= " SET fk_account = ".((int) $fk_account);
  2524. $sql .= " WHERE rowid=".((int) $this->id);
  2525. $resql = $this->db->query($sql);
  2526. if (!$resql) {
  2527. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  2528. $this->error = $this->db->lasterror();
  2529. $error++;
  2530. } else {
  2531. if (!$notrigger) {
  2532. // Call trigger
  2533. $this->context = array('bankaccountupdate'=>1);
  2534. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2535. if ($result < 0) {
  2536. $error++;
  2537. }
  2538. // End call trigger
  2539. }
  2540. }
  2541. if ($error) {
  2542. $this->db->rollback();
  2543. return -1;
  2544. } else {
  2545. $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
  2546. $this->db->commit();
  2547. return 1;
  2548. }
  2549. }
  2550. // TODO: Move line related operations to CommonObjectLine?
  2551. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2552. /**
  2553. * Save a new position (field rang) for details lines.
  2554. * You can choose to set position for lines with already a position or lines without any position defined.
  2555. *
  2556. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2557. * @param string $rowidorder ASC or DESC
  2558. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2559. * @return int <0 if KO, >0 if OK
  2560. */
  2561. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2562. {
  2563. // phpcs:enable
  2564. if (!$this->table_element_line) {
  2565. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2566. return -1;
  2567. }
  2568. if (!$this->fk_element) {
  2569. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2570. return -1;
  2571. }
  2572. // Count number of lines to reorder (according to choice $renum)
  2573. $nl = 0;
  2574. $sql = 'SELECT count(rowid) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2575. $sql .= ' WHERE '.$this->fk_element.'='.$this->id;
  2576. if (!$renum) {
  2577. $sql .= ' AND rang = 0';
  2578. }
  2579. if ($renum) {
  2580. $sql .= ' AND rang <> 0';
  2581. }
  2582. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  2583. $resql = $this->db->query($sql);
  2584. if ($resql) {
  2585. $row = $this->db->fetch_row($resql);
  2586. $nl = $row[0];
  2587. } else {
  2588. dol_print_error($this->db);
  2589. }
  2590. if ($nl > 0) {
  2591. // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
  2592. $rows = array();
  2593. // We first search all lines that are parent lines (for multilevel details lines)
  2594. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2595. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2596. if ($fk_parent_line) {
  2597. $sql .= ' AND fk_parent_line IS NULL';
  2598. }
  2599. $sql .= ' ORDER BY rang ASC, rowid '.$rowidorder;
  2600. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  2601. $resql = $this->db->query($sql);
  2602. if ($resql) {
  2603. $i = 0;
  2604. $num = $this->db->num_rows($resql);
  2605. while ($i < $num) {
  2606. $row = $this->db->fetch_row($resql);
  2607. $rows[] = $row[0]; // Add parent line into array rows
  2608. $childrens = $this->getChildrenOfLine($row[0]);
  2609. if (!empty($childrens)) {
  2610. foreach ($childrens as $child) {
  2611. array_push($rows, $child);
  2612. }
  2613. }
  2614. $i++;
  2615. }
  2616. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2617. if (!empty($rows)) {
  2618. foreach ($rows as $key => $row) {
  2619. $this->updateRangOfLine($row, ($key + 1));
  2620. }
  2621. }
  2622. } else {
  2623. dol_print_error($this->db);
  2624. }
  2625. }
  2626. return 1;
  2627. }
  2628. /**
  2629. * Get children of line
  2630. *
  2631. * @param int $id Id of parent line
  2632. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2633. * @return array Array with list of children lines id
  2634. */
  2635. public function getChildrenOfLine($id, $includealltree = 0)
  2636. {
  2637. $rows = array();
  2638. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2639. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2640. $sql .= ' AND fk_parent_line = '.$id;
  2641. $sql .= ' ORDER BY rang ASC';
  2642. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id."", LOG_DEBUG);
  2643. $resql = $this->db->query($sql);
  2644. if ($resql) {
  2645. if ($this->db->num_rows($resql) > 0) {
  2646. while ($row = $this->db->fetch_row($resql)) {
  2647. $rows[] = $row[0];
  2648. if (!empty($includealltree)) {
  2649. $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2650. }
  2651. }
  2652. }
  2653. }
  2654. return $rows;
  2655. }
  2656. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2657. /**
  2658. * Update a line to have a lower rank
  2659. *
  2660. * @param int $rowid Id of line
  2661. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2662. * @return void
  2663. */
  2664. public function line_up($rowid, $fk_parent_line = true)
  2665. {
  2666. // phpcs:enable
  2667. $this->line_order(false, 'ASC', $fk_parent_line);
  2668. // Get rang of line
  2669. $rang = $this->getRangOfLine($rowid);
  2670. // Update position of line
  2671. $this->updateLineUp($rowid, $rang);
  2672. }
  2673. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2674. /**
  2675. * Update a line to have a higher rank
  2676. *
  2677. * @param int $rowid Id of line
  2678. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2679. * @return void
  2680. */
  2681. public function line_down($rowid, $fk_parent_line = true)
  2682. {
  2683. // phpcs:enable
  2684. $this->line_order(false, 'ASC', $fk_parent_line);
  2685. // Get rang of line
  2686. $rang = $this->getRangOfLine($rowid);
  2687. // Get max value for rang
  2688. $max = $this->line_max();
  2689. // Update position of line
  2690. $this->updateLineDown($rowid, $rang, $max);
  2691. }
  2692. /**
  2693. * Update position of line (rang)
  2694. *
  2695. * @param int $rowid Id of line
  2696. * @param int $rang Position
  2697. * @return void
  2698. */
  2699. public function updateRangOfLine($rowid, $rang)
  2700. {
  2701. global $hookmanager;
  2702. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2703. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction'))) {
  2704. $fieldposition = 'position';
  2705. }
  2706. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.((int) $rang);
  2707. $sql .= ' WHERE rowid = '.((int) $rowid);
  2708. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2709. if (!$this->db->query($sql)) {
  2710. dol_print_error($this->db);
  2711. }
  2712. $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
  2713. $action='';
  2714. $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
  2715. }
  2716. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2717. /**
  2718. * Update position of line with ajax (rang)
  2719. *
  2720. * @param array $rows Array of rows
  2721. * @return void
  2722. */
  2723. public function line_ajaxorder($rows)
  2724. {
  2725. // phpcs:enable
  2726. $num = count($rows);
  2727. for ($i = 0; $i < $num; $i++) {
  2728. $this->updateRangOfLine($rows[$i], ($i + 1));
  2729. }
  2730. }
  2731. /**
  2732. * Update position of line up (rang)
  2733. *
  2734. * @param int $rowid Id of line
  2735. * @param int $rang Position
  2736. * @return void
  2737. */
  2738. public function updateLineUp($rowid, $rang)
  2739. {
  2740. if ($rang > 1) {
  2741. $fieldposition = 'rang';
  2742. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
  2743. $fieldposition = 'position';
  2744. }
  2745. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.((int) $rang);
  2746. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2747. $sql .= ' AND rang = '.($rang - 1);
  2748. if ($this->db->query($sql)) {
  2749. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.((int) ($rang - 1));
  2750. $sql .= ' WHERE rowid = '.((int) $rowid);
  2751. if (!$this->db->query($sql)) {
  2752. dol_print_error($this->db);
  2753. }
  2754. } else {
  2755. dol_print_error($this->db);
  2756. }
  2757. }
  2758. }
  2759. /**
  2760. * Update position of line down (rang)
  2761. *
  2762. * @param int $rowid Id of line
  2763. * @param int $rang Position
  2764. * @param int $max Max
  2765. * @return void
  2766. */
  2767. public function updateLineDown($rowid, $rang, $max)
  2768. {
  2769. if ($rang < $max) {
  2770. $fieldposition = 'rang';
  2771. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
  2772. $fieldposition = 'position';
  2773. }
  2774. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.((int) $rang);
  2775. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2776. $sql .= ' AND rang = '.((int) ($rang + 1));
  2777. if ($this->db->query($sql)) {
  2778. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.((int) ($rang + 1));
  2779. $sql .= ' WHERE rowid = '.((int) $rowid);
  2780. if (!$this->db->query($sql)) {
  2781. dol_print_error($this->db);
  2782. }
  2783. } else {
  2784. dol_print_error($this->db);
  2785. }
  2786. }
  2787. }
  2788. /**
  2789. * Get position of line (rang)
  2790. *
  2791. * @param int $rowid Id of line
  2792. * @return int Value of rang in table of lines
  2793. */
  2794. public function getRangOfLine($rowid)
  2795. {
  2796. $sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2797. $sql .= ' WHERE rowid ='.((int) $rowid);
  2798. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  2799. $resql = $this->db->query($sql);
  2800. if ($resql) {
  2801. $row = $this->db->fetch_row($resql);
  2802. return $row[0];
  2803. }
  2804. }
  2805. /**
  2806. * Get rowid of the line relative to its position
  2807. *
  2808. * @param int $rang Rang value
  2809. * @return int Rowid of the line
  2810. */
  2811. public function getIdOfLine($rang)
  2812. {
  2813. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2814. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2815. $sql .= ' AND rang = '.((int) $rang);
  2816. $resql = $this->db->query($sql);
  2817. if ($resql) {
  2818. $row = $this->db->fetch_row($resql);
  2819. return $row[0];
  2820. }
  2821. }
  2822. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2823. /**
  2824. * Get max value used for position of line (rang)
  2825. *
  2826. * @param int $fk_parent_line Parent line id
  2827. * @return int Max value of rang in table of lines
  2828. */
  2829. public function line_max($fk_parent_line = 0)
  2830. {
  2831. // phpcs:enable
  2832. $positionfield = 'rang';
  2833. if ($this->table_element == 'bom_bom') {
  2834. $positionfield = 'position';
  2835. }
  2836. // Search the last rang with fk_parent_line
  2837. if ($fk_parent_line) {
  2838. $sql = 'SELECT max('.$positionfield.') FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2839. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2840. $sql .= ' AND fk_parent_line = '.$fk_parent_line;
  2841. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2842. $resql = $this->db->query($sql);
  2843. if ($resql) {
  2844. $row = $this->db->fetch_row($resql);
  2845. if (!empty($row[0])) {
  2846. return $row[0];
  2847. } else {
  2848. return $this->getRangOfLine($fk_parent_line);
  2849. }
  2850. }
  2851. } else {
  2852. // If not, search the last rang of element
  2853. $sql = 'SELECT max('.$positionfield.') FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2854. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2855. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2856. $resql = $this->db->query($sql);
  2857. if ($resql) {
  2858. $row = $this->db->fetch_row($resql);
  2859. return $row[0];
  2860. }
  2861. }
  2862. }
  2863. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2864. /**
  2865. * Update external ref of element
  2866. *
  2867. * @param string $ref_ext Update field ref_ext
  2868. * @return int <0 if KO, >0 if OK
  2869. */
  2870. public function update_ref_ext($ref_ext)
  2871. {
  2872. // phpcs:enable
  2873. if (!$this->table_element) {
  2874. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  2875. return -1;
  2876. }
  2877. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2878. $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  2879. $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".$this->id;
  2880. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  2881. if ($this->db->query($sql)) {
  2882. $this->ref_ext = $ref_ext;
  2883. return 1;
  2884. } else {
  2885. $this->error = $this->db->error();
  2886. return -1;
  2887. }
  2888. }
  2889. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2890. /**
  2891. * Update note of element
  2892. *
  2893. * @param string $note New value for note
  2894. * @param string $suffix '', '_public' or '_private'
  2895. * @return int <0 if KO, >0 if OK
  2896. */
  2897. public function update_note($note, $suffix = '')
  2898. {
  2899. // phpcs:enable
  2900. global $user;
  2901. if (!$this->table_element) {
  2902. $this->error = 'update_note was called on objet with property table_element not defined';
  2903. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  2904. return -1;
  2905. }
  2906. if (!in_array($suffix, array('', '_public', '_private'))) {
  2907. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  2908. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  2909. return -2;
  2910. }
  2911. $newsuffix = $suffix;
  2912. // Special cas
  2913. if ($this->table_element == 'product' && $newsuffix == '_private') {
  2914. $newsuffix = '';
  2915. }
  2916. if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  2917. $fieldusermod = "fk_user_mod";
  2918. } elseif ($this->table_element == 'ecm_files') {
  2919. $fieldusermod = "fk_user_m";
  2920. } else {
  2921. $fieldusermod = "fk_user_modif";
  2922. }
  2923. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2924. $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
  2925. $sql .= " ,".$fieldusermod." = ".$user->id;
  2926. $sql .= " WHERE rowid =".$this->id;
  2927. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  2928. if ($this->db->query($sql)) {
  2929. if ($suffix == '_public') {
  2930. $this->note_public = $note;
  2931. } elseif ($suffix == '_private') {
  2932. $this->note_private = $note;
  2933. } else {
  2934. $this->note = $note; // deprecated
  2935. $this->note_private = $note;
  2936. }
  2937. return 1;
  2938. } else {
  2939. $this->error = $this->db->lasterror();
  2940. return -1;
  2941. }
  2942. }
  2943. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2944. /**
  2945. * Update public note (kept for backward compatibility)
  2946. *
  2947. * @param string $note New value for note
  2948. * @return int <0 if KO, >0 if OK
  2949. * @deprecated
  2950. * @see update_note()
  2951. */
  2952. public function update_note_public($note)
  2953. {
  2954. // phpcs:enable
  2955. return $this->update_note($note, '_public');
  2956. }
  2957. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2958. /**
  2959. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  2960. * Must be called at end of methods addline or updateline.
  2961. *
  2962. * @param int $exclspec >0 = Exclude special product (product_type=9)
  2963. * @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
  2964. * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object.
  2965. * @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.
  2966. * @return int <0 if KO, >0 if OK
  2967. */
  2968. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  2969. {
  2970. // phpcs:enable
  2971. global $conf, $hookmanager, $action;
  2972. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  2973. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  2974. if ($reshook > 0) {
  2975. return 1; // replacement code
  2976. } elseif ($reshook < 0) {
  2977. return -1; // failure
  2978. } // reshook = 0 => execute normal code
  2979. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  2980. $MODULE = "";
  2981. if ($this->element == 'propal') {
  2982. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  2983. } elseif ($this->element == 'commande' || $this->element == 'order') {
  2984. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  2985. } elseif ($this->element == 'facture' || $this->element == 'invoice') {
  2986. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  2987. } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier') {
  2988. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  2989. } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
  2990. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  2991. } elseif ($this->element == 'supplier_proposal') {
  2992. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  2993. }
  2994. if (!empty($MODULE)) {
  2995. if (!empty($conf->global->$MODULE)) {
  2996. $modsactivated = explode(',', $conf->global->$MODULE);
  2997. foreach ($modsactivated as $mod) {
  2998. if ($conf->$mod->enabled) {
  2999. return 1; // update was disabled by specific setup
  3000. }
  3001. }
  3002. }
  3003. }
  3004. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  3005. if ($roundingadjust == '-1') {
  3006. $roundingadjust = 'auto'; // For backward compatibility
  3007. }
  3008. $forcedroundingmode = $roundingadjust;
  3009. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
  3010. $forcedroundingmode = $conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
  3011. } elseif ($forcedroundingmode == 'auto') {
  3012. $forcedroundingmode = '0';
  3013. }
  3014. $error = 0;
  3015. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  3016. // Define constants to find lines to sum
  3017. $fieldtva = 'total_tva';
  3018. $fieldlocaltax1 = 'total_localtax1';
  3019. $fieldlocaltax2 = 'total_localtax2';
  3020. $fieldup = 'subprice';
  3021. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3022. $fieldtva = 'tva';
  3023. $fieldup = 'pu_ht';
  3024. }
  3025. if ($this->element == 'expensereport') {
  3026. $fieldup = 'value_unit';
  3027. }
  3028. $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,';
  3029. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  3030. if ($this->table_element_line == 'facturedet') {
  3031. $sql .= ', situation_percent';
  3032. }
  3033. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3034. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  3035. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  3036. if ($exclspec) {
  3037. $product_field = 'product_type';
  3038. if ($this->table_element_line == 'contratdet') {
  3039. $product_field = ''; // contratdet table has no product_type field
  3040. }
  3041. if ($product_field) {
  3042. $sql .= ' AND '.$product_field.' <> 9';
  3043. }
  3044. }
  3045. $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
  3046. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3047. $resql = $this->db->query($sql);
  3048. if ($resql) {
  3049. $this->total_ht = 0;
  3050. $this->total_tva = 0;
  3051. $this->total_localtax1 = 0;
  3052. $this->total_localtax2 = 0;
  3053. $this->total_ttc = 0;
  3054. $total_ht_by_vats = array();
  3055. $total_tva_by_vats = array();
  3056. $total_ttc_by_vats = array();
  3057. $this->multicurrency_total_ht = 0;
  3058. $this->multicurrency_total_tva = 0;
  3059. $this->multicurrency_total_ttc = 0;
  3060. $num = $this->db->num_rows($resql);
  3061. $i = 0;
  3062. while ($i < $num) {
  3063. $obj = $this->db->fetch_object($resql);
  3064. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  3065. $parameters = array('fk_element' => $obj->rowid);
  3066. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3067. 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'
  3068. // This part of code is to fix data. We should not call it too often.
  3069. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  3070. $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);
  3071. $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.
  3072. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  3073. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
  3074. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  3075. if ($diff_when_using_price_ht && $diff_on_current_total) {
  3076. $sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
  3077. 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);
  3078. $resqlfix = $this->db->query($sqlfix);
  3079. if (!$resqlfix) {
  3080. dol_print_error($this->db, 'Failed to update line');
  3081. }
  3082. $obj->total_tva = $tmpcal[1];
  3083. $obj->total_ttc = $tmpcal[2];
  3084. }
  3085. }
  3086. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  3087. $this->total_tva += $obj->total_tva;
  3088. $this->total_localtax1 += $obj->total_localtax1;
  3089. $this->total_localtax2 += $obj->total_localtax2;
  3090. $this->total_ttc += $obj->total_ttc;
  3091. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  3092. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  3093. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  3094. if (!isset($total_ht_by_vats[$obj->vatrate])) {
  3095. $total_ht_by_vats[$obj->vatrate] = 0;
  3096. }
  3097. if (!isset($total_tva_by_vats[$obj->vatrate])) {
  3098. $total_tva_by_vats[$obj->vatrate] = 0;
  3099. }
  3100. if (!isset($total_ttc_by_vats[$obj->vatrate])) {
  3101. $total_ttc_by_vats[$obj->vatrate] = 0;
  3102. }
  3103. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  3104. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  3105. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  3106. if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  3107. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  3108. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  3109. //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";
  3110. if ($diff) {
  3111. if (abs($diff) > 0.1) {
  3112. $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.';
  3113. dol_syslog($errmsg, LOG_WARNING);
  3114. dol_print_error('', $errmsg);
  3115. exit;
  3116. }
  3117. $sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".($obj->total_tva - $diff).", total_ttc = ".($obj->total_ttc - $diff)." WHERE rowid = ".$obj->rowid;
  3118. 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);
  3119. $resqlfix = $this->db->query($sqlfix);
  3120. if (!$resqlfix) {
  3121. dol_print_error($this->db, 'Failed to update line');
  3122. }
  3123. $this->total_tva -= $diff;
  3124. $this->total_ttc -= $diff;
  3125. $total_tva_by_vats[$obj->vatrate] -= $diff;
  3126. $total_ttc_by_vats[$obj->vatrate] -= $diff;
  3127. }
  3128. }
  3129. $i++;
  3130. }
  3131. // Add revenue stamp to total
  3132. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  3133. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  3134. // Situations totals
  3135. if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
  3136. $prev_sits = $this->get_prev_sits();
  3137. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  3138. $this->total_ht -= $sit->total_ht;
  3139. $this->total_tva -= $sit->total_tva;
  3140. $this->total_localtax1 -= $sit->total_localtax1;
  3141. $this->total_localtax2 -= $sit->total_localtax2;
  3142. $this->total_ttc -= $sit->total_ttc;
  3143. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  3144. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  3145. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  3146. }
  3147. }
  3148. $this->db->free($resql);
  3149. // Now update global field total_ht, total_ttc and tva
  3150. $fieldht = 'total_ht';
  3151. $fieldtva = 'tva';
  3152. $fieldlocaltax1 = 'localtax1';
  3153. $fieldlocaltax2 = 'localtax2';
  3154. $fieldttc = 'total_ttc';
  3155. // Specific code for backward compatibility with old field names
  3156. if ($this->element == 'facture' || $this->element == 'facturerec') {
  3157. $fieldtva = 'total_tva';
  3158. }
  3159. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3160. $fieldtva = 'total_tva';
  3161. }
  3162. if ($this->element == 'propal') {
  3163. $fieldtva = 'total_tva';
  3164. }
  3165. if ($this->element == 'expensereport') {
  3166. $fieldtva = 'total_tva';
  3167. }
  3168. if ($this->element == 'supplier_proposal') {
  3169. $fieldtva = 'total_tva';
  3170. }
  3171. if ($this->element == 'commande') {
  3172. $fieldtva = 'total_tva';
  3173. }
  3174. if ($this->element == 'order_supplier') {
  3175. $fieldtva = 'total_tva';
  3176. }
  3177. if (empty($nodatabaseupdate)) {
  3178. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
  3179. $sql .= " ".$fieldht." = ".price2num($this->total_ht).",";
  3180. $sql .= " ".$fieldtva." = ".price2num($this->total_tva).",";
  3181. $sql .= " ".$fieldlocaltax1." = ".price2num($this->total_localtax1).",";
  3182. $sql .= " ".$fieldlocaltax2." = ".price2num($this->total_localtax2).",";
  3183. $sql .= " ".$fieldttc." = ".price2num($this->total_ttc);
  3184. $sql .= ", multicurrency_total_ht = ".price2num($this->multicurrency_total_ht, 'MT', 1);
  3185. $sql .= ", multicurrency_total_tva = ".price2num($this->multicurrency_total_tva, 'MT', 1);
  3186. $sql .= ", multicurrency_total_ttc = ".price2num($this->multicurrency_total_ttc, 'MT', 1);
  3187. $sql .= ' WHERE rowid = '.$this->id;
  3188. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3189. $resql = $this->db->query($sql);
  3190. if (!$resql) {
  3191. $error++;
  3192. $this->error = $this->db->lasterror();
  3193. $this->errors[] = $this->db->lasterror();
  3194. }
  3195. }
  3196. if (!$error) {
  3197. return 1;
  3198. } else {
  3199. return -1;
  3200. }
  3201. } else {
  3202. dol_print_error($this->db, 'Bad request in update_price');
  3203. return -1;
  3204. }
  3205. }
  3206. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3207. /**
  3208. * Add objects linked in llx_element_element.
  3209. *
  3210. * @param string $origin Linked element type
  3211. * @param int $origin_id Linked element id
  3212. * @param User $f_user User that create
  3213. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3214. * @return int <=0 if KO, >0 if OK
  3215. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  3216. */
  3217. public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
  3218. {
  3219. // phpcs:enable
  3220. global $user;
  3221. $origin = (!empty($origin) ? $origin : $this->origin);
  3222. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  3223. $f_user = isset($f_user) ? $f_user : $user;
  3224. // Special case
  3225. if ($origin == 'order') {
  3226. $origin = 'commande';
  3227. }
  3228. if ($origin == 'invoice') {
  3229. $origin = 'facture';
  3230. }
  3231. if ($origin == 'invoice_template') {
  3232. $origin = 'facturerec';
  3233. }
  3234. if ($origin == 'supplierorder') {
  3235. $origin = 'order_supplier';
  3236. }
  3237. $this->db->begin();
  3238. $error = 0;
  3239. $sql = "INSERT INTO " . MAIN_DB_PREFIX . "element_element (";
  3240. $sql .= "fk_source";
  3241. $sql .= ", sourcetype";
  3242. $sql .= ", fk_target";
  3243. $sql .= ", targettype";
  3244. $sql .= ") VALUES (";
  3245. $sql .= $origin_id;
  3246. $sql .= ", '" . $this->db->escape($origin) . "'";
  3247. $sql .= ", " . $this->id;
  3248. $sql .= ", '" . $this->db->escape($this->element) . "'";
  3249. $sql .= ")";
  3250. dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
  3251. if ($this->db->query($sql)) {
  3252. if (!$notrigger) {
  3253. // Call trigger
  3254. $this->context['link_origin'] = $origin;
  3255. $this->context['link_origin_id'] = $origin_id;
  3256. $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
  3257. if ($result < 0) {
  3258. $error++;
  3259. }
  3260. // End call triggers
  3261. }
  3262. } else {
  3263. $this->error = $this->db->lasterror();
  3264. $error++;
  3265. }
  3266. if (!$error) {
  3267. $this->db->commit();
  3268. return 1;
  3269. } else {
  3270. $this->db->rollback();
  3271. return 0;
  3272. }
  3273. }
  3274. /**
  3275. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  3276. * this->linkedObjectsIds array +
  3277. * this->linkedObjects array if $loadalsoobjects = 1
  3278. * Possible usage for parameters:
  3279. * - all parameters empty -> we look all link to current object (current object can be source or target)
  3280. * - source id+type -> will get target list linked to source
  3281. * - target id+type -> will get source list linked to target
  3282. * - source id+type + target type -> will get target list of the type
  3283. * - target id+type + target source -> will get source list of the type
  3284. *
  3285. * @param int $sourceid Object source id (if not defined, id of object)
  3286. * @param string $sourcetype Object source type (if not defined, element name of object)
  3287. * @param int $targetid Object target id (if not defined, id of object)
  3288. * @param string $targettype Object target type (if not defined, elemennt name of object)
  3289. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  3290. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  3291. * @param string $orderby SQL 'ORDER BY' clause
  3292. * @param int $loadalsoobjects Load also array this->linkedObjects (Use 0 to increase performances)
  3293. * @return int <0 if KO, >0 if OK
  3294. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  3295. */
  3296. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  3297. {
  3298. global $conf;
  3299. $this->linkedObjectsIds = array();
  3300. $this->linkedObjects = array();
  3301. $justsource = false;
  3302. $justtarget = false;
  3303. $withtargettype = false;
  3304. $withsourcetype = false;
  3305. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
  3306. $justsource = true; // the source (id and type) is a search criteria
  3307. if (!empty($targettype)) {
  3308. $withtargettype = true;
  3309. }
  3310. }
  3311. if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
  3312. $justtarget = true; // the target (id and type) is a search criteria
  3313. if (!empty($sourcetype)) {
  3314. $withsourcetype = true;
  3315. }
  3316. }
  3317. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3318. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3319. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3320. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3321. /*if (empty($sourceid) && empty($targetid))
  3322. {
  3323. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  3324. return -1;
  3325. }*/
  3326. // Links between objects are stored in table element_element
  3327. $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype';
  3328. $sql .= ' FROM '.MAIN_DB_PREFIX.'element_element';
  3329. $sql .= " WHERE ";
  3330. if ($justsource || $justtarget) {
  3331. if ($justsource) {
  3332. $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3333. if ($withtargettype) {
  3334. $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
  3335. }
  3336. } elseif ($justtarget) {
  3337. $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
  3338. if ($withsourcetype) {
  3339. $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3340. }
  3341. }
  3342. } else {
  3343. $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
  3344. $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
  3345. }
  3346. $sql .= ' ORDER BY '.$orderby;
  3347. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  3348. $resql = $this->db->query($sql);
  3349. if ($resql) {
  3350. $num = $this->db->num_rows($resql);
  3351. $i = 0;
  3352. while ($i < $num) {
  3353. $obj = $this->db->fetch_object($resql);
  3354. if ($justsource || $justtarget) {
  3355. if ($justsource) {
  3356. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3357. } elseif ($justtarget) {
  3358. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3359. }
  3360. } else {
  3361. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
  3362. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3363. }
  3364. if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
  3365. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3366. }
  3367. }
  3368. $i++;
  3369. }
  3370. if (!empty($this->linkedObjectsIds)) {
  3371. $tmparray = $this->linkedObjectsIds;
  3372. foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  3373. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  3374. $module = $element = $subelement = $objecttype;
  3375. $regs = array();
  3376. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  3377. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  3378. $module = $element = $regs[1];
  3379. $subelement = $regs[2];
  3380. }
  3381. $classpath = $element.'/class';
  3382. // To work with non standard classpath or module name
  3383. if ($objecttype == 'facture') {
  3384. $classpath = 'compta/facture/class';
  3385. } elseif ($objecttype == 'facturerec') {
  3386. $classpath = 'compta/facture/class';
  3387. $module = 'facture';
  3388. } elseif ($objecttype == 'propal') {
  3389. $classpath = 'comm/propal/class';
  3390. } elseif ($objecttype == 'supplier_proposal') {
  3391. $classpath = 'supplier_proposal/class';
  3392. } elseif ($objecttype == 'shipping') {
  3393. $classpath = 'expedition/class';
  3394. $subelement = 'expedition';
  3395. $module = 'expedition_bon';
  3396. } elseif ($objecttype == 'delivery') {
  3397. $classpath = 'delivery/class';
  3398. $subelement = 'delivery';
  3399. $module = 'delivery_note';
  3400. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  3401. $classpath = 'fourn/class';
  3402. $module = 'fournisseur';
  3403. } elseif ($objecttype == 'fichinter') {
  3404. $classpath = 'fichinter/class';
  3405. $subelement = 'fichinter';
  3406. $module = 'ficheinter';
  3407. } elseif ($objecttype == 'subscription') {
  3408. $classpath = 'adherents/class';
  3409. $module = 'adherent';
  3410. } elseif ($objecttype == 'contact') {
  3411. $module = 'societe';
  3412. }
  3413. // Set classfile
  3414. $classfile = strtolower($subelement);
  3415. $classname = ucfirst($subelement);
  3416. if ($objecttype == 'order') {
  3417. $classfile = 'commande';
  3418. $classname = 'Commande';
  3419. } elseif ($objecttype == 'invoice_supplier') {
  3420. $classfile = 'fournisseur.facture';
  3421. $classname = 'FactureFournisseur';
  3422. } elseif ($objecttype == 'order_supplier') {
  3423. $classfile = 'fournisseur.commande';
  3424. $classname = 'CommandeFournisseur';
  3425. } elseif ($objecttype == 'supplier_proposal') {
  3426. $classfile = 'supplier_proposal';
  3427. $classname = 'SupplierProposal';
  3428. } elseif ($objecttype == 'facturerec') {
  3429. $classfile = 'facture-rec';
  3430. $classname = 'FactureRec';
  3431. } elseif ($objecttype == 'subscription') {
  3432. $classfile = 'subscription';
  3433. $classname = 'Subscription';
  3434. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  3435. $classpath = 'projet/class';
  3436. $classfile = 'project';
  3437. $classname = 'Project';
  3438. } elseif ($objecttype == 'conferenceorboothattendee') {
  3439. $classpath = 'eventorganization/class';
  3440. $classfile = 'conferenceorboothattendee';
  3441. $classname = 'ConferenceOrBoothAttendee';
  3442. $module = 'eventorganization';
  3443. } elseif ($objecttype == 'conferenceorbooth') {
  3444. $classpath = 'eventorganization/class';
  3445. $classfile = 'conferenceorbooth';
  3446. $classname = 'ConferenceOrBooth';
  3447. $module = 'eventorganization';
  3448. }
  3449. // Here $module, $classfile and $classname are set
  3450. if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
  3451. if ($loadalsoobjects) {
  3452. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  3453. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  3454. if (class_exists($classname)) {
  3455. foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
  3456. $object = new $classname($this->db);
  3457. $ret = $object->fetch($objectid);
  3458. if ($ret >= 0) {
  3459. $this->linkedObjects[$objecttype][$i] = $object;
  3460. }
  3461. }
  3462. }
  3463. }
  3464. } else {
  3465. unset($this->linkedObjectsIds[$objecttype]);
  3466. }
  3467. }
  3468. }
  3469. return 1;
  3470. } else {
  3471. dol_print_error($this->db);
  3472. return -1;
  3473. }
  3474. }
  3475. /**
  3476. * Update object linked of a current object
  3477. *
  3478. * @param int $sourceid Object source id
  3479. * @param string $sourcetype Object source type
  3480. * @param int $targetid Object target id
  3481. * @param string $targettype Object target type
  3482. * @param User $f_user User that create
  3483. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3484. * @return int >0 if OK, <0 if KO
  3485. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3486. */
  3487. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
  3488. {
  3489. global $user;
  3490. $updatesource = false;
  3491. $updatetarget = false;
  3492. $f_user = isset($f_user) ? $f_user : $user;
  3493. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3494. $updatesource = true;
  3495. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3496. $updatetarget = true;
  3497. }
  3498. $this->db->begin();
  3499. $error = 0;
  3500. $sql = "UPDATE " . MAIN_DB_PREFIX . "element_element SET ";
  3501. if ($updatesource) {
  3502. $sql .= "fk_source = " . $sourceid;
  3503. $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3504. $sql .= " WHERE fk_target = " . $this->id;
  3505. $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
  3506. } elseif ($updatetarget) {
  3507. $sql .= "fk_target = " . $targetid;
  3508. $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
  3509. $sql .= " WHERE fk_source = " . $this->id;
  3510. $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3511. }
  3512. dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
  3513. if ($this->db->query($sql)) {
  3514. if (!$notrigger) {
  3515. // Call trigger
  3516. $this->context['link_source_id'] = $sourceid;
  3517. $this->context['link_source_type'] = $sourcetype;
  3518. $this->context['link_target_id'] = $targetid;
  3519. $this->context['link_target_type'] = $targettype;
  3520. $result = $this->call_trigger('OBJECT_LINK_UPDATE', $f_user);
  3521. if ($result < 0) {
  3522. $error++;
  3523. }
  3524. // End call triggers
  3525. }
  3526. } else {
  3527. $this->error = $this->db->lasterror();
  3528. $error++;
  3529. }
  3530. if (!$error) {
  3531. $this->db->commit();
  3532. return 1;
  3533. } else {
  3534. $this->db->rollback();
  3535. return -1;
  3536. }
  3537. }
  3538. /**
  3539. * Delete all links between an object $this
  3540. *
  3541. * @param int $sourceid Object source id
  3542. * @param string $sourcetype Object source type
  3543. * @param int $targetid Object target id
  3544. * @param string $targettype Object target type
  3545. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3546. * @param User $f_user User that create
  3547. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3548. * @return int >0 if OK, <0 if KO
  3549. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3550. */
  3551. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
  3552. {
  3553. global $user;
  3554. $deletesource = false;
  3555. $deletetarget = false;
  3556. $f_user = isset($f_user) ? $f_user : $user;
  3557. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3558. $deletesource = true;
  3559. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3560. $deletetarget = true;
  3561. }
  3562. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3563. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3564. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3565. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3566. $this->db->begin();
  3567. $error = 0;
  3568. if (!$notrigger) {
  3569. // Call trigger
  3570. $this->context['link_id'] = $rowid;
  3571. $this->context['link_source_id'] = $sourceid;
  3572. $this->context['link_source_type'] = $sourcetype;
  3573. $this->context['link_target_id'] = $targetid;
  3574. $this->context['link_target_type'] = $targettype;
  3575. $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
  3576. if ($result < 0) {
  3577. $error++;
  3578. }
  3579. // End call triggers
  3580. }
  3581. if (!$error) {
  3582. $sql = "DELETE FROM " . MAIN_DB_PREFIX . "element_element";
  3583. $sql .= " WHERE";
  3584. if ($rowid > 0) {
  3585. $sql .= " rowid = " . ((int) $rowid);
  3586. } else {
  3587. if ($deletesource) {
  3588. $sql .= " fk_source = " . $sourceid . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3589. $sql .= " AND fk_target = " . $this->id . " AND targettype = '" . $this->db->escape($this->element) . "'";
  3590. } elseif ($deletetarget) {
  3591. $sql .= " fk_target = " . $targetid . " AND targettype = '" . $this->db->escape($targettype) . "'";
  3592. $sql .= " AND fk_source = " . $this->id . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3593. } else {
  3594. $sql .= " (fk_source = " . $this->id . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
  3595. $sql .= " OR";
  3596. $sql .= " (fk_target = " . $this->id . " AND targettype = '" . $this->db->escape($this->element) . "')";
  3597. }
  3598. }
  3599. dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
  3600. if (!$this->db->query($sql)) {
  3601. $this->error = $this->db->lasterror();
  3602. $this->errors[] = $this->error;
  3603. $error++;
  3604. }
  3605. }
  3606. if (!$error) {
  3607. $this->db->commit();
  3608. return 1;
  3609. } else {
  3610. $this->db->rollback();
  3611. return 0;
  3612. }
  3613. }
  3614. /**
  3615. * Function used to get an array with all items linked to an object id in association table
  3616. *
  3617. * @param int $fk_object_where id of object we need to get linked items
  3618. * @param string $field_select name of field we need to get a list
  3619. * @param string $field_where name of field of object we need to get linked items
  3620. * @param string $table_element name of association table
  3621. * @return array Array of record
  3622. */
  3623. public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
  3624. {
  3625. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3626. return -1;
  3627. }
  3628. global $db;
  3629. $sql = 'SELECT '.$field_select.' FROM '.MAIN_DB_PREFIX.$table_element.' WHERE '.$field_where.' = '.((int) $fk_object_where);
  3630. $resql = $db->query($sql);
  3631. $TRes = array();
  3632. if (!empty($resql)) {
  3633. while ($res = $db->fetch_object($resql)) {
  3634. $TRes[] = $res->{$field_select};
  3635. }
  3636. }
  3637. return $TRes;
  3638. }
  3639. /**
  3640. * Function used to remove all items linked to an object id in association table
  3641. *
  3642. * @param int $fk_object_where id of object we need to remove linked items
  3643. * @param string $field_where name of field of object we need to delete linked items
  3644. * @param string $table_element name of association table
  3645. * @return int <0 if KO, 0 if nothing done, >0 if OK and something done
  3646. */
  3647. public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
  3648. {
  3649. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3650. return -1;
  3651. }
  3652. global $db;
  3653. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table_element.' WHERE '.$field_where.' = '.((int) $fk_object_where);
  3654. $resql = $db->query($sql);
  3655. if (empty($resql)) {
  3656. return 0;
  3657. }
  3658. return 1;
  3659. }
  3660. /**
  3661. * Set status of an object
  3662. *
  3663. * @param int $status Status to set
  3664. * @param int $elementId Id of element to force (use this->id by default)
  3665. * @param string $elementType Type of element to force (use this->table_element by default)
  3666. * @param string $trigkey Trigger key to use for trigger
  3667. * @return int <0 if KO, >0 if OK
  3668. */
  3669. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '')
  3670. {
  3671. global $user, $langs, $conf;
  3672. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3673. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3674. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3675. $this->db->begin();
  3676. $fieldstatus = "fk_statut";
  3677. if ($elementTable == 'facture_rec') {
  3678. $fieldstatus = "suspended";
  3679. }
  3680. if ($elementTable == 'mailing') {
  3681. $fieldstatus = "statut";
  3682. }
  3683. if ($elementTable == 'cronjob') {
  3684. $fieldstatus = "status";
  3685. }
  3686. if ($elementTable == 'user') {
  3687. $fieldstatus = "statut";
  3688. }
  3689. if ($elementTable == 'expensereport') {
  3690. $fieldstatus = "fk_statut";
  3691. }
  3692. if ($elementTable == 'commande_fournisseur_dispatch') {
  3693. $fieldstatus = "status";
  3694. }
  3695. if (is_array($this->fields) && array_key_exists('status', $this->fields)) {
  3696. $fieldstatus = 'status';
  3697. }
  3698. $sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable;
  3699. $sql .= " SET ".$fieldstatus." = ".((int) $status);
  3700. // If status = 1 = validated, update also fk_user_valid
  3701. if ($status == 1 && $elementTable == 'expensereport') {
  3702. $sql .= ", fk_user_valid = ".((int) $user->id);
  3703. }
  3704. $sql .= " WHERE rowid=".((int) $elementId);
  3705. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  3706. if ($this->db->query($sql)) {
  3707. $error = 0;
  3708. // Try autoset of trigkey
  3709. if (empty($trigkey)) {
  3710. if ($this->element == 'supplier_proposal' && $status == 2) {
  3711. $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3712. }
  3713. if ($this->element == 'supplier_proposal' && $status == 3) {
  3714. $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3715. }
  3716. if ($this->element == 'supplier_proposal' && $status == 4) {
  3717. $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3718. }
  3719. if ($this->element == 'fichinter' && $status == 3) {
  3720. $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3721. }
  3722. if ($this->element == 'fichinter' && $status == 2) {
  3723. $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3724. }
  3725. if ($this->element == 'fichinter' && $status == 1) {
  3726. $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3727. }
  3728. }
  3729. if ($trigkey) {
  3730. // Call trigger
  3731. $result = $this->call_trigger($trigkey, $user);
  3732. if ($result < 0) {
  3733. $error++;
  3734. }
  3735. // End call triggers
  3736. }
  3737. if (!$error) {
  3738. $this->db->commit();
  3739. if (empty($savElementId)) { // If the element we update was $this (so $elementId is null)
  3740. $this->statut = $status;
  3741. $this->status = $status;
  3742. }
  3743. return 1;
  3744. } else {
  3745. $this->db->rollback();
  3746. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  3747. return -1;
  3748. }
  3749. } else {
  3750. $this->error = $this->db->lasterror();
  3751. $this->db->rollback();
  3752. return -1;
  3753. }
  3754. }
  3755. /**
  3756. * Load type of canvas of an object if it exists
  3757. *
  3758. * @param int $id Record id
  3759. * @param string $ref Record ref
  3760. * @return int <0 if KO, 0 if nothing done, >0 if OK
  3761. */
  3762. public function getCanvas($id = 0, $ref = '')
  3763. {
  3764. global $conf;
  3765. if (empty($id) && empty($ref)) {
  3766. return 0;
  3767. }
  3768. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
  3769. return 0; // To increase speed. Not enabled by default.
  3770. }
  3771. // Clean parameters
  3772. $ref = trim($ref);
  3773. $sql = "SELECT rowid, canvas";
  3774. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
  3775. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  3776. if (!empty($id)) {
  3777. $sql .= " AND rowid = ".((int) $id);
  3778. }
  3779. if (!empty($ref)) {
  3780. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  3781. }
  3782. $resql = $this->db->query($sql);
  3783. if ($resql) {
  3784. $obj = $this->db->fetch_object($resql);
  3785. if ($obj) {
  3786. $this->canvas = $obj->canvas;
  3787. return 1;
  3788. } else {
  3789. return 0;
  3790. }
  3791. } else {
  3792. dol_print_error($this->db);
  3793. return -1;
  3794. }
  3795. }
  3796. /**
  3797. * Get special code of a line
  3798. *
  3799. * @param int $lineid Id of line
  3800. * @return int Special code
  3801. */
  3802. public function getSpecialCode($lineid)
  3803. {
  3804. $sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  3805. $sql .= ' WHERE rowid = '.((int) $lineid);
  3806. $resql = $this->db->query($sql);
  3807. if ($resql) {
  3808. $row = $this->db->fetch_row($resql);
  3809. return $row[0];
  3810. }
  3811. }
  3812. /**
  3813. * Function to check if an object is used by others.
  3814. * Check is done into this->childtables. There is no check into llx_element_element.
  3815. *
  3816. * @param int $id Force id of object
  3817. * @return int <0 if KO, 0 if not used, >0 if already used
  3818. */
  3819. public function isObjectUsed($id = 0)
  3820. {
  3821. global $langs;
  3822. if (empty($id)) {
  3823. $id = $this->id;
  3824. }
  3825. // Check parameters
  3826. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
  3827. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  3828. return -1;
  3829. }
  3830. $arraytoscan = $this->childtables;
  3831. // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
  3832. $tmparray = array_keys($this->childtables);
  3833. if (is_numeric($tmparray[0])) {
  3834. $arraytoscan = array_flip($this->childtables);
  3835. }
  3836. // Test if child exists
  3837. $haschild = 0;
  3838. foreach ($arraytoscan as $table => $elementname) {
  3839. //print $id.'-'.$table.'-'.$elementname.'<br>';
  3840. // Check if third party can be deleted
  3841. $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table;
  3842. $sql .= " WHERE ".$this->fk_element." = ".((int) $id);
  3843. $resql = $this->db->query($sql);
  3844. if ($resql) {
  3845. $obj = $this->db->fetch_object($resql);
  3846. if ($obj->nb > 0) {
  3847. $langs->load("errors");
  3848. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  3849. $haschild += $obj->nb;
  3850. if (is_numeric($elementname)) { // old usage
  3851. $this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table);
  3852. } else // new usage: $elementname=Translation key
  3853. {
  3854. $this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname));
  3855. }
  3856. break; // We found at least one, we stop here
  3857. }
  3858. } else {
  3859. $this->errors[] = $this->db->lasterror();
  3860. return -1;
  3861. }
  3862. }
  3863. if ($haschild > 0) {
  3864. $this->errors[] = "ErrorRecordHasChildren";
  3865. return $haschild;
  3866. } else {
  3867. return 0;
  3868. }
  3869. }
  3870. /**
  3871. * Function to say how many lines object contains
  3872. *
  3873. * @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
  3874. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  3875. */
  3876. public function hasProductsOrServices($predefined = -1)
  3877. {
  3878. $nb = 0;
  3879. foreach ($this->lines as $key => $val) {
  3880. $qualified = 0;
  3881. if ($predefined == -1) {
  3882. $qualified = 1;
  3883. }
  3884. if ($predefined == 1 && $val->fk_product > 0) {
  3885. $qualified = 1;
  3886. }
  3887. if ($predefined == 0 && $val->fk_product <= 0) {
  3888. $qualified = 1;
  3889. }
  3890. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
  3891. $qualified = 1;
  3892. }
  3893. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
  3894. $qualified = 1;
  3895. }
  3896. if ($qualified) {
  3897. $nb++;
  3898. }
  3899. }
  3900. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  3901. return $nb;
  3902. }
  3903. /**
  3904. * Function that returns the total amount HT of discounts applied for all lines.
  3905. *
  3906. * @return float|string Total amout of discount
  3907. */
  3908. public function getTotalDiscount()
  3909. {
  3910. if (!empty($this->table_element_line) ) {
  3911. $total_discount = 0.00;
  3912. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  3913. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  3914. $sql .= " WHERE ".$this->fk_element." = ".$this->id;
  3915. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  3916. $resql = $this->db->query($sql);
  3917. if ($resql) {
  3918. $num = $this->db->num_rows($resql);
  3919. $i = 0;
  3920. while ($i < $num) {
  3921. $obj = $this->db->fetch_object($resql);
  3922. $pu_ht = $obj->pu_ht;
  3923. $qty = $obj->qty;
  3924. $total_ht = $obj->total_ht;
  3925. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  3926. $total_discount += $total_discount_line;
  3927. $i++;
  3928. }
  3929. }
  3930. //print $total_discount; exit;
  3931. return price2num($total_discount);
  3932. }
  3933. return null;
  3934. }
  3935. /**
  3936. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  3937. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  3938. *
  3939. * @return array array('weight'=>...,'volume'=>...)
  3940. */
  3941. public function getTotalWeightVolume()
  3942. {
  3943. $totalWeight = 0;
  3944. $totalVolume = 0;
  3945. // defined for shipment only
  3946. $totalOrdered = '';
  3947. // defined for shipment only
  3948. $totalToShip = '';
  3949. foreach ($this->lines as $line) {
  3950. if (isset($line->qty_asked)) {
  3951. if (empty($totalOrdered)) {
  3952. $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  3953. }
  3954. $totalOrdered += $line->qty_asked; // defined for shipment only
  3955. }
  3956. if (isset($line->qty_shipped)) {
  3957. if (empty($totalToShip)) {
  3958. $totalToShip = 0; // Avoid warning because $totalToShip is ''
  3959. }
  3960. $totalToShip += $line->qty_shipped; // defined for shipment only
  3961. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
  3962. if (empty($totalToShip)) {
  3963. $totalToShip = 0;
  3964. }
  3965. $totalToShip += $line->qty; // defined for reception only
  3966. }
  3967. // Define qty, weight, volume, weight_units, volume_units
  3968. if ($this->element == 'shipping') {
  3969. // for shipments
  3970. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  3971. } else {
  3972. $qty = $line->qty ? $line->qty : 0;
  3973. }
  3974. $weight = $line->weight ? $line->weight : 0;
  3975. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  3976. $volume = $line->volume ? $line->volume : 0;
  3977. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  3978. $weight_units = $line->weight_units;
  3979. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  3980. $volume_units = $line->volume_units;
  3981. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  3982. $weightUnit = 0;
  3983. $volumeUnit = 0;
  3984. if (!empty($weight_units)) {
  3985. $weightUnit = $weight_units;
  3986. }
  3987. if (!empty($volume_units)) {
  3988. $volumeUnit = $volume_units;
  3989. }
  3990. if (empty($totalWeight)) {
  3991. $totalWeight = 0; // Avoid warning because $totalWeight is ''
  3992. }
  3993. if (empty($totalVolume)) {
  3994. $totalVolume = 0; // Avoid warning because $totalVolume is ''
  3995. }
  3996. //var_dump($line->volume_units);
  3997. if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  3998. $trueWeightUnit = pow(10, $weightUnit);
  3999. $totalWeight += $weight * $qty * $trueWeightUnit;
  4000. } else {
  4001. if ($weight_units == 99) {
  4002. // conversion 1 Pound = 0.45359237 KG
  4003. $trueWeightUnit = 0.45359237;
  4004. $totalWeight += $weight * $qty * $trueWeightUnit;
  4005. } elseif ($weight_units == 98) {
  4006. // conversion 1 Ounce = 0.0283495 KG
  4007. $trueWeightUnit = 0.0283495;
  4008. $totalWeight += $weight * $qty * $trueWeightUnit;
  4009. } else {
  4010. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  4011. }
  4012. }
  4013. if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4014. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  4015. $trueVolumeUnit = pow(10, $volumeUnit);
  4016. //print $line->volume;
  4017. $totalVolume += $volume * $qty * $trueVolumeUnit;
  4018. } else {
  4019. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  4020. }
  4021. }
  4022. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  4023. }
  4024. /**
  4025. * Set extra parameters
  4026. *
  4027. * @return int <0 if KO, >0 if OK
  4028. */
  4029. public function setExtraParameters()
  4030. {
  4031. $this->db->begin();
  4032. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  4033. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  4034. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  4035. $sql .= " WHERE rowid = ".$this->id;
  4036. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  4037. $resql = $this->db->query($sql);
  4038. if (!$resql) {
  4039. $this->error = $this->db->lasterror();
  4040. $this->db->rollback();
  4041. return -1;
  4042. } else {
  4043. $this->db->commit();
  4044. return 1;
  4045. }
  4046. }
  4047. // --------------------
  4048. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  4049. // --------------------
  4050. /* This is to show add lines */
  4051. /**
  4052. * Show add free and predefined products/services form
  4053. *
  4054. * @param int $dateSelector 1=Show also date range input fields
  4055. * @param Societe $seller Object thirdparty who sell
  4056. * @param Societe $buyer Object thirdparty who buy
  4057. * @param string $defaulttpldir Directory where to find the template
  4058. * @return void
  4059. */
  4060. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  4061. {
  4062. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  4063. global $form;
  4064. // Line extrafield
  4065. if (!is_object($extrafields)) {
  4066. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4067. $extrafields = new ExtraFields($this->db);
  4068. }
  4069. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4070. // Output template part (modules that overwrite templates must declare this into descriptor)
  4071. // Use global variables + $dateSelector + $seller and $buyer
  4072. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  4073. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4074. foreach ($dirtpls as $module => $reldir) {
  4075. if (!empty($module)) {
  4076. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  4077. } else {
  4078. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  4079. }
  4080. if (empty($conf->file->strict_mode)) {
  4081. $res = @include $tpl;
  4082. } else {
  4083. $res = include $tpl; // for debug
  4084. }
  4085. if ($res) {
  4086. break;
  4087. }
  4088. }
  4089. }
  4090. /* This is to show array of line of details */
  4091. /**
  4092. * Return HTML table for object lines
  4093. * TODO Move this into an output class file (htmlline.class.php)
  4094. * If lines are into a template, title must also be into a template
  4095. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4096. *
  4097. * @param string $action Action code
  4098. * @param string $seller Object of seller third party
  4099. * @param string $buyer Object of buyer third party
  4100. * @param int $selected Object line selected
  4101. * @param int $dateSelector 1=Show also date range input fields
  4102. * @param string $defaulttpldir Directory where to find the template
  4103. * @return void
  4104. */
  4105. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  4106. {
  4107. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  4108. // TODO We should not use global var for this
  4109. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  4110. // Define usemargins
  4111. $usemargins = 0;
  4112. if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
  4113. $usemargins = 1;
  4114. }
  4115. $num = count($this->lines);
  4116. // Line extrafield
  4117. if (!is_object($extrafields)) {
  4118. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4119. $extrafields = new ExtraFields($this->db);
  4120. }
  4121. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4122. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  4123. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4124. if (empty($reshook)) {
  4125. // Output template part (modules that overwrite templates must declare this into descriptor)
  4126. // Use global variables + $dateSelector + $seller and $buyer
  4127. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  4128. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4129. foreach ($dirtpls as $module => $reldir) {
  4130. if (!empty($module)) {
  4131. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  4132. } else {
  4133. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  4134. }
  4135. if (empty($conf->file->strict_mode)) {
  4136. $res = @include $tpl;
  4137. } else {
  4138. $res = include $tpl; // for debug
  4139. }
  4140. if ($res) {
  4141. break;
  4142. }
  4143. }
  4144. }
  4145. $i = 0;
  4146. print "<!-- begin printObjectLines() --><tbody>\n";
  4147. foreach ($this->lines as $line) {
  4148. //Line extrafield
  4149. $line->fetch_optionals();
  4150. //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  4151. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4152. if (empty($line->fk_parent_line)) {
  4153. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  4154. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4155. } else {
  4156. $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);
  4157. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4158. }
  4159. }
  4160. if (empty($reshook)) {
  4161. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  4162. }
  4163. $i++;
  4164. }
  4165. print "</tbody><!-- end printObjectLines() -->\n";
  4166. }
  4167. /**
  4168. * Return HTML content of a detail line
  4169. * TODO Move this into an output class file (htmlline.class.php)
  4170. *
  4171. * @param string $action GET/POST action
  4172. * @param CommonObjectLine $line Selected object line to output
  4173. * @param string $var Is it a an odd line (true)
  4174. * @param int $num Number of line (0)
  4175. * @param int $i I
  4176. * @param int $dateSelector 1=Show also date range input fields
  4177. * @param string $seller Object of seller third party
  4178. * @param string $buyer Object of buyer third party
  4179. * @param int $selected Object line selected
  4180. * @param Extrafields $extrafields Object of extrafields
  4181. * @param string $defaulttpldir Directory where to find the template (deprecated)
  4182. * @return void
  4183. */
  4184. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  4185. {
  4186. global $conf, $langs, $user, $object, $hookmanager;
  4187. global $form;
  4188. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  4189. $object_rights = $this->getRights();
  4190. $element = $this->element;
  4191. $text = '';
  4192. $description = '';
  4193. // Line in view mode
  4194. if ($action != 'editline' || $selected != $line->id) {
  4195. // Product
  4196. if ($line->fk_product > 0) {
  4197. $product_static = new Product($this->db);
  4198. $product_static->fetch($line->fk_product);
  4199. $product_static->ref = $line->ref; //can change ref in hook
  4200. $product_static->label = $line->label; //can change label in hook
  4201. $text = $product_static->getNomUrl(1);
  4202. // Define output language and label
  4203. if (!empty($conf->global->MAIN_MULTILANGS)) {
  4204. if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
  4205. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  4206. return;
  4207. }
  4208. $prod = new Product($this->db);
  4209. $prod->fetch($line->fk_product);
  4210. $outputlangs = $langs;
  4211. $newlang = '';
  4212. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  4213. $newlang = GETPOST('lang_id', 'aZ09');
  4214. }
  4215. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
  4216. $newlang = $this->thirdparty->default_lang; // To use language of customer
  4217. }
  4218. if (!empty($newlang)) {
  4219. $outputlangs = new Translate("", $conf);
  4220. $outputlangs->setDefaultLang($newlang);
  4221. }
  4222. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  4223. } else {
  4224. $label = $line->product_label;
  4225. }
  4226. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  4227. $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.
  4228. }
  4229. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4230. // Output template part (modules that overwrite templates must declare this into descriptor)
  4231. // Use global variables + $dateSelector + $seller and $buyer
  4232. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4233. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4234. foreach ($dirtpls as $module => $reldir) {
  4235. if (!empty($module)) {
  4236. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  4237. } else {
  4238. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  4239. }
  4240. if (empty($conf->file->strict_mode)) {
  4241. $res = @include $tpl;
  4242. } else {
  4243. $res = include $tpl; // for debug
  4244. }
  4245. if ($res) {
  4246. break;
  4247. }
  4248. }
  4249. }
  4250. // Line in update mode
  4251. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
  4252. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  4253. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4254. // Output template part (modules that overwrite templates must declare this into descriptor)
  4255. // Use global variables + $dateSelector + $seller and $buyer
  4256. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4257. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4258. foreach ($dirtpls as $module => $reldir) {
  4259. if (!empty($module)) {
  4260. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  4261. } else {
  4262. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  4263. }
  4264. if (empty($conf->file->strict_mode)) {
  4265. $res = @include $tpl;
  4266. } else {
  4267. $res = include $tpl; // for debug
  4268. }
  4269. if ($res) {
  4270. break;
  4271. }
  4272. }
  4273. }
  4274. }
  4275. /* This is to show array of line of details of source object */
  4276. /**
  4277. * Return HTML table table of source object lines
  4278. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4279. * If lines are into a template, title must also be into a template
  4280. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  4281. *
  4282. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  4283. * @param array $selectedLines Array of lines id for selected lines
  4284. * @return void
  4285. */
  4286. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  4287. {
  4288. global $langs, $hookmanager, $conf, $form;
  4289. print '<tr class="liste_titre">';
  4290. print '<td>'.$langs->trans('Ref').'</td>';
  4291. print '<td>'.$langs->trans('Description').'</td>';
  4292. print '<td class="right">'.$langs->trans('VATRate').'</td>';
  4293. print '<td class="right">'.$langs->trans('PriceUHT').'</td>';
  4294. if (!empty($conf->multicurrency->enabled)) {
  4295. print '<td class="right">'.$langs->trans('PriceUHTCurrency').'</td>';
  4296. }
  4297. print '<td class="right">'.$langs->trans('Qty').'</td>';
  4298. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4299. print '<td class="left">'.$langs->trans('Unit').'</td>';
  4300. }
  4301. print '<td class="right">'.$langs->trans('ReductionShort').'</td>';
  4302. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  4303. print '</tr>';
  4304. $i = 0;
  4305. if (!empty($this->lines)) {
  4306. foreach ($this->lines as $line) {
  4307. $reshook = 0;
  4308. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
  4309. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4310. if (empty($line->fk_parent_line)) {
  4311. $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
  4312. $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4313. } else {
  4314. $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines, 'fk_parent_line'=>$line->fk_parent_line);
  4315. $reshook = $hookmanager->executeHooks('printOriginObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4316. }
  4317. }
  4318. if (empty($reshook)) {
  4319. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  4320. }
  4321. $i++;
  4322. }
  4323. }
  4324. }
  4325. /**
  4326. * Return HTML with a line of table array of source object lines
  4327. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4328. * If lines are into a template, title must also be into a template
  4329. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4330. *
  4331. * @param CommonObjectLine $line Line
  4332. * @param string $var Var
  4333. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  4334. * @param string $defaulttpldir Directory where to find the template
  4335. * @param array $selectedLines Array of lines id for selected lines
  4336. * @return void
  4337. */
  4338. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  4339. {
  4340. global $langs, $conf;
  4341. //var_dump($line);
  4342. if (!empty($line->date_start)) {
  4343. $date_start = $line->date_start;
  4344. } else {
  4345. $date_start = $line->date_debut_prevue;
  4346. if ($line->date_debut_reel) {
  4347. $date_start = $line->date_debut_reel;
  4348. }
  4349. }
  4350. if (!empty($line->date_end)) {
  4351. $date_end = $line->date_end;
  4352. } else {
  4353. $date_end = $line->date_fin_prevue;
  4354. if ($line->date_fin_reel) {
  4355. $date_end = $line->date_fin_reel;
  4356. }
  4357. }
  4358. $this->tpl['id'] = $line->id;
  4359. $this->tpl['label'] = '';
  4360. if (!empty($line->fk_parent_line)) {
  4361. $this->tpl['label'] .= img_picto('', 'rightarrow');
  4362. }
  4363. if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
  4364. $discount = new DiscountAbsolute($this->db);
  4365. $discount->fk_soc = $this->socid;
  4366. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  4367. } elseif (!empty($line->fk_product)) {
  4368. $productstatic = new Product($this->db);
  4369. $productstatic->id = $line->fk_product;
  4370. $productstatic->ref = $line->ref;
  4371. $productstatic->type = $line->fk_product_type;
  4372. if (empty($productstatic->ref)) {
  4373. $line->fetch_product();
  4374. $productstatic = $line->product;
  4375. }
  4376. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  4377. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  4378. // Dates
  4379. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4380. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4381. }
  4382. } else {
  4383. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  4384. if (!empty($line->desc)) {
  4385. $this->tpl['label'] .= $line->desc;
  4386. } else {
  4387. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  4388. }
  4389. // Dates
  4390. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4391. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4392. }
  4393. }
  4394. if (!empty($line->desc)) {
  4395. if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
  4396. $discount = new DiscountAbsolute($this->db);
  4397. $discount->fetch($line->fk_remise_except);
  4398. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  4399. } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
  4400. $discount = new DiscountAbsolute($this->db);
  4401. $discount->fetch($line->fk_remise_except);
  4402. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  4403. } elseif ($line->desc == '(EXCESS RECEIVED)') {
  4404. $discount = new DiscountAbsolute($this->db);
  4405. $discount->fetch($line->fk_remise_except);
  4406. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  4407. } elseif ($line->desc == '(EXCESS PAID)') {
  4408. $discount = new DiscountAbsolute($this->db);
  4409. $discount->fetch($line->fk_remise_except);
  4410. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  4411. } else {
  4412. $this->tpl['description'] = dol_trunc($line->desc, 60);
  4413. }
  4414. } else {
  4415. $this->tpl['description'] = '&nbsp;';
  4416. }
  4417. // VAT Rate
  4418. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  4419. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  4420. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
  4421. $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  4422. }
  4423. $this->tpl['price'] = price($line->subprice);
  4424. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  4425. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  4426. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4427. $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  4428. }
  4429. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  4430. // Is the line strike or not
  4431. $this->tpl['strike'] = 0;
  4432. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
  4433. $this->tpl['strike'] = 1;
  4434. }
  4435. // Output template part (modules that overwrite templates must declare this into descriptor)
  4436. // Use global variables + $dateSelector + $seller and $buyer
  4437. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4438. foreach ($dirtpls as $module => $reldir) {
  4439. if (!empty($module)) {
  4440. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  4441. } else {
  4442. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  4443. }
  4444. if (empty($conf->file->strict_mode)) {
  4445. $res = @include $tpl;
  4446. } else {
  4447. $res = include $tpl; // for debug
  4448. }
  4449. if ($res) {
  4450. break;
  4451. }
  4452. }
  4453. }
  4454. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4455. /**
  4456. * Add resources to the current object : add entry into llx_element_resources
  4457. * Need $this->element & $this->id
  4458. *
  4459. * @param int $resource_id Resource id
  4460. * @param string $resource_type 'resource'
  4461. * @param int $busy Busy or not
  4462. * @param int $mandatory Mandatory or not
  4463. * @return int <=0 if KO, >0 if OK
  4464. */
  4465. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  4466. {
  4467. // phpcs:enable
  4468. $this->db->begin();
  4469. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources (";
  4470. $sql .= "resource_id";
  4471. $sql .= ", resource_type";
  4472. $sql .= ", element_id";
  4473. $sql .= ", element_type";
  4474. $sql .= ", busy";
  4475. $sql .= ", mandatory";
  4476. $sql .= ") VALUES (";
  4477. $sql .= $resource_id;
  4478. $sql .= ", '".$this->db->escape($resource_type)."'";
  4479. $sql .= ", '".$this->db->escape($this->id)."'";
  4480. $sql .= ", '".$this->db->escape($this->element)."'";
  4481. $sql .= ", '".$this->db->escape($busy)."'";
  4482. $sql .= ", '".$this->db->escape($mandatory)."'";
  4483. $sql .= ")";
  4484. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  4485. if ($this->db->query($sql)) {
  4486. $this->db->commit();
  4487. return 1;
  4488. } else {
  4489. $this->error = $this->db->lasterror();
  4490. $this->db->rollback();
  4491. return 0;
  4492. }
  4493. }
  4494. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4495. /**
  4496. * Delete a link to resource line
  4497. *
  4498. * @param int $rowid Id of resource line to delete
  4499. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  4500. * @param int $notrigger Disable all triggers
  4501. * @return int >0 if OK, <0 if KO
  4502. */
  4503. public function delete_resource($rowid, $element, $notrigger = 0)
  4504. {
  4505. // phpcs:enable
  4506. global $user;
  4507. $this->db->begin();
  4508. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
  4509. $sql .= " WHERE rowid = ".((int) $rowid);
  4510. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  4511. $resql = $this->db->query($sql);
  4512. if (!$resql) {
  4513. $this->error = $this->db->lasterror();
  4514. $this->db->rollback();
  4515. return -1;
  4516. } else {
  4517. if (!$notrigger) {
  4518. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  4519. if ($result < 0) {
  4520. $this->db->rollback();
  4521. return -1;
  4522. }
  4523. }
  4524. $this->db->commit();
  4525. return 1;
  4526. }
  4527. }
  4528. /**
  4529. * Overwrite magic function to solve problem of cloning object that are kept as references
  4530. *
  4531. * @return void
  4532. */
  4533. public function __clone()
  4534. {
  4535. // Force a copy of this->lines, otherwise it will point to same object.
  4536. if (isset($this->lines) && is_array($this->lines)) {
  4537. $nboflines = count($this->lines);
  4538. for ($i = 0; $i < $nboflines; $i++) {
  4539. $this->lines[$i] = clone $this->lines[$i];
  4540. }
  4541. }
  4542. }
  4543. /**
  4544. * Common function for all objects extending CommonObject for generating documents
  4545. *
  4546. * @param string $modelspath Relative folder where generators are placed
  4547. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4548. * @param Translate $outputlangs Output language to use
  4549. * @param int $hidedetails 1 to hide details. 0 by default
  4550. * @param int $hidedesc 1 to hide product description. 0 by default
  4551. * @param int $hideref 1 to hide product reference. 0 by default
  4552. * @param null|array $moreparams Array to provide more information
  4553. * @return int >0 if OK, <0 if KO
  4554. * @see addFileIntoDatabaseIndex()
  4555. */
  4556. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4557. {
  4558. global $conf, $langs, $user, $hookmanager, $action;
  4559. $srctemplatepath = '';
  4560. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  4561. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4562. if (empty($reshook)) {
  4563. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4564. if (empty($modele)) {
  4565. $this->error = 'BadValueForParameterModele';
  4566. return -1;
  4567. }
  4568. // Increase limit for PDF build
  4569. $err = error_reporting();
  4570. error_reporting(0);
  4571. @set_time_limit(120);
  4572. error_reporting($err);
  4573. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4574. $tmp = explode(':', $modele, 2);
  4575. if (!empty($tmp[1])) {
  4576. $modele = $tmp[0];
  4577. $srctemplatepath = $tmp[1];
  4578. }
  4579. // Search template files
  4580. $file = '';
  4581. $classname = '';
  4582. $filefound = '';
  4583. $dirmodels = array('/');
  4584. if (is_array($conf->modules_parts['models'])) {
  4585. $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4586. }
  4587. foreach ($dirmodels as $reldir) {
  4588. foreach (array('doc', 'pdf') as $prefix) {
  4589. if (in_array(get_class($this), array('Adherent'))) {
  4590. // Member module use prefix_modele.class.php
  4591. $file = $prefix."_".$modele.".class.php";
  4592. } else {
  4593. // Other module use prefix_modele.modules.php
  4594. $file = $prefix."_".$modele.".modules.php";
  4595. }
  4596. // On verifie l'emplacement du modele
  4597. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  4598. if (file_exists($file)) {
  4599. $filefound = $file;
  4600. $classname = $prefix.'_'.$modele;
  4601. break;
  4602. }
  4603. }
  4604. if ($filefound) {
  4605. break;
  4606. }
  4607. }
  4608. // If generator was found
  4609. if ($filefound) {
  4610. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4611. require_once $file;
  4612. $obj = new $classname($this->db);
  4613. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4614. if ($obj->type == 'odt' && empty($srctemplatepath)) {
  4615. $varfortemplatedir = $obj->scandir;
  4616. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
  4617. $dirtoscan = $conf->global->$varfortemplatedir;
  4618. $listoffiles = array();
  4619. // Now we add first model found in directories scanned
  4620. $listofdir = explode(',', $dirtoscan);
  4621. foreach ($listofdir as $key => $tmpdir) {
  4622. $tmpdir = trim($tmpdir);
  4623. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4624. if (!$tmpdir) {
  4625. unset($listofdir[$key]);
  4626. continue;
  4627. }
  4628. if (is_dir($tmpdir)) {
  4629. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4630. if (count($tmpfiles)) {
  4631. $listoffiles = array_merge($listoffiles, $tmpfiles);
  4632. }
  4633. }
  4634. }
  4635. if (count($listoffiles)) {
  4636. foreach ($listoffiles as $record) {
  4637. $srctemplatepath = $record['fullname'];
  4638. break;
  4639. }
  4640. }
  4641. }
  4642. if (empty($srctemplatepath)) {
  4643. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4644. return -1;
  4645. }
  4646. }
  4647. if ($obj->type == 'odt' && !empty($srctemplatepath)) {
  4648. if (!dol_is_file($srctemplatepath)) {
  4649. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  4650. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4651. return -1;
  4652. }
  4653. }
  4654. // We save charset_output to restore it because write_file can change it if needed for
  4655. // output format that does not support UTF8.
  4656. $sav_charset_output = $outputlangs->charset_output;
  4657. if (in_array(get_class($this), array('Adherent'))) {
  4658. $arrayofrecords = array(); // The write_file of templates of adherent class need this var
  4659. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams);
  4660. } else {
  4661. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4662. }
  4663. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4664. if ($resultwritefile > 0) {
  4665. $outputlangs->charset_output = $sav_charset_output;
  4666. // We delete old preview
  4667. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4668. dol_delete_preview($this);
  4669. // Index file in database
  4670. if (!empty($obj->result['fullpath'])) {
  4671. $destfull = $obj->result['fullpath'];
  4672. $upload_dir = dirname($destfull);
  4673. $destfile = basename($destfull);
  4674. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  4675. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  4676. $filename = basename($destfile);
  4677. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4678. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4679. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4680. $ecmfile = new EcmFiles($this->db);
  4681. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  4682. // Set the public "share" key
  4683. $setsharekey = false;
  4684. if ($this->element == 'propal') {
  4685. $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok
  4686. if ($useonlinesignature) {
  4687. $setsharekey = true;
  4688. }
  4689. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4690. $setsharekey = true;
  4691. }
  4692. }
  4693. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  4694. $setsharekey = true;
  4695. }
  4696. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  4697. $setsharekey = true;
  4698. }
  4699. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4700. $setsharekey = true;
  4701. }
  4702. if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4703. $setsharekey = true;
  4704. }
  4705. if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4706. $setsharekey = true;
  4707. }
  4708. if ($setsharekey) {
  4709. if (empty($ecmfile->share)) { // Because object not found or share not set yet
  4710. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  4711. $ecmfile->share = getRandomPassword(true);
  4712. }
  4713. }
  4714. if ($result > 0) {
  4715. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4716. $ecmfile->fullpath_orig = '';
  4717. $ecmfile->gen_or_uploaded = 'generated';
  4718. $ecmfile->description = ''; // indexed content
  4719. $ecmfile->keywords = ''; // keyword content
  4720. $result = $ecmfile->update($user);
  4721. if ($result < 0) {
  4722. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4723. }
  4724. } else {
  4725. $ecmfile->entity = $conf->entity;
  4726. $ecmfile->filepath = $rel_dir;
  4727. $ecmfile->filename = $filename;
  4728. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4729. $ecmfile->fullpath_orig = '';
  4730. $ecmfile->gen_or_uploaded = 'generated';
  4731. $ecmfile->description = ''; // indexed content
  4732. $ecmfile->keywords = ''; // keyword content
  4733. $ecmfile->src_object_type = $this->table_element;
  4734. $ecmfile->src_object_id = $this->id;
  4735. $result = $ecmfile->create($user);
  4736. if ($result < 0) {
  4737. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4738. }
  4739. }
  4740. /*$this->result['fullname']=$destfull;
  4741. $this->result['filepath']=$ecmfile->filepath;
  4742. $this->result['filename']=$ecmfile->filename;*/
  4743. //var_dump($obj->update_main_doc_field);exit;
  4744. // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
  4745. $update_main_doc_field = 0;
  4746. if (!empty($obj->update_main_doc_field)) {
  4747. $update_main_doc_field = 1;
  4748. }
  4749. if ($update_main_doc_field && !empty($this->table_element)) {
  4750. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath.'/'.$ecmfile->filename)."'";
  4751. $sql .= ' WHERE rowid = '.$this->id;
  4752. $resql = $this->db->query($sql);
  4753. if (!$resql) {
  4754. dol_print_error($this->db);
  4755. } else {
  4756. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  4757. }
  4758. }
  4759. }
  4760. } else {
  4761. 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);
  4762. }
  4763. // Success in building document. We build meta file.
  4764. dol_meta_create($this);
  4765. return 1;
  4766. } else {
  4767. $outputlangs->charset_output = $sav_charset_output;
  4768. dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
  4769. return -1;
  4770. }
  4771. } else {
  4772. if (!$filefound) {
  4773. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4774. dol_print_error('', $this->error);
  4775. } else {
  4776. $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
  4777. dol_print_error('', $this->error);
  4778. }
  4779. return -1;
  4780. }
  4781. } else {
  4782. return $reshook;
  4783. }
  4784. }
  4785. /**
  4786. * Build thumb
  4787. * @todo Move this into files.lib.php
  4788. *
  4789. * @param string $file Path file in UTF8 to original file to create thumbs from.
  4790. * @return void
  4791. */
  4792. public function addThumbs($file)
  4793. {
  4794. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  4795. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  4796. $file_osencoded = dol_osencode($file);
  4797. if (file_exists($file_osencoded)) {
  4798. // Create small thumbs for company (Ratio is near 16/9)
  4799. // Used on logon for example
  4800. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  4801. // Create mini thumbs for company (Ratio is near 16/9)
  4802. // Used on menu or for setup page for example
  4803. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  4804. }
  4805. }
  4806. /* Functions common to commonobject and commonobjectline */
  4807. /* For default values */
  4808. /**
  4809. * Return the default value to use for a field when showing the create form of object.
  4810. * Return values in this order:
  4811. * 1) If parameter is available into POST, we return it first.
  4812. * 2) If not but an alternate value was provided as parameter of function, we return it.
  4813. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  4814. * 4) Return value found into database (TODO No yet implemented)
  4815. *
  4816. * @param string $fieldname Name of field
  4817. * @param string $alternatevalue Alternate value to use
  4818. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  4819. **/
  4820. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
  4821. {
  4822. global $conf, $_POST;
  4823. // If param here has been posted, we use this value first.
  4824. if (GETPOSTISSET($fieldname)) {
  4825. return GETPOST($fieldname, 'alphanohtml', 3);
  4826. }
  4827. if (isset($alternatevalue)) {
  4828. return $alternatevalue;
  4829. }
  4830. $newelement = $this->element;
  4831. if ($newelement == 'facture') {
  4832. $newelement = 'invoice';
  4833. }
  4834. if ($newelement == 'commande') {
  4835. $newelement = 'order';
  4836. }
  4837. if (empty($newelement)) {
  4838. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  4839. return '';
  4840. }
  4841. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  4842. //var_dump($keyforfieldname);
  4843. if (isset($conf->global->$keyforfieldname)) {
  4844. return $conf->global->$keyforfieldname;
  4845. }
  4846. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  4847. }
  4848. /* For triggers */
  4849. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4850. /**
  4851. * Call trigger based on this instance.
  4852. * Some context information may also be provided into array property this->context.
  4853. * NB: Error from trigger are stacked in interface->errors
  4854. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  4855. *
  4856. * @param string $triggerName trigger's name to execute
  4857. * @param User $user Object user
  4858. * @return int Result of run_triggers
  4859. */
  4860. public function call_trigger($triggerName, $user)
  4861. {
  4862. // phpcs:enable
  4863. global $langs, $conf;
  4864. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  4865. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4866. $langs = new Translate('', $conf);
  4867. }
  4868. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  4869. $interface = new Interfaces($this->db);
  4870. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  4871. if ($result < 0) {
  4872. if (!empty($this->errors)) {
  4873. $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.
  4874. } else {
  4875. $this->errors = $interface->errors;
  4876. }
  4877. }
  4878. return $result;
  4879. }
  4880. /* Functions for data in other language */
  4881. /**
  4882. * Function to get alternative languages of a data into $this->array_languages
  4883. * This method is NOT called by method fetch of objects but must be called separately.
  4884. *
  4885. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  4886. * @see fetch_optionnals()
  4887. */
  4888. public function fetchValuesForExtraLanguages()
  4889. {
  4890. // To avoid SQL errors. Probably not the better solution though
  4891. if (!$this->element) {
  4892. return 0;
  4893. }
  4894. if (!($this->id > 0)) {
  4895. return 0;
  4896. }
  4897. if (is_array($this->array_languages)) {
  4898. return 1;
  4899. }
  4900. $this->array_languages = array();
  4901. $element = $this->element;
  4902. if ($element == 'categorie') {
  4903. $element = 'categories'; // For compatibility
  4904. }
  4905. // Request to get translation values for object
  4906. $sql = "SELECT rowid, property, lang , value";
  4907. $sql .= " FROM ".MAIN_DB_PREFIX."object_lang";
  4908. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  4909. $sql .= " AND fk_object = ".$this->id;
  4910. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  4911. $resql = $this->db->query($sql);
  4912. if ($resql) {
  4913. $numrows = $this->db->num_rows($resql);
  4914. if ($numrows) {
  4915. $i = 0;
  4916. while ($i < $numrows) {
  4917. $obj = $this->db->fetch_object($resql);
  4918. $key = $obj->property;
  4919. $value = $obj->value;
  4920. $codelang = $obj->lang;
  4921. $type = $this->fields[$key]['type'];
  4922. // we can add this attribute to object
  4923. if (preg_match('/date/', $type)) {
  4924. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  4925. } else {
  4926. $this->array_languages[$key][$codelang] = $value;
  4927. }
  4928. $i++;
  4929. }
  4930. }
  4931. $this->db->free($resql);
  4932. if ($numrows) {
  4933. return $numrows;
  4934. } else {
  4935. return 0;
  4936. }
  4937. } else {
  4938. dol_print_error($this->db);
  4939. return -1;
  4940. }
  4941. }
  4942. /**
  4943. * Fill array_options property of object by extrafields value (using for data sent by forms)
  4944. *
  4945. * @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.
  4946. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  4947. */
  4948. public function setValuesForExtraLanguages($onlykey = '')
  4949. {
  4950. global $_POST, $langs;
  4951. // Get extra fields
  4952. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  4953. $tmparray = explode('-', $postfieldkey);
  4954. if ($tmparray[0] != 'field') {
  4955. continue;
  4956. }
  4957. $element = $tmparray[1];
  4958. $key = $tmparray[2];
  4959. $codelang = $tmparray[3];
  4960. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  4961. if (!empty($onlykey) && $key != $onlykey) {
  4962. continue;
  4963. }
  4964. if ($element != $this->element) {
  4965. continue;
  4966. }
  4967. $key_type = $this->fields[$key]['type'];
  4968. $enabled = 1;
  4969. if (isset($this->fields[$key]['enabled'])) {
  4970. $enabled = dol_eval($this->fields[$key]['enabled'], 1);
  4971. }
  4972. /*$perms = 1;
  4973. if (isset($this->fields[$key]['perms']))
  4974. {
  4975. $perms = dol_eval($this->fields[$key]['perms'], 1);
  4976. }*/
  4977. if (empty($enabled)) {
  4978. continue;
  4979. }
  4980. //if (empty($perms)) continue;
  4981. if (in_array($key_type, array('date'))) {
  4982. // Clean parameters
  4983. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  4984. $value_key = dol_mktime(0, 0, 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]);
  4985. } elseif (in_array($key_type, array('datetime'))) {
  4986. // Clean parameters
  4987. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  4988. $value_key = dol_mktime($_POST[$postfieldkey."hour"], $_POST[$postfieldkey."min"], 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]);
  4989. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  4990. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  4991. if (!empty($value_arr)) {
  4992. $value_key = implode(',', $value_arr);
  4993. } else {
  4994. $value_key = '';
  4995. }
  4996. } elseif (in_array($key_type, array('price', 'double'))) {
  4997. $value_arr = GETPOST($postfieldkey, 'alpha');
  4998. $value_key = price2num($value_arr);
  4999. } else {
  5000. $value_key = GETPOST($postfieldkey);
  5001. if (in_array($key_type, array('link')) && $value_key == '-1') {
  5002. $value_key = '';
  5003. }
  5004. }
  5005. $this->array_languages[$key][$codelang] = $value_key;
  5006. /*if ($nofillrequired) {
  5007. $langs->load('errors');
  5008. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  5009. return -1;
  5010. }*/
  5011. }
  5012. return 1;
  5013. }
  5014. /* Functions for extrafields */
  5015. /**
  5016. * Function to make a fetch but set environment to avoid to load computed values before.
  5017. *
  5018. * @param int $id ID of object
  5019. * @return int >0 if OK, 0 if not found, <0 if KO
  5020. */
  5021. public function fetchNoCompute($id)
  5022. {
  5023. global $conf;
  5024. $savDisableCompute = $conf->disable_compute;
  5025. $conf->disable_compute = 1;
  5026. $ret = $this->fetch($id);
  5027. $conf->disable_compute = $savDisableCompute;
  5028. return $ret;
  5029. }
  5030. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5031. /**
  5032. * Function to get extra fields of an object into $this->array_options
  5033. * This method is in most cases called by method fetch of objects but you can call it separately.
  5034. *
  5035. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  5036. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  5037. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  5038. * @see fetchValuesForExtraLanguages()
  5039. */
  5040. public function fetch_optionals($rowid = null, $optionsArray = null)
  5041. {
  5042. // phpcs:enable
  5043. global $conf, $extrafields;
  5044. if (empty($rowid)) {
  5045. $rowid = $this->id;
  5046. }
  5047. if (empty($rowid) && isset($this->rowid)) {
  5048. $rowid = $this->rowid; // deprecated
  5049. }
  5050. // To avoid SQL errors. Probably not the better solution though
  5051. if (!$this->table_element) {
  5052. return 0;
  5053. }
  5054. $this->array_options = array();
  5055. if (!is_array($optionsArray)) {
  5056. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  5057. if (!isset($extrafields) || !is_object($extrafields)) {
  5058. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5059. $extrafields = new ExtraFields($this->db);
  5060. }
  5061. // Load array of extrafields for elementype = $this->table_element
  5062. if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
  5063. $extrafields->fetch_name_optionals_label($this->table_element);
  5064. }
  5065. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  5066. } else {
  5067. global $extrafields;
  5068. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  5069. }
  5070. $table_element = $this->table_element;
  5071. if ($table_element == 'categorie') {
  5072. $table_element = 'categories'; // For compatibility
  5073. }
  5074. // Request to get complementary values
  5075. if (is_array($optionsArray) && count($optionsArray) > 0) {
  5076. $sql = "SELECT rowid";
  5077. foreach ($optionsArray as $name => $label) {
  5078. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
  5079. $sql .= ", ".$name;
  5080. }
  5081. }
  5082. $sql .= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
  5083. $sql .= " WHERE fk_object = ".((int) $rowid);
  5084. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5085. $resql = $this->db->query($sql);
  5086. if ($resql) {
  5087. $numrows = $this->db->num_rows($resql);
  5088. if ($numrows) {
  5089. $tab = $this->db->fetch_array($resql);
  5090. foreach ($tab as $key => $value) {
  5091. // 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)
  5092. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
  5093. // we can add this attribute to object
  5094. if (!empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
  5095. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  5096. $this->array_options["options_".$key] = $this->db->jdate($value);
  5097. } else {
  5098. $this->array_options["options_".$key] = $value;
  5099. }
  5100. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  5101. }
  5102. }
  5103. // If field is a computed field, value must become result of compute
  5104. foreach ($tab as $key => $value) {
  5105. if (!empty($extrafields) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
  5106. //var_dump($conf->disable_compute);
  5107. if (empty($conf->disable_compute)) {
  5108. $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0);
  5109. }
  5110. }
  5111. }
  5112. }
  5113. $this->db->free($resql);
  5114. if ($numrows) {
  5115. return $numrows;
  5116. } else {
  5117. return 0;
  5118. }
  5119. } else {
  5120. $this->errors[]=$this->db->lasterror;
  5121. return -1;
  5122. }
  5123. }
  5124. return 0;
  5125. }
  5126. /**
  5127. * Delete all extra fields values for the current object.
  5128. *
  5129. * @return int <0 if KO, >0 if OK
  5130. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  5131. */
  5132. public function deleteExtraFields()
  5133. {
  5134. global $conf;
  5135. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5136. return 0;
  5137. }
  5138. $this->db->begin();
  5139. $table_element = $this->table_element;
  5140. if ($table_element == 'categorie') {
  5141. $table_element = 'categories'; // For compatibility
  5142. }
  5143. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  5144. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
  5145. $resql = $this->db->query($sql_del);
  5146. if (!$resql) {
  5147. $this->error = $this->db->lasterror();
  5148. $this->db->rollback();
  5149. return -1;
  5150. } else {
  5151. $this->db->commit();
  5152. return 1;
  5153. }
  5154. }
  5155. /**
  5156. * Add/Update all extra fields values for the current object.
  5157. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5158. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5159. *
  5160. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5161. * @param User $userused Object user
  5162. * @return int -1=error, O=did nothing, 1=OK
  5163. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  5164. */
  5165. public function insertExtraFields($trigger = '', $userused = null)
  5166. {
  5167. global $conf, $langs, $user;
  5168. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5169. return 0;
  5170. }
  5171. if (empty($userused)) {
  5172. $userused = $user;
  5173. }
  5174. $error = 0;
  5175. if (!empty($this->array_options)) {
  5176. // Check parameters
  5177. $langs->load('admin');
  5178. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5179. $extrafields = new ExtraFields($this->db);
  5180. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  5181. // Eliminate copied source object extra fields that do not exist in target object
  5182. $new_array_options = array();
  5183. foreach ($this->array_options as $key => $value) {
  5184. if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
  5185. $new_array_options[$key] = $value;
  5186. } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
  5187. $new_array_options['options_'.$key] = $value;
  5188. }
  5189. }
  5190. foreach ($new_array_options as $key => $value) {
  5191. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5192. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  5193. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  5194. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  5195. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  5196. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  5197. // Similar code than into insertExtraFields
  5198. if ($attributeRequired) {
  5199. $mandatorypb = false;
  5200. if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
  5201. $mandatorypb = true;
  5202. }
  5203. if ($this->array_options[$key] === '') {
  5204. $mandatorypb = true;
  5205. }
  5206. if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
  5207. $mandatorypb = true;
  5208. }
  5209. if ($mandatorypb) {
  5210. $langs->load("errors");
  5211. dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
  5212. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5213. return -1;
  5214. }
  5215. }
  5216. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5217. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5218. if (!empty($attrfieldcomputed)) {
  5219. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5220. $value = dol_eval($attrfieldcomputed, 1, 0);
  5221. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5222. $new_array_options[$key] = $value;
  5223. } else {
  5224. $new_array_options[$key] = null;
  5225. }
  5226. }
  5227. switch ($attributeType) {
  5228. case 'int':
  5229. if (!is_numeric($value) && $value != '') {
  5230. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5231. return -1;
  5232. } elseif ($value == '') {
  5233. $new_array_options[$key] = null;
  5234. }
  5235. break;
  5236. case 'price':
  5237. case 'double':
  5238. $value = price2num($value);
  5239. if (!is_numeric($value) && $value != '') {
  5240. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5241. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5242. return -1;
  5243. } elseif ($value == '') {
  5244. $new_array_options[$key] = null;
  5245. }
  5246. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5247. $new_array_options[$key] = $value;
  5248. break;
  5249. /*case 'select': // Not required, we chosed value='0' for undefined values
  5250. if ($value=='-1')
  5251. {
  5252. $this->array_options[$key] = null;
  5253. }
  5254. break;*/
  5255. case 'password':
  5256. $algo = '';
  5257. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
  5258. // If there is an encryption choice, we use it to crypt data before insert
  5259. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  5260. $algo = reset($tmparrays);
  5261. if ($algo != '') {
  5262. //global $action; // $action may be 'create', 'update', 'update_extras'...
  5263. //var_dump($action);
  5264. //var_dump($this->oldcopy);exit;
  5265. 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
  5266. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  5267. 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.
  5268. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5269. } else {
  5270. // var_dump($algo);
  5271. $newvalue = dol_hash($this->array_options[$key], $algo);
  5272. $new_array_options[$key] = $newvalue;
  5273. }
  5274. } else {
  5275. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5276. }
  5277. }
  5278. } else // Common usage
  5279. {
  5280. $new_array_options[$key] = $this->array_options[$key];
  5281. }
  5282. break;
  5283. case 'date':
  5284. case 'datetime':
  5285. // If data is a string instead of a timestamp, we convert it
  5286. if (!is_int($this->array_options[$key])) {
  5287. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5288. }
  5289. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  5290. break;
  5291. case 'link':
  5292. $param_list = array_keys($attributeParam['options']);
  5293. // 0 : ObjectName
  5294. // 1 : classPath
  5295. $InfoFieldList = explode(":", $param_list[0]);
  5296. dol_include_once($InfoFieldList[1]);
  5297. if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
  5298. if ($value == '-1') { // -1 is key for no defined in combo list of objects
  5299. $new_array_options[$key] = '';
  5300. } elseif ($value) {
  5301. $object = new $InfoFieldList[0]($this->db);
  5302. if (is_numeric($value)) {
  5303. $res = $object->fetch($value); // Common case
  5304. } else {
  5305. $res = $object->fetch('', $value); // For compatibility
  5306. }
  5307. if ($res > 0) {
  5308. $new_array_options[$key] = $object->id;
  5309. } else {
  5310. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5311. $this->db->rollback();
  5312. return -1;
  5313. }
  5314. }
  5315. } else {
  5316. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5317. }
  5318. break;
  5319. }
  5320. }
  5321. $this->db->begin();
  5322. $table_element = $this->table_element;
  5323. if ($table_element == 'categorie') {
  5324. $table_element = 'categories'; // For compatibility
  5325. }
  5326. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  5327. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
  5328. $this->db->query($sql_del);
  5329. $sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object";
  5330. foreach ($new_array_options as $key => $value) {
  5331. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5332. // Add field of attribut
  5333. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
  5334. $sql .= ",".$attributeKey;
  5335. }
  5336. }
  5337. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5338. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5339. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5340. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5341. $sql .= ",".$tmpkey;
  5342. }
  5343. }
  5344. }
  5345. $sql .= ") VALUES (".$this->id;
  5346. foreach ($new_array_options as $key => $value) {
  5347. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5348. // Add field of attribute
  5349. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
  5350. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
  5351. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  5352. } else {
  5353. $sql .= ",null";
  5354. }
  5355. }
  5356. }
  5357. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5358. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5359. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5360. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5361. if (in_array($tmpval, array('int', 'double', 'price'))) {
  5362. $sql .= ", 0";
  5363. } else {
  5364. $sql .= ", ''";
  5365. }
  5366. }
  5367. }
  5368. }
  5369. $sql .= ")";
  5370. $resql = $this->db->query($sql);
  5371. if (!$resql) {
  5372. $this->error = $this->db->lasterror();
  5373. $error++;
  5374. }
  5375. if (!$error && $trigger) {
  5376. // Call trigger
  5377. $this->context = array('extrafieldaddupdate'=>1);
  5378. $result = $this->call_trigger($trigger, $userused);
  5379. if ($result < 0) {
  5380. $error++;
  5381. }
  5382. // End call trigger
  5383. }
  5384. if ($error) {
  5385. $this->db->rollback();
  5386. return -1;
  5387. } else {
  5388. $this->db->commit();
  5389. return 1;
  5390. }
  5391. } else {
  5392. return 0;
  5393. }
  5394. }
  5395. /**
  5396. * Add/Update all extra fields values for the current object.
  5397. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5398. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5399. *
  5400. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5401. * @param User $userused Object user
  5402. * @return int -1=error, O=did nothing, 1=OK
  5403. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  5404. */
  5405. public function insertExtraLanguages($trigger = '', $userused = null)
  5406. {
  5407. global $conf, $langs, $user;
  5408. if (empty($userused)) {
  5409. $userused = $user;
  5410. }
  5411. $error = 0;
  5412. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5413. return 0; // For avoid conflicts if trigger used
  5414. }
  5415. if (is_array($this->array_languages)) {
  5416. $new_array_languages = $this->array_languages;
  5417. foreach ($new_array_languages as $key => $value) {
  5418. $attributeKey = $key;
  5419. $attributeType = $this->fields[$attributeKey]['type'];
  5420. $attributeLabel = $this->fields[$attributeKey]['label'];
  5421. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5422. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5423. switch ($attributeType) {
  5424. case 'int':
  5425. if (!is_numeric($value) && $value != '') {
  5426. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5427. return -1;
  5428. } elseif ($value == '') {
  5429. $new_array_languages[$key] = null;
  5430. }
  5431. break;
  5432. case 'double':
  5433. $value = price2num($value);
  5434. if (!is_numeric($value) && $value != '') {
  5435. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5436. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5437. return -1;
  5438. } elseif ($value == '') {
  5439. $new_array_languages[$key] = null;
  5440. }
  5441. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5442. $new_array_languages[$key] = $value;
  5443. break;
  5444. /*case 'select': // Not required, we chosed value='0' for undefined values
  5445. if ($value=='-1')
  5446. {
  5447. $this->array_options[$key] = null;
  5448. }
  5449. break;*/
  5450. }
  5451. }
  5452. $this->db->begin();
  5453. $table_element = $this->table_element;
  5454. if ($table_element == 'categorie') {
  5455. $table_element = 'categories'; // For compatibility
  5456. }
  5457. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  5458. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  5459. foreach ($langcodearray as $langcode => $value) {
  5460. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX."object_lang";
  5461. $sql_del .= " WHERE fk_object = ".$this->id." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  5462. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  5463. $this->db->query($sql_del);
  5464. if ($value !== '') {
  5465. $sql = "INSERT INTO ".MAIN_DB_PREFIX."object_lang (fk_object, property, type_object, lang, value";
  5466. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  5467. $sql .= ")";
  5468. $resql = $this->db->query($sql);
  5469. if (!$resql) {
  5470. $this->error = $this->db->lasterror();
  5471. $error++;
  5472. break;
  5473. }
  5474. }
  5475. }
  5476. }
  5477. if (!$error && $trigger) {
  5478. // Call trigger
  5479. $this->context = array('extralanguagesaddupdate'=>1);
  5480. $result = $this->call_trigger($trigger, $userused);
  5481. if ($result < 0) {
  5482. $error++;
  5483. }
  5484. // End call trigger
  5485. }
  5486. if ($error) {
  5487. $this->db->rollback();
  5488. return -1;
  5489. } else {
  5490. $this->db->commit();
  5491. return 1;
  5492. }
  5493. } else {
  5494. return 0;
  5495. }
  5496. }
  5497. /**
  5498. * Update 1 extra field value for the current object. Keep other fields unchanged.
  5499. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5500. *
  5501. * @param string $key Key of the extrafield to update (without starting 'options_')
  5502. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5503. * @param User $userused Object user
  5504. * @return int -1=error, O=did nothing, 1=OK
  5505. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  5506. */
  5507. public function updateExtraField($key, $trigger = null, $userused = null)
  5508. {
  5509. global $conf, $langs, $user;
  5510. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5511. return 0;
  5512. }
  5513. if (empty($userused)) {
  5514. $userused = $user;
  5515. }
  5516. $error = 0;
  5517. if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
  5518. // Check parameters
  5519. $langs->load('admin');
  5520. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5521. $extrafields = new ExtraFields($this->db);
  5522. $extrafields->fetch_name_optionals_label($this->table_element);
  5523. $value = $this->array_options["options_".$key];
  5524. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  5525. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  5526. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  5527. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  5528. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  5529. // Similar code than into insertExtraFields
  5530. if ($attributeRequired) {
  5531. $mandatorypb = false;
  5532. if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
  5533. $mandatorypb = true;
  5534. }
  5535. if ($this->array_options["options_".$key] === '') {
  5536. $mandatorypb = true;
  5537. }
  5538. if ($mandatorypb) {
  5539. $langs->load("errors");
  5540. dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
  5541. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5542. return -1;
  5543. }
  5544. }
  5545. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5546. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5547. if (!empty($attrfieldcomputed)) {
  5548. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5549. $value = dol_eval($attrfieldcomputed, 1, 0);
  5550. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5551. $this->array_options["options_".$key] = $value;
  5552. } else {
  5553. $this->array_options["options_".$key] = null;
  5554. }
  5555. }
  5556. switch ($attributeType) {
  5557. case 'int':
  5558. if (!is_numeric($value) && $value != '') {
  5559. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5560. return -1;
  5561. } elseif ($value === '') {
  5562. $this->array_options["options_".$key] = null;
  5563. }
  5564. break;
  5565. case 'double':
  5566. $value = price2num($value);
  5567. if (!is_numeric($value) && $value != '') {
  5568. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5569. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5570. return -1;
  5571. } elseif ($value === '') {
  5572. $this->array_options["options_".$key] = null;
  5573. }
  5574. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5575. $this->array_options["options_".$key] = $value;
  5576. break;
  5577. /*case 'select': // Not required, we chosed value='0' for undefined values
  5578. if ($value=='-1')
  5579. {
  5580. $this->array_options[$key] = null;
  5581. }
  5582. break;*/
  5583. case 'price':
  5584. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  5585. break;
  5586. case 'date':
  5587. case 'datetime':
  5588. if (empty($this->array_options["options_".$key])) {
  5589. $this->array_options["options_".$key] = null;
  5590. } else {
  5591. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5592. }
  5593. break;
  5594. /*
  5595. case 'link':
  5596. $param_list = array_keys($attributeParam['options']);
  5597. // 0 : ObjectName
  5598. // 1 : classPath
  5599. $InfoFieldList = explode(":", $param_list[0]);
  5600. dol_include_once($InfoFieldList[1]);
  5601. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  5602. {
  5603. if ($value == '-1') // -1 is key for no defined in combo list of objects
  5604. {
  5605. $new_array_options[$key] = '';
  5606. } elseif ($value) {
  5607. $object = new $InfoFieldList[0]($this->db);
  5608. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  5609. else $res = $object->fetch('', $value); // For compatibility
  5610. if ($res > 0) $new_array_options[$key] = $object->id;
  5611. else {
  5612. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5613. $this->db->rollback();
  5614. return -1;
  5615. }
  5616. }
  5617. } else {
  5618. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5619. }
  5620. break;
  5621. */
  5622. }
  5623. $this->db->begin();
  5624. $linealreadyfound = 0;
  5625. // 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)
  5626. $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields WHERE fk_object = ".$this->id;
  5627. $resql = $this->db->query($sql);
  5628. if ($resql) {
  5629. $tmpobj = $this->db->fetch_object($resql);
  5630. if ($tmpobj) {
  5631. $linealreadyfound = $tmpobj->nb;
  5632. }
  5633. }
  5634. if ($linealreadyfound) {
  5635. if ($this->array_options["options_".$key] === null) {
  5636. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key." = null";
  5637. } else {
  5638. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
  5639. }
  5640. $sql .= " WHERE fk_object = ".$this->id;
  5641. } else {
  5642. $result = $this->insertExtraFields('', $user);
  5643. if ($result < 0) {
  5644. $error++;
  5645. }
  5646. }
  5647. $resql = $this->db->query($sql);
  5648. if (!$resql) {
  5649. $error++;
  5650. $this->error = $this->db->lasterror();
  5651. }
  5652. if (!$error && $trigger) {
  5653. // Call trigger
  5654. $this->context = array('extrafieldupdate'=>1);
  5655. $result = $this->call_trigger($trigger, $userused);
  5656. if ($result < 0) {
  5657. $error++;
  5658. }
  5659. // End call trigger
  5660. }
  5661. if ($error) {
  5662. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  5663. $this->db->rollback();
  5664. return -1;
  5665. } else {
  5666. $this->db->commit();
  5667. return 1;
  5668. }
  5669. } else {
  5670. return 0;
  5671. }
  5672. }
  5673. /**
  5674. * Update an extra language value for the current object.
  5675. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5676. *
  5677. * @param string $key Key of the extrafield (without starting 'options_')
  5678. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5679. * @param User $userused Object user
  5680. * @return int -1=error, O=did nothing, 1=OK
  5681. * @see updateExtraFields(), insertExtraLanguages()
  5682. */
  5683. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  5684. {
  5685. global $conf, $langs, $user;
  5686. if (empty($userused)) {
  5687. $userused = $user;
  5688. }
  5689. $error = 0;
  5690. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5691. return 0; // For avoid conflicts if trigger used
  5692. }
  5693. return 0;
  5694. }
  5695. /**
  5696. * Return HTML string to put an input field into a page
  5697. * Code very similar with showInputField of extra fields
  5698. *
  5699. * @param array $val Array of properties for field to show (used only if ->fields not defined)
  5700. * @param string $key Key of attribute
  5701. * @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)
  5702. * @param string $moreparam To add more parameters on html input tag
  5703. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5704. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5705. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  5706. * @param int $nonewbutton Force to not show the new button on field that are links to object
  5707. * @return string
  5708. */
  5709. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  5710. {
  5711. global $conf, $langs, $form;
  5712. if (!is_object($form)) {
  5713. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  5714. $form = new Form($this->db);
  5715. }
  5716. if (!empty($this->fields)) {
  5717. $val = $this->fields[$key];
  5718. }
  5719. // Validation tests and output
  5720. $fieldValidationErrorMsg = '';
  5721. $validationClass = '';
  5722. $fieldValidationErrorMsg = $this->getFieldError($key);
  5723. if (!empty($fieldValidationErrorMsg)) {
  5724. $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
  5725. } else {
  5726. $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
  5727. }
  5728. $out = '';
  5729. $type = '';
  5730. $isDependList=0;
  5731. $param = array();
  5732. $param['options'] = array();
  5733. $reg = array();
  5734. $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
  5735. // Because we work on extrafields
  5736. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5737. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5738. $type = 'link';
  5739. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5740. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5741. $type = 'link';
  5742. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  5743. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5744. $type = 'link';
  5745. } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5746. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5747. $type = 'sellist';
  5748. } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5749. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5750. $type = 'sellist';
  5751. } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
  5752. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5753. $type = 'sellist';
  5754. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  5755. $param['options'] = array();
  5756. $type = 'varchar';
  5757. $size = $reg[1];
  5758. } elseif (preg_match('/varchar/', $val['type'])) {
  5759. $param['options'] = array();
  5760. $type = 'varchar';
  5761. } else {
  5762. $param['options'] = array();
  5763. $type = $this->fields[$key]['type'];
  5764. }
  5765. // Special case that force options and type ($type can be integer, varchar, ...)
  5766. if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
  5767. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  5768. $type = 'select';
  5769. }
  5770. $label = $this->fields[$key]['label'];
  5771. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  5772. $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
  5773. $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
  5774. $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
  5775. $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
  5776. $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
  5777. $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
  5778. $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
  5779. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  5780. $objectid = $this->id;
  5781. if ($computed) {
  5782. if (!preg_match('/^search_/', $keyprefix)) {
  5783. return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  5784. } else {
  5785. return '';
  5786. }
  5787. }
  5788. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  5789. if (empty($morecss) && !empty($val['css'])) {
  5790. $morecss = $val['css'];
  5791. } elseif (empty($morecss)) {
  5792. if ($type == 'date') {
  5793. $morecss = 'minwidth100imp';
  5794. } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
  5795. $morecss = 'minwidth200imp';
  5796. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  5797. $morecss = 'maxwidth75';
  5798. } elseif ($type == 'url') {
  5799. $morecss = 'minwidth400';
  5800. } elseif ($type == 'boolean') {
  5801. $morecss = '';
  5802. } else {
  5803. if (round($size) < 12) {
  5804. $morecss = 'minwidth100';
  5805. } elseif (round($size) <= 48) {
  5806. $morecss = 'minwidth200';
  5807. } else {
  5808. $morecss = 'minwidth400';
  5809. }
  5810. }
  5811. }
  5812. // Add validation state class
  5813. if (!empty($validationClass)) {
  5814. $morecss.= ' '.$validationClass;
  5815. }
  5816. if (in_array($type, array('date'))) {
  5817. $tmp = explode(',', $size);
  5818. $newsize = $tmp[0];
  5819. $showtime = 0;
  5820. // Do not show current date when field not required (see selectDate() method)
  5821. if (!$required && $value == '') {
  5822. $value = '-1';
  5823. }
  5824. // TODO Must also support $moreparam
  5825. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  5826. } elseif (in_array($type, array('datetime'))) {
  5827. $tmp = explode(',', $size);
  5828. $newsize = $tmp[0];
  5829. $showtime = 1;
  5830. // Do not show current date when field not required (see selectDate() method)
  5831. if (!$required && $value == '') $value = '-1';
  5832. // TODO Must also support $moreparam
  5833. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
  5834. } elseif (in_array($type, array('duration'))) {
  5835. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  5836. } elseif (in_array($type, array('int', 'integer'))) {
  5837. $tmp = explode(',', $size);
  5838. $newsize = $tmp[0];
  5839. $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' : '').'>';
  5840. } elseif (in_array($type, array('real'))) {
  5841. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5842. } elseif (preg_match('/varchar/', $type)) {
  5843. $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' : '').'>';
  5844. } elseif (in_array($type, array('mail', 'phone', 'url'))) {
  5845. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5846. } elseif (preg_match('/^text/', $type)) {
  5847. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  5848. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5849. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  5850. $out = $doleditor->Create(1);
  5851. } else {
  5852. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5853. }
  5854. } elseif (preg_match('/^html/', $type)) {
  5855. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  5856. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5857. $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%');
  5858. $out = $doleditor->Create(1);
  5859. } else {
  5860. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5861. }
  5862. } elseif ($type == 'boolean') {
  5863. $checked = '';
  5864. if (!empty($value)) {
  5865. $checked = ' checked value="1" ';
  5866. } else {
  5867. $checked = ' value="1" ';
  5868. }
  5869. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  5870. } elseif ($type == 'price') {
  5871. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5872. $value = price($value);
  5873. }
  5874. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  5875. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  5876. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5877. $value = price($value);
  5878. }
  5879. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  5880. } elseif ($type == 'select') {
  5881. $out = '';
  5882. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  5883. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5884. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  5885. }
  5886. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  5887. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
  5888. $out .= '<option value="0">&nbsp;</option>';
  5889. }
  5890. foreach ($param['options'] as $key => $val) {
  5891. if ((string) $key == '') {
  5892. continue;
  5893. }
  5894. list($val, $parent) = explode('|', $val);
  5895. $out .= '<option value="'.$key.'"';
  5896. $out .= (((string) $value == (string) $key) ? ' selected' : '');
  5897. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  5898. $out .= '>'.$val.'</option>';
  5899. }
  5900. $out .= '</select>';
  5901. } elseif ($type == 'sellist') {
  5902. $out = '';
  5903. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  5904. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5905. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  5906. }
  5907. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  5908. if (is_array($param['options'])) {
  5909. $param_list = array_keys($param['options']);
  5910. $InfoFieldList = explode(":", $param_list[0]);
  5911. $parentName = '';
  5912. $parentField = '';
  5913. // 0 : tableName
  5914. // 1 : label field name
  5915. // 2 : key fields name (if differ of rowid)
  5916. // 3 : key field parent (for dependent lists)
  5917. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  5918. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  5919. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  5920. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  5921. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  5922. } else {
  5923. $keyList = $InfoFieldList[2].' as rowid';
  5924. }
  5925. }
  5926. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  5927. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  5928. $keyList .= ', '.$parentField;
  5929. }
  5930. $fields_label = explode('|', $InfoFieldList[1]);
  5931. if (is_array($fields_label)) {
  5932. $keyList .= ', ';
  5933. $keyList .= implode(', ', $fields_label);
  5934. }
  5935. $sqlwhere = '';
  5936. $sql = 'SELECT '.$keyList;
  5937. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  5938. if (!empty($InfoFieldList[4])) {
  5939. // can use SELECT request
  5940. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  5941. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  5942. }
  5943. // current object id can be use into filter
  5944. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  5945. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  5946. } else {
  5947. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  5948. }
  5949. //We have to join on extrafield table
  5950. if (strpos($InfoFieldList[4], 'extra') !== false) {
  5951. $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
  5952. $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
  5953. } else {
  5954. $sqlwhere .= ' WHERE '.$InfoFieldList[4];
  5955. }
  5956. } else {
  5957. $sqlwhere .= ' WHERE 1=1';
  5958. }
  5959. // Some tables may have field, some other not. For the moment we disable it.
  5960. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  5961. $sqlwhere .= ' AND entity = '.$conf->entity;
  5962. }
  5963. $sql .= $sqlwhere;
  5964. //print $sql;
  5965. $sql .= ' ORDER BY '.implode(', ', $fields_label);
  5966. dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
  5967. $resql = $this->db->query($sql);
  5968. if ($resql) {
  5969. $out .= '<option value="0">&nbsp;</option>';
  5970. $num = $this->db->num_rows($resql);
  5971. $i = 0;
  5972. while ($i < $num) {
  5973. $labeltoshow = '';
  5974. $obj = $this->db->fetch_object($resql);
  5975. // Several field into label (eq table:code|libelle:rowid)
  5976. $notrans = false;
  5977. $fields_label = explode('|', $InfoFieldList[1]);
  5978. if (count($fields_label) > 1) {
  5979. $notrans = true;
  5980. foreach ($fields_label as $field_toshow) {
  5981. $labeltoshow .= $obj->$field_toshow.' ';
  5982. }
  5983. } else {
  5984. $labeltoshow = $obj->{$InfoFieldList[1]};
  5985. }
  5986. $labeltoshow = dol_trunc($labeltoshow, 45);
  5987. if ($value == $obj->rowid) {
  5988. foreach ($fields_label as $field_toshow) {
  5989. $translabel = $langs->trans($obj->$field_toshow);
  5990. if ($translabel != $obj->$field_toshow) {
  5991. $labeltoshow = dol_trunc($translabel, 18).' ';
  5992. } else {
  5993. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  5994. }
  5995. }
  5996. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  5997. } else {
  5998. if (!$notrans) {
  5999. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6000. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6001. $labeltoshow = dol_trunc($translabel, 18);
  6002. } else {
  6003. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  6004. }
  6005. }
  6006. if (empty($labeltoshow)) {
  6007. $labeltoshow = '(not defined)';
  6008. }
  6009. if ($value == $obj->rowid) {
  6010. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6011. }
  6012. if (!empty($InfoFieldList[3]) && $parentField) {
  6013. $parent = $parentName.':'.$obj->{$parentField};
  6014. $isDependList=1;
  6015. }
  6016. $out .= '<option value="'.$obj->rowid.'"';
  6017. $out .= ($value == $obj->rowid ? ' selected' : '');
  6018. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6019. $out .= '>'.$labeltoshow.'</option>';
  6020. }
  6021. $i++;
  6022. }
  6023. $this->db->free($resql);
  6024. } else {
  6025. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6026. }
  6027. }
  6028. $out .= '</select>';
  6029. } elseif ($type == 'checkbox') {
  6030. $value_arr = explode(',', $value);
  6031. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
  6032. } elseif ($type == 'radio') {
  6033. $out = '';
  6034. foreach ($param['options'] as $keyopt => $val) {
  6035. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  6036. $out .= ' value="'.$keyopt.'"';
  6037. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  6038. $out .= ($value == $keyopt ? 'checked' : '');
  6039. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
  6040. }
  6041. } elseif ($type == 'chkbxlst') {
  6042. if (is_array($value)) {
  6043. $value_arr = $value;
  6044. } else {
  6045. $value_arr = explode(',', $value);
  6046. }
  6047. if (is_array($param['options'])) {
  6048. $param_list = array_keys($param['options']);
  6049. $InfoFieldList = explode(":", $param_list[0]);
  6050. $parentName = '';
  6051. $parentField = '';
  6052. // 0 : tableName
  6053. // 1 : label field name
  6054. // 2 : key fields name (if differ of rowid)
  6055. // 3 : key field parent (for dependent lists)
  6056. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6057. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6058. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6059. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6060. $keyList .= ', '.$parentField;
  6061. }
  6062. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6063. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6064. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6065. } else {
  6066. $keyList = $InfoFieldList[2].' as rowid';
  6067. }
  6068. }
  6069. $fields_label = explode('|', $InfoFieldList[1]);
  6070. if (is_array($fields_label)) {
  6071. $keyList .= ', ';
  6072. $keyList .= implode(', ', $fields_label);
  6073. }
  6074. $sqlwhere = '';
  6075. $sql = 'SELECT '.$keyList;
  6076. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6077. if (!empty($InfoFieldList[4])) {
  6078. // can use SELECT request
  6079. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6080. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6081. }
  6082. // current object id can be use into filter
  6083. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6084. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6085. } else {
  6086. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6087. }
  6088. // We have to join on extrafield table
  6089. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6090. $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
  6091. $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
  6092. } else {
  6093. $sqlwhere .= ' WHERE '.$InfoFieldList[4];
  6094. }
  6095. } else {
  6096. $sqlwhere .= ' WHERE 1=1';
  6097. }
  6098. // Some tables may have field, some other not. For the moment we disable it.
  6099. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6100. $sqlwhere .= ' AND entity = '.$conf->entity;
  6101. }
  6102. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  6103. // print $sql;
  6104. $sql .= $sqlwhere;
  6105. dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
  6106. $resql = $this->db->query($sql);
  6107. if ($resql) {
  6108. $num = $this->db->num_rows($resql);
  6109. $i = 0;
  6110. $data = array();
  6111. while ($i < $num) {
  6112. $labeltoshow = '';
  6113. $obj = $this->db->fetch_object($resql);
  6114. $notrans = false;
  6115. // Several field into label (eq table:code|libelle:rowid)
  6116. $fields_label = explode('|', $InfoFieldList[1]);
  6117. if (count($fields_label) > 1) {
  6118. $notrans = true;
  6119. foreach ($fields_label as $field_toshow) {
  6120. $labeltoshow .= $obj->$field_toshow.' ';
  6121. }
  6122. } else {
  6123. $labeltoshow = $obj->{$InfoFieldList[1]};
  6124. }
  6125. $labeltoshow = dol_trunc($labeltoshow, 45);
  6126. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6127. foreach ($fields_label as $field_toshow) {
  6128. $translabel = $langs->trans($obj->$field_toshow);
  6129. if ($translabel != $obj->$field_toshow) {
  6130. $labeltoshow = dol_trunc($translabel, 18).' ';
  6131. } else {
  6132. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  6133. }
  6134. }
  6135. $data[$obj->rowid] = $labeltoshow;
  6136. } else {
  6137. if (!$notrans) {
  6138. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6139. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6140. $labeltoshow = dol_trunc($translabel, 18);
  6141. } else {
  6142. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  6143. }
  6144. }
  6145. if (empty($labeltoshow)) {
  6146. $labeltoshow = '(not defined)';
  6147. }
  6148. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6149. $data[$obj->rowid] = $labeltoshow;
  6150. }
  6151. if (!empty($InfoFieldList[3]) && $parentField) {
  6152. $parent = $parentName.':'.$obj->{$parentField};
  6153. $isDependList=1;
  6154. }
  6155. $data[$obj->rowid] = $labeltoshow;
  6156. }
  6157. $i++;
  6158. }
  6159. $this->db->free($resql);
  6160. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
  6161. } else {
  6162. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6163. }
  6164. }
  6165. } elseif ($type == 'link') {
  6166. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter]]'
  6167. $param_list_array = explode(':', $param_list[0]);
  6168. $showempty = (($required && $default != '') ? 0 : 1);
  6169. if (!preg_match('/search_/', $keyprefix)) {
  6170. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6171. if (!empty($this->fields[$key]['picto'])) {
  6172. $morecss .= ' widthcentpercentminusxx';
  6173. } else {
  6174. $morecss .= ' widthcentpercentminusx';
  6175. }
  6176. } else {
  6177. if (!empty($this->fields[$key]['picto'])) {
  6178. $morecss .= ' widthcentpercentminusx';
  6179. }
  6180. }
  6181. }
  6182. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  6183. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6184. 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".
  6185. list($class, $classfile) = explode(':', $param_list[0]);
  6186. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
  6187. $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  6188. } else {
  6189. $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  6190. }
  6191. $paramforthenewlink = '';
  6192. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  6193. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  6194. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  6195. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  6196. $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>';
  6197. }
  6198. }
  6199. } elseif ($type == 'password') {
  6200. // If prefix is 'search_', field is used as a filter, we use a common text field.
  6201. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  6202. } elseif ($type == 'array') {
  6203. $newval = $val;
  6204. $newval['type'] = 'varchar(256)';
  6205. $out = '';
  6206. if (!empty($value)) {
  6207. foreach ($value as $option) {
  6208. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6209. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  6210. }
  6211. }
  6212. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6213. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6214. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  6215. if (!empty($conf->use_javascript_ajax)) {
  6216. $out .= '
  6217. <script>
  6218. $(document).ready(function() {
  6219. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  6220. $("'.dol_escape_js($newInput).'").insertBefore(this);
  6221. });
  6222. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  6223. $(this).parent().remove();
  6224. });
  6225. });
  6226. </script>';
  6227. }
  6228. }
  6229. if (!empty($hidden)) {
  6230. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  6231. }
  6232. if ($isDependList==1) {
  6233. $out .= $this->getJSListDependancies('_common');
  6234. }
  6235. /* Add comments
  6236. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  6237. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  6238. */
  6239. // Display error message for field
  6240. if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
  6241. $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
  6242. }
  6243. return $out;
  6244. }
  6245. /**
  6246. * Return HTML string to show a field into a page
  6247. * Code very similar with showOutputField of extra fields
  6248. *
  6249. * @param array $val Array of properties of field to show
  6250. * @param string $key Key of attribute
  6251. * @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)
  6252. * @param string $moreparam To add more parametes on html input tag
  6253. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6254. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6255. * @param mixed $morecss Value for css to define size. May also be a numeric.
  6256. * @return string
  6257. */
  6258. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  6259. {
  6260. global $conf, $langs, $form;
  6261. if (!is_object($form)) {
  6262. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6263. $form = new Form($this->db);
  6264. }
  6265. $objectid = $this->id; // Not used ???
  6266. $label = empty($val['label']) ? '' : $val['label'];
  6267. $type = empty($val['type']) ? '' : $val['type'];
  6268. $size = empty($val['css']) ? '' : $val['css'];
  6269. $reg = array();
  6270. // Convert var to be able to share same code than showOutputField of extrafields
  6271. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6272. $type = 'varchar'; // convert varchar(xx) int varchar
  6273. $size = $reg[1];
  6274. } elseif (preg_match('/varchar/', $type)) {
  6275. $type = 'varchar'; // convert varchar(xx) int varchar
  6276. }
  6277. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6278. $type = 'select';
  6279. }
  6280. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6281. $type = 'link';
  6282. }
  6283. $default = empty($val['default']) ? '' : $val['default'];
  6284. $computed = empty($val['computed']) ? '' : $val['computed'];
  6285. $unique = empty($val['unique']) ? '' : $val['unique'];
  6286. $required = empty($val['required']) ? '' : $val['required'];
  6287. $param = array();
  6288. $param['options'] = array();
  6289. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6290. $param['options'] = $val['arrayofkeyval'];
  6291. }
  6292. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6293. $type = 'link';
  6294. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6295. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6296. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6297. $type = 'sellist';
  6298. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6299. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6300. $type = 'sellist';
  6301. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6302. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6303. $type = 'sellist';
  6304. }
  6305. $langfile = empty($val['langfile']) ? '' : $val['langfile'];
  6306. $list = (empty($val['list']) ? '' : $val['list']);
  6307. $help = (empty($val['help']) ? '' : $val['help']);
  6308. $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)
  6309. if ($hidden) {
  6310. return '';
  6311. }
  6312. // If field is a computed field, value must become result of compute
  6313. if ($computed) {
  6314. // Make the eval of compute string
  6315. //var_dump($computed);
  6316. $value = dol_eval($computed, 1, 0);
  6317. }
  6318. if (empty($morecss)) {
  6319. if ($type == 'date') {
  6320. $morecss = 'minwidth100imp';
  6321. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6322. $morecss = 'minwidth200imp';
  6323. } elseif (in_array($type, array('int', 'double', 'price'))) {
  6324. $morecss = 'maxwidth75';
  6325. } elseif ($type == 'url') {
  6326. $morecss = 'minwidth400';
  6327. } elseif ($type == 'boolean') {
  6328. $morecss = '';
  6329. } else {
  6330. if (is_numeric($size) && round($size) < 12) {
  6331. $morecss = 'minwidth100';
  6332. } elseif (is_numeric($size) && round($size) <= 48) {
  6333. $morecss = 'minwidth200';
  6334. } else {
  6335. $morecss = 'minwidth400';
  6336. }
  6337. }
  6338. }
  6339. // Format output value differently according to properties of field
  6340. if ($key == 'ref' && method_exists($this, 'getNomUrl')) {
  6341. $value = $this->getNomUrl(1, '', 0, '', 1);
  6342. } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
  6343. $value = $this->getLibStatut(3);
  6344. } elseif ($type == 'date') {
  6345. if (!empty($value)) {
  6346. $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
  6347. } else {
  6348. $value = '';
  6349. }
  6350. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6351. if (!empty($value)) {
  6352. $value = dol_print_date($value, 'dayhour', 'tzuserrel');
  6353. } else {
  6354. $value = '';
  6355. }
  6356. } elseif ($type == 'duration') {
  6357. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6358. if (!is_null($value) && $value !== '') {
  6359. $value = convertSecondToTime($value, 'allhourmin');
  6360. }
  6361. } elseif ($type == 'double' || $type == 'real') {
  6362. if (!is_null($value) && $value !== '') {
  6363. $value = price($value);
  6364. }
  6365. } elseif ($type == 'boolean') {
  6366. $checked = '';
  6367. if (!empty($value)) {
  6368. $checked = ' checked ';
  6369. }
  6370. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  6371. } elseif ($type == 'mail') {
  6372. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  6373. } elseif ($type == 'url') {
  6374. $value = dol_print_url($value, '_blank', 32, 1);
  6375. } elseif ($type == 'phone') {
  6376. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
  6377. } elseif ($type == 'price') {
  6378. if (!is_null($value) && $value !== '') {
  6379. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  6380. }
  6381. } elseif ($type == 'select') {
  6382. $value = $param['options'][$value];
  6383. } elseif ($type == 'sellist') {
  6384. $param_list = array_keys($param['options']);
  6385. $InfoFieldList = explode(":", $param_list[0]);
  6386. $selectkey = "rowid";
  6387. $keyList = 'rowid';
  6388. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6389. $selectkey = $InfoFieldList[2];
  6390. $keyList = $InfoFieldList[2].' as rowid';
  6391. }
  6392. $fields_label = explode('|', $InfoFieldList[1]);
  6393. if (is_array($fields_label)) {
  6394. $keyList .= ', ';
  6395. $keyList .= implode(', ', $fields_label);
  6396. }
  6397. $sql = 'SELECT '.$keyList;
  6398. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6399. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6400. $sql .= ' as main';
  6401. }
  6402. if ($selectkey == 'rowid' && empty($value)) {
  6403. $sql .= " WHERE ".$selectkey." = 0";
  6404. } elseif ($selectkey == 'rowid') {
  6405. $sql .= " WHERE ".$selectkey." = ".((int) $value);
  6406. } else {
  6407. $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
  6408. }
  6409. //$sql.= ' AND entity = '.$conf->entity;
  6410. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  6411. $resql = $this->db->query($sql);
  6412. if ($resql) {
  6413. $value = ''; // value was used, so now we reste it to use it to build final output
  6414. $obj = $this->db->fetch_object($resql);
  6415. // Several field into label (eq table:code|libelle:rowid)
  6416. $fields_label = explode('|', $InfoFieldList[1]);
  6417. if (is_array($fields_label) && count($fields_label) > 1) {
  6418. foreach ($fields_label as $field_toshow) {
  6419. $translabel = '';
  6420. if (!empty($obj->$field_toshow)) {
  6421. $translabel = $langs->trans($obj->$field_toshow);
  6422. }
  6423. if ($translabel != $field_toshow) {
  6424. $value .= dol_trunc($translabel, 18).' ';
  6425. } else {
  6426. $value .= $obj->$field_toshow.' ';
  6427. }
  6428. }
  6429. } else {
  6430. $translabel = '';
  6431. if (!empty($obj->{$InfoFieldList[1]})) {
  6432. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6433. }
  6434. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6435. $value = dol_trunc($translabel, 18);
  6436. } else {
  6437. $value = $obj->{$InfoFieldList[1]};
  6438. }
  6439. }
  6440. } else {
  6441. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6442. }
  6443. } elseif ($type == 'radio') {
  6444. $value = $param['options'][$value];
  6445. } elseif ($type == 'checkbox') {
  6446. $value_arr = explode(',', $value);
  6447. $value = '';
  6448. if (is_array($value_arr) && count($value_arr) > 0) {
  6449. $toprint = array();
  6450. foreach ($value_arr as $keyval => $valueval) {
  6451. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  6452. }
  6453. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6454. }
  6455. } elseif ($type == 'chkbxlst') {
  6456. $value_arr = explode(',', $value);
  6457. $param_list = array_keys($param['options']);
  6458. $InfoFieldList = explode(":", $param_list[0]);
  6459. $selectkey = "rowid";
  6460. $keyList = 'rowid';
  6461. if (count($InfoFieldList) >= 3) {
  6462. $selectkey = $InfoFieldList[2];
  6463. $keyList = $InfoFieldList[2].' as rowid';
  6464. }
  6465. $fields_label = explode('|', $InfoFieldList[1]);
  6466. if (is_array($fields_label)) {
  6467. $keyList .= ', ';
  6468. $keyList .= implode(', ', $fields_label);
  6469. }
  6470. $sql = 'SELECT '.$keyList;
  6471. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6472. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6473. $sql .= ' as main';
  6474. }
  6475. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  6476. // $sql.= ' AND entity = '.$conf->entity;
  6477. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  6478. $resql = $this->db->query($sql);
  6479. if ($resql) {
  6480. $value = ''; // value was used, so now we reste it to use it to build final output
  6481. $toprint = array();
  6482. while ($obj = $this->db->fetch_object($resql)) {
  6483. // Several field into label (eq table:code|libelle:rowid)
  6484. $fields_label = explode('|', $InfoFieldList[1]);
  6485. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6486. if (is_array($fields_label) && count($fields_label) > 1) {
  6487. foreach ($fields_label as $field_toshow) {
  6488. $translabel = '';
  6489. if (!empty($obj->$field_toshow)) {
  6490. $translabel = $langs->trans($obj->$field_toshow);
  6491. }
  6492. if ($translabel != $field_toshow) {
  6493. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6494. } else {
  6495. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->$field_toshow.'</li>';
  6496. }
  6497. }
  6498. } else {
  6499. $translabel = '';
  6500. if (!empty($obj->{$InfoFieldList[1]})) {
  6501. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6502. }
  6503. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6504. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6505. } else {
  6506. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->{$InfoFieldList[1]}.'</li>';
  6507. }
  6508. }
  6509. }
  6510. }
  6511. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6512. } else {
  6513. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6514. }
  6515. } elseif ($type == 'link') {
  6516. $out = '';
  6517. // only if something to display (perf)
  6518. if ($value) {
  6519. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6520. $InfoFieldList = explode(":", $param_list[0]);
  6521. $classname = $InfoFieldList[0];
  6522. $classpath = $InfoFieldList[1];
  6523. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  6524. $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
  6525. if (!empty($classpath)) {
  6526. dol_include_once($InfoFieldList[1]);
  6527. if ($classname && class_exists($classname)) {
  6528. $object = new $classname($this->db);
  6529. $object->fetch($value);
  6530. $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
  6531. }
  6532. } else {
  6533. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  6534. return 'Error bad setup of extrafield';
  6535. }
  6536. } else {
  6537. $value = '';
  6538. }
  6539. } elseif (preg_match('/^(text|html)/', $type)) {
  6540. $value = dol_htmlentitiesbr($value);
  6541. } elseif ($type == 'password') {
  6542. $value = preg_replace('/./i', '*', $value);
  6543. } elseif ($type == 'array') {
  6544. $value = implode('<br>', $value);
  6545. }
  6546. //print $type.'-'.$size.'-'.$value;
  6547. $out = $value;
  6548. return $out;
  6549. }
  6550. /**
  6551. * clear validation message result for a field
  6552. *
  6553. * @param string $fieldKey Key of attribute to clear
  6554. * @return null
  6555. */
  6556. public function clearFieldError($fieldKey)
  6557. {
  6558. $this->error = '';
  6559. unset($this->validateFieldsErrors[$fieldKey]);
  6560. }
  6561. /**
  6562. * set validation error message a field
  6563. *
  6564. * @param string $fieldKey Key of attribute
  6565. * @param string $msg the field error message
  6566. * @return null
  6567. */
  6568. public function setFieldError($fieldKey, $msg = '')
  6569. {
  6570. global $langs;
  6571. if (empty($msg)) { $msg = $langs->trans("UnknowError"); }
  6572. $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
  6573. }
  6574. /**
  6575. * get field error message
  6576. *
  6577. * @param string $fieldKey Key of attribute
  6578. * @return string
  6579. */
  6580. public function getFieldError($fieldKey)
  6581. {
  6582. if (!empty($this->validateFieldsErrors[$fieldKey])) {
  6583. return $this->validateFieldsErrors[$fieldKey];
  6584. }
  6585. return '';
  6586. }
  6587. /**
  6588. * Return validation test result for a field
  6589. *
  6590. * @param array $val Array of properties of field to show
  6591. * @param string $fieldKey Key of attribute
  6592. * @param string $fieldValue value of attribute
  6593. * @return bool return false if fail true on success, see $this->error for error message
  6594. */
  6595. public function validateField($val, $fieldKey, $fieldValue)
  6596. {
  6597. global $langs;
  6598. if (!class_exists('Validate')) { require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php'; }
  6599. $this->clearFieldError($fieldKey);
  6600. if (!isset($val[$fieldKey])) {
  6601. $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
  6602. return false;
  6603. }
  6604. $param = array();
  6605. $param['options'] = array();
  6606. $type = $val[$fieldKey]['type'];
  6607. $required = false;
  6608. if (isset($val[$fieldKey]['notnull']) && $val[$fieldKey]['notnull'] === 1) {
  6609. // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  6610. $required = true;
  6611. }
  6612. $maxSize = 0;
  6613. $minSize = 0;
  6614. //
  6615. // PREPARE Elements
  6616. //
  6617. // Convert var to be able to share same code than showOutputField of extrafields
  6618. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6619. $type = 'varchar'; // convert varchar(xx) int varchar
  6620. $maxSize = $reg[1];
  6621. } elseif (preg_match('/varchar/', $type)) {
  6622. $type = 'varchar'; // convert varchar(xx) int varchar
  6623. }
  6624. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6625. $type = 'select';
  6626. }
  6627. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6628. $type = 'link';
  6629. }
  6630. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6631. $param['options'] = $val['arrayofkeyval'];
  6632. }
  6633. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6634. $type = 'link';
  6635. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6636. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6637. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6638. $type = 'sellist';
  6639. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6640. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6641. $type = 'sellist';
  6642. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6643. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6644. $type = 'sellist';
  6645. }
  6646. //
  6647. // TEST Value
  6648. //
  6649. // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
  6650. $validate = new Validate($this->db, $langs);
  6651. // little trick : to perform tests with good performances sort tests by quick to low
  6652. //
  6653. // COMMON TESTS
  6654. //
  6655. // Required test and empty value
  6656. if ($required && !$validate->isNotEmptyString($fieldValue)) {
  6657. $this->setFieldError($fieldKey, $validate->error);
  6658. return false;
  6659. } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
  6660. // if no value sent and the field is not mandatory, no need to perform tests
  6661. return true;
  6662. }
  6663. // MAX Size test
  6664. if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
  6665. $this->setFieldError($fieldKey, $validate->error);
  6666. return false;
  6667. }
  6668. // MIN Size test
  6669. if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
  6670. $this->setFieldError($fieldKey, $validate->error);
  6671. return false;
  6672. }
  6673. //
  6674. // TESTS for TYPE
  6675. //
  6676. if (in_array($type, array('date', 'datetime', 'timestamp'))) {
  6677. if (!$validate->isTimestamp($fieldValue)) {
  6678. $this->setFieldError($fieldKey, $validate->error);
  6679. return false;
  6680. } else { return true; }
  6681. } elseif ($type == 'duration') {
  6682. if (!$validate->isDuration($fieldValue)) {
  6683. $this->setFieldError($fieldKey, $validate->error);
  6684. return false;
  6685. } else { return true; }
  6686. } elseif (in_array($type, array('double', 'real', 'price'))) {
  6687. // is numeric
  6688. if (!$validate->isDuration($fieldValue)) {
  6689. $this->setFieldError($fieldKey, $validate->error);
  6690. return false;
  6691. } else { return true; }
  6692. } elseif ($type == 'boolean') {
  6693. if (!$validate->isBool($fieldValue)) {
  6694. $this->setFieldError($fieldKey, $validate->error);
  6695. return false;
  6696. } else { return true; }
  6697. } elseif ($type == 'mail') {
  6698. if (!$validate->isEmail($fieldValue)) {
  6699. $this->setFieldError($fieldKey, $validate->error);
  6700. return false;
  6701. }
  6702. } elseif ($type == 'url') {
  6703. if (!$validate->isUrl($fieldValue)) {
  6704. $this->setFieldError($fieldKey, $validate->error);
  6705. return false;
  6706. } else { return true; }
  6707. } elseif ($type == 'phone') {
  6708. if (!$validate->isPhone($fieldValue)) {
  6709. $this->setFieldError($fieldKey, $validate->error);
  6710. return false;
  6711. } else { return true; }
  6712. } elseif ($type == 'select' || $type == 'radio') {
  6713. if (!isset($param['options'][$fieldValue])) {
  6714. $this->error = $langs->trans('RequireValidValue');
  6715. return false;
  6716. } else { return true; }
  6717. } elseif ($type == 'sellist' || $type == 'chkbxlst') {
  6718. $param_list = array_keys($param['options']);
  6719. $InfoFieldList = explode(":", $param_list[0]);
  6720. $value_arr = explode(',', $fieldValue);
  6721. $value_arr = array_map(array($this->db, 'escape'), $value_arr);
  6722. $selectkey = "rowid";
  6723. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6724. $selectkey = $InfoFieldList[2];
  6725. }
  6726. if (!isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
  6727. $this->setFieldError($fieldKey, $validate->error);
  6728. return false;
  6729. } else { return true; }
  6730. } elseif ($type == 'link') {
  6731. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6732. $InfoFieldList = explode(":", $param_list[0]);
  6733. $classname = $InfoFieldList[0];
  6734. $classpath = $InfoFieldList[1];
  6735. if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
  6736. $this->setFieldError($fieldKey, $validate->error);
  6737. return false;
  6738. } else { return true; }
  6739. }
  6740. // if no test failled all is ok
  6741. return true;
  6742. }
  6743. /**
  6744. * Function to show lines of extrafields with output datas.
  6745. * 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
  6746. *
  6747. * @param Extrafields $extrafields Extrafield Object
  6748. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  6749. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  6750. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  6751. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  6752. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  6753. * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...)
  6754. * @return string
  6755. */
  6756. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
  6757. {
  6758. global $db, $conf, $langs, $action, $form, $hookmanager;
  6759. if (!is_object($form)) {
  6760. $form = new Form($db);
  6761. }
  6762. $out = '';
  6763. $parameters = array();
  6764. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  6765. if (empty($reshook)) {
  6766. 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) {
  6767. $out .= "\n";
  6768. $out .= '<!-- showOptionals --> ';
  6769. $out .= "\n";
  6770. $extrafields_collapse_num = '';
  6771. $e = 0;
  6772. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
  6773. // Show only the key field in params
  6774. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
  6775. continue;
  6776. }
  6777. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  6778. $enabled = 1;
  6779. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  6780. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1);
  6781. }
  6782. if (empty($enabled)) {
  6783. continue;
  6784. }
  6785. $visibility = 1;
  6786. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  6787. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1);
  6788. }
  6789. $perms = 1;
  6790. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  6791. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1);
  6792. }
  6793. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
  6794. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  6795. } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
  6796. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  6797. } elseif ($mode == 'view' && empty($visibility)) {
  6798. continue;
  6799. }
  6800. if (empty($perms)) {
  6801. continue;
  6802. }
  6803. // Load language if required
  6804. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  6805. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  6806. }
  6807. $colspan = '';
  6808. if (is_array($params) && count($params) > 0 && $display_type=='card') {
  6809. if (array_key_exists('cols', $params)) {
  6810. $colspan = $params['cols'];
  6811. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  6812. $reg = array();
  6813. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  6814. $colspan = $reg[1];
  6815. } else {
  6816. $colspan = $params['colspan'];
  6817. }
  6818. }
  6819. }
  6820. switch ($mode) {
  6821. case "view":
  6822. $value = $this->array_options["options_".$key.$keysuffix]; // Value may be clean or formated later
  6823. break;
  6824. case "create":
  6825. case "edit":
  6826. // We get the value of property found with GETPOST so it takes into account:
  6827. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  6828. $check = 'alphanohtml';
  6829. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  6830. $check = 'restricthtml';
  6831. }
  6832. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  6833. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  6834. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
  6835. if (is_array($getposttemp)) {
  6836. // $getposttemp is an array but following code expects a comma separated string
  6837. $value = implode(",", $getposttemp);
  6838. } else {
  6839. $value = $getposttemp;
  6840. }
  6841. } else {
  6842. $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.
  6843. }
  6844. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  6845. break;
  6846. }
  6847. // Output value of the current field
  6848. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  6849. $extrafields_collapse_num = '';
  6850. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  6851. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  6852. $extrafield_param_list = array_keys($extrafield_param['options']);
  6853. if (count($extrafield_param_list) > 0) {
  6854. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  6855. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  6856. $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  6857. }
  6858. }
  6859. }
  6860. $out .= $extrafields->showSeparator($key, $this, ($colspan + 1), $display_type);
  6861. } else {
  6862. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  6863. $csstyle = '';
  6864. if (is_array($params) && count($params) > 0) {
  6865. if (array_key_exists('class', $params)) {
  6866. $class .= $params['class'].' ';
  6867. }
  6868. if (array_key_exists('style', $params)) {
  6869. $csstyle = $params['style'];
  6870. }
  6871. }
  6872. // add html5 elements
  6873. $domData = ' data-element="extrafield"';
  6874. $domData .= ' data-targetelement="'.$this->element.'"';
  6875. $domData .= ' data-targetid="'.$this->id.'"';
  6876. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  6877. if ($display_type=='card') {
  6878. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
  6879. $colspan = '0';
  6880. }
  6881. if ($action == 'selectlines') {
  6882. $colspan++;
  6883. }
  6884. }
  6885. // Convert date into timestamp format (value in memory must be a timestamp)
  6886. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
  6887. $datenotinstring = $this->array_options['options_'.$key];
  6888. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  6889. $datenotinstring = $this->db->jdate($datenotinstring);
  6890. }
  6891. $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;
  6892. }
  6893. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
  6894. $datenotinstring = $this->array_options['options_'.$key];
  6895. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  6896. $datenotinstring = $this->db->jdate($datenotinstring);
  6897. }
  6898. $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;
  6899. }
  6900. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  6901. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
  6902. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? price2num($value) : $this->array_options['options_'.$key];
  6903. }
  6904. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  6905. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int'))) {
  6906. if ($action == 'create') {
  6907. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  6908. }
  6909. }
  6910. $labeltoshow = $langs->trans($label);
  6911. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  6912. if ($display_type == 'card') {
  6913. $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.' >';
  6914. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && $action == 'view') {
  6915. $out .= '<td></td>';
  6916. }
  6917. $out .= '<td class="wordbreak';
  6918. } elseif ($display_type == 'line') {
  6919. $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.' >';
  6920. $out .= '<div style="display: inline-block; padding-right:4px" class="wordbreak';
  6921. }
  6922. //$out .= "titlefield";
  6923. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  6924. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  6925. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  6926. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  6927. $out .= '">';
  6928. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  6929. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  6930. } else {
  6931. $out .= $labeltoshow;
  6932. }
  6933. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  6934. $out .= '&nbsp;<font color="red">*</font>';
  6935. }
  6936. } else {
  6937. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  6938. $out .= ' fieldrequired';
  6939. }
  6940. $out .= '">';
  6941. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  6942. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  6943. } else {
  6944. $out .= $labeltoshow;
  6945. }
  6946. }
  6947. $out .= ($display_type == 'card' ? '</td>' : '</div>');
  6948. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  6949. if ($display_type == 'card') {
  6950. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="'.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  6951. } elseif ($display_type == 'line') {
  6952. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').' style="display: inline-block" class="'.$this->element.'_extras_'.$key.'">';
  6953. }
  6954. switch ($mode) {
  6955. case "view":
  6956. $out .= $extrafields->showOutputField($key, $value);
  6957. break;
  6958. case "create":
  6959. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  6960. break;
  6961. case "edit":
  6962. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  6963. break;
  6964. }
  6965. $out .= ($display_type=='card' ? '</td>' : '</div>');
  6966. /*for($ii = 0; $ii < ($colspan - 1); $ii++)
  6967. {
  6968. $out .='<td class="'.$this->element.'_extras_'.$key.'"></td>';
  6969. }*/
  6970. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
  6971. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  6972. } else {
  6973. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  6974. }
  6975. $e++;
  6976. }
  6977. }
  6978. $out .= "\n";
  6979. // Add code to manage list depending on others
  6980. if (!empty($conf->use_javascript_ajax)) {
  6981. $out .= $this->getJSListDependancies();
  6982. }
  6983. $out .= '<!-- /showOptionals --> '."\n";
  6984. }
  6985. }
  6986. $out .= $hookmanager->resPrint;
  6987. return $out;
  6988. }
  6989. /**
  6990. * @param string $type Type for prefix
  6991. * @return string Javacript code to manage dependency
  6992. */
  6993. public function getJSListDependancies($type = '_extra')
  6994. {
  6995. $out = '
  6996. <script>
  6997. jQuery(document).ready(function() {
  6998. function showOptions'.$type.'(child_list, parent_list, orig_select)
  6999. {
  7000. var val = $("select[name=\""+parent_list+"\"]").val();
  7001. var parentVal = parent_list + ":" + val;
  7002. if(typeof val == "string"){
  7003. if(val != "") {
  7004. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7005. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7006. $("select[name=\""+child_list+"\"]").append(options);
  7007. } else {
  7008. var options = orig_select.find("option[parent]").clone();
  7009. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7010. $("select[name=\""+child_list+"\"]").append(options);
  7011. }
  7012. } else if(val > 0) {
  7013. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7014. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7015. $("select[name=\""+child_list+"\"]").append(options);
  7016. } else {
  7017. var options = orig_select.find("option[parent]").clone();
  7018. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7019. $("select[name=\""+child_list+"\"]").append(options);
  7020. }
  7021. }
  7022. function setListDependencies'.$type.'() {
  7023. jQuery("select option[parent]").parent().each(function() {
  7024. var orig_select = {};
  7025. var child_list = $(this).attr("name");
  7026. orig_select[child_list] = $(this).clone();
  7027. var parent = $(this).find("option[parent]:first").attr("parent");
  7028. var infos = parent.split(":");
  7029. var parent_list = infos[0];
  7030. //Hide daughters lists
  7031. if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
  7032. $("#"+child_list).hide();
  7033. //Show mother lists
  7034. } else if ($("#"+parent_list).val() != 0){
  7035. $("#"+parent_list).show();
  7036. }
  7037. //Show the child list if the parent list value is selected
  7038. $("select[name=\""+parent_list+"\"]").click(function() {
  7039. if ($(this).val() != 0){
  7040. $("#"+child_list).show()
  7041. }
  7042. });
  7043. //When we change parent list
  7044. $("select[name=\""+parent_list+"\"]").change(function() {
  7045. showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
  7046. //Select the value 0 on child list after a change on the parent list
  7047. $("#"+child_list).val(0).trigger("change");
  7048. //Hide child lists if the parent value is set to 0
  7049. if ($(this).val() == 0){
  7050. $("#"+child_list).hide();
  7051. }
  7052. });
  7053. });
  7054. }
  7055. setListDependencies'.$type.'();
  7056. });
  7057. </script>'."\n";
  7058. return $out;
  7059. }
  7060. /**
  7061. * Returns the rights used for this class
  7062. * @return stdClass
  7063. */
  7064. public function getRights()
  7065. {
  7066. global $user;
  7067. $element = $this->element;
  7068. if ($element == 'facturerec') {
  7069. $element = 'facture';
  7070. }
  7071. return $user->rights->{$element};
  7072. }
  7073. /**
  7074. * Function used to replace a thirdparty id with another one.
  7075. * This function is meant to be called from replaceThirdparty with the appropiate tables
  7076. * Column name fk_soc MUST be used to identify thirdparties
  7077. *
  7078. * @param DoliDB $db Database handler
  7079. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  7080. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  7081. * @param string[] $tables Tables that need to be changed
  7082. * @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)
  7083. * @return bool True if success, False if error
  7084. */
  7085. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7086. {
  7087. foreach ($tables as $table) {
  7088. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
  7089. if (!$db->query($sql)) {
  7090. if ($ignoreerrors) {
  7091. 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.
  7092. }
  7093. //$this->errors = $db->lasterror();
  7094. return false;
  7095. }
  7096. }
  7097. return true;
  7098. }
  7099. /**
  7100. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  7101. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  7102. * else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  7103. * else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  7104. * else set min buy price as buy price
  7105. *
  7106. * @param float $unitPrice Product unit price
  7107. * @param float $discountPercent Line discount percent
  7108. * @param int $fk_product Product id
  7109. * @return float <0 if KO, buyprice if OK
  7110. */
  7111. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  7112. {
  7113. global $conf;
  7114. $buyPrice = 0;
  7115. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
  7116. // When ForceBuyingPriceIfNull is set
  7117. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  7118. } else {
  7119. // Get cost price for margin calculation
  7120. if (!empty($fk_product) && $fk_product > 0) {
  7121. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
  7122. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7123. $product = new Product($this->db);
  7124. $result = $product->fetch($fk_product);
  7125. if ($result <= 0) {
  7126. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7127. return -1;
  7128. }
  7129. if ($product->cost_price > 0) {
  7130. $buyPrice = $product->cost_price;
  7131. } elseif ($product->pmp > 0) {
  7132. $buyPrice = $product->pmp;
  7133. }
  7134. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
  7135. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7136. $product = new Product($this->db);
  7137. $result = $product->fetch($fk_product);
  7138. if ($result <= 0) {
  7139. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7140. return -1;
  7141. }
  7142. if ($product->pmp > 0) {
  7143. $buyPrice = $product->pmp;
  7144. }
  7145. }
  7146. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
  7147. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  7148. $productFournisseur = new ProductFournisseur($this->db);
  7149. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
  7150. $buyPrice = $productFournisseur->fourn_unitprice;
  7151. } elseif ($result < 0) {
  7152. $this->errors[] = $productFournisseur->error;
  7153. return -2;
  7154. }
  7155. }
  7156. }
  7157. }
  7158. return $buyPrice;
  7159. }
  7160. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7161. /**
  7162. * Show photos of an object (nbmax maximum), into several columns
  7163. *
  7164. * @param string $modulepart 'product', 'ticket', ...
  7165. * @param string $sdir Directory to scan (full absolute path)
  7166. * @param int $size 0=original size, 1='small' use thumbnail if possible
  7167. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  7168. * @param int $nbbyrow Number of image per line or -1 to use div. Used only if size=1.
  7169. * @param int $showfilename 1=Show filename
  7170. * @param int $showaction 1=Show icon with action links (resize, delete)
  7171. * @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.
  7172. * @param int $maxWidth Max width of original image when size='small'
  7173. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  7174. * @param int $notitle Do not add title tag on image
  7175. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  7176. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  7177. */
  7178. 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)
  7179. {
  7180. // phpcs:enable
  7181. global $conf, $user, $langs;
  7182. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7183. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  7184. $sortfield = 'position_name';
  7185. $sortorder = 'asc';
  7186. $dir = $sdir.'/';
  7187. $pdir = '/';
  7188. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7189. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7190. // For backward compatibility
  7191. if ($modulepart == 'product') {
  7192. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  7193. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7194. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7195. }
  7196. }
  7197. // Defined relative dir to DOL_DATA_ROOT
  7198. $relativedir = '';
  7199. if ($dir) {
  7200. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  7201. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  7202. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  7203. }
  7204. $dirthumb = $dir.'thumbs/';
  7205. $pdirthumb = $pdir.'thumbs/';
  7206. $return = '<!-- Photo -->'."\n";
  7207. $nbphoto = 0;
  7208. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  7209. /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
  7210. {
  7211. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  7212. $filearray=array_merge($filearray, $filearrayold);
  7213. }*/
  7214. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  7215. if (count($filearray)) {
  7216. if ($sortfield && $sortorder) {
  7217. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  7218. }
  7219. foreach ($filearray as $key => $val) {
  7220. $photo = '';
  7221. $file = $val['name'];
  7222. //if (! utf8_check($file)) $file=utf8_encode($file); // To be sure file is stored in UTF8 in memory
  7223. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  7224. if (image_format_supported($file) >= 0) {
  7225. $nbphoto++;
  7226. $photo = $file;
  7227. $viewfilename = $file;
  7228. if ($size == 1 || $size == 'small') { // Format vignette
  7229. // Find name of thumb file
  7230. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  7231. if (!dol_is_file($dirthumb.$photo_vignette)) {
  7232. $photo_vignette = '';
  7233. }
  7234. // Get filesize of original file
  7235. $imgarray = dol_getImageSize($dir.$photo);
  7236. if ($nbbyrow > 0) {
  7237. if ($nbphoto == 1) {
  7238. $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  7239. }
  7240. if ($nbphoto % $nbbyrow == 1) {
  7241. $return .= '<tr class="center valignmiddle" style="border: 1px">';
  7242. }
  7243. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
  7244. } elseif ($nbbyrow < 0) {
  7245. $return .= '<div class="inline-block">';
  7246. }
  7247. $return .= "\n";
  7248. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  7249. if (empty($nolink)) {
  7250. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  7251. if ($urladvanced) {
  7252. $return .= '<a href="'.$urladvanced.'">';
  7253. } else {
  7254. $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
  7255. }
  7256. }
  7257. // Show image (width height=$maxHeight)
  7258. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  7259. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  7260. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  7261. if ($notitle) {
  7262. $alt = '';
  7263. }
  7264. if ($usesharelink) {
  7265. if ($val['share']) {
  7266. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7267. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  7268. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7269. } else {
  7270. $return .= '<!-- Show original file -->';
  7271. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7272. }
  7273. } else {
  7274. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  7275. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  7276. }
  7277. } else {
  7278. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7279. $return .= '<!-- Show thumb -->';
  7280. $return .= '<img class="photo photowithmargin maxwidth150onsmartphone" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdirthumb.$photo_vignette).'" title="'.dol_escape_htmltag($alt).'">';
  7281. } else {
  7282. $return .= '<!-- Show original file -->';
  7283. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" title="'.dol_escape_htmltag($alt).'">';
  7284. }
  7285. }
  7286. if (empty($nolink)) {
  7287. $return .= '</a>';
  7288. }
  7289. $return .= "\n";
  7290. if ($showfilename) {
  7291. $return .= '<br>'.$viewfilename;
  7292. }
  7293. if ($showaction) {
  7294. $return .= '<br>';
  7295. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  7296. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
  7297. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=addthumb&amp;file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'), 'refresh').'&nbsp;&nbsp;</a>';
  7298. }
  7299. // Special cas for product
  7300. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7301. // Link to resize
  7302. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&amp;file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  7303. // Link to delete
  7304. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;token='.newToken().'&amp;file='.urlencode($pdir.$viewfilename).'">';
  7305. $return .= img_delete().'</a>';
  7306. }
  7307. }
  7308. $return .= "\n";
  7309. if ($nbbyrow > 0) {
  7310. $return .= '</td>';
  7311. if (($nbphoto % $nbbyrow) == 0) {
  7312. $return .= '</tr>';
  7313. }
  7314. } elseif ($nbbyrow < 0) {
  7315. $return .= '</div>';
  7316. }
  7317. }
  7318. if (empty($size)) { // Format origine
  7319. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  7320. if ($showfilename) {
  7321. $return .= '<br>'.$viewfilename;
  7322. }
  7323. if ($showaction) {
  7324. // Special case for product
  7325. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7326. // Link to resize
  7327. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&amp;file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  7328. // Link to delete
  7329. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;token='.newToken().'&amp;file='.urlencode($pdir.$viewfilename).'">';
  7330. $return .= img_delete().'</a>';
  7331. }
  7332. }
  7333. }
  7334. // On continue ou on arrete de boucler ?
  7335. if ($nbmax && $nbphoto >= $nbmax) {
  7336. break;
  7337. }
  7338. }
  7339. }
  7340. if ($size == 1 || $size == 'small') {
  7341. if ($nbbyrow > 0) {
  7342. // Ferme tableau
  7343. while ($nbphoto % $nbbyrow) {
  7344. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  7345. $nbphoto++;
  7346. }
  7347. if ($nbphoto) {
  7348. $return .= '</table>';
  7349. }
  7350. }
  7351. }
  7352. }
  7353. $this->nbphoto = $nbphoto;
  7354. return $return;
  7355. }
  7356. /**
  7357. * Function test if type is array
  7358. *
  7359. * @param array $info content informations of field
  7360. * @return bool true if array
  7361. */
  7362. protected function isArray($info)
  7363. {
  7364. if (is_array($info)) {
  7365. if (isset($info['type']) && $info['type'] == 'array') {
  7366. return true;
  7367. } else {
  7368. return false;
  7369. }
  7370. }
  7371. return false;
  7372. }
  7373. /**
  7374. * Function test if type is date
  7375. *
  7376. * @param array $info content informations of field
  7377. * @return bool true if date
  7378. */
  7379. public function isDate($info)
  7380. {
  7381. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
  7382. return true;
  7383. }
  7384. return false;
  7385. }
  7386. /**
  7387. * Function test if type is duration
  7388. *
  7389. * @param array $info content informations of field
  7390. * @return bool true if field of type duration
  7391. */
  7392. public function isDuration($info)
  7393. {
  7394. if (is_array($info)) {
  7395. if (isset($info['type']) && ($info['type'] == 'duration')) {
  7396. return true;
  7397. } else {
  7398. return false;
  7399. }
  7400. } else {
  7401. return false;
  7402. }
  7403. }
  7404. /**
  7405. * Function test if type is integer
  7406. *
  7407. * @param array $info content informations of field
  7408. * @return bool true if integer
  7409. */
  7410. public function isInt($info)
  7411. {
  7412. if (is_array($info)) {
  7413. if (isset($info['type']) && ($info['type'] == 'int' || preg_match('/^integer/i', $info['type']))) {
  7414. return true;
  7415. } else {
  7416. return false;
  7417. }
  7418. } else {
  7419. return false;
  7420. }
  7421. }
  7422. /**
  7423. * Function test if type is float
  7424. *
  7425. * @param array $info content informations of field
  7426. * @return bool true if float
  7427. */
  7428. public function isFloat($info)
  7429. {
  7430. if (is_array($info)) {
  7431. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
  7432. return true;
  7433. } else {
  7434. return false;
  7435. }
  7436. }
  7437. return false;
  7438. }
  7439. /**
  7440. * Function test if type is text
  7441. *
  7442. * @param array $info content informations of field
  7443. * @return bool true if type text
  7444. */
  7445. public function isText($info)
  7446. {
  7447. if (is_array($info)) {
  7448. if (isset($info['type']) && $info['type'] == 'text') {
  7449. return true;
  7450. } else {
  7451. return false;
  7452. }
  7453. }
  7454. return false;
  7455. }
  7456. /**
  7457. * Function test if field can be null
  7458. *
  7459. * @param array $info content informations of field
  7460. * @return bool true if it can be null
  7461. */
  7462. protected function canBeNull($info)
  7463. {
  7464. if (is_array($info)) {
  7465. if (isset($info['notnull']) && $info['notnull'] != '1') {
  7466. return true;
  7467. } else {
  7468. return false;
  7469. }
  7470. }
  7471. return true;
  7472. }
  7473. /**
  7474. * Function test if field is forced to null if zero or empty
  7475. *
  7476. * @param array $info content informations of field
  7477. * @return bool true if forced to null
  7478. */
  7479. protected function isForcedToNullIfZero($info)
  7480. {
  7481. if (is_array($info)) {
  7482. if (isset($info['notnull']) && $info['notnull'] == '-1') {
  7483. return true;
  7484. } else {
  7485. return false;
  7486. }
  7487. }
  7488. return false;
  7489. }
  7490. /**
  7491. * Function test if is indexed
  7492. *
  7493. * @param array $info content informations of field
  7494. * @return bool
  7495. */
  7496. protected function isIndex($info)
  7497. {
  7498. if (is_array($info)) {
  7499. if (isset($info['index']) && $info['index'] == true) {
  7500. return true;
  7501. } else {
  7502. return false;
  7503. }
  7504. }
  7505. return false;
  7506. }
  7507. /**
  7508. * Function to prepare a part of the query for insert.
  7509. * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
  7510. * $this->${field} should be a clean value. The page can run
  7511. *
  7512. * @return array
  7513. */
  7514. protected function setSaveQuery()
  7515. {
  7516. global $conf;
  7517. $queryarray = array();
  7518. foreach ($this->fields as $field => $info) { // Loop on definition of fields
  7519. // Depending on field type ('datetime', ...)
  7520. if ($this->isDate($info)) {
  7521. if (empty($this->{$field})) {
  7522. $queryarray[$field] = null;
  7523. } else {
  7524. $queryarray[$field] = $this->db->idate($this->{$field});
  7525. }
  7526. } elseif ($this->isDuration($info)) {
  7527. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7528. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7529. if (!isset($this->{$field})) {
  7530. $queryarray[$field] = 0;
  7531. } else {
  7532. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7533. }
  7534. } else {
  7535. $queryarray[$field] = null;
  7536. }
  7537. } elseif ($this->isInt($info) || $this->isFloat($info)) {
  7538. if ($field == 'entity' && is_null($this->{$field})) {
  7539. $queryarray[$field] = $conf->entity;
  7540. } else {
  7541. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7542. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7543. if (!isset($this->{$field})) {
  7544. $queryarray[$field] = 0;
  7545. } elseif ($this->isInt($info)) {
  7546. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7547. } elseif ($this->isFloat($info)) {
  7548. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7549. }
  7550. } else {
  7551. $queryarray[$field] = null;
  7552. }
  7553. }
  7554. } else {
  7555. $queryarray[$field] = $this->{$field};
  7556. }
  7557. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
  7558. unset($queryarray[$field]);
  7559. }
  7560. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
  7561. $queryarray[$field] = null; // May force 0 to null
  7562. }
  7563. }
  7564. return $queryarray;
  7565. }
  7566. /**
  7567. * Function to load data from a SQL pointer into properties of current object $this
  7568. *
  7569. * @param stdClass $obj Contain data of object from database
  7570. * @return void
  7571. */
  7572. public function setVarsFromFetchObj(&$obj)
  7573. {
  7574. global $db;
  7575. foreach ($this->fields as $field => $info) {
  7576. if ($this->isDate($info)) {
  7577. if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
  7578. $this->{$field} = '';
  7579. } else {
  7580. $this->{$field} = $db->jdate($obj->{$field});
  7581. }
  7582. } elseif ($this->isInt($info)) {
  7583. if ($field == 'rowid') {
  7584. $this->id = (int) $obj->{$field};
  7585. } else {
  7586. if ($this->isForcedToNullIfZero($info)) {
  7587. if (empty($obj->{$field})) {
  7588. $this->{$field} = null;
  7589. } else {
  7590. $this->{$field} = (double) $obj->{$field};
  7591. }
  7592. } else {
  7593. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7594. $this->{$field} = (int) $obj->{$field};
  7595. } else {
  7596. $this->{$field} = null;
  7597. }
  7598. }
  7599. }
  7600. } elseif ($this->isFloat($info)) {
  7601. if ($this->isForcedToNullIfZero($info)) {
  7602. if (empty($obj->{$field})) {
  7603. $this->{$field} = null;
  7604. } else {
  7605. $this->{$field} = (double) $obj->{$field};
  7606. }
  7607. } else {
  7608. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7609. $this->{$field} = (double) $obj->{$field};
  7610. } else {
  7611. $this->{$field} = null;
  7612. }
  7613. }
  7614. } else {
  7615. $this->{$field} = $obj->{$field};
  7616. }
  7617. }
  7618. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  7619. if (!isset($this->fields['ref']) && isset($this->id)) {
  7620. $this->ref = $this->id;
  7621. }
  7622. }
  7623. /**
  7624. * Function to concat keys of fields
  7625. *
  7626. * @param string $alias String of alias of table for fields. For example 't'.
  7627. * @return string list of alias fields
  7628. */
  7629. public function getFieldList($alias = '')
  7630. {
  7631. $keys = array_keys($this->fields);
  7632. if (!empty($alias)) {
  7633. $keys_with_alias = array();
  7634. foreach ($keys as $fieldname) {
  7635. $keys_with_alias[] = $alias . '.' . $fieldname;
  7636. }
  7637. return implode(',', $keys_with_alias);
  7638. } else {
  7639. return implode(',', $keys);
  7640. }
  7641. }
  7642. /**
  7643. * Add quote to field value if necessary
  7644. *
  7645. * @param string|int $value Value to protect
  7646. * @param array $fieldsentry Properties of field
  7647. * @return string
  7648. */
  7649. protected function quote($value, $fieldsentry)
  7650. {
  7651. if (is_null($value)) {
  7652. return 'NULL';
  7653. } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
  7654. return $this->db->escape("$value");
  7655. } elseif ($fieldsentry['type'] == 'boolean') {
  7656. if ($value) {
  7657. return 'true';
  7658. } else {
  7659. return 'false';
  7660. }
  7661. } else {
  7662. return "'".$this->db->escape($value)."'";
  7663. }
  7664. }
  7665. /**
  7666. * Create object into database
  7667. *
  7668. * @param User $user User that creates
  7669. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7670. * @return int <0 if KO, Id of created object if OK
  7671. */
  7672. public function createCommon(User $user, $notrigger = false)
  7673. {
  7674. global $langs;
  7675. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  7676. $error = 0;
  7677. $now = dol_now();
  7678. $fieldvalues = $this->setSaveQuery();
  7679. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
  7680. $fieldvalues['date_creation'] = $this->db->idate($now);
  7681. }
  7682. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
  7683. $fieldvalues['fk_user_creat'] = $user->id;
  7684. }
  7685. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  7686. if (array_key_exists('ref', $fieldvalues)) {
  7687. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  7688. }
  7689. $keys = array();
  7690. $values = array(); // Array to store string forged for SQL syntax
  7691. foreach ($fieldvalues as $k => $v) {
  7692. $keys[$k] = $k;
  7693. $value = $this->fields[$k];
  7694. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  7695. }
  7696. // Clean and check mandatory
  7697. foreach ($keys as $key) {
  7698. // If field is an implicit foreign key field
  7699. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  7700. $values[$key] = '';
  7701. }
  7702. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  7703. $values[$key] = '';
  7704. }
  7705. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
  7706. $error++;
  7707. $langs->load("errors");
  7708. dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
  7709. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  7710. }
  7711. // If value is null and there is a default value for field
  7712. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
  7713. $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
  7714. }
  7715. // If field is an implicit foreign key field
  7716. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  7717. if (isset($this->fields[$key]['default'])) {
  7718. $values[$key] = $this->fields[$key]['default'];
  7719. } else {
  7720. $values[$key] = 'null';
  7721. }
  7722. }
  7723. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
  7724. $values[$key] = 'null';
  7725. }
  7726. }
  7727. if ($error) {
  7728. return -1;
  7729. }
  7730. $this->db->begin();
  7731. if (!$error) {
  7732. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
  7733. $sql .= ' ('.implode(", ", $keys).')';
  7734. $sql .= ' VALUES ('.implode(", ", $values).')';
  7735. $res = $this->db->query($sql);
  7736. if ($res === false) {
  7737. $error++;
  7738. $this->errors[] = $this->db->lasterror();
  7739. }
  7740. }
  7741. if (!$error) {
  7742. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
  7743. }
  7744. // If we have a field ref with a default value of (PROV)
  7745. if (!$error) {
  7746. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
  7747. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ref = '(PROV".$this->id.")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
  7748. $resqlupdate = $this->db->query($sql);
  7749. if ($resqlupdate === false) {
  7750. $error++;
  7751. $this->errors[] = $this->db->lasterror();
  7752. } else {
  7753. $this->ref = '(PROV'.$this->id.')';
  7754. }
  7755. }
  7756. }
  7757. // Create extrafields
  7758. if (!$error) {
  7759. $result = $this->insertExtraFields();
  7760. if ($result < 0) {
  7761. $error++;
  7762. }
  7763. }
  7764. // Create lines
  7765. if (!empty($this->table_element_line) && !empty($this->fk_element)) {
  7766. $num = (is_array($this->lines) ? count($this->lines) : 0);
  7767. for ($i = 0; $i < $num; $i++) {
  7768. $line = $this->lines[$i];
  7769. $keyforparent = $this->fk_element;
  7770. $line->$keyforparent = $this->id;
  7771. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  7772. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  7773. if (!is_object($line)) {
  7774. $line = (object) $line;
  7775. }
  7776. $result = $line->create($user, 1);
  7777. if ($result < 0) {
  7778. $this->error = $line->error;
  7779. $this->db->rollback();
  7780. return -1;
  7781. }
  7782. }
  7783. }
  7784. // Triggers
  7785. if (!$error && !$notrigger) {
  7786. // Call triggers
  7787. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  7788. if ($result < 0) {
  7789. $error++;
  7790. }
  7791. // End call triggers
  7792. }
  7793. // Commit or rollback
  7794. if ($error) {
  7795. $this->db->rollback();
  7796. return -1;
  7797. } else {
  7798. $this->db->commit();
  7799. return $this->id;
  7800. }
  7801. }
  7802. /**
  7803. * Load object in memory from the database
  7804. *
  7805. * @param int $id Id object
  7806. * @param string $ref Ref
  7807. * @param string $morewhere More SQL filters (' AND ...')
  7808. * @return int <0 if KO, 0 if not found, >0 if OK
  7809. */
  7810. public function fetchCommon($id, $ref = null, $morewhere = '')
  7811. {
  7812. if (empty($id) && empty($ref) && empty($morewhere)) {
  7813. return -1;
  7814. }
  7815. $fieldlist = $this->getFieldList('t');
  7816. if (empty($fieldlist)) {
  7817. return 0;
  7818. }
  7819. $sql = 'SELECT '.$fieldlist;
  7820. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  7821. if (!empty($id)) {
  7822. $sql .= ' WHERE t.rowid = '.((int) $id);
  7823. } elseif (!empty($ref)) {
  7824. $sql .= " WHERE t.ref = ".$this->quote($ref, $this->fields['ref']);
  7825. } else {
  7826. $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  7827. }
  7828. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  7829. $sql .= ' AND t.entity IN ('.getEntity($this->table_element).')';
  7830. }
  7831. if ($morewhere) {
  7832. $sql .= $morewhere;
  7833. }
  7834. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  7835. $res = $this->db->query($sql);
  7836. if ($res) {
  7837. $obj = $this->db->fetch_object($res);
  7838. if ($obj) {
  7839. $this->setVarsFromFetchObj($obj);
  7840. // Retrieve all extrafield
  7841. // fetch optionals attributes and labels
  7842. $this->fetch_optionals();
  7843. return $this->id;
  7844. } else {
  7845. return 0;
  7846. }
  7847. } else {
  7848. $this->error = $this->db->lasterror();
  7849. $this->errors[] = $this->error;
  7850. return -1;
  7851. }
  7852. }
  7853. /**
  7854. * Load object in memory from the database
  7855. *
  7856. * @param string $morewhere More SQL filters (' AND ...')
  7857. * @return int <0 if KO, 0 if not found, >0 if OK
  7858. */
  7859. public function fetchLinesCommon($morewhere = '')
  7860. {
  7861. $objectlineclassname = get_class($this).'Line';
  7862. if (!class_exists($objectlineclassname)) {
  7863. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  7864. return -1;
  7865. }
  7866. $objectline = new $objectlineclassname($this->db);
  7867. $sql = 'SELECT '.$objectline->getFieldList('l');
  7868. $sql .= ' FROM '.MAIN_DB_PREFIX.$objectline->table_element.' as l';
  7869. $sql .= ' WHERE l.fk_'.$this->element.' = '.$this->id;
  7870. if ($morewhere) {
  7871. $sql .= $morewhere;
  7872. }
  7873. if (isset($objectline->fields['position'])) {
  7874. $sql .= $this->db->order('position', 'ASC');
  7875. }
  7876. $resql = $this->db->query($sql);
  7877. if ($resql) {
  7878. $num_rows = $this->db->num_rows($resql);
  7879. $i = 0;
  7880. while ($i < $num_rows) {
  7881. $obj = $this->db->fetch_object($resql);
  7882. if ($obj) {
  7883. $newline = new $objectlineclassname($this->db);
  7884. $newline->setVarsFromFetchObj($obj);
  7885. $this->lines[] = $newline;
  7886. }
  7887. $i++;
  7888. }
  7889. return 1;
  7890. } else {
  7891. $this->error = $this->db->lasterror();
  7892. $this->errors[] = $this->error;
  7893. return -1;
  7894. }
  7895. }
  7896. /**
  7897. * Update object into database
  7898. *
  7899. * @param User $user User that modifies
  7900. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7901. * @return int <0 if KO, >0 if OK
  7902. */
  7903. public function updateCommon(User $user, $notrigger = false)
  7904. {
  7905. global $conf, $langs;
  7906. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  7907. $error = 0;
  7908. $now = dol_now();
  7909. $fieldvalues = $this->setSaveQuery();
  7910. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
  7911. $fieldvalues['date_modification'] = $this->db->idate($now);
  7912. }
  7913. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
  7914. $fieldvalues['fk_user_modif'] = $user->id;
  7915. }
  7916. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  7917. if (array_key_exists('ref', $fieldvalues)) {
  7918. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  7919. }
  7920. // Add quotes and escape on fields with type string
  7921. $keys = array();
  7922. $values = array();
  7923. $tmp = array();
  7924. foreach ($fieldvalues as $k => $v) {
  7925. $keys[$k] = $k;
  7926. $value = $this->fields[$k];
  7927. $values[$k] = $this->quote($v, $value);
  7928. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  7929. }
  7930. // Clean and check mandatory fields
  7931. foreach ($keys as $key) {
  7932. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  7933. $values[$key] = ''; // This is an implicit foreign key field
  7934. }
  7935. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  7936. $values[$key] = ''; // This is an explicit foreign key field
  7937. }
  7938. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  7939. /*
  7940. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  7941. {
  7942. $error++;
  7943. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  7944. }*/
  7945. }
  7946. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
  7947. $this->db->begin();
  7948. if (!$error) {
  7949. $res = $this->db->query($sql);
  7950. if ($res === false) {
  7951. $error++;
  7952. $this->errors[] = $this->db->lasterror();
  7953. }
  7954. }
  7955. // Update extrafield
  7956. if (!$error) {
  7957. $result = $this->insertExtraFields();
  7958. if ($result < 0) {
  7959. $error++;
  7960. }
  7961. }
  7962. // Triggers
  7963. if (!$error && !$notrigger) {
  7964. // Call triggers
  7965. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  7966. if ($result < 0) {
  7967. $error++;
  7968. } //Do also here what you must do to rollback action if trigger fail
  7969. // End call triggers
  7970. }
  7971. // Commit or rollback
  7972. if ($error) {
  7973. $this->db->rollback();
  7974. return -1;
  7975. } else {
  7976. $this->db->commit();
  7977. return $this->id;
  7978. }
  7979. }
  7980. /**
  7981. * Delete object in database
  7982. *
  7983. * @param User $user User that deletes
  7984. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7985. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  7986. * @return int <=0 if KO, >0 if OK
  7987. */
  7988. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  7989. {
  7990. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  7991. $error = 0;
  7992. $this->db->begin();
  7993. if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
  7994. foreach ($this->childtables as $table) {
  7995. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
  7996. $resql = $this->db->query($sql);
  7997. if (!$resql) {
  7998. $this->error = $this->db->lasterror();
  7999. $this->errors[] = $this->error;
  8000. $this->db->rollback();
  8001. return -1;
  8002. }
  8003. }
  8004. } elseif (!empty($this->fk_element) && !empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
  8005. $objectisused = $this->isObjectUsed($this->id);
  8006. if (!empty($objectisused)) {
  8007. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  8008. $this->error = 'ErrorRecordHasChildren';
  8009. $this->errors[] = $this->error;
  8010. $this->db->rollback();
  8011. return 0;
  8012. }
  8013. }
  8014. // Delete cascade first
  8015. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  8016. foreach ($this->childtablesoncascade as $table) {
  8017. $deleteFromObject = explode(':', $table);
  8018. if (count($deleteFromObject) >= 2) {
  8019. $className = str_replace('@', '', $deleteFromObject[0]);
  8020. $filePath = $deleteFromObject[1];
  8021. $columnName = $deleteFromObject[2];
  8022. if (dol_include_once($filePath)) {
  8023. $childObject = new $className($this->db);
  8024. if (method_exists($childObject, 'deleteByParentField')) {
  8025. $result = $childObject->deleteByParentField($this->id, $columnName);
  8026. if ($result < 0) {
  8027. $error++;
  8028. $this->errors[] = $childObject->error;
  8029. break;
  8030. }
  8031. } else {
  8032. $error++;
  8033. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  8034. break;
  8035. }
  8036. } else {
  8037. $error++;
  8038. $this->errors[] = 'Cannot include child class file '.$filePath;
  8039. break;
  8040. }
  8041. } else {
  8042. // Delete record in child table
  8043. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
  8044. $resql = $this->db->query($sql);
  8045. if (!$resql) {
  8046. $error++;
  8047. $this->error = $this->db->lasterror();
  8048. $this->errors[] = $this->error;
  8049. break;
  8050. }
  8051. }
  8052. }
  8053. }
  8054. if (!$error) {
  8055. if (!$notrigger) {
  8056. // Call triggers
  8057. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  8058. if ($result < 0) {
  8059. $error++;
  8060. } // Do also here what you must do to rollback action if trigger fail
  8061. // End call triggers
  8062. }
  8063. }
  8064. // Delete llx_ecm_files
  8065. if (!$error) {
  8066. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  8067. if (!$res) {
  8068. $error++;
  8069. }
  8070. }
  8071. if (!$error && !empty($this->isextrafieldmanaged)) {
  8072. $result = $this->deleteExtraFields();
  8073. if ($result < 0) {
  8074. $error++;
  8075. }
  8076. }
  8077. if (!$error) {
  8078. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.((int) $this->id);
  8079. $resql = $this->db->query($sql);
  8080. if (!$resql) {
  8081. $error++;
  8082. $this->errors[] = $this->db->lasterror();
  8083. }
  8084. }
  8085. // Commit or rollback
  8086. if ($error) {
  8087. $this->db->rollback();
  8088. return -1;
  8089. } else {
  8090. $this->db->commit();
  8091. return 1;
  8092. }
  8093. }
  8094. /**
  8095. * Delete all child object from a parent ID
  8096. *
  8097. * @param int $parentId Parent Id
  8098. * @param string $parentField Name of Foreign key parent column
  8099. * @return int <0 if KO, >0 if OK
  8100. * @throws Exception
  8101. */
  8102. public function deleteByParentField($parentId = 0, $parentField = '')
  8103. {
  8104. global $user;
  8105. $error = 0;
  8106. $deleted = 0;
  8107. if (!empty($parentId) && !empty($parentField)) {
  8108. $this->db->begin();
  8109. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$this->table_element;
  8110. $sql .= ' WHERE '.$parentField.' = '.(int) $parentId;
  8111. $resql = $this->db->query($sql);
  8112. if (!$resql) {
  8113. $this->errors[] = $this->db->lasterror();
  8114. $error++;
  8115. } else {
  8116. while ($obj = $this->db->fetch_object($resql)) {
  8117. $result = $this->fetch($obj->rowid);
  8118. if ($result < 0) {
  8119. $error++;
  8120. $this->errors[] = $this->error;
  8121. } else {
  8122. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  8123. $result = $this->delete();
  8124. } else {
  8125. $result = $this->delete($user);
  8126. }
  8127. if ($result < 0) {
  8128. $error++;
  8129. $this->errors[] = $this->error;
  8130. } else {
  8131. $deleted++;
  8132. }
  8133. }
  8134. }
  8135. }
  8136. if (empty($error)) {
  8137. $this->db->commit();
  8138. return $deleted;
  8139. } else {
  8140. $this->error = implode(', ', $this->errors);
  8141. $this->db->rollback();
  8142. return $error * -1;
  8143. }
  8144. }
  8145. return $deleted;
  8146. }
  8147. /**
  8148. * Delete a line of object in database
  8149. *
  8150. * @param User $user User that delete
  8151. * @param int $idline Id of line to delete
  8152. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8153. * @return int >0 if OK, <0 if KO
  8154. */
  8155. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  8156. {
  8157. global $conf;
  8158. $error = 0;
  8159. $tmpforobjectclass = get_class($this);
  8160. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  8161. // Call trigger
  8162. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  8163. if ($result < 0) {
  8164. return -1;
  8165. }
  8166. // End call triggers
  8167. $this->db->begin();
  8168. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  8169. $sql .= " WHERE rowid = ".((int) $idline);
  8170. dol_syslog(get_class($this)."::deleteLineCommon", LOG_DEBUG);
  8171. $resql = $this->db->query($sql);
  8172. if (!$resql) {
  8173. $this->error = "Error ".$this->db->lasterror();
  8174. $error++;
  8175. }
  8176. if (empty($error)) {
  8177. // Remove extrafields
  8178. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  8179. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  8180. $tmpobjectline->id = $idline;
  8181. $result = $tmpobjectline->deleteExtraFields();
  8182. if ($result < 0) {
  8183. $error++;
  8184. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  8185. }
  8186. }
  8187. }
  8188. if (empty($error)) {
  8189. $this->db->commit();
  8190. return 1;
  8191. } else {
  8192. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  8193. $this->db->rollback();
  8194. return -1;
  8195. }
  8196. }
  8197. /**
  8198. * Set to a status
  8199. *
  8200. * @param User $user Object user that modify
  8201. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  8202. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  8203. * @param string $triggercode Trigger code to use
  8204. * @return int <0 if KO, >0 if OK
  8205. */
  8206. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  8207. {
  8208. $error = 0;
  8209. $this->db->begin();
  8210. $statusfield = 'status';
  8211. if ($this->element == 'don' || $this->element == 'donation') {
  8212. $statusfield = 'fk_statut';
  8213. }
  8214. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  8215. $sql .= " SET ".$statusfield." = ".((int) $status);
  8216. $sql .= " WHERE rowid = ".$this->id;
  8217. if ($this->db->query($sql)) {
  8218. if (!$error) {
  8219. $this->oldcopy = clone $this;
  8220. }
  8221. if (!$error && !$notrigger) {
  8222. // Call trigger
  8223. $result = $this->call_trigger($triggercode, $user);
  8224. if ($result < 0) {
  8225. $error++;
  8226. }
  8227. }
  8228. if (!$error) {
  8229. $this->status = $status;
  8230. $this->db->commit();
  8231. return 1;
  8232. } else {
  8233. $this->db->rollback();
  8234. return -1;
  8235. }
  8236. } else {
  8237. $this->error = $this->db->error();
  8238. $this->db->rollback();
  8239. return -1;
  8240. }
  8241. }
  8242. /**
  8243. * Initialise object with example values
  8244. * Id must be 0 if object instance is a specimen
  8245. *
  8246. * @return int
  8247. */
  8248. public function initAsSpecimenCommon()
  8249. {
  8250. global $user;
  8251. $this->id = 0;
  8252. $this->specimen = 1;
  8253. $fields = array(
  8254. 'label' => 'This is label',
  8255. 'ref' => 'ABCD1234',
  8256. 'description' => 'This is a description',
  8257. 'qty' => 123.12,
  8258. 'note_public' => 'Public note',
  8259. 'note_private' => 'Private note',
  8260. 'date_creation' => (dol_now() - 3600 * 48),
  8261. 'date_modification' => (dol_now() - 3600 * 24),
  8262. 'fk_user_creat' => $user->id,
  8263. 'fk_user_modif' => $user->id,
  8264. 'date' => dol_now(),
  8265. );
  8266. foreach ($fields as $key => $value) {
  8267. if (array_key_exists($key, $this->fields)) {
  8268. $this->{$key} = $value;
  8269. }
  8270. }
  8271. return 1;
  8272. }
  8273. /* Part for comments */
  8274. /**
  8275. * Load comments linked with current task
  8276. * @return boolean 1 if ok
  8277. */
  8278. public function fetchComments()
  8279. {
  8280. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  8281. $comment = new Comment($this->db);
  8282. $result = $comment->fetchAllFor($this->element, $this->id);
  8283. if ($result < 0) {
  8284. $this->errors = array_merge($this->errors, $comment->errors);
  8285. return -1;
  8286. } else {
  8287. $this->comments = $comment->comments;
  8288. }
  8289. return count($this->comments);
  8290. }
  8291. /**
  8292. * Return nb comments already posted
  8293. *
  8294. * @return int
  8295. */
  8296. public function getNbComments()
  8297. {
  8298. return count($this->comments);
  8299. }
  8300. /**
  8301. * Trim object parameters
  8302. *
  8303. * @param string[] $parameters array of parameters to trim
  8304. * @return void
  8305. */
  8306. public function trimParameters($parameters)
  8307. {
  8308. if (!is_array($parameters)) {
  8309. return;
  8310. }
  8311. foreach ($parameters as $parameter) {
  8312. if (isset($this->$parameter)) {
  8313. $this->$parameter = trim($this->$parameter);
  8314. }
  8315. }
  8316. }
  8317. /* Part for categories/tags */
  8318. /**
  8319. * Sets object to given categories.
  8320. *
  8321. * Deletes object from existing categories not supplied.
  8322. * Adds it to non existing supplied categories.
  8323. * Existing categories are left untouch.
  8324. *
  8325. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  8326. * @return int Array of category objects or < 0 if KO
  8327. */
  8328. public function getCategoriesCommon($type_categ)
  8329. {
  8330. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8331. // Get current categories
  8332. $c = new Categorie($this->db);
  8333. $existing = $c->containing($this->id, $type_categ, 'id');
  8334. return $existing;
  8335. }
  8336. /**
  8337. * Sets object to given categories.
  8338. *
  8339. * Adds it to non existing supplied categories.
  8340. * Deletes object from existing categories not supplied (if remove_existing==true).
  8341. * Existing categories are left untouch.
  8342. *
  8343. * @param int[]|int $categories Category ID or array of Categories IDs
  8344. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) definied into const class Categorie type
  8345. * @param boolean $remove_existing True: Remove existings categories from Object if not supplies by $categories, False: let them
  8346. * @return int <0 if KO, >0 if OK
  8347. */
  8348. public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
  8349. {
  8350. dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
  8351. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8352. if (empty($type_categ)) {
  8353. dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
  8354. return -1;
  8355. }
  8356. // Handle single category
  8357. if (!is_array($categories)) {
  8358. $categories = array($categories);
  8359. }
  8360. // Get current categories
  8361. $c = new Categorie($this->db);
  8362. $existing = $c->containing($this->id, $type_categ, 'id');
  8363. if ($remove_existing) {
  8364. // Diff
  8365. if (is_array($existing)) {
  8366. $to_del = array_diff($existing, $categories);
  8367. $to_add = array_diff($categories, $existing);
  8368. } else {
  8369. $to_del = array(); // Nothing to delete
  8370. $to_add = $categories;
  8371. }
  8372. } else {
  8373. $to_del = array(); // Nothing to delete
  8374. $to_add = array_diff($categories, $existing);
  8375. }
  8376. $error = 0;
  8377. $ok=0;
  8378. // Process
  8379. foreach ($to_del as $del) {
  8380. if ($c->fetch($del) > 0) {
  8381. $result=$c->del_type($this, $type_categ);
  8382. if ($result < 0) {
  8383. $error++;
  8384. $this->error = $c->error;
  8385. $this->errors = $c->errors;
  8386. break;
  8387. } else {
  8388. $ok+=$result;
  8389. }
  8390. }
  8391. }
  8392. foreach ($to_add as $add) {
  8393. if ($c->fetch($add) > 0) {
  8394. $result = $c->add_type($this, $type_categ);
  8395. if ($result < 0) {
  8396. $error++;
  8397. $this->error = $c->error;
  8398. $this->errors = $c->errors;
  8399. break;
  8400. } else {
  8401. $ok+=$result;
  8402. }
  8403. }
  8404. }
  8405. return $error ? -1 * $error : $ok;
  8406. }
  8407. /**
  8408. * Copy related categories to another object
  8409. *
  8410. * @param int $fromId Id object source
  8411. * @param int $toId Id object cible
  8412. * @param string $type Type of category ('product', ...)
  8413. * @return int < 0 if error, > 0 if ok
  8414. */
  8415. public function cloneCategories($fromId, $toId, $type = '')
  8416. {
  8417. $this->db->begin();
  8418. if (empty($type)) {
  8419. $type = $this->table_element;
  8420. }
  8421. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8422. $categorystatic = new Categorie($this->db);
  8423. $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  8424. $sql .= " SELECT fk_categorie, $toId FROM ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  8425. $sql .= " WHERE fk_product = ".((int) $fromId);
  8426. if (!$this->db->query($sql)) {
  8427. $this->error = $this->db->lasterror();
  8428. $this->db->rollback();
  8429. return -1;
  8430. }
  8431. $this->db->commit();
  8432. return 1;
  8433. }
  8434. /**
  8435. * Delete related files of object in database
  8436. *
  8437. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  8438. * @return bool True if OK, False if KO
  8439. */
  8440. public function deleteEcmFiles($mode = 0)
  8441. {
  8442. global $conf;
  8443. $this->db->begin();
  8444. // Delete in database with mode 0
  8445. if ($mode == 0) {
  8446. switch ($this->element) {
  8447. case 'propal':
  8448. $element = 'propale';
  8449. break;
  8450. case 'product':
  8451. $element = 'produit';
  8452. break;
  8453. case 'order_supplier':
  8454. $element = 'fournisseur/commande';
  8455. break;
  8456. case 'invoice_supplier':
  8457. $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  8458. break;
  8459. case 'shipping':
  8460. $element = 'expedition/sending';
  8461. break;
  8462. default:
  8463. $element = $this->element;
  8464. }
  8465. // Delete ecm_files extrafields
  8466. $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files_extrafields WHERE fk_object IN (";
  8467. $sql .= " SELECT rowid FROM ".MAIN_DB_PREFIX."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8468. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".$conf->entity; // No need of getEntity here
  8469. $sql .= ")";
  8470. if (!$this->db->query($sql)) {
  8471. $this->error = $this->db->lasterror();
  8472. $this->db->rollback();
  8473. return false;
  8474. }
  8475. // Delete ecm_files
  8476. $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files";
  8477. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8478. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".$conf->entity; // No need of getEntity here
  8479. if (!$this->db->query($sql)) {
  8480. $this->error = $this->db->lasterror();
  8481. $this->db->rollback();
  8482. return false;
  8483. }
  8484. }
  8485. // Delete in database with mode 1
  8486. if ($mode == 1) {
  8487. $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files_extrafields";
  8488. $sql .= " WHERE fk_object IN (SELECT rowid FROM ".MAIN_DB_PREFIX."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? '' : '@'.$this->module))."' AND src_object_id = ".$this->id.")";
  8489. $resql = $this->db->query($sql);
  8490. if (!$resql) {
  8491. $this->error = $this->db->lasterror();
  8492. $this->db->rollback();
  8493. return false;
  8494. }
  8495. $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files";
  8496. $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? '' : '@'.$this->module))."' AND src_object_id = ".((int) $this->id);
  8497. $resql = $this->db->query($sql);
  8498. if (!$resql) {
  8499. $this->error = $this->db->lasterror();
  8500. $this->db->rollback();
  8501. return false;
  8502. }
  8503. }
  8504. $this->db->commit();
  8505. return true;
  8506. }
  8507. }