commonobject.class.php 349 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153
  1. <?php
  2. /* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
  5. * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
  6. * Copyright (C) 2011-2019 Philippe Grand <philippe.grand@atoo-net.com>
  7. * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
  8. * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  9. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  10. * Copyright (C) 2015-2022 Alexandre Spangaro <aspangaro@open-dsi.fr>
  11. * Copyright (C) 2016 Bahfir abbes <dolipar@dolipar.org>
  12. * Copyright (C) 2017 ATM Consulting <support@atm-consulting.fr>
  13. * Copyright (C) 2017-2019 Nicolas ZABOURI <info@inovea-conseil.com>
  14. * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
  15. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  16. * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
  17. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  18. * Copyright (C) 2021 Grégory Blémand <gregory.blemand@atm-consulting.fr>
  19. *
  20. * This program is free software; you can redistribute it and/or modify
  21. * it under the terms of the GNU General Public License as published by
  22. * the Free Software Foundation; either version 3 of the License, or
  23. * (at your option) any later version.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU General Public License
  31. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  32. */
  33. /**
  34. * \file htdocs/core/class/commonobject.class.php
  35. * \ingroup core
  36. * \brief File of parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  37. */
  38. /**
  39. * Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  40. */
  41. abstract class CommonObject
  42. {
  43. const TRIGGER_PREFIX = ''; // to be overriden in child class implementations, i.e. 'BILL', 'TASK', 'PROPAL', etc.
  44. /**
  45. * @var DoliDb Database handler (result of a new DoliDB)
  46. */
  47. public $db;
  48. /**
  49. * @var int The object identifier
  50. */
  51. public $id;
  52. /**
  53. * @var int The environment ID when using a multicompany module
  54. */
  55. public $entity;
  56. /**
  57. * @var string Error string
  58. * @see $errors
  59. */
  60. public $error;
  61. /**
  62. * @var string Error string that is hidden but can be used to store complementatry technical code.
  63. */
  64. public $errorhidden;
  65. /**
  66. * @var string[] Array of error strings
  67. */
  68. public $errors = array();
  69. /**
  70. * @var array To store error results of ->validateField()
  71. */
  72. public $validateFieldsErrors = array();
  73. /**
  74. * @var string ID to identify managed object
  75. */
  76. public $element;
  77. /**
  78. * @var string Name to use for 'features' parameter to check module permissions with restrictedArea(). Undefined means same value than $element.
  79. */
  80. public $element_for_permission;
  81. /**
  82. * @var string Name of table without prefix where object is stored
  83. */
  84. public $table_element;
  85. /**
  86. * @var string Name of subtable line
  87. */
  88. public $table_element_line = '';
  89. /**
  90. * @var string Key value used to track if data is coming from import wizard
  91. */
  92. public $import_key;
  93. /**
  94. * @var mixed Contains data to manage extrafields
  95. */
  96. public $array_options = array();
  97. /**
  98. * @var mixed Array to store alternative languages values of object
  99. */
  100. public $array_languages = null; // Value is array() when load already tried
  101. /**
  102. * @var array To store result of ->liste_contact()
  103. */
  104. public $contacts_ids;
  105. /**
  106. * @var mixed Array of linked objects, set and used when calling ->create() to be able to create links during the creation of object
  107. */
  108. public $linked_objects;
  109. /**
  110. * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked
  111. */
  112. public $linkedObjectsIds;
  113. /**
  114. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  115. */
  116. public $linkedObjects;
  117. /**
  118. * @var boolean Array of boolean with object id as key and value as true if linkedObjects full loaded. Loaded by ->fetchObjectLinked. Important for pdf generation time reduction.
  119. */
  120. public $linkedObjectsFullLoaded = array();
  121. /**
  122. * @var Object To store a cloned copy of object before to edit it and keep track of old properties
  123. */
  124. public $oldcopy;
  125. /**
  126. * @var string Column name of the ref field.
  127. */
  128. protected $table_ref_field = '';
  129. /**
  130. * @var integer 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user
  131. */
  132. public $restrictiononfksoc = 0;
  133. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  134. /**
  135. * @var array<string,mixed> Can be used to pass information when only object is provided to method
  136. */
  137. public $context = array();
  138. /**
  139. * @var string Contains canvas name if record is an alternative canvas record
  140. */
  141. public $canvas;
  142. /**
  143. * @var Project The related project object
  144. * @see fetch_projet()
  145. */
  146. public $project;
  147. /**
  148. * @var int The related project ID
  149. * @see setProject(), project
  150. */
  151. public $fk_project;
  152. /**
  153. * @deprecated
  154. * @see project
  155. */
  156. public $projet;
  157. /**
  158. * @deprecated
  159. * @see $fk_project
  160. */
  161. public $fk_projet;
  162. /**
  163. * @var Contact A related contact object
  164. * @see fetch_contact()
  165. */
  166. public $contact;
  167. /**
  168. * @var int The related contact ID
  169. * @see fetch_contact()
  170. */
  171. public $contact_id;
  172. /**
  173. * @var Societe A related thirdparty object
  174. * @see fetch_thirdparty()
  175. */
  176. public $thirdparty;
  177. /**
  178. * @var User A related user
  179. * @see fetch_user()
  180. */
  181. public $user;
  182. /**
  183. * @var string The type of originating object ('commande', 'facture', ...). Note: on some object this field is called $origin_type
  184. * @see fetch_origin()
  185. */
  186. public $origin;
  187. /**
  188. * @var int The id of originating object
  189. * @see fetch_origin()
  190. */
  191. public $origin_id;
  192. /**
  193. * @var string The object's reference
  194. */
  195. public $ref;
  196. /**
  197. * @var string An external reference for the object
  198. */
  199. public $ref_ext;
  200. /**
  201. * @var string The object's previous reference
  202. */
  203. public $ref_previous;
  204. /**
  205. * @var string The object's next reference
  206. */
  207. public $ref_next;
  208. /**
  209. * @var string Ref to store on object to save the new ref to use for example when making a validate() of an object
  210. */
  211. public $newref;
  212. /**
  213. * @var int The object's status. Prefer use of status.
  214. * @see setStatut()
  215. */
  216. public $statut;
  217. /**
  218. * @var int The object's status
  219. * @see setStatut()
  220. */
  221. public $status;
  222. /**
  223. * @var string
  224. * @see getFullAddress()
  225. */
  226. public $country;
  227. /**
  228. * @var int
  229. * @see getFullAddress(), country
  230. */
  231. public $country_id;
  232. /**
  233. * @var string The ISO country code on 2 chars.
  234. * @see getFullAddress(), isInEEC(), country
  235. */
  236. public $country_code;
  237. /**
  238. * @var string
  239. * @see getFullAddress()
  240. */
  241. public $state;
  242. /**
  243. * @var int
  244. * @see getFullAddress(), state
  245. */
  246. public $state_id;
  247. /**
  248. * @var string
  249. * @see getFullAddress(), $state
  250. */
  251. public $state_code;
  252. /**
  253. * @var int
  254. * @see getFullAddress(), $region_code, $region
  255. */
  256. public $region_id;
  257. /**
  258. * @var string
  259. * @see getFullAddress(), $region_id, $region
  260. */
  261. public $region_code;
  262. /**
  263. * @var string
  264. * @see getFullAddress(), $region_id, $region_code
  265. */
  266. public $region;
  267. /**
  268. * @var int
  269. * @see fetch_barcode()
  270. */
  271. public $barcode_type;
  272. /**
  273. * @var string
  274. * @see fetch_barcode(), barcode_type
  275. */
  276. public $barcode_type_code;
  277. /**
  278. * @var string
  279. * @see fetch_barcode(), barcode_type
  280. */
  281. public $barcode_type_label;
  282. /**
  283. * @var string
  284. * @see fetch_barcode(), barcode_type
  285. */
  286. public $barcode_type_coder;
  287. /**
  288. * @var int Payment method ID (cheque, cash, ...)
  289. * @see setPaymentMethods()
  290. */
  291. public $mode_reglement_id;
  292. /**
  293. * @var int Payment terms ID
  294. * @see setPaymentTerms()
  295. */
  296. public $cond_reglement_id;
  297. /**
  298. * @var int Demand reason ID
  299. */
  300. public $demand_reason_id;
  301. /**
  302. * @var int Transport mode ID (For module intracomm report)
  303. * @see setTransportMode()
  304. */
  305. public $transport_mode_id;
  306. /**
  307. * @var int Payment terms ID
  308. * @deprecated Kept for compatibility
  309. * @see cond_reglement_id;
  310. */
  311. public $cond_reglement;
  312. /**
  313. * @var int Delivery address ID
  314. * @see setDeliveryAddress()
  315. * @deprecated
  316. */
  317. public $fk_delivery_address;
  318. /**
  319. * @var int Shipping method ID
  320. * @see setShippingMethod()
  321. */
  322. public $shipping_method_id;
  323. /**
  324. * @var string
  325. * @see SetDocModel()
  326. */
  327. public $model_pdf;
  328. /**
  329. * @var string
  330. * @deprecated
  331. * @see $model_pdf
  332. */
  333. public $modelpdf;
  334. /**
  335. * @var string
  336. * Contains relative path of last generated main file
  337. */
  338. public $last_main_doc;
  339. /**
  340. * @var int Bank account ID sometimes, ID of record into llx_bank sometimes
  341. * @deprecated
  342. * @see $fk_account
  343. */
  344. public $fk_bank;
  345. /**
  346. * @var int Bank account ID
  347. * @see SetBankAccount()
  348. */
  349. public $fk_account;
  350. /**
  351. * @var string Open ID
  352. */
  353. public $openid;
  354. /**
  355. * @var string Public note
  356. * @see update_note()
  357. */
  358. public $note_public;
  359. /**
  360. * @var string Private note
  361. * @see update_note()
  362. */
  363. public $note_private;
  364. /**
  365. * @deprecated
  366. * @see $note_private
  367. */
  368. public $note;
  369. /**
  370. * @var float Total amount before taxes
  371. * @see update_price()
  372. */
  373. public $total_ht;
  374. /**
  375. * @var float Total VAT amount
  376. * @see update_price()
  377. */
  378. public $total_tva;
  379. /**
  380. * @var float Total local tax 1 amount
  381. * @see update_price()
  382. */
  383. public $total_localtax1;
  384. /**
  385. * @var float Total local tax 2 amount
  386. * @see update_price()
  387. */
  388. public $total_localtax2;
  389. /**
  390. * @var float Total amount with taxes
  391. * @see update_price()
  392. */
  393. public $total_ttc;
  394. /**
  395. * @var CommonObjectLine[]
  396. */
  397. public $lines;
  398. /**
  399. * @var mixed Contains comments
  400. * @see fetchComments()
  401. */
  402. public $comments = array();
  403. /**
  404. * @var string The name
  405. */
  406. public $name;
  407. /**
  408. * @var string The lastname
  409. */
  410. public $lastname;
  411. /**
  412. * @var string The firstname
  413. */
  414. public $firstname;
  415. /**
  416. * @var string The civility code, not an integer
  417. */
  418. public $civility_id;
  419. // Dates
  420. /**
  421. * @var integer|string date_creation
  422. */
  423. public $date_creation;
  424. /**
  425. * @var integer|string $date_validation;
  426. */
  427. public $date_validation; // Date validation
  428. /**
  429. * @var integer|string $date_modification;
  430. */
  431. public $date_modification; // Date last change (tms field)
  432. /**
  433. * @var integer|string $date_cloture;
  434. */
  435. public $date_cloture; // Date closing (tms field)
  436. /**
  437. * @var User|int User author/creation
  438. * @TODO Merge with user_creation
  439. */
  440. public $user_author;
  441. /**
  442. * @var User|int User author/creation
  443. * @TODO Remove type id
  444. */
  445. public $user_creation;
  446. /**
  447. * @var int User id author/creation
  448. */
  449. public $user_creation_id;
  450. /**
  451. * @var User|int User of validation
  452. * @TODO Merge with user_validation
  453. */
  454. public $user_valid;
  455. /**
  456. * @var User|int User of validation
  457. * @TODO Remove type id
  458. */
  459. public $user_validation;
  460. /**
  461. * @var int User id of validation
  462. */
  463. public $user_validation_id;
  464. /**
  465. * @var int User id closing object
  466. */
  467. public $user_closing_id;
  468. /**
  469. * @var User|int User last modifier
  470. * @TODO Remove type id
  471. */
  472. public $user_modification;
  473. /**
  474. * @var int User id last modifier
  475. */
  476. public $user_modification_id;
  477. public $next_prev_filter;
  478. /**
  479. * @var int 1 if object is specimen
  480. */
  481. public $specimen = 0;
  482. /**
  483. * @var int Id of contact to send object (used by the trigger of module Agenda)
  484. */
  485. public $sendtoid;
  486. /**
  487. * @var float Amount already paid (used to show correct status)
  488. */
  489. public $alreadypaid;
  490. /**
  491. * @var array List of child tables. To test if we can delete object.
  492. */
  493. protected $childtables = array();
  494. /**
  495. * @var array List of child tables. To know object to delete on cascade.
  496. * If name is like '@ClassName:FilePathClass:ParentFkFieldName', it will
  497. * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object.
  498. */
  499. protected $childtablesoncascade = array();
  500. // No constructor as it is an abstract class
  501. /**
  502. * Check an object id/ref exists
  503. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  504. *
  505. * @param string $element String of element ('product', 'facture', ...)
  506. * @param int $id Id of object
  507. * @param string $ref Ref of object to check
  508. * @param string $ref_ext Ref ext of object to check
  509. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  510. */
  511. public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
  512. {
  513. global $db, $conf;
  514. $sql = "SELECT rowid, ref, ref_ext";
  515. $sql .= " FROM ".$db->prefix().$element;
  516. $sql .= " WHERE entity IN (".getEntity($element).")";
  517. if ($id > 0) {
  518. $sql .= " AND rowid = ".((int) $id);
  519. } elseif ($ref) {
  520. $sql .= " AND ref = '".$db->escape($ref)."'";
  521. } elseif ($ref_ext) {
  522. $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
  523. } else {
  524. $error = 'ErrorWrongParameters';
  525. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  526. return -1;
  527. }
  528. if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
  529. $sql .= " AND entity = ".((int) $conf->entity);
  530. }
  531. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  532. $resql = $db->query($sql);
  533. if ($resql) {
  534. $num = $db->num_rows($resql);
  535. if ($num > 0) {
  536. return 1;
  537. } else {
  538. return 0;
  539. }
  540. }
  541. return -1;
  542. }
  543. /**
  544. * Method to output saved errors
  545. *
  546. * @return string String with errors
  547. */
  548. public function errorsToString()
  549. {
  550. return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
  551. }
  552. /**
  553. * Return customer ref for screen output.
  554. *
  555. * @param string $objref Customer ref
  556. * @return string Customer ref formated
  557. */
  558. public function getFormatedCustomerRef($objref)
  559. {
  560. global $hookmanager;
  561. $parameters = array('objref'=>$objref);
  562. $action = '';
  563. $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  564. if ($reshook > 0) {
  565. return $hookmanager->resArray['objref'];
  566. }
  567. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  568. }
  569. /**
  570. * Return supplier ref for screen output.
  571. *
  572. * @param string $objref Supplier ref
  573. * @return string Supplier ref formated
  574. */
  575. public function getFormatedSupplierRef($objref)
  576. {
  577. global $hookmanager;
  578. $parameters = array('objref'=>$objref);
  579. $action = '';
  580. $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  581. if ($reshook > 0) {
  582. return $hookmanager->resArray['objref'];
  583. }
  584. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  585. }
  586. /**
  587. * Return full name (civility+' '+name+' '+lastname)
  588. *
  589. * @param Translate $langs Language object for translation of civility (used only if option is 1)
  590. * @param int $option 0=No option, 1=Add civility
  591. * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname, 3=Firstname if defined else lastname, 4=Lastname, 5=Lastname if defined else firstname
  592. * @param int $maxlen Maximum length
  593. * @return string String with full name
  594. */
  595. public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
  596. {
  597. //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
  598. $lastname = $this->lastname;
  599. $firstname = $this->firstname;
  600. if (empty($lastname)) {
  601. $lastname = (isset($this->lastname) ? $this->lastname : (isset($this->name) ? $this->name : (isset($this->nom) ? $this->nom : (isset($this->societe) ? $this->societe : (isset($this->company) ? $this->company : '')))));
  602. }
  603. $ret = '';
  604. if (!empty($option) && !empty($this->civility_code)) {
  605. if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) {
  606. $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
  607. } else {
  608. $ret .= $this->civility_code.' ';
  609. }
  610. }
  611. $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
  612. return dol_trunc($ret, $maxlen);
  613. }
  614. /**
  615. * Set to upper or ucwords/lower if needed
  616. *
  617. * @return void;
  618. */
  619. public function setUpperOrLowerCase()
  620. {
  621. global $conf;
  622. if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
  623. $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
  624. $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
  625. $this->name = dol_ucwords(dol_strtolower($this->name));
  626. $this->name_alias = dol_ucwords(dol_strtolower($this->name_alias));
  627. }
  628. if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
  629. $this->lastname = dol_strtoupper($this->lastname);
  630. $this->name = dol_strtoupper($this->name);
  631. $this->name_alias = dol_strtoupper($this->name_alias);
  632. }
  633. if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
  634. $this->address = dol_strtoupper($this->address);
  635. $this->town = dol_strtoupper($this->town);
  636. }
  637. }
  638. /**
  639. * Return clicable link of object (with eventually picto)
  640. *
  641. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  642. * @return string HTML Code for Kanban thumb.
  643. */
  644. public function getKanbanView($option = '')
  645. {
  646. $return = '<div class="box-flex-item box-flex-grow-zero">';
  647. $return .= '<div class="info-box info-box-sm">';
  648. $return .= '<span class="info-box-icon bg-infobox-action">';
  649. $return .= img_picto('', $this->picto);
  650. //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
  651. $return .= '</span>';
  652. $return .= '<div class="info-box-content">';
  653. $return .= '<span class="info-box-ref">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  654. if (property_exists($this, 'label')) {
  655. $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
  656. }
  657. if (method_exists($this, 'getLibStatut')) {
  658. $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(5).'</div>';
  659. }
  660. $return .= '</div>';
  661. $return .= '</div>';
  662. $return .= '</div>';
  663. return $return;
  664. }
  665. /**
  666. * Return full address of contact
  667. *
  668. * @param int $withcountry 1=Add country into address string
  669. * @param string $sep Separator to use to build string
  670. * @param int $withregion 1=Add region into address string
  671. * @param string $extralangcode User extralanguages as value
  672. * @return string Full address string
  673. */
  674. public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
  675. {
  676. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
  677. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  678. $tmparray = getCountry($this->country_id, 'all');
  679. $this->country_code = $tmparray['code'];
  680. $this->country = $tmparray['label'];
  681. }
  682. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
  683. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  684. $tmparray = getState($this->state_id, 'all', 0, 1);
  685. $this->state_code = $tmparray['code'];
  686. $this->state = $tmparray['label'];
  687. $this->region_code = $tmparray['region_code'];
  688. $this->region = $tmparray['region'];
  689. }
  690. return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
  691. }
  692. /**
  693. * Return full address for banner
  694. *
  695. * @param string $htmlkey HTML id to make banner content unique
  696. * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member)
  697. * @return string Full address string
  698. */
  699. public function getBannerAddress($htmlkey, $object)
  700. {
  701. global $conf, $langs, $form, $extralanguages;
  702. $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
  703. $contactid = 0;
  704. $thirdpartyid = 0;
  705. $elementforaltlanguage = $this->element;
  706. if ($this->element == 'societe') {
  707. $thirdpartyid = $this->id;
  708. }
  709. if ($this->element == 'contact') {
  710. $contactid = $this->id;
  711. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  712. }
  713. if ($this->element == 'user') {
  714. $contactid = $this->contact_id;
  715. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  716. }
  717. $out = '';
  718. $outdone = 0;
  719. $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
  720. if ($coords) {
  721. if (!empty($conf->use_javascript_ajax)) {
  722. // Add picto with tooltip on map
  723. $namecoords = '';
  724. if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
  725. $namecoords .= $object->name.'<br>';
  726. }
  727. $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
  728. // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
  729. $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
  730. $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
  731. $out .= '</a> ';
  732. }
  733. $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  734. $outdone++;
  735. $outdone++;
  736. // List of extra languages
  737. $arrayoflangcode = array();
  738. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  739. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  740. }
  741. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  742. if (!is_object($extralanguages)) {
  743. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  744. $extralanguages = new ExtraLanguages($this->db);
  745. }
  746. $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
  747. if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
  748. $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
  749. $this->fetchValuesForExtraLanguages();
  750. if (!is_object($form)) {
  751. $form = new Form($this->db);
  752. }
  753. $htmltext = '';
  754. // If there is extra languages
  755. foreach ($arrayoflangcode as $extralangcode) {
  756. $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  757. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
  758. $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  759. }
  760. $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  761. }
  762. }
  763. }
  764. if (!in_array($this->country_code, $countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS) // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
  765. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
  766. if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
  767. $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
  768. } else {
  769. $out .= ($outdone ? ' - ' : '').$this->state;
  770. }
  771. $outdone++;
  772. }
  773. if (!empty($this->phone) || !empty($this->phone_pro) || !empty($this->phone_mobile) || !empty($this->phone_perso) || !empty($this->fax) || !empty($this->office_phone) || !empty($this->user_mobile) || !empty($this->office_fax)) {
  774. $out .= ($outdone ? '<br>' : '');
  775. }
  776. if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  777. $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  778. $outdone++;
  779. }
  780. if (!empty($this->phone_pro)) {
  781. $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  782. $outdone++;
  783. }
  784. if (!empty($this->phone_mobile)) {
  785. $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  786. $outdone++;
  787. }
  788. if (!empty($this->phone_perso)) {
  789. $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
  790. $outdone++;
  791. }
  792. if (!empty($this->office_phone)) {
  793. $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  794. $outdone++;
  795. }
  796. if (!empty($this->user_mobile)) {
  797. $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  798. $outdone++;
  799. }
  800. if (!empty($this->fax)) {
  801. $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  802. $outdone++;
  803. }
  804. if (!empty($this->office_fax)) {
  805. $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  806. $outdone++;
  807. }
  808. if ($out) {
  809. $out .= '<div style="clear: both;"></div>';
  810. }
  811. $outdone = 0;
  812. if (!empty($this->email)) {
  813. $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
  814. $outdone++;
  815. }
  816. if (!empty($this->url)) {
  817. //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
  818. $out .= dol_print_url($this->url, '_blank', 0, 1);
  819. $outdone++;
  820. }
  821. if (!empty($conf->socialnetworks->enabled)) {
  822. $outsocialnetwork = '';
  823. if (!empty($this->socialnetworks) && is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
  824. $socialnetworksdict = getArrayOfSocialNetworks();
  825. foreach ($this->socialnetworks as $key => $value) {
  826. if ($value) {
  827. $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
  828. }
  829. $outdone++;
  830. }
  831. } else { // Old code to remove
  832. if (!empty($this->skype)) {
  833. $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
  834. }
  835. $outdone++;
  836. if (!empty($this->jabberid)) {
  837. $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
  838. }
  839. $outdone++;
  840. if (!empty($this->twitter)) {
  841. $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
  842. }
  843. $outdone++;
  844. if (!empty($this->facebook)) {
  845. $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
  846. }
  847. $outdone++;
  848. if (!empty($this->linkedin)) {
  849. $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
  850. }
  851. $outdone++;
  852. }
  853. if ($outsocialnetwork) {
  854. $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
  855. }
  856. }
  857. if ($out) {
  858. return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
  859. } else {
  860. return '';
  861. }
  862. }
  863. /**
  864. * Return the link of last main doc file for direct public download.
  865. *
  866. * @param string $modulepart Module related to document
  867. * @param int $initsharekey Init the share key if it was not yet defined
  868. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  869. * @return string Link or empty string if there is no download link
  870. */
  871. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  872. {
  873. global $user, $dolibarr_main_url_root;
  874. if (empty($this->last_main_doc)) {
  875. return ''; // No way to known which document name to use
  876. }
  877. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  878. $ecmfile = new EcmFiles($this->db);
  879. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  880. if ($result < 0) {
  881. $this->error = $ecmfile->error;
  882. $this->errors = $ecmfile->errors;
  883. return -1;
  884. }
  885. if (empty($ecmfile->id)) {
  886. // Add entry into index
  887. if ($initsharekey) {
  888. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  889. // TODO We can't, we dont' have full path of file, only last_main_doc and ->element, so we must first rebuild full path $destfull
  890. /*
  891. $ecmfile->filepath = $rel_dir;
  892. $ecmfile->filename = $filename;
  893. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  894. $ecmfile->fullpath_orig = '';
  895. $ecmfile->gen_or_uploaded = 'generated';
  896. $ecmfile->description = ''; // indexed content
  897. $ecmfile->keywords = ''; // keyword content
  898. $ecmfile->share = getRandomPassword(true);
  899. $result = $ecmfile->create($user);
  900. if ($result < 0)
  901. {
  902. $this->error = $ecmfile->error;
  903. $this->errors = $ecmfile->errors;
  904. }
  905. */
  906. } else {
  907. return '';
  908. }
  909. } elseif (empty($ecmfile->share)) {
  910. // Add entry into index
  911. if ($initsharekey) {
  912. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  913. $ecmfile->share = getRandomPassword(true);
  914. $ecmfile->update($user);
  915. } else {
  916. return '';
  917. }
  918. }
  919. // Define $urlwithroot
  920. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  921. // This is to use external domain name found into config file
  922. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  923. //else
  924. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  925. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  926. $forcedownload = 0;
  927. $paramlink = '';
  928. //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  929. //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  930. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  931. if (!empty($ecmfile->share)) {
  932. $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
  933. }
  934. if ($forcedownload) {
  935. $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  936. }
  937. if ($relativelink) {
  938. $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
  939. } else {
  940. $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  941. }
  942. // Here $ecmfile->share is defined
  943. return $linktoreturn;
  944. }
  945. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  946. /**
  947. * Add a link between element $this->element and a contact
  948. *
  949. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  950. * @param int|string $type_contact Type of contact (code or id). Must be id or code found into table llx_c_type_contact. For example: SALESREPFOLL
  951. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  952. * @param int $notrigger Disable all triggers
  953. * @return int <0 if KO, 0 if already added, >0 if OK
  954. */
  955. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  956. {
  957. // phpcs:enable
  958. global $user, $langs;
  959. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  960. // Check parameters
  961. if ($fk_socpeople <= 0) {
  962. $langs->load("errors");
  963. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  964. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  965. return -1;
  966. }
  967. if (!$type_contact) {
  968. $langs->load("errors");
  969. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  970. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  971. return -2;
  972. }
  973. $id_type_contact = 0;
  974. if (is_numeric($type_contact)) {
  975. $id_type_contact = $type_contact;
  976. } else {
  977. // We look for id type_contact
  978. $sql = "SELECT tc.rowid";
  979. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  980. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  981. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  982. $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  983. //print $sql;
  984. $resql = $this->db->query($sql);
  985. if ($resql) {
  986. $obj = $this->db->fetch_object($resql);
  987. if ($obj) {
  988. $id_type_contact = $obj->rowid;
  989. }
  990. }
  991. }
  992. if ($id_type_contact == 0) {
  993. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  994. dol_syslog("CODE_NOT_VALID_FOR_THIS_ELEMENT: Code type of contact '".$type_contact."' does not exists or is not active for element ".$this->element.", we can ignore it");
  995. return -3;
  996. }
  997. $datecreate = dol_now();
  998. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  999. $TListeContacts = $this->liste_contact(-1, $source);
  1000. $already_added = false;
  1001. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  1002. foreach ($TListeContacts as $array_contact) {
  1003. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  1004. $already_added = true;
  1005. break;
  1006. }
  1007. }
  1008. }
  1009. if (!$already_added) {
  1010. $this->db->begin();
  1011. // Insert into database
  1012. $sql = "INSERT INTO ".$this->db->prefix()."element_contact";
  1013. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  1014. $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
  1015. $sql .= "'".$this->db->idate($datecreate)."'";
  1016. $sql .= ", 4, ".((int) $id_type_contact);
  1017. $sql .= ")";
  1018. $resql = $this->db->query($sql);
  1019. if ($resql) {
  1020. if (!$notrigger) {
  1021. $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  1022. if ($result < 0) {
  1023. $this->db->rollback();
  1024. return -1;
  1025. }
  1026. }
  1027. $this->db->commit();
  1028. return 1;
  1029. } else {
  1030. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1031. $this->error = $this->db->errno();
  1032. $this->db->rollback();
  1033. return -2;
  1034. } else {
  1035. $this->error = $this->db->lasterror();
  1036. $this->db->rollback();
  1037. return -1;
  1038. }
  1039. }
  1040. } else {
  1041. return 0;
  1042. }
  1043. }
  1044. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1045. /**
  1046. * Copy contact from one element to current
  1047. *
  1048. * @param CommonObject $objFrom Source element
  1049. * @param string $source Nature of contact ('internal' or 'external')
  1050. * @return int >0 if OK, <0 if KO
  1051. */
  1052. public function copy_linked_contact($objFrom, $source = 'internal')
  1053. {
  1054. // phpcs:enable
  1055. $contacts = $objFrom->liste_contact(-1, $source);
  1056. foreach ($contacts as $contact) {
  1057. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
  1058. return -1;
  1059. }
  1060. }
  1061. return 1;
  1062. }
  1063. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1064. /**
  1065. * Update a link to contact line
  1066. *
  1067. * @param int $rowid Id of line contact-element
  1068. * @param int $statut New status of link
  1069. * @param int $type_contact_id Id of contact type (not modified if 0)
  1070. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  1071. * @return int <0 if KO, >= 0 if OK
  1072. */
  1073. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  1074. {
  1075. // phpcs:enable
  1076. // Insert into database
  1077. $sql = "UPDATE ".$this->db->prefix()."element_contact set";
  1078. $sql .= " statut = ".$statut;
  1079. if ($type_contact_id) {
  1080. $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
  1081. }
  1082. if ($fk_socpeople) {
  1083. $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
  1084. }
  1085. $sql .= " where rowid = ".((int) $rowid);
  1086. $resql = $this->db->query($sql);
  1087. if ($resql) {
  1088. return 0;
  1089. } else {
  1090. $this->error = $this->db->lasterror();
  1091. return -1;
  1092. }
  1093. }
  1094. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1095. /**
  1096. * Delete a link to contact line
  1097. *
  1098. * @param int $rowid Id of contact link line to delete
  1099. * @param int $notrigger Disable all triggers
  1100. * @return int >0 if OK, <0 if KO
  1101. */
  1102. public function delete_contact($rowid, $notrigger = 0)
  1103. {
  1104. // phpcs:enable
  1105. global $user;
  1106. $this->db->begin();
  1107. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1108. $sql .= " WHERE rowid = ".((int) $rowid);
  1109. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  1110. if ($this->db->query($sql)) {
  1111. if (!$notrigger) {
  1112. $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  1113. if ($result < 0) {
  1114. $this->db->rollback();
  1115. return -1;
  1116. }
  1117. }
  1118. $this->db->commit();
  1119. return 1;
  1120. } else {
  1121. $this->error = $this->db->lasterror();
  1122. $this->db->rollback();
  1123. return -1;
  1124. }
  1125. }
  1126. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1127. /**
  1128. * Delete all links between an object $this and all its contacts in llx_element_contact
  1129. *
  1130. * @param string $source '' or 'internal' or 'external'
  1131. * @param string $code Type of contact (code or id)
  1132. * @return int <0 if KO, 0=Nothing done, >0 if OK
  1133. */
  1134. public function delete_linked_contact($source = '', $code = '')
  1135. {
  1136. // phpcs:enable
  1137. $listId = '';
  1138. $temp = array();
  1139. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  1140. if (!empty($typeContact)) {
  1141. foreach ($typeContact as $key => $value) {
  1142. array_push($temp, $key);
  1143. }
  1144. $listId = implode(",", $temp);
  1145. }
  1146. // If $listId is empty, we have not criteria on fk_c_type_contact so we will delete record on element_id for
  1147. // any type or record instead of only the ones of the current object. So we do nothing in such a case.
  1148. if (empty($listId)) {
  1149. return 0;
  1150. }
  1151. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1152. $sql .= " WHERE element_id = ".((int) $this->id);
  1153. $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
  1154. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  1155. if ($this->db->query($sql)) {
  1156. return 1;
  1157. } else {
  1158. $this->error = $this->db->lasterror();
  1159. return -1;
  1160. }
  1161. }
  1162. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1163. /**
  1164. * Get array of all contacts for an object
  1165. *
  1166. * @param int $status Status of links to get (-1=all)
  1167. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  1168. * @param int $list 0:Return array contains all properties, 1:Return array contains just id
  1169. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1170. * @return array|int Array of contacts, -1 if error
  1171. */
  1172. public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
  1173. {
  1174. // phpcs:enable
  1175. global $langs;
  1176. $tab = array();
  1177. $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
  1178. if ($source == 'internal') {
  1179. $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  1180. }
  1181. if ($source == 'external' || $source == 'thirdparty') {
  1182. $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1183. }
  1184. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  1185. $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
  1186. $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
  1187. $sql .= ", ".$this->db->prefix()."element_contact ec";
  1188. if ($source == 'internal') {
  1189. $sql .= " LEFT JOIN ".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid";
  1190. }
  1191. if ($source == 'external' || $source == 'thirdparty') {
  1192. $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid";
  1193. }
  1194. $sql .= " WHERE ec.element_id = ".((int) $this->id);
  1195. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1196. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1197. if ($code) {
  1198. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1199. }
  1200. if ($source == 'internal') {
  1201. $sql .= " AND tc.source = 'internal'";
  1202. }
  1203. if ($source == 'external' || $source == 'thirdparty') {
  1204. $sql .= " AND tc.source = 'external'";
  1205. }
  1206. $sql .= " AND tc.active=1";
  1207. if ($status >= 0) {
  1208. $sql .= " AND ec.statut = ".((int) $status);
  1209. }
  1210. $sql .= " ORDER BY t.lastname ASC";
  1211. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  1212. $resql = $this->db->query($sql);
  1213. if ($resql) {
  1214. $num = $this->db->num_rows($resql);
  1215. $i = 0;
  1216. while ($i < $num) {
  1217. $obj = $this->db->fetch_object($resql);
  1218. if (!$list) {
  1219. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1220. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1221. $tab[$i] = array(
  1222. 'source' => $obj->source,
  1223. 'socid' => $obj->socid,
  1224. 'id' => $obj->id,
  1225. 'nom' => $obj->lastname, // For backward compatibility
  1226. 'civility' => $obj->civility,
  1227. 'lastname' => $obj->lastname,
  1228. 'firstname' => $obj->firstname,
  1229. 'email'=>$obj->email,
  1230. 'login'=> (empty($obj->login) ? '' : $obj->login),
  1231. 'photo' => (empty($obj->photo) ? '' : $obj->photo),
  1232. 'statuscontact' => $obj->statuscontact,
  1233. 'rowid' => $obj->rowid,
  1234. 'code' => $obj->code,
  1235. 'libelle' => $libelle_type,
  1236. 'status' => $obj->statuslink,
  1237. 'fk_c_type_contact' => $obj->fk_c_type_contact
  1238. );
  1239. } else {
  1240. $tab[$i] = $obj->id;
  1241. }
  1242. $i++;
  1243. }
  1244. return $tab;
  1245. } else {
  1246. $this->error = $this->db->lasterror();
  1247. dol_print_error($this->db);
  1248. return -1;
  1249. }
  1250. }
  1251. /**
  1252. * Update status of a contact linked to object
  1253. *
  1254. * @param int $rowid Id of link between object and contact
  1255. * @return int <0 if KO, >=0 if OK
  1256. */
  1257. public function swapContactStatus($rowid)
  1258. {
  1259. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1260. $sql .= " tc.code, tc.libelle";
  1261. $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
  1262. $sql .= " WHERE ec.rowid =".((int) $rowid);
  1263. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1264. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1265. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  1266. $resql = $this->db->query($sql);
  1267. if ($resql) {
  1268. $obj = $this->db->fetch_object($resql);
  1269. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1270. $result = $this->update_contact($rowid, $newstatut);
  1271. $this->db->free($resql);
  1272. return $result;
  1273. } else {
  1274. $this->error = $this->db->error();
  1275. dol_print_error($this->db);
  1276. return -1;
  1277. }
  1278. }
  1279. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1280. /**
  1281. * Return array with list of possible values for type of contacts
  1282. *
  1283. * @param string $source 'internal', 'external' or 'all'
  1284. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  1285. * @param int $option 0=Return array id->label, 1=Return array code->label
  1286. * @param int $activeonly 0=all status of contact, 1=only the active
  1287. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1288. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1289. */
  1290. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1291. {
  1292. // phpcs:enable
  1293. global $langs;
  1294. if (empty($order)) {
  1295. $order = 'position';
  1296. }
  1297. if ($order == 'position') {
  1298. $order .= ',code';
  1299. }
  1300. $tab = array();
  1301. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  1302. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1303. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1304. if ($activeonly == 1) {
  1305. $sql .= " AND tc.active=1"; // only the active types
  1306. }
  1307. if (!empty($source) && $source != 'all') {
  1308. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1309. }
  1310. if (!empty($code)) {
  1311. $sql .= " AND tc.code='".$this->db->escape($code)."'";
  1312. }
  1313. $sql .= $this->db->order($order, 'ASC');
  1314. //print "sql=".$sql;
  1315. $resql = $this->db->query($sql);
  1316. if ($resql) {
  1317. $num = $this->db->num_rows($resql);
  1318. $i = 0;
  1319. while ($i < $num) {
  1320. $obj = $this->db->fetch_object($resql);
  1321. $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
  1322. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1323. if (empty($option)) {
  1324. $tab[$obj->rowid] = $libelle_type;
  1325. } else {
  1326. $tab[$obj->code] = $libelle_type;
  1327. }
  1328. $i++;
  1329. }
  1330. return $tab;
  1331. } else {
  1332. $this->error = $this->db->lasterror();
  1333. //dol_print_error($this->db);
  1334. return null;
  1335. }
  1336. }
  1337. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1338. /**
  1339. * Return array with list of possible values for type of contacts
  1340. *
  1341. * @param string $source 'internal', 'external' or 'all'
  1342. * @param int $option 0=Return array id->label, 1=Return array code->label
  1343. * @param int $activeonly 0=all status of contact, 1=only the active
  1344. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1345. * @param string $element Filter on 1 element type
  1346. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1347. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1348. */
  1349. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1350. {
  1351. // phpcs:enable
  1352. global $langs, $conf;
  1353. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1354. $tab = array();
  1355. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
  1356. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1357. $sqlWhere = array();
  1358. if (!empty($element)) {
  1359. $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
  1360. }
  1361. if (!empty($excludeelement)) {
  1362. $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
  1363. }
  1364. if ($activeonly == 1) {
  1365. $sqlWhere[] = " tc.active=1"; // only the active types
  1366. }
  1367. if (!empty($source) && $source != 'all') {
  1368. $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
  1369. }
  1370. if (!empty($code)) {
  1371. $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
  1372. }
  1373. if (count($sqlWhere) > 0) {
  1374. $sql .= " WHERE ".implode(' AND ', $sqlWhere);
  1375. }
  1376. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1377. dol_syslog(__METHOD__, LOG_DEBUG);
  1378. $resql = $this->db->query($sql);
  1379. if ($resql) {
  1380. $num = $this->db->num_rows($resql);
  1381. if ($num > 0) {
  1382. $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
  1383. while ($obj = $this->db->fetch_object($resql)) {
  1384. $modulename = $obj->element;
  1385. if (strpos($obj->element, 'project') !== false) {
  1386. $modulename = 'projet';
  1387. } elseif ($obj->element == 'contrat') {
  1388. $element = 'contract';
  1389. } elseif ($obj->element == 'action') {
  1390. $modulename = 'agenda';
  1391. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1392. $modulename = 'fournisseur';
  1393. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1394. $modulename = 'fournisseur';
  1395. }
  1396. if (!empty($conf->{$modulename}->enabled)) {
  1397. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1398. $tmpelement = $obj->element;
  1399. $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
  1400. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1401. if (empty($option)) {
  1402. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1403. } else {
  1404. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1405. }
  1406. }
  1407. }
  1408. }
  1409. return $tab;
  1410. } else {
  1411. $this->error = $this->db->lasterror();
  1412. return null;
  1413. }
  1414. }
  1415. /**
  1416. * Return id of contacts for a source and a contact code.
  1417. * Example: contact client de facturation ('external', 'BILLING')
  1418. * Example: contact client de livraison ('external', 'SHIPPING')
  1419. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1420. *
  1421. * @param string $source 'external' or 'internal'
  1422. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1423. * @param int $status limited to a certain status
  1424. * @return array List of id for such contacts
  1425. */
  1426. public function getIdContact($source, $code, $status = 0)
  1427. {
  1428. global $conf;
  1429. $result = array();
  1430. $i = 0;
  1431. //cas particulier pour les expeditions
  1432. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1433. $id = $this->origin_id;
  1434. $element = 'commande';
  1435. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1436. $id = $this->origin_id;
  1437. $element = 'order_supplier';
  1438. } else {
  1439. $id = $this->id;
  1440. $element = $this->element;
  1441. }
  1442. $sql = "SELECT ec.fk_socpeople";
  1443. $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
  1444. if ($source == 'internal') {
  1445. $sql .= " ".$this->db->prefix()."user as c,";
  1446. }
  1447. if ($source == 'external') {
  1448. $sql .= " ".$this->db->prefix()."socpeople as c,";
  1449. }
  1450. $sql .= " ".$this->db->prefix()."c_type_contact as tc";
  1451. $sql .= " WHERE ec.element_id = ".((int) $id);
  1452. $sql .= " AND ec.fk_socpeople = c.rowid";
  1453. if ($source == 'internal') {
  1454. $sql .= " AND c.entity IN (".getEntity('user').")";
  1455. }
  1456. if ($source == 'external') {
  1457. $sql .= " AND c.entity IN (".getEntity('societe').")";
  1458. }
  1459. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1460. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1461. $sql .= " AND tc.source = '".$this->db->escape($source)."'";
  1462. if ($code) {
  1463. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1464. }
  1465. $sql .= " AND tc.active = 1";
  1466. if ($status) {
  1467. $sql .= " AND ec.statut = ".((int) $status);
  1468. }
  1469. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1470. $resql = $this->db->query($sql);
  1471. if ($resql) {
  1472. while ($obj = $this->db->fetch_object($resql)) {
  1473. $result[$i] = $obj->fk_socpeople;
  1474. $i++;
  1475. }
  1476. } else {
  1477. $this->error = $this->db->error();
  1478. return null;
  1479. }
  1480. return $result;
  1481. }
  1482. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1483. /**
  1484. * Load object contact with id=$this->contact_id into $this->contact
  1485. *
  1486. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1487. * @return int <0 if KO, >0 if OK
  1488. */
  1489. public function fetch_contact($contactid = null)
  1490. {
  1491. // phpcs:enable
  1492. if (empty($contactid)) {
  1493. $contactid = $this->contact_id;
  1494. }
  1495. if (empty($contactid)) {
  1496. return 0;
  1497. }
  1498. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1499. $contact = new Contact($this->db);
  1500. $result = $contact->fetch($contactid);
  1501. $this->contact = $contact;
  1502. return $result;
  1503. }
  1504. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1505. /**
  1506. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1507. *
  1508. * @param int $force_thirdparty_id Force thirdparty id
  1509. * @return int <0 if KO, >0 if OK
  1510. */
  1511. public function fetch_thirdparty($force_thirdparty_id = 0)
  1512. {
  1513. // phpcs:enable
  1514. global $conf;
  1515. if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
  1516. return 0;
  1517. }
  1518. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1519. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
  1520. if ($force_thirdparty_id) {
  1521. $idtofetch = $force_thirdparty_id;
  1522. }
  1523. if ($idtofetch) {
  1524. $thirdparty = new Societe($this->db);
  1525. $result = $thirdparty->fetch($idtofetch);
  1526. if ($result<0) {
  1527. $this->errors=array_merge($this->errors, $thirdparty->errors);
  1528. }
  1529. $this->thirdparty = $thirdparty;
  1530. // Use first price level if level not defined for third party
  1531. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1532. $this->thirdparty->price_level = 1;
  1533. }
  1534. return $result;
  1535. } else {
  1536. return -1;
  1537. }
  1538. }
  1539. /**
  1540. * Looks for an object with ref matching the wildcard provided
  1541. * It does only work when $this->table_ref_field is set
  1542. *
  1543. * @param string $ref Wildcard
  1544. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1545. */
  1546. public function fetchOneLike($ref)
  1547. {
  1548. if (!$this->table_ref_field) {
  1549. return 0;
  1550. }
  1551. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element." WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."' LIMIT 1";
  1552. $query = $this->db->query($sql);
  1553. if (!$this->db->num_rows($query)) {
  1554. return 0;
  1555. }
  1556. $result = $this->db->fetch_object($query);
  1557. return $this->fetch($result->rowid);
  1558. }
  1559. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1560. /**
  1561. * Load data for barcode into properties ->barcode_type*
  1562. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1563. * if it is not defined, ->element must be defined to know default barcode type.
  1564. *
  1565. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1566. */
  1567. public function fetch_barcode()
  1568. {
  1569. // phpcs:enable
  1570. global $conf;
  1571. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1572. $idtype = $this->barcode_type;
  1573. 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
  1574. if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
  1575. $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1576. } elseif ($this->element == 'societe') {
  1577. $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1578. } else {
  1579. dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1580. }
  1581. }
  1582. if ($idtype > 0) {
  1583. 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
  1584. $sql = "SELECT rowid, code, libelle as label, coder";
  1585. $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
  1586. $sql .= " WHERE rowid = ".((int) $idtype);
  1587. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1588. $resql = $this->db->query($sql);
  1589. if ($resql) {
  1590. $obj = $this->db->fetch_object($resql);
  1591. $this->barcode_type = $obj->rowid;
  1592. $this->barcode_type_code = $obj->code;
  1593. $this->barcode_type_label = $obj->label;
  1594. $this->barcode_type_coder = $obj->coder;
  1595. return 1;
  1596. } else {
  1597. dol_print_error($this->db);
  1598. return -1;
  1599. }
  1600. }
  1601. }
  1602. return 0;
  1603. }
  1604. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1605. /**
  1606. * Load the project with id $this->fk_project into this->project
  1607. *
  1608. * @return int <0 if KO, >=0 if OK
  1609. */
  1610. public function fetch_project()
  1611. {
  1612. // phpcs:enable
  1613. return $this->fetch_projet();
  1614. }
  1615. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1616. /**
  1617. * Load the project with id $this->fk_project into this->project
  1618. *
  1619. * @return int <0 if KO, >=0 if OK
  1620. */
  1621. public function fetch_projet()
  1622. {
  1623. // phpcs:enable
  1624. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1625. if (empty($this->fk_project) && !empty($this->fk_projet)) {
  1626. $this->fk_project = $this->fk_projet; // For backward compatibility
  1627. }
  1628. if (empty($this->fk_project)) {
  1629. return 0;
  1630. }
  1631. $project = new Project($this->db);
  1632. $result = $project->fetch($this->fk_project);
  1633. $this->projet = $project; // deprecated
  1634. $this->project = $project;
  1635. return $result;
  1636. }
  1637. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1638. /**
  1639. * Load the product with id $this->fk_product into this->product
  1640. *
  1641. * @return int <0 if KO, >=0 if OK
  1642. */
  1643. public function fetch_product()
  1644. {
  1645. // phpcs:enable
  1646. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1647. if (empty($this->fk_product)) {
  1648. return 0;
  1649. }
  1650. $product = new Product($this->db);
  1651. $result = $product->fetch($this->fk_product);
  1652. $this->product = $product;
  1653. return $result;
  1654. }
  1655. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1656. /**
  1657. * Load the user with id $userid into this->user
  1658. *
  1659. * @param int $userid Id du contact
  1660. * @return int <0 if KO, >0 if OK
  1661. */
  1662. public function fetch_user($userid)
  1663. {
  1664. // phpcs:enable
  1665. $user = new User($this->db);
  1666. $result = $user->fetch($userid);
  1667. $this->user = $user;
  1668. return $result;
  1669. }
  1670. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1671. /**
  1672. * Read linked origin object
  1673. *
  1674. * @return void
  1675. */
  1676. public function fetch_origin()
  1677. {
  1678. // phpcs:enable
  1679. if ($this->origin == 'shipping') {
  1680. $this->origin = 'expedition';
  1681. }
  1682. if ($this->origin == 'delivery') {
  1683. $this->origin = 'livraison';
  1684. }
  1685. if ($this->origin == 'order_supplier') {
  1686. $this->origin = 'commandeFournisseur';
  1687. }
  1688. $origin = $this->origin;
  1689. $classname = ucfirst($origin);
  1690. $this->$origin = new $classname($this->db);
  1691. $this->$origin->fetch($this->origin_id);
  1692. }
  1693. /**
  1694. * Load object from specific field
  1695. *
  1696. * @param string $table Table element or element line
  1697. * @param string $field Field selected
  1698. * @param string $key Import key
  1699. * @param string $element Element name
  1700. * @return int <0 if KO, >0 if OK
  1701. */
  1702. public function fetchObjectFrom($table, $field, $key, $element = null)
  1703. {
  1704. global $conf;
  1705. $result = false;
  1706. $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
  1707. $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
  1708. if (!empty($element)) {
  1709. $sql .= " AND entity IN (".getEntity($element).")";
  1710. } else {
  1711. $sql .= " AND entity = ".((int) $conf->entity);
  1712. }
  1713. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1714. $resql = $this->db->query($sql);
  1715. if ($resql) {
  1716. $row = $this->db->fetch_row($resql);
  1717. // Test for avoid error -1
  1718. if ($row[0] > 0) {
  1719. $result = $this->fetch($row[0]);
  1720. }
  1721. }
  1722. return $result;
  1723. }
  1724. /**
  1725. * Getter generic. Load value from a specific field
  1726. *
  1727. * @param string $table Table of element or element line
  1728. * @param int $id Element id
  1729. * @param string $field Field selected
  1730. * @return int <0 if KO, >0 if OK
  1731. */
  1732. public function getValueFrom($table, $id, $field)
  1733. {
  1734. $result = false;
  1735. if (!empty($id) && !empty($field) && !empty($table)) {
  1736. $sql = "SELECT ".$field." FROM ".$this->db->prefix().$table;
  1737. $sql .= " WHERE rowid = ".((int) $id);
  1738. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1739. $resql = $this->db->query($sql);
  1740. if ($resql) {
  1741. $row = $this->db->fetch_row($resql);
  1742. $result = $row[0];
  1743. }
  1744. }
  1745. return $result;
  1746. }
  1747. /**
  1748. * Setter generic. Update a specific field into database.
  1749. * Warning: Trigger is run only if param trigkey is provided.
  1750. *
  1751. * @param string $field Field to update
  1752. * @param mixed $value New value
  1753. * @param string $table To force other table element or element line (should not be used)
  1754. * @param int $id To force other object id (should not be used)
  1755. * @param string $format Data format ('text', 'date'). 'text' is used if not defined
  1756. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1757. * @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'
  1758. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1759. * @param string $fk_user_field Name of field to save user id making change
  1760. * @return int <0 if KO, >0 if OK
  1761. * @see updateExtraField()
  1762. */
  1763. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1764. {
  1765. global $user, $langs, $conf;
  1766. if (empty($table)) {
  1767. $table = $this->table_element;
  1768. }
  1769. if (empty($id)) {
  1770. $id = $this->id;
  1771. }
  1772. if (empty($format)) {
  1773. $format = 'text';
  1774. }
  1775. if (empty($id_field)) {
  1776. $id_field = 'rowid';
  1777. }
  1778. $error = 0;
  1779. $this->db->begin();
  1780. // Special case
  1781. if ($table == 'product' && $field == 'note_private') {
  1782. $field = 'note';
  1783. }
  1784. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  1785. $fk_user_field = 'fk_user_mod';
  1786. }
  1787. $sql = "UPDATE ".$this->db->prefix().$table." SET ";
  1788. if ($format == 'text') {
  1789. $sql .= $field." = '".$this->db->escape($value)."'";
  1790. } elseif ($format == 'int') {
  1791. $sql .= $field." = ".((int) $value);
  1792. } elseif ($format == 'date') {
  1793. $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1794. }
  1795. if ($fk_user_field) {
  1796. if (!empty($fuser) && is_object($fuser)) {
  1797. $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
  1798. } elseif (empty($fuser) || $fuser != 'none') {
  1799. $sql .= ", ".$fk_user_field." = ".((int) $user->id);
  1800. }
  1801. }
  1802. $sql .= " WHERE ".$id_field." = ".((int) $id);
  1803. dol_syslog(__METHOD__."", LOG_DEBUG);
  1804. $resql = $this->db->query($sql);
  1805. if ($resql) {
  1806. if ($trigkey) {
  1807. // call trigger with updated object values
  1808. if (empty($this->fields) && method_exists($this, 'fetch')) {
  1809. $result = $this->fetch($id);
  1810. } else {
  1811. $result = $this->fetchCommon($id);
  1812. }
  1813. if ($result >= 0) {
  1814. $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1815. }
  1816. if ($result < 0) {
  1817. $error++;
  1818. }
  1819. }
  1820. if (!$error) {
  1821. if (property_exists($this, $field)) {
  1822. $this->$field = $value;
  1823. }
  1824. $this->db->commit();
  1825. return 1;
  1826. } else {
  1827. $this->db->rollback();
  1828. return -2;
  1829. }
  1830. } else {
  1831. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1832. $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
  1833. } else {
  1834. $this->error = $this->db->lasterror();
  1835. }
  1836. $this->db->rollback();
  1837. return -1;
  1838. }
  1839. }
  1840. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1841. /**
  1842. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1843. *
  1844. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')". Do not allow user input data here.
  1845. * @param string $fieldid Name of field to use for the select MAX and MIN
  1846. * @param int $nodbprefix Do not include DB prefix to forge table name
  1847. * @return int <0 if KO, >0 if OK
  1848. */
  1849. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1850. {
  1851. // phpcs:enable
  1852. global $conf, $user;
  1853. if (!$this->table_element) {
  1854. dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1855. return -1;
  1856. }
  1857. if ($fieldid == 'none') {
  1858. return 1;
  1859. }
  1860. // For backward compatibility
  1861. if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
  1862. $fieldid = 'titre';
  1863. }
  1864. // Security on socid
  1865. $socid = 0;
  1866. if ($user->socid > 0) {
  1867. $socid = $user->socid;
  1868. }
  1869. // this->ismultientitymanaged contains
  1870. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1871. $aliastablesociete = 's';
  1872. if ($this->element == 'societe') {
  1873. $aliastablesociete = 'te'; // te as table_element
  1874. }
  1875. $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
  1876. $sql = "SELECT MAX(te.".$fieldid.")";
  1877. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1878. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1879. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1880. }
  1881. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1882. $tmparray = explode('@', $this->ismultientitymanaged);
  1883. $sql .= ", ".$this->db->prefix().$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1884. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1885. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1886. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1887. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1888. }
  1889. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1890. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1891. }
  1892. $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)
  1893. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1894. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1895. }
  1896. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1897. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1898. }
  1899. if (!empty($filter)) {
  1900. if (!preg_match('/^\s*AND/i', $filter)) {
  1901. $sql .= " AND "; // For backward compatibility
  1902. }
  1903. $sql .= $filter;
  1904. }
  1905. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1906. $tmparray = explode('@', $this->ismultientitymanaged);
  1907. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1908. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1909. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1910. }
  1911. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1912. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1913. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1914. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1915. } else {
  1916. $sql .= " AND ug.fk_user = te.rowid";
  1917. $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
  1918. }
  1919. } else {
  1920. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1921. }
  1922. }
  1923. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1924. $tmparray = explode('@', $this->ismultientitymanaged);
  1925. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1926. }
  1927. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1928. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1929. }
  1930. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1931. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1932. }
  1933. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1934. $sql .= ' AND te.rowid = '.((int) $socid);
  1935. }
  1936. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1937. $result = $this->db->query($sql);
  1938. if (!$result) {
  1939. $this->error = $this->db->lasterror();
  1940. return -1;
  1941. }
  1942. $row = $this->db->fetch_row($result);
  1943. $this->ref_previous = $row[0];
  1944. $sql = "SELECT MIN(te.".$fieldid.")";
  1945. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1946. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1947. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1948. }
  1949. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1950. $tmparray = explode('@', $this->ismultientitymanaged);
  1951. $sql .= ", ".$this->db->prefix().$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1952. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1953. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1954. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1955. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1956. }
  1957. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1958. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1959. }
  1960. $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)
  1961. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1962. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1963. }
  1964. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1965. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1966. }
  1967. if (!empty($filter)) {
  1968. if (!preg_match('/^\s*AND/i', $filter)) {
  1969. $sql .= " AND "; // For backward compatibility
  1970. }
  1971. $sql .= $filter;
  1972. }
  1973. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1974. $tmparray = explode('@', $this->ismultientitymanaged);
  1975. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1976. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1977. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1978. }
  1979. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1980. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1981. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1982. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1983. } else {
  1984. $sql .= " AND ug.fk_user = te.rowid";
  1985. $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
  1986. }
  1987. } else {
  1988. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1989. }
  1990. }
  1991. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1992. $tmparray = explode('@', $this->ismultientitymanaged);
  1993. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1994. }
  1995. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1996. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1997. }
  1998. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1999. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  2000. }
  2001. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  2002. $sql .= ' AND te.rowid = '.((int) $socid);
  2003. }
  2004. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  2005. // 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
  2006. $result = $this->db->query($sql);
  2007. if (!$result) {
  2008. $this->error = $this->db->lasterror();
  2009. return -2;
  2010. }
  2011. $row = $this->db->fetch_row($result);
  2012. $this->ref_next = $row[0];
  2013. return 1;
  2014. }
  2015. /**
  2016. * Return list of id of contacts of object
  2017. *
  2018. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  2019. * @return array Array of id of contacts (if source=external or internal)
  2020. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  2021. */
  2022. public function getListContactId($source = 'external')
  2023. {
  2024. $contactAlreadySelected = array();
  2025. $tab = $this->liste_contact(-1, $source);
  2026. $num = count($tab);
  2027. $i = 0;
  2028. while ($i < $num) {
  2029. if ($source == 'thirdparty') {
  2030. $contactAlreadySelected[$i] = $tab[$i]['socid'];
  2031. } else {
  2032. $contactAlreadySelected[$i] = $tab[$i]['id'];
  2033. }
  2034. $i++;
  2035. }
  2036. return $contactAlreadySelected;
  2037. }
  2038. /**
  2039. * Link element with a project
  2040. *
  2041. * @param int $projectid Project id to link element to
  2042. * @param int $notrigger Disable the trigger
  2043. * @return int <0 if KO, >0 if OK
  2044. */
  2045. public function setProject($projectid, $notrigger = 0)
  2046. {
  2047. global $user;
  2048. $error = 0;
  2049. if (!$this->table_element) {
  2050. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  2051. return -1;
  2052. }
  2053. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2054. if (!empty($this->fields['fk_project'])) { // Common case
  2055. if ($projectid) {
  2056. $sql .= " SET fk_project = ".((int) $projectid);
  2057. } else {
  2058. $sql .= " SET fk_project = NULL";
  2059. }
  2060. $sql .= ' WHERE rowid = '.((int) $this->id);
  2061. } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
  2062. if ($projectid) {
  2063. $sql .= " SET fk_project = ".((int) $projectid);
  2064. } else {
  2065. $sql .= " SET fk_project = NULL";
  2066. }
  2067. $sql .= ' WHERE id = '.((int) $this->id);
  2068. } else // Special case for old architecture objects
  2069. {
  2070. if ($projectid) {
  2071. $sql .= ' SET fk_projet = '.((int) $projectid);
  2072. } else {
  2073. $sql .= ' SET fk_projet = NULL';
  2074. }
  2075. $sql .= " WHERE rowid = ".((int) $this->id);
  2076. }
  2077. $this->db->begin();
  2078. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  2079. if ($this->db->query($sql)) {
  2080. $this->fk_project = ((int) $projectid);
  2081. } else {
  2082. dol_print_error($this->db);
  2083. $error++;
  2084. }
  2085. // Triggers
  2086. if (!$error && !$notrigger) {
  2087. // Call triggers
  2088. $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
  2089. if ($result < 0) {
  2090. $error++;
  2091. } //Do also here what you must do to rollback action if trigger fail
  2092. // End call triggers
  2093. }
  2094. // Commit or rollback
  2095. if ($error) {
  2096. $this->db->rollback();
  2097. return -1;
  2098. } else {
  2099. $this->db->commit();
  2100. return 1;
  2101. }
  2102. }
  2103. /**
  2104. * Change the payments methods
  2105. *
  2106. * @param int $id Id of new payment method
  2107. * @return int >0 if OK, <0 if KO
  2108. */
  2109. public function setPaymentMethods($id)
  2110. {
  2111. global $user;
  2112. $error = 0; $notrigger = 0;
  2113. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  2114. if ($this->statut >= 0 || $this->element == 'societe') {
  2115. // TODO uniformize field name
  2116. $fieldname = 'fk_mode_reglement';
  2117. if ($this->element == 'societe') {
  2118. $fieldname = 'mode_reglement';
  2119. }
  2120. if (get_class($this) == 'Fournisseur') {
  2121. $fieldname = 'mode_reglement_supplier';
  2122. }
  2123. if (get_class($this) == 'Tva') {
  2124. $fieldname = 'fk_typepayment';
  2125. }
  2126. if (get_class($this) == 'Salary') {
  2127. $fieldname = 'fk_typepayment';
  2128. }
  2129. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2130. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2131. $sql .= ' WHERE rowid='.((int) $this->id);
  2132. if ($this->db->query($sql)) {
  2133. $this->mode_reglement_id = $id;
  2134. // for supplier
  2135. if (get_class($this) == 'Fournisseur') {
  2136. $this->mode_reglement_supplier_id = $id;
  2137. }
  2138. // Triggers
  2139. if (!$error && !$notrigger) {
  2140. // Call triggers
  2141. if (get_class($this) == 'Commande') {
  2142. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2143. } else {
  2144. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  2145. }
  2146. if ($result < 0) {
  2147. $error++;
  2148. }
  2149. // End call triggers
  2150. }
  2151. return 1;
  2152. } else {
  2153. dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
  2154. $this->error = $this->db->error();
  2155. return -1;
  2156. }
  2157. } else {
  2158. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  2159. $this->error = 'Status of the object is incompatible '.$this->statut;
  2160. return -2;
  2161. }
  2162. }
  2163. /**
  2164. * Change the multicurrency code
  2165. *
  2166. * @param string $code multicurrency code
  2167. * @return int >0 if OK, <0 if KO
  2168. */
  2169. public function setMulticurrencyCode($code)
  2170. {
  2171. dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
  2172. if ($this->statut >= 0 || $this->element == 'societe') {
  2173. $fieldname = 'multicurrency_code';
  2174. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2175. $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
  2176. $sql .= ' WHERE rowid='.((int) $this->id);
  2177. if ($this->db->query($sql)) {
  2178. $this->multicurrency_code = $code;
  2179. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  2180. if ($rate) {
  2181. $this->setMulticurrencyRate($rate, 2);
  2182. }
  2183. return 1;
  2184. } else {
  2185. dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
  2186. $this->error = $this->db->error();
  2187. return -1;
  2188. }
  2189. } else {
  2190. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  2191. $this->error = 'Status of the object is incompatible '.$this->statut;
  2192. return -2;
  2193. }
  2194. }
  2195. /**
  2196. * Change the multicurrency rate
  2197. *
  2198. * @param double $rate multicurrency rate
  2199. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  2200. * @return int >0 if OK, <0 if KO
  2201. */
  2202. public function setMulticurrencyRate($rate, $mode = 1)
  2203. {
  2204. dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
  2205. if ($this->statut >= 0 || $this->element == 'societe') {
  2206. $fieldname = 'multicurrency_tx';
  2207. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2208. $sql .= " SET ".$fieldname." = ".((float) $rate);
  2209. $sql .= ' WHERE rowid='.((int) $this->id);
  2210. if ($this->db->query($sql)) {
  2211. $this->multicurrency_tx = $rate;
  2212. // Update line price
  2213. if (!empty($this->lines)) {
  2214. foreach ($this->lines as &$line) {
  2215. // Amounts in company currency will be recalculated
  2216. if ($mode == 1) {
  2217. $line->subprice = 0;
  2218. }
  2219. // Amounts in foreign currency will be recalculated
  2220. if ($mode == 2) {
  2221. $line->multicurrency_subprice = 0;
  2222. }
  2223. switch ($this->element) {
  2224. case 'propal':
  2225. $this->updateline(
  2226. $line->id,
  2227. $line->subprice,
  2228. $line->qty,
  2229. $line->remise_percent,
  2230. $line->tva_tx,
  2231. $line->localtax1_tx,
  2232. $line->localtax2_tx,
  2233. ($line->description ? $line->description : $line->desc),
  2234. 'HT',
  2235. $line->info_bits,
  2236. $line->special_code,
  2237. $line->fk_parent_line,
  2238. $line->skip_update_total,
  2239. $line->fk_fournprice,
  2240. $line->pa_ht,
  2241. $line->label,
  2242. $line->product_type,
  2243. $line->date_start,
  2244. $line->date_end,
  2245. $line->array_options,
  2246. $line->fk_unit,
  2247. $line->multicurrency_subprice
  2248. );
  2249. break;
  2250. case 'commande':
  2251. $this->updateline(
  2252. $line->id,
  2253. ($line->description ? $line->description : $line->desc),
  2254. $line->subprice,
  2255. $line->qty,
  2256. $line->remise_percent,
  2257. $line->tva_tx,
  2258. $line->localtax1_tx,
  2259. $line->localtax2_tx,
  2260. 'HT',
  2261. $line->info_bits,
  2262. $line->date_start,
  2263. $line->date_end,
  2264. $line->product_type,
  2265. $line->fk_parent_line,
  2266. $line->skip_update_total,
  2267. $line->fk_fournprice,
  2268. $line->pa_ht,
  2269. $line->label,
  2270. $line->special_code,
  2271. $line->array_options,
  2272. $line->fk_unit,
  2273. $line->multicurrency_subprice
  2274. );
  2275. break;
  2276. case 'facture':
  2277. $this->updateline(
  2278. $line->id,
  2279. ($line->description ? $line->description : $line->desc),
  2280. $line->subprice,
  2281. $line->qty,
  2282. $line->remise_percent,
  2283. $line->date_start,
  2284. $line->date_end,
  2285. $line->tva_tx,
  2286. $line->localtax1_tx,
  2287. $line->localtax2_tx,
  2288. 'HT',
  2289. $line->info_bits,
  2290. $line->product_type,
  2291. $line->fk_parent_line,
  2292. $line->skip_update_total,
  2293. $line->fk_fournprice,
  2294. $line->pa_ht,
  2295. $line->label,
  2296. $line->special_code,
  2297. $line->array_options,
  2298. $line->situation_percent,
  2299. $line->fk_unit,
  2300. $line->multicurrency_subprice
  2301. );
  2302. break;
  2303. case 'supplier_proposal':
  2304. $this->updateline(
  2305. $line->id,
  2306. $line->subprice,
  2307. $line->qty,
  2308. $line->remise_percent,
  2309. $line->tva_tx,
  2310. $line->localtax1_tx,
  2311. $line->localtax2_tx,
  2312. ($line->description ? $line->description : $line->desc),
  2313. 'HT',
  2314. $line->info_bits,
  2315. $line->special_code,
  2316. $line->fk_parent_line,
  2317. $line->skip_update_total,
  2318. $line->fk_fournprice,
  2319. $line->pa_ht,
  2320. $line->label,
  2321. $line->product_type,
  2322. $line->array_options,
  2323. $line->ref_fourn,
  2324. $line->multicurrency_subprice
  2325. );
  2326. break;
  2327. case 'order_supplier':
  2328. $this->updateline(
  2329. $line->id,
  2330. ($line->description ? $line->description : $line->desc),
  2331. $line->subprice,
  2332. $line->qty,
  2333. $line->remise_percent,
  2334. $line->tva_tx,
  2335. $line->localtax1_tx,
  2336. $line->localtax2_tx,
  2337. 'HT',
  2338. $line->info_bits,
  2339. $line->product_type,
  2340. false,
  2341. $line->date_start,
  2342. $line->date_end,
  2343. $line->array_options,
  2344. $line->fk_unit,
  2345. $line->multicurrency_subprice,
  2346. $line->ref_supplier
  2347. );
  2348. break;
  2349. case 'invoice_supplier':
  2350. $this->updateline(
  2351. $line->id,
  2352. ($line->description ? $line->description : $line->desc),
  2353. $line->subprice,
  2354. $line->tva_tx,
  2355. $line->localtax1_tx,
  2356. $line->localtax2_tx,
  2357. $line->qty,
  2358. 0,
  2359. 'HT',
  2360. $line->info_bits,
  2361. $line->product_type,
  2362. $line->remise_percent,
  2363. false,
  2364. $line->date_start,
  2365. $line->date_end,
  2366. $line->array_options,
  2367. $line->fk_unit,
  2368. $line->multicurrency_subprice,
  2369. $line->ref_supplier
  2370. );
  2371. break;
  2372. default:
  2373. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  2374. break;
  2375. }
  2376. }
  2377. }
  2378. return 1;
  2379. } else {
  2380. dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
  2381. $this->error = $this->db->error();
  2382. return -1;
  2383. }
  2384. } else {
  2385. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  2386. $this->error = 'Status of the object is incompatible '.$this->statut;
  2387. return -2;
  2388. }
  2389. }
  2390. /**
  2391. * Change the payments terms
  2392. *
  2393. * @param int $id Id of new payment terms
  2394. * @param string $deposit_percent % of deposit if needed by payment terms
  2395. * @return int >0 if OK, <0 if KO
  2396. */
  2397. public function setPaymentTerms($id, $deposit_percent = null)
  2398. {
  2399. dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
  2400. if ($this->statut >= 0 || $this->element == 'societe') {
  2401. // TODO uniformize field name
  2402. $fieldname = 'fk_cond_reglement';
  2403. if ($this->element == 'societe') {
  2404. $fieldname = 'cond_reglement';
  2405. }
  2406. if (get_class($this) == 'Fournisseur') {
  2407. $fieldname = 'cond_reglement_supplier';
  2408. }
  2409. if (empty($deposit_percent) || $deposit_percent < 0) {
  2410. $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id);
  2411. }
  2412. if ($deposit_percent > 100) {
  2413. $deposit_percent = 100;
  2414. }
  2415. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2416. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2417. if (in_array($this->table_element, array('propal', 'commande'))) {
  2418. $sql .= " , deposit_percent = " . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'");
  2419. }
  2420. $sql .= ' WHERE rowid='.((int) $this->id);
  2421. if ($this->db->query($sql)) {
  2422. $this->cond_reglement_id = $id;
  2423. // for supplier
  2424. if (get_class($this) == 'Fournisseur') {
  2425. $this->cond_reglement_supplier_id = $id;
  2426. }
  2427. $this->cond_reglement = $id; // for compatibility
  2428. $this->deposit_percent = $deposit_percent;
  2429. return 1;
  2430. } else {
  2431. dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
  2432. $this->error = $this->db->error();
  2433. return -1;
  2434. }
  2435. } else {
  2436. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  2437. $this->error = 'Status of the object is incompatible '.$this->statut;
  2438. return -2;
  2439. }
  2440. }
  2441. /**
  2442. * Change the transport mode methods
  2443. *
  2444. * @param int $id Id of transport mode
  2445. * @return int >0 if OK, <0 if KO
  2446. */
  2447. public function setTransportMode($id)
  2448. {
  2449. dol_syslog(get_class($this).'::setTransportMode('.$id.')');
  2450. if ($this->statut >= 0 || $this->element == 'societe') {
  2451. $fieldname = 'fk_transport_mode';
  2452. if ($this->element == 'societe') {
  2453. $fieldname = 'transport_mode';
  2454. }
  2455. if (get_class($this) == 'Fournisseur') {
  2456. $fieldname = 'transport_mode_supplier';
  2457. }
  2458. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2459. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2460. $sql .= ' WHERE rowid='.((int) $this->id);
  2461. if ($this->db->query($sql)) {
  2462. $this->transport_mode_id = $id;
  2463. // for supplier
  2464. if (get_class($this) == 'Fournisseur') {
  2465. $this->transport_mode_supplier_id = $id;
  2466. }
  2467. return 1;
  2468. } else {
  2469. dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
  2470. $this->error = $this->db->error();
  2471. return -1;
  2472. }
  2473. } else {
  2474. dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
  2475. $this->error = 'Status of the object is incompatible '.$this->statut;
  2476. return -2;
  2477. }
  2478. }
  2479. /**
  2480. * Change the retained warranty payments terms
  2481. *
  2482. * @param int $id Id of new payment terms
  2483. * @return int >0 if OK, <0 if KO
  2484. */
  2485. public function setRetainedWarrantyPaymentTerms($id)
  2486. {
  2487. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
  2488. if ($this->statut >= 0 || $this->element == 'societe') {
  2489. $fieldname = 'retained_warranty_fk_cond_reglement';
  2490. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2491. $sql .= " SET ".$fieldname." = ".((int) $id);
  2492. $sql .= ' WHERE rowid='.((int) $this->id);
  2493. if ($this->db->query($sql)) {
  2494. $this->retained_warranty_fk_cond_reglement = $id;
  2495. return 1;
  2496. } else {
  2497. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
  2498. $this->error = $this->db->error();
  2499. return -1;
  2500. }
  2501. } else {
  2502. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  2503. $this->error = 'Status of the object is incompatible '.$this->statut;
  2504. return -2;
  2505. }
  2506. }
  2507. /**
  2508. * Define delivery address
  2509. * @deprecated
  2510. *
  2511. * @param int $id Address id
  2512. * @return int <0 si ko, >0 si ok
  2513. */
  2514. public function setDeliveryAddress($id)
  2515. {
  2516. $fieldname = 'fk_delivery_address';
  2517. if ($this->element == 'delivery' || $this->element == 'shipping') {
  2518. $fieldname = 'fk_address';
  2519. }
  2520. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$fieldname." = ".((int) $id);
  2521. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
  2522. if ($this->db->query($sql)) {
  2523. $this->fk_delivery_address = $id;
  2524. return 1;
  2525. } else {
  2526. $this->error = $this->db->error();
  2527. dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
  2528. return -1;
  2529. }
  2530. }
  2531. /**
  2532. * Change the shipping method
  2533. *
  2534. * @param int $shipping_method_id Id of shipping method
  2535. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2536. * @param User $userused Object user
  2537. *
  2538. * @return int 1 if OK, 0 if KO
  2539. */
  2540. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  2541. {
  2542. global $user;
  2543. if (empty($userused)) {
  2544. $userused = $user;
  2545. }
  2546. $error = 0;
  2547. if (!$this->table_element) {
  2548. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2549. return -1;
  2550. }
  2551. $this->db->begin();
  2552. if ($shipping_method_id < 0) {
  2553. $shipping_method_id = 'NULL';
  2554. }
  2555. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  2556. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2557. $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
  2558. $sql .= " WHERE rowid=".((int) $this->id);
  2559. $resql = $this->db->query($sql);
  2560. if (!$resql) {
  2561. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  2562. $this->error = $this->db->lasterror();
  2563. $error++;
  2564. } else {
  2565. if (!$notrigger) {
  2566. // Call trigger
  2567. $this->context = array('shippingmethodupdate'=>1);
  2568. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2569. if ($result < 0) {
  2570. $error++;
  2571. }
  2572. // End call trigger
  2573. }
  2574. }
  2575. if ($error) {
  2576. $this->db->rollback();
  2577. return -1;
  2578. } else {
  2579. $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
  2580. $this->db->commit();
  2581. return 1;
  2582. }
  2583. }
  2584. /**
  2585. * Change the warehouse
  2586. *
  2587. * @param int $warehouse_id Id of warehouse
  2588. * @return int 1 if OK, 0 if KO
  2589. */
  2590. public function setWarehouse($warehouse_id)
  2591. {
  2592. if (!$this->table_element) {
  2593. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2594. return -1;
  2595. }
  2596. if ($warehouse_id < 0) {
  2597. $warehouse_id = 'NULL';
  2598. }
  2599. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  2600. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2601. $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
  2602. $sql .= " WHERE rowid=".((int) $this->id);
  2603. if ($this->db->query($sql)) {
  2604. $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
  2605. return 1;
  2606. } else {
  2607. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  2608. $this->error = $this->db->error();
  2609. return 0;
  2610. }
  2611. }
  2612. /**
  2613. * Set last model used by doc generator
  2614. *
  2615. * @param User $user User object that make change
  2616. * @param string $modelpdf Modele name
  2617. * @return int <0 if KO, >0 if OK
  2618. */
  2619. public function setDocModel($user, $modelpdf)
  2620. {
  2621. if (!$this->table_element) {
  2622. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2623. return -1;
  2624. }
  2625. $newmodelpdf = dol_trunc($modelpdf, 255);
  2626. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2627. $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  2628. $sql .= " WHERE rowid = ".((int) $this->id);
  2629. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  2630. $resql = $this->db->query($sql);
  2631. if ($resql) {
  2632. $this->model_pdf = $modelpdf;
  2633. $this->modelpdf = $modelpdf; // For bakward compatibility
  2634. return 1;
  2635. } else {
  2636. dol_print_error($this->db);
  2637. return 0;
  2638. }
  2639. }
  2640. /**
  2641. * Change the bank account
  2642. *
  2643. * @param int $fk_account Id of bank account
  2644. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2645. * @param User $userused Object user
  2646. * @return int 1 if OK, 0 if KO
  2647. */
  2648. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2649. {
  2650. global $user;
  2651. if (empty($userused)) {
  2652. $userused = $user;
  2653. }
  2654. $error = 0;
  2655. if (!$this->table_element) {
  2656. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2657. return -1;
  2658. }
  2659. $this->db->begin();
  2660. if ($fk_account < 0) {
  2661. $fk_account = 'NULL';
  2662. }
  2663. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  2664. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2665. $sql .= " SET fk_account = ".((int) $fk_account);
  2666. $sql .= " WHERE rowid=".((int) $this->id);
  2667. $resql = $this->db->query($sql);
  2668. if (!$resql) {
  2669. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  2670. $this->error = $this->db->lasterror();
  2671. $error++;
  2672. } else {
  2673. if (!$notrigger) {
  2674. // Call trigger
  2675. $this->context = array('bankaccountupdate'=>1);
  2676. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2677. if ($result < 0) {
  2678. $error++;
  2679. }
  2680. // End call trigger
  2681. }
  2682. }
  2683. if ($error) {
  2684. $this->db->rollback();
  2685. return -1;
  2686. } else {
  2687. $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
  2688. $this->db->commit();
  2689. return 1;
  2690. }
  2691. }
  2692. // TODO: Move line related operations to CommonObjectLine?
  2693. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2694. /**
  2695. * Save a new position (field rang) for details lines.
  2696. * You can choose to set position for lines with already a position or lines without any position defined.
  2697. *
  2698. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2699. * @param string $rowidorder ASC or DESC
  2700. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2701. * @return int <0 if KO, >0 if OK
  2702. */
  2703. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2704. {
  2705. // phpcs:enable
  2706. if (!$this->table_element_line) {
  2707. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2708. return -1;
  2709. }
  2710. if (!$this->fk_element) {
  2711. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2712. return -1;
  2713. }
  2714. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2715. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2716. $fieldposition = 'position';
  2717. }
  2718. // Count number of lines to reorder (according to choice $renum)
  2719. $nl = 0;
  2720. $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
  2721. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2722. if (!$renum) {
  2723. $sql .= " AND " . $fieldposition . " = 0";
  2724. }
  2725. if ($renum) {
  2726. $sql .= " AND " . $fieldposition . " <> 0";
  2727. }
  2728. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  2729. $resql = $this->db->query($sql);
  2730. if ($resql) {
  2731. $row = $this->db->fetch_row($resql);
  2732. $nl = $row[0];
  2733. } else {
  2734. dol_print_error($this->db);
  2735. }
  2736. if ($nl > 0) {
  2737. // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
  2738. $rows = array();
  2739. // We first search all lines that are parent lines (for multilevel details lines)
  2740. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2741. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2742. if ($fk_parent_line) {
  2743. $sql .= ' AND fk_parent_line IS NULL';
  2744. }
  2745. $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder;
  2746. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  2747. $resql = $this->db->query($sql);
  2748. if ($resql) {
  2749. $i = 0;
  2750. $num = $this->db->num_rows($resql);
  2751. while ($i < $num) {
  2752. $row = $this->db->fetch_row($resql);
  2753. $rows[] = $row[0]; // Add parent line into array rows
  2754. $childrens = $this->getChildrenOfLine($row[0]);
  2755. if (!empty($childrens)) {
  2756. foreach ($childrens as $child) {
  2757. array_push($rows, $child);
  2758. }
  2759. }
  2760. $i++;
  2761. }
  2762. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2763. if (!empty($rows)) {
  2764. foreach ($rows as $key => $row) {
  2765. $this->updateRangOfLine($row, ($key + 1));
  2766. }
  2767. }
  2768. } else {
  2769. dol_print_error($this->db);
  2770. }
  2771. }
  2772. return 1;
  2773. }
  2774. /**
  2775. * Get children of line
  2776. *
  2777. * @param int $id Id of parent line
  2778. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2779. * @return array Array with list of children lines id
  2780. */
  2781. public function getChildrenOfLine($id, $includealltree = 0)
  2782. {
  2783. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2784. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2785. $fieldposition = 'position';
  2786. }
  2787. $rows = array();
  2788. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2789. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2790. $sql .= ' AND fk_parent_line = '.((int) $id);
  2791. $sql .= " ORDER BY " . $fieldposition . " ASC";
  2792. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
  2793. $resql = $this->db->query($sql);
  2794. if ($resql) {
  2795. if ($this->db->num_rows($resql) > 0) {
  2796. while ($row = $this->db->fetch_row($resql)) {
  2797. $rows[] = $row[0];
  2798. if (!empty($includealltree)) {
  2799. $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2800. }
  2801. }
  2802. }
  2803. }
  2804. return $rows;
  2805. }
  2806. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2807. /**
  2808. * Update a line to have a lower rank
  2809. *
  2810. * @param int $rowid Id of line
  2811. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2812. * @return void
  2813. */
  2814. public function line_up($rowid, $fk_parent_line = true)
  2815. {
  2816. // phpcs:enable
  2817. $this->line_order(false, 'ASC', $fk_parent_line);
  2818. // Get rang of line
  2819. $rang = $this->getRangOfLine($rowid);
  2820. // Update position of line
  2821. $this->updateLineUp($rowid, $rang);
  2822. }
  2823. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2824. /**
  2825. * Update a line to have a higher rank
  2826. *
  2827. * @param int $rowid Id of line
  2828. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2829. * @return void
  2830. */
  2831. public function line_down($rowid, $fk_parent_line = true)
  2832. {
  2833. // phpcs:enable
  2834. $this->line_order(false, 'ASC', $fk_parent_line);
  2835. // Get rang of line
  2836. $rang = $this->getRangOfLine($rowid);
  2837. // Get max value for rang
  2838. $max = $this->line_max();
  2839. // Update position of line
  2840. $this->updateLineDown($rowid, $rang, $max);
  2841. }
  2842. /**
  2843. * Update position of line (rang)
  2844. *
  2845. * @param int $rowid Id of line
  2846. * @param int $rang Position
  2847. * @return int <0 if KO, >0 if OK
  2848. */
  2849. public function updateRangOfLine($rowid, $rang)
  2850. {
  2851. global $hookmanager;
  2852. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2853. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2854. $fieldposition = 'position';
  2855. }
  2856. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2857. $sql .= ' WHERE rowid = '.((int) $rowid);
  2858. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2859. if (!$this->db->query($sql)) {
  2860. dol_print_error($this->db);
  2861. return -1;
  2862. } else {
  2863. $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
  2864. $action='';
  2865. $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
  2866. return 1;
  2867. }
  2868. }
  2869. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2870. /**
  2871. * Update position of line with ajax (rang)
  2872. *
  2873. * @param array $rows Array of rows
  2874. * @return void
  2875. */
  2876. public function line_ajaxorder($rows)
  2877. {
  2878. // phpcs:enable
  2879. $num = count($rows);
  2880. for ($i = 0; $i < $num; $i++) {
  2881. $this->updateRangOfLine($rows[$i], ($i + 1));
  2882. }
  2883. }
  2884. /**
  2885. * Update position of line up (rang)
  2886. *
  2887. * @param int $rowid Id of line
  2888. * @param int $rang Position
  2889. * @return void
  2890. */
  2891. public function updateLineUp($rowid, $rang)
  2892. {
  2893. if ($rang > 1) {
  2894. $fieldposition = 'rang';
  2895. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2896. $fieldposition = 'position';
  2897. }
  2898. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2899. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2900. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1));
  2901. if ($this->db->query($sql)) {
  2902. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
  2903. $sql .= ' WHERE rowid = '.((int) $rowid);
  2904. if (!$this->db->query($sql)) {
  2905. dol_print_error($this->db);
  2906. }
  2907. } else {
  2908. dol_print_error($this->db);
  2909. }
  2910. }
  2911. }
  2912. /**
  2913. * Update position of line down (rang)
  2914. *
  2915. * @param int $rowid Id of line
  2916. * @param int $rang Position
  2917. * @param int $max Max
  2918. * @return void
  2919. */
  2920. public function updateLineDown($rowid, $rang, $max)
  2921. {
  2922. if ($rang < $max) {
  2923. $fieldposition = 'rang';
  2924. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2925. $fieldposition = 'position';
  2926. }
  2927. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2928. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2929. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1));
  2930. if ($this->db->query($sql)) {
  2931. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
  2932. $sql .= ' WHERE rowid = '.((int) $rowid);
  2933. if (!$this->db->query($sql)) {
  2934. dol_print_error($this->db);
  2935. }
  2936. } else {
  2937. dol_print_error($this->db);
  2938. }
  2939. }
  2940. }
  2941. /**
  2942. * Get position of line (rang)
  2943. *
  2944. * @param int $rowid Id of line
  2945. * @return int Value of rang in table of lines
  2946. */
  2947. public function getRangOfLine($rowid)
  2948. {
  2949. $fieldposition = 'rang';
  2950. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2951. $fieldposition = 'position';
  2952. }
  2953. $sql = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line;
  2954. $sql .= " WHERE rowid = ".((int) $rowid);
  2955. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  2956. $resql = $this->db->query($sql);
  2957. if ($resql) {
  2958. $row = $this->db->fetch_row($resql);
  2959. return $row[0];
  2960. }
  2961. }
  2962. /**
  2963. * Get rowid of the line relative to its position
  2964. *
  2965. * @param int $rang Rang value
  2966. * @return int Rowid of the line
  2967. */
  2968. public function getIdOfLine($rang)
  2969. {
  2970. $fieldposition = 'rang';
  2971. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2972. $fieldposition = 'position';
  2973. }
  2974. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2975. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2976. $sql .= " AND " . $fieldposition . " = ".((int) $rang);
  2977. $resql = $this->db->query($sql);
  2978. if ($resql) {
  2979. $row = $this->db->fetch_row($resql);
  2980. return $row[0];
  2981. }
  2982. }
  2983. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2984. /**
  2985. * Get max value used for position of line (rang)
  2986. *
  2987. * @param int $fk_parent_line Parent line id
  2988. * @return int Max value of rang in table of lines
  2989. */
  2990. public function line_max($fk_parent_line = 0)
  2991. {
  2992. // phpcs:enable
  2993. $positionfield = 'rang';
  2994. if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
  2995. $positionfield = 'position';
  2996. }
  2997. // Search the last rang with fk_parent_line
  2998. if ($fk_parent_line) {
  2999. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  3000. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3001. $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
  3002. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  3003. $resql = $this->db->query($sql);
  3004. if ($resql) {
  3005. $row = $this->db->fetch_row($resql);
  3006. if (!empty($row[0])) {
  3007. return $row[0];
  3008. } else {
  3009. return $this->getRangOfLine($fk_parent_line);
  3010. }
  3011. }
  3012. } else {
  3013. // If not, search the last rang of element
  3014. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  3015. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3016. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  3017. $resql = $this->db->query($sql);
  3018. if ($resql) {
  3019. $row = $this->db->fetch_row($resql);
  3020. return $row[0];
  3021. }
  3022. }
  3023. }
  3024. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3025. /**
  3026. * Update external ref of element
  3027. *
  3028. * @param string $ref_ext Update field ref_ext
  3029. * @return int <0 if KO, >0 if OK
  3030. */
  3031. public function update_ref_ext($ref_ext)
  3032. {
  3033. // phpcs:enable
  3034. if (!$this->table_element) {
  3035. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  3036. return -1;
  3037. }
  3038. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  3039. $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  3040. $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
  3041. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  3042. if ($this->db->query($sql)) {
  3043. $this->ref_ext = $ref_ext;
  3044. return 1;
  3045. } else {
  3046. $this->error = $this->db->error();
  3047. return -1;
  3048. }
  3049. }
  3050. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3051. /**
  3052. * Update note of element
  3053. *
  3054. * @param string $note New value for note
  3055. * @param string $suffix '', '_public' or '_private'
  3056. * @return int <0 if KO, >0 if OK
  3057. */
  3058. public function update_note($note, $suffix = '')
  3059. {
  3060. // phpcs:enable
  3061. global $user, $conf;
  3062. if (!$this->table_element) {
  3063. $this->error = 'update_note was called on objet with property table_element not defined';
  3064. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  3065. return -1;
  3066. }
  3067. if (!in_array($suffix, array('', '_public', '_private'))) {
  3068. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  3069. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  3070. return -2;
  3071. }
  3072. $newsuffix = $suffix;
  3073. // Special cas
  3074. if ($this->table_element == 'product' && $newsuffix == '_private') {
  3075. $newsuffix = '';
  3076. }
  3077. if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  3078. $fieldusermod = "fk_user_mod";
  3079. } elseif ($this->table_element == 'ecm_files') {
  3080. $fieldusermod = "fk_user_m";
  3081. } else {
  3082. $fieldusermod = "fk_user_modif";
  3083. }
  3084. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  3085. $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
  3086. $sql .= ", ".$fieldusermod." = ".((int) $user->id);
  3087. $sql .= " WHERE rowid = ".((int) $this->id);
  3088. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  3089. if ($this->db->query($sql)) {
  3090. if ($suffix == '_public') {
  3091. $this->note_public = $note;
  3092. } elseif ($suffix == '_private') {
  3093. $this->note_private = $note;
  3094. } else {
  3095. $this->note = $note; // deprecated
  3096. $this->note_private = $note;
  3097. }
  3098. // MMI Trigger
  3099. if (!empty($conf->global->MMICORE_UPDATE_NOTE_TRIGGER_UPDATE) && !empty($conf->global->MMICORE_UPDATE_NOTE_TRIGGER_UPDATE_LIST) && !empty($this->element)) {
  3100. $list = [];
  3101. preg_match_all('/([a-z_]+):([A-Z_]+)/', $conf->global->MMICORE_UPDATE_NOTE_TRIGGER_UPDATE_LIST, $matches);
  3102. if (!empty($matches)) foreach($matches[1] as $i=>$j) {
  3103. $list[$j] = $matches[2][$i];
  3104. }
  3105. //var_dump($list); die();
  3106. if (isset($list[$this->element])) {
  3107. //echo $list[$this->element].'_MODIFY';
  3108. $result = $this->call_trigger($list[$this->element].'_MODIFY', $user);
  3109. }
  3110. }
  3111. return 1;
  3112. } else {
  3113. $this->error = $this->db->lasterror();
  3114. return -1;
  3115. }
  3116. }
  3117. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3118. /**
  3119. * Update public note (kept for backward compatibility)
  3120. *
  3121. * @param string $note New value for note
  3122. * @return int <0 if KO, >0 if OK
  3123. * @deprecated
  3124. * @see update_note()
  3125. */
  3126. public function update_note_public($note)
  3127. {
  3128. // phpcs:enable
  3129. return $this->update_note($note, '_public');
  3130. }
  3131. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3132. /**
  3133. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  3134. * Must be called at end of methods addline or updateline.
  3135. *
  3136. * @param int $exclspec >0 = Exclude special product (product_type=9)
  3137. * @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
  3138. * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object.
  3139. * @param Societe $seller If roundingadjust is '0' or '1' or maybe 'auto', it means we recalculate total for lines before calculating total for object and for this, we need seller object (used to analyze lines to check corrupted data).
  3140. * @return int <0 if KO, >0 if OK
  3141. */
  3142. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  3143. {
  3144. // phpcs:enable
  3145. global $conf, $hookmanager, $action;
  3146. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  3147. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3148. if ($reshook > 0) {
  3149. return 1; // replacement code
  3150. } elseif ($reshook < 0) {
  3151. return -1; // failure
  3152. } // reshook = 0 => execute normal code
  3153. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  3154. $MODULE = "";
  3155. if ($this->element == 'propal') {
  3156. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  3157. } elseif ($this->element == 'commande' || $this->element == 'order') {
  3158. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  3159. } elseif ($this->element == 'facture' || $this->element == 'invoice') {
  3160. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  3161. } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
  3162. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  3163. } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
  3164. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  3165. } elseif ($this->element == 'supplier_proposal') {
  3166. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  3167. }
  3168. if (!empty($MODULE)) {
  3169. if (!empty($conf->global->$MODULE)) {
  3170. $modsactivated = explode(',', $conf->global->$MODULE);
  3171. foreach ($modsactivated as $mod) {
  3172. if ($conf->$mod->enabled) {
  3173. return 1; // update was disabled by specific setup
  3174. }
  3175. }
  3176. }
  3177. }
  3178. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  3179. if ($roundingadjust == '-1') {
  3180. $roundingadjust = 'auto'; // For backward compatibility
  3181. }
  3182. $forcedroundingmode = $roundingadjust;
  3183. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
  3184. $forcedroundingmode = getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND');
  3185. } elseif ($forcedroundingmode == 'auto') {
  3186. $forcedroundingmode = '0';
  3187. }
  3188. $error = 0;
  3189. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  3190. // Define constants to find lines to sum
  3191. $fieldtva = 'total_tva';
  3192. $fieldlocaltax1 = 'total_localtax1';
  3193. $fieldlocaltax2 = 'total_localtax2';
  3194. $fieldup = 'subprice';
  3195. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3196. $fieldtva = 'tva';
  3197. $fieldup = 'pu_ht';
  3198. }
  3199. if ($this->element == 'invoice_supplier_rec') {
  3200. $fieldup = 'pu_ht';
  3201. }
  3202. if ($this->element == 'expensereport') {
  3203. $fieldup = 'value_unit';
  3204. }
  3205. $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,";
  3206. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  3207. if ($this->table_element_line == 'facturedet') {
  3208. $sql .= ', situation_percent';
  3209. }
  3210. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3211. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  3212. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3213. if ($exclspec) {
  3214. $product_field = 'product_type';
  3215. if ($this->table_element_line == 'contratdet') {
  3216. $product_field = ''; // contratdet table has no product_type field
  3217. }
  3218. if ($product_field) {
  3219. $sql .= " AND ".$product_field." <> 9";
  3220. }
  3221. }
  3222. $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
  3223. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3224. $resql = $this->db->query($sql);
  3225. if ($resql) {
  3226. $this->total_ht = 0;
  3227. $this->total_tva = 0;
  3228. $this->total_localtax1 = 0;
  3229. $this->total_localtax2 = 0;
  3230. $this->total_ttc = 0;
  3231. $total_ht_by_vats = array();
  3232. $total_tva_by_vats = array();
  3233. $total_ttc_by_vats = array();
  3234. $this->multicurrency_total_ht = 0;
  3235. $this->multicurrency_total_tva = 0;
  3236. $this->multicurrency_total_ttc = 0;
  3237. $num = $this->db->num_rows($resql);
  3238. $i = 0;
  3239. while ($i < $num) {
  3240. $obj = $this->db->fetch_object($resql);
  3241. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  3242. $parameters = array('fk_element' => $obj->rowid);
  3243. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3244. 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'
  3245. // This part of code is to fix data. We should not call it too often.
  3246. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  3247. $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);
  3248. $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.
  3249. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  3250. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
  3251. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  3252. if ($diff_when_using_price_ht && $diff_on_current_total) {
  3253. $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2])." WHERE rowid = ".((int) $obj->rowid);
  3254. 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);
  3255. $resqlfix = $this->db->query($sqlfix);
  3256. if (!$resqlfix) {
  3257. dol_print_error($this->db, 'Failed to update line');
  3258. }
  3259. $obj->total_tva = $tmpcal[1];
  3260. $obj->total_ttc = $tmpcal[2];
  3261. }
  3262. }
  3263. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  3264. $this->total_tva += $obj->total_tva;
  3265. $this->total_localtax1 += $obj->total_localtax1;
  3266. $this->total_localtax2 += $obj->total_localtax2;
  3267. $this->total_ttc += $obj->total_ttc;
  3268. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  3269. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  3270. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  3271. if (!isset($total_ht_by_vats[$obj->vatrate])) {
  3272. $total_ht_by_vats[$obj->vatrate] = 0;
  3273. }
  3274. if (!isset($total_tva_by_vats[$obj->vatrate])) {
  3275. $total_tva_by_vats[$obj->vatrate] = 0;
  3276. }
  3277. if (!isset($total_ttc_by_vats[$obj->vatrate])) {
  3278. $total_ttc_by_vats[$obj->vatrate] = 0;
  3279. }
  3280. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  3281. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  3282. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  3283. if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  3284. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  3285. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  3286. //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";
  3287. if ($diff) {
  3288. if (abs($diff) > 0.1) {
  3289. $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.';
  3290. dol_syslog($errmsg, LOG_WARNING);
  3291. dol_print_error('', $errmsg);
  3292. exit;
  3293. }
  3294. $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num($obj->total_tva - $diff).", total_ttc = ".price2num($obj->total_ttc - $diff)." WHERE rowid = ".((int) $obj->rowid);
  3295. 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);
  3296. $resqlfix = $this->db->query($sqlfix);
  3297. if (!$resqlfix) {
  3298. dol_print_error($this->db, 'Failed to update line');
  3299. }
  3300. $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1);
  3301. $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1);
  3302. $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1);
  3303. $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1);
  3304. }
  3305. }
  3306. $i++;
  3307. }
  3308. // Add revenue stamp to total
  3309. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  3310. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  3311. // Situations totals
  3312. if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
  3313. $prev_sits = $this->get_prev_sits();
  3314. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  3315. $this->total_ht -= $sit->total_ht;
  3316. $this->total_tva -= $sit->total_tva;
  3317. $this->total_localtax1 -= $sit->total_localtax1;
  3318. $this->total_localtax2 -= $sit->total_localtax2;
  3319. $this->total_ttc -= $sit->total_ttc;
  3320. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  3321. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  3322. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  3323. }
  3324. }
  3325. // Clean total
  3326. $this->total_ht = (float) price2num($this->total_ht);
  3327. $this->total_tva = (float) price2num($this->total_tva);
  3328. $this->total_localtax1 = (float) price2num($this->total_localtax1);
  3329. $this->total_localtax2 = (float) price2num($this->total_localtax2);
  3330. $this->total_ttc = (float) price2num($this->total_ttc);
  3331. $this->db->free($resql);
  3332. // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_*
  3333. $fieldht = 'total_ht';
  3334. $fieldtva = 'tva';
  3335. $fieldlocaltax1 = 'localtax1';
  3336. $fieldlocaltax2 = 'localtax2';
  3337. $fieldttc = 'total_ttc';
  3338. // Specific code for backward compatibility with old field names
  3339. if ($this->element == 'facture' || $this->element == 'facturerec') {
  3340. $fieldtva = 'total_tva';
  3341. }
  3342. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
  3343. $fieldtva = 'total_tva';
  3344. }
  3345. if ($this->element == 'propal') {
  3346. $fieldtva = 'total_tva';
  3347. }
  3348. if ($this->element == 'expensereport') {
  3349. $fieldtva = 'total_tva';
  3350. }
  3351. if ($this->element == 'supplier_proposal') {
  3352. $fieldtva = 'total_tva';
  3353. }
  3354. if ($this->element == 'commande') {
  3355. $fieldtva = 'total_tva';
  3356. }
  3357. if ($this->element == 'order_supplier') {
  3358. $fieldtva = 'total_tva';
  3359. }
  3360. if (empty($nodatabaseupdate)) {
  3361. $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
  3362. $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht, 'MT', 1)).",";
  3363. $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva, 'MT', 1)).",";
  3364. $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1, 'MT', 1)).",";
  3365. $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2, 'MT', 1)).",";
  3366. $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc, 'MT', 1));
  3367. $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
  3368. $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
  3369. $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
  3370. $sql .= " WHERE rowid = ".((int) $this->id);
  3371. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3372. $resql = $this->db->query($sql);
  3373. if (!$resql) {
  3374. $error++;
  3375. $this->error = $this->db->lasterror();
  3376. $this->errors[] = $this->db->lasterror();
  3377. }
  3378. }
  3379. if (!$error) {
  3380. return 1;
  3381. } else {
  3382. return -1;
  3383. }
  3384. } else {
  3385. dol_print_error($this->db, 'Bad request in update_price');
  3386. return -1;
  3387. }
  3388. }
  3389. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3390. /**
  3391. * Add an object link into llx_element_element.
  3392. *
  3393. * @param string $origin Linked element type
  3394. * @param int $origin_id Linked element id
  3395. * @param User $f_user User that create
  3396. * @param int $notrigger 1=Does not execute triggers, 0=execute triggers
  3397. * @return int <=0 if KO, >0 if OK
  3398. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  3399. */
  3400. public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
  3401. {
  3402. // phpcs:enable
  3403. global $user, $hookmanager, $action;
  3404. $origin = (!empty($origin) ? $origin : $this->origin);
  3405. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  3406. $f_user = isset($f_user) ? $f_user : $user;
  3407. // Special case
  3408. if ($origin == 'order') {
  3409. $origin = 'commande';
  3410. }
  3411. if ($origin == 'invoice') {
  3412. $origin = 'facture';
  3413. }
  3414. if ($origin == 'invoice_template') {
  3415. $origin = 'facturerec';
  3416. }
  3417. if ($origin == 'supplierorder') {
  3418. $origin = 'order_supplier';
  3419. }
  3420. // Elements of the core modules which have `$module` property but may to which we don't want to prefix module part to the element name for finding the linked object in llx_element_element.
  3421. // It's because an entry for this element may be exist in llx_element_element before this modification (version <=14.2) and ave named only with their element name in fk_source or fk_target.
  3422. $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
  3423. // Add module part to target type if object has $module property and isn't in core modules.
  3424. $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
  3425. $parameters = array('targettype'=>$targettype);
  3426. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3427. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3428. if ($reshook > 0) {
  3429. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3430. }
  3431. $this->db->begin();
  3432. $error = 0;
  3433. $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
  3434. $sql .= "fk_source";
  3435. $sql .= ", sourcetype";
  3436. $sql .= ", fk_target";
  3437. $sql .= ", targettype";
  3438. $sql .= ") VALUES (";
  3439. $sql .= ((int) $origin_id);
  3440. $sql .= ", '" . $this->db->escape($origin) . "'";
  3441. $sql .= ", " . ((int) $this->id);
  3442. $sql .= ", '" . $this->db->escape($targettype) . "'";
  3443. $sql .= ")";
  3444. dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
  3445. if ($this->db->query($sql)) {
  3446. if (!$notrigger) {
  3447. // Call trigger
  3448. $this->context['link_origin'] = $origin;
  3449. $this->context['link_origin_id'] = $origin_id;
  3450. $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
  3451. if ($result < 0) {
  3452. $error++;
  3453. }
  3454. // End call triggers
  3455. }
  3456. } else {
  3457. $this->error = $this->db->lasterror();
  3458. $error++;
  3459. }
  3460. if (!$error) {
  3461. $this->db->commit();
  3462. return 1;
  3463. } else {
  3464. $this->db->rollback();
  3465. return 0;
  3466. }
  3467. }
  3468. /**
  3469. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  3470. * this->linkedObjectsIds array +
  3471. * this->linkedObjects array if $loadalsoobjects = 1 or $loadalsoobjects = type
  3472. * Possible usage for parameters:
  3473. * - all parameters empty -> we look all link to current object (current object can be source or target)
  3474. * - source id+type -> will get list of targets linked to source
  3475. * - target id+type -> will get list of sources linked to target
  3476. * - source id+type + target type -> will get list of targets of the type linked to source
  3477. * - target id+type + source type -> will get list of sources of the type linked to target
  3478. *
  3479. * @param int $sourceid Object source id (if not defined, id of object)
  3480. * @param string $sourcetype Object source type (if not defined, element name of object)
  3481. * @param int $targetid Object target id (if not defined, id of object)
  3482. * @param string $targettype Object target type (if not defined, element name of object)
  3483. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  3484. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  3485. * @param string $orderby SQL 'ORDER BY' clause
  3486. * @param int|string $loadalsoobjects Load also array this->linkedObjects. Use 0 to increase performances, Use 1 to load all, Use value of type ('facture', 'facturerec', ...) to load only a type of object.
  3487. * @return int <0 if KO, >0 if OK
  3488. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  3489. */
  3490. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  3491. {
  3492. global $conf, $hookmanager, $action;
  3493. // Important for pdf generation time reduction
  3494. // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
  3495. if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
  3496. return 1;
  3497. }
  3498. $this->linkedObjectsIds = array();
  3499. $this->linkedObjects = array();
  3500. $justsource = false;
  3501. $justtarget = false;
  3502. $withtargettype = false;
  3503. $withsourcetype = false;
  3504. $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
  3505. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3506. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3507. if ($reshook > 0) {
  3508. if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
  3509. if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
  3510. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3511. if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
  3512. }
  3513. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
  3514. $justsource = true; // the source (id and type) is a search criteria
  3515. if (!empty($targettype)) {
  3516. $withtargettype = true;
  3517. }
  3518. }
  3519. if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
  3520. $justtarget = true; // the target (id and type) is a search criteria
  3521. if (!empty($sourcetype)) {
  3522. $withsourcetype = true;
  3523. }
  3524. }
  3525. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3526. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3527. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3528. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3529. /*if (empty($sourceid) && empty($targetid))
  3530. {
  3531. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  3532. return -1;
  3533. }*/
  3534. // Links between objects are stored in table element_element
  3535. $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
  3536. $sql .= " FROM ".$this->db->prefix()."element_element";
  3537. $sql .= " WHERE ";
  3538. if ($justsource || $justtarget) {
  3539. if ($justsource) {
  3540. $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3541. if ($withtargettype) {
  3542. $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
  3543. }
  3544. } elseif ($justtarget) {
  3545. $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
  3546. if ($withsourcetype) {
  3547. $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3548. }
  3549. }
  3550. } else {
  3551. $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
  3552. $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
  3553. if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
  3554. $this->linkedObjectsFullLoaded[$this->id] = true;
  3555. }
  3556. }
  3557. $sql .= " ORDER BY ".$orderby;
  3558. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  3559. $resql = $this->db->query($sql);
  3560. if ($resql) {
  3561. $num = $this->db->num_rows($resql);
  3562. $i = 0;
  3563. while ($i < $num) {
  3564. $obj = $this->db->fetch_object($resql);
  3565. if ($justsource || $justtarget) {
  3566. if ($justsource) {
  3567. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3568. } elseif ($justtarget) {
  3569. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3570. }
  3571. } else {
  3572. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
  3573. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3574. }
  3575. if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
  3576. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3577. }
  3578. }
  3579. $i++;
  3580. }
  3581. if (!empty($this->linkedObjectsIds)) {
  3582. $tmparray = $this->linkedObjectsIds;
  3583. foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  3584. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  3585. $module = $element = $subelement = $objecttype;
  3586. $regs = array();
  3587. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  3588. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  3589. $module = $element = $regs[1];
  3590. $subelement = $regs[2];
  3591. }
  3592. $classpath = $element.'/class';
  3593. // To work with non standard classpath or module name
  3594. if ($objecttype == 'facture') {
  3595. $classpath = 'compta/facture/class';
  3596. } elseif ($objecttype == 'facturerec') {
  3597. $classpath = 'compta/facture/class';
  3598. $module = 'facture';
  3599. } elseif ($objecttype == 'propal') {
  3600. $classpath = 'comm/propal/class';
  3601. } elseif ($objecttype == 'supplier_proposal') {
  3602. $classpath = 'supplier_proposal/class';
  3603. } elseif ($objecttype == 'shipping') {
  3604. $classpath = 'expedition/class';
  3605. $subelement = 'expedition';
  3606. $module = 'expedition_bon';
  3607. } elseif ($objecttype == 'delivery') {
  3608. $classpath = 'delivery/class';
  3609. $subelement = 'delivery';
  3610. $module = 'delivery_note';
  3611. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  3612. $classpath = 'fourn/class';
  3613. $module = 'fournisseur';
  3614. } elseif ($objecttype == 'fichinter') {
  3615. $classpath = 'fichinter/class';
  3616. $subelement = 'fichinter';
  3617. $module = 'ficheinter';
  3618. } elseif ($objecttype == 'subscription') {
  3619. $classpath = 'adherents/class';
  3620. $module = 'adherent';
  3621. } elseif ($objecttype == 'contact') {
  3622. $module = 'societe';
  3623. }
  3624. // Set classfile
  3625. $classfile = strtolower($subelement);
  3626. $classname = ucfirst($subelement);
  3627. if ($objecttype == 'order') {
  3628. $classfile = 'commande';
  3629. $classname = 'Commande';
  3630. } elseif ($objecttype == 'invoice_supplier') {
  3631. $classfile = 'fournisseur.facture';
  3632. $classname = 'FactureFournisseur';
  3633. } elseif ($objecttype == 'order_supplier') {
  3634. $classfile = 'fournisseur.commande';
  3635. $classname = 'CommandeFournisseur';
  3636. } elseif ($objecttype == 'supplier_proposal') {
  3637. $classfile = 'supplier_proposal';
  3638. $classname = 'SupplierProposal';
  3639. } elseif ($objecttype == 'facturerec') {
  3640. $classfile = 'facture-rec';
  3641. $classname = 'FactureRec';
  3642. } elseif ($objecttype == 'subscription') {
  3643. $classfile = 'subscription';
  3644. $classname = 'Subscription';
  3645. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  3646. $classpath = 'projet/class';
  3647. $classfile = 'project';
  3648. $classname = 'Project';
  3649. } elseif ($objecttype == 'conferenceorboothattendee') {
  3650. $classpath = 'eventorganization/class';
  3651. $classfile = 'conferenceorboothattendee';
  3652. $classname = 'ConferenceOrBoothAttendee';
  3653. $module = 'eventorganization';
  3654. } elseif ($objecttype == 'conferenceorbooth') {
  3655. $classpath = 'eventorganization/class';
  3656. $classfile = 'conferenceorbooth';
  3657. $classname = 'ConferenceOrBooth';
  3658. $module = 'eventorganization';
  3659. } elseif ($objecttype == 'mo') {
  3660. $classpath = 'mrp/class';
  3661. $classfile = 'mo';
  3662. $classname = 'Mo';
  3663. $module = 'mrp';
  3664. }
  3665. // Here $module, $classfile and $classname are set, we can use them.
  3666. if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
  3667. if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
  3668. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  3669. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  3670. if (class_exists($classname)) {
  3671. foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
  3672. $object = new $classname($this->db);
  3673. $ret = $object->fetch($objectid);
  3674. if ($ret >= 0) {
  3675. $this->linkedObjects[$objecttype][$i] = $object;
  3676. }
  3677. }
  3678. }
  3679. }
  3680. } else {
  3681. unset($this->linkedObjectsIds[$objecttype]);
  3682. }
  3683. }
  3684. }
  3685. return 1;
  3686. } else {
  3687. dol_print_error($this->db);
  3688. return -1;
  3689. }
  3690. }
  3691. /**
  3692. * Clear the cache saying that all linked object were already loaded. So next fetchObjectLinked will reload all links.
  3693. *
  3694. * @return int <0 if KO, >0 if OK
  3695. * @see fetchObjectLinked()
  3696. */
  3697. public function clearObjectLinkedCache()
  3698. {
  3699. if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
  3700. unset($this->linkedObjectsFullLoaded[$this->id]);
  3701. }
  3702. return 1;
  3703. }
  3704. /**
  3705. * Update object linked of a current object
  3706. *
  3707. * @param int $sourceid Object source id
  3708. * @param string $sourcetype Object source type
  3709. * @param int $targetid Object target id
  3710. * @param string $targettype Object target type
  3711. * @param User $f_user User that create
  3712. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3713. * @return int >0 if OK, <0 if KO
  3714. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3715. */
  3716. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
  3717. {
  3718. global $user;
  3719. $updatesource = false;
  3720. $updatetarget = false;
  3721. $f_user = isset($f_user) ? $f_user : $user;
  3722. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3723. $updatesource = true;
  3724. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3725. $updatetarget = true;
  3726. }
  3727. $this->db->begin();
  3728. $error = 0;
  3729. $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
  3730. if ($updatesource) {
  3731. $sql .= "fk_source = " . ((int) $sourceid);
  3732. $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3733. $sql .= " WHERE fk_target = " . ((int) $this->id);
  3734. $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
  3735. } elseif ($updatetarget) {
  3736. $sql .= "fk_target = " . ((int) $targetid);
  3737. $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
  3738. $sql .= " WHERE fk_source = " . ((int) $this->id);
  3739. $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3740. }
  3741. dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
  3742. if ($this->db->query($sql)) {
  3743. if (!$notrigger) {
  3744. // Call trigger
  3745. $this->context['link_source_id'] = $sourceid;
  3746. $this->context['link_source_type'] = $sourcetype;
  3747. $this->context['link_target_id'] = $targetid;
  3748. $this->context['link_target_type'] = $targettype;
  3749. $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
  3750. if ($result < 0) {
  3751. $error++;
  3752. }
  3753. // End call triggers
  3754. }
  3755. } else {
  3756. $this->error = $this->db->lasterror();
  3757. $error++;
  3758. }
  3759. if (!$error) {
  3760. $this->db->commit();
  3761. return 1;
  3762. } else {
  3763. $this->db->rollback();
  3764. return -1;
  3765. }
  3766. }
  3767. /**
  3768. * Delete all links between an object $this
  3769. *
  3770. * @param int $sourceid Object source id
  3771. * @param string $sourcetype Object source type
  3772. * @param int $targetid Object target id
  3773. * @param string $targettype Object target type
  3774. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3775. * @param User $f_user User that create
  3776. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3777. * @return int >0 if OK, <0 if KO
  3778. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3779. */
  3780. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
  3781. {
  3782. global $user;
  3783. $deletesource = false;
  3784. $deletetarget = false;
  3785. $f_user = isset($f_user) ? $f_user : $user;
  3786. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3787. $deletesource = true;
  3788. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3789. $deletetarget = true;
  3790. }
  3791. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3792. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3793. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3794. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3795. $this->db->begin();
  3796. $error = 0;
  3797. if (!$notrigger) {
  3798. // Call trigger
  3799. $this->context['link_id'] = $rowid;
  3800. $this->context['link_source_id'] = $sourceid;
  3801. $this->context['link_source_type'] = $sourcetype;
  3802. $this->context['link_target_id'] = $targetid;
  3803. $this->context['link_target_type'] = $targettype;
  3804. $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
  3805. if ($result < 0) {
  3806. $error++;
  3807. }
  3808. // End call triggers
  3809. }
  3810. if (!$error) {
  3811. $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
  3812. $sql .= " WHERE";
  3813. if ($rowid > 0) {
  3814. $sql .= " rowid = " . ((int) $rowid);
  3815. } else {
  3816. if ($deletesource) {
  3817. $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3818. $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
  3819. } elseif ($deletetarget) {
  3820. $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
  3821. $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3822. } else {
  3823. $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
  3824. $sql .= " OR";
  3825. $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
  3826. }
  3827. }
  3828. dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
  3829. if (!$this->db->query($sql)) {
  3830. $this->error = $this->db->lasterror();
  3831. $this->errors[] = $this->error;
  3832. $error++;
  3833. }
  3834. }
  3835. if (!$error) {
  3836. $this->db->commit();
  3837. return 1;
  3838. } else {
  3839. $this->db->rollback();
  3840. return 0;
  3841. }
  3842. }
  3843. /**
  3844. * Function used to get an array with all items linked to an object id in association table
  3845. *
  3846. * @param int $fk_object_where id of object we need to get linked items
  3847. * @param string $field_select name of field we need to get a list
  3848. * @param string $field_where name of field of object we need to get linked items
  3849. * @param string $table_element name of association table
  3850. * @return array Array of record
  3851. */
  3852. public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
  3853. {
  3854. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3855. return -1;
  3856. }
  3857. global $db;
  3858. $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3859. $resql = $db->query($sql);
  3860. $TRes = array();
  3861. if (!empty($resql)) {
  3862. while ($res = $db->fetch_object($resql)) {
  3863. $TRes[] = $res->{$field_select};
  3864. }
  3865. }
  3866. return $TRes;
  3867. }
  3868. /**
  3869. * Function used to remove all items linked to an object id in association table
  3870. *
  3871. * @param int $fk_object_where id of object we need to remove linked items
  3872. * @param string $field_where name of field of object we need to delete linked items
  3873. * @param string $table_element name of association table
  3874. * @return int <0 if KO, 0 if nothing done, >0 if OK and something done
  3875. */
  3876. public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
  3877. {
  3878. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3879. return -1;
  3880. }
  3881. global $db;
  3882. $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3883. $resql = $db->query($sql);
  3884. if (empty($resql)) {
  3885. return 0;
  3886. }
  3887. return 1;
  3888. }
  3889. /**
  3890. * Set status of an object
  3891. *
  3892. * @param int $status Status to set
  3893. * @param int $elementId Id of element to force (use this->id by default if null)
  3894. * @param string $elementType Type of element to force (use this->table_element by default)
  3895. * @param string $trigkey Trigger key to use for trigger. Use '' means automatic but it is not recommended and is deprecated.
  3896. * @param string $fieldstatus Name of status field in this->table_element
  3897. * @return int <0 if KO, >0 if OK
  3898. */
  3899. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
  3900. {
  3901. global $user, $langs, $conf;
  3902. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3903. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3904. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3905. $this->db->begin();
  3906. if ($elementTable == 'facture_rec') {
  3907. $fieldstatus = "suspended";
  3908. }
  3909. if ($elementTable == 'mailing') {
  3910. $fieldstatus = "statut";
  3911. }
  3912. if ($elementTable == 'cronjob') {
  3913. $fieldstatus = "status";
  3914. }
  3915. if ($elementTable == 'user') {
  3916. $fieldstatus = "statut";
  3917. }
  3918. if ($elementTable == 'expensereport') {
  3919. $fieldstatus = "fk_statut";
  3920. }
  3921. if ($elementTable == 'commande_fournisseur_dispatch') {
  3922. $fieldstatus = "status";
  3923. }
  3924. if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
  3925. $fieldstatus = 'status';
  3926. }
  3927. $sql = "UPDATE ".$this->db->prefix().$elementTable;
  3928. $sql .= " SET ".$fieldstatus." = ".((int) $status);
  3929. // If status = 1 = validated, update also fk_user_valid
  3930. // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
  3931. if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
  3932. $sql .= ", fk_user_valid = ".((int) $user->id);
  3933. }
  3934. if ($status == 1 && in_array($elementTable, array('expensereport'))) {
  3935. $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
  3936. }
  3937. if ($status == 1 && in_array($elementTable, array('inventory'))) {
  3938. $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
  3939. }
  3940. $sql .= " WHERE rowid = ".((int) $elementId);
  3941. $sql .= " AND ".$fieldstatus." <> ".((int) $status); // We avoid update if status already correct
  3942. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  3943. $resql = $this->db->query($sql);
  3944. if ($resql) {
  3945. $error = 0;
  3946. $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
  3947. if ($nb_rows_affected > 0) {
  3948. if (empty($trigkey)) {
  3949. // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
  3950. if ($this->element == 'supplier_proposal' && $status == 2) {
  3951. $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3952. }
  3953. if ($this->element == 'supplier_proposal' && $status == 3) {
  3954. $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3955. }
  3956. if ($this->element == 'supplier_proposal' && $status == 4) {
  3957. $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3958. }
  3959. if ($this->element == 'fichinter' && $status == 3) {
  3960. $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3961. }
  3962. if ($this->element == 'fichinter' && $status == 2) {
  3963. $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3964. }
  3965. if ($this->element == 'fichinter' && $status == 1) {
  3966. $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3967. }
  3968. }
  3969. if ($trigkey) {
  3970. // Call trigger
  3971. $result = $this->call_trigger($trigkey, $user);
  3972. if ($result < 0) {
  3973. $error++;
  3974. }
  3975. // End call triggers
  3976. }
  3977. } else {
  3978. // The status was probably already good. We do nothing more, no triggers.
  3979. }
  3980. if (!$error) {
  3981. $this->db->commit();
  3982. if (empty($savElementId)) {
  3983. // If the element we update is $this (so $elementId was provided as null)
  3984. if ($fieldstatus == 'tosell') {
  3985. $this->status = $status;
  3986. } elseif ($fieldstatus == 'tobuy') {
  3987. $this->status_buy = $status;
  3988. } else {
  3989. $this->statut = $status;
  3990. $this->status = $status;
  3991. }
  3992. }
  3993. return 1;
  3994. } else {
  3995. $this->db->rollback();
  3996. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  3997. return -1;
  3998. }
  3999. } else {
  4000. $this->error = $this->db->lasterror();
  4001. $this->db->rollback();
  4002. return -1;
  4003. }
  4004. }
  4005. /**
  4006. * Load type of canvas of an object if it exists
  4007. *
  4008. * @param int $id Record id
  4009. * @param string $ref Record ref
  4010. * @return int <0 if KO, 0 if nothing done, >0 if OK
  4011. */
  4012. public function getCanvas($id = 0, $ref = '')
  4013. {
  4014. global $conf;
  4015. if (empty($id) && empty($ref)) {
  4016. return 0;
  4017. }
  4018. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
  4019. return 0; // To increase speed. Not enabled by default.
  4020. }
  4021. // Clean parameters
  4022. $ref = trim($ref);
  4023. $sql = "SELECT rowid, canvas";
  4024. $sql .= " FROM ".$this->db->prefix().$this->table_element;
  4025. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  4026. if (!empty($id)) {
  4027. $sql .= " AND rowid = ".((int) $id);
  4028. }
  4029. if (!empty($ref)) {
  4030. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  4031. }
  4032. $resql = $this->db->query($sql);
  4033. if ($resql) {
  4034. $obj = $this->db->fetch_object($resql);
  4035. if ($obj) {
  4036. $this->canvas = $obj->canvas;
  4037. return 1;
  4038. } else {
  4039. return 0;
  4040. }
  4041. } else {
  4042. dol_print_error($this->db);
  4043. return -1;
  4044. }
  4045. }
  4046. /**
  4047. * Get special code of a line
  4048. *
  4049. * @param int $lineid Id of line
  4050. * @return int Special code
  4051. */
  4052. public function getSpecialCode($lineid)
  4053. {
  4054. $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
  4055. $sql .= " WHERE rowid = ".((int) $lineid);
  4056. $resql = $this->db->query($sql);
  4057. if ($resql) {
  4058. $row = $this->db->fetch_row($resql);
  4059. return $row[0];
  4060. }
  4061. }
  4062. /**
  4063. * Function to check if an object is used by others.
  4064. * Check is done into this->childtables. There is no check into llx_element_element.
  4065. *
  4066. * @param int $id Force id of object
  4067. * @param int $entity Force entity to check
  4068. * @return int <0 if KO, 0 if not used, >0 if already used
  4069. */
  4070. public function isObjectUsed($id = 0, $entity = 0)
  4071. {
  4072. global $langs;
  4073. if (empty($id)) {
  4074. $id = $this->id;
  4075. }
  4076. // Check parameters
  4077. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
  4078. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  4079. return -1;
  4080. }
  4081. $arraytoscan = $this->childtables;
  4082. // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
  4083. $tmparray = array_keys($this->childtables);
  4084. if (is_numeric($tmparray[0])) {
  4085. $arraytoscan = array_flip($this->childtables);
  4086. }
  4087. // Test if child exists
  4088. $haschild = 0;
  4089. foreach ($arraytoscan as $table => $element) {
  4090. //print $id.'-'.$table.'-'.$elementname.'<br>';
  4091. // Check if element can be deleted
  4092. $sql = "SELECT COUNT(*) as nb";
  4093. $sql.= " FROM ".$this->db->prefix().$table." as c";
  4094. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4095. $sql.= ", ".$this->db->prefix().$element['parent']." as p";
  4096. }
  4097. $sql.= " WHERE c.".$this->fk_element." = ".((int) $id);
  4098. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4099. $sql.= " AND c.".$element['parentkey']." = p.rowid";
  4100. }
  4101. if (!empty($entity)) {
  4102. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4103. $sql.= " AND p.entity = ".((int) $entity);
  4104. } else {
  4105. $sql.= " AND c.entity = ".((int) $entity);
  4106. }
  4107. }
  4108. $resql = $this->db->query($sql);
  4109. if ($resql) {
  4110. $obj = $this->db->fetch_object($resql);
  4111. if ($obj->nb > 0) {
  4112. $langs->load("errors");
  4113. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  4114. $haschild += $obj->nb;
  4115. if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
  4116. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
  4117. } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
  4118. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
  4119. } else { // new usage: $element['name']=Translation key
  4120. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
  4121. }
  4122. break; // We found at least one, we stop here
  4123. }
  4124. } else {
  4125. $this->errors[] = $this->db->lasterror();
  4126. return -1;
  4127. }
  4128. }
  4129. if ($haschild > 0) {
  4130. $this->errors[] = "ErrorRecordHasChildren";
  4131. return $haschild;
  4132. } else {
  4133. return 0;
  4134. }
  4135. }
  4136. /**
  4137. * Function to say how many lines object contains
  4138. *
  4139. * @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
  4140. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  4141. */
  4142. public function hasProductsOrServices($predefined = -1)
  4143. {
  4144. $nb = 0;
  4145. foreach ($this->lines as $key => $val) {
  4146. $qualified = 0;
  4147. if ($predefined == -1) {
  4148. $qualified = 1;
  4149. }
  4150. if ($predefined == 1 && $val->fk_product > 0) {
  4151. $qualified = 1;
  4152. }
  4153. if ($predefined == 0 && $val->fk_product <= 0) {
  4154. $qualified = 1;
  4155. }
  4156. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
  4157. $qualified = 1;
  4158. }
  4159. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
  4160. $qualified = 1;
  4161. }
  4162. if ($qualified) {
  4163. $nb++;
  4164. }
  4165. }
  4166. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  4167. return $nb;
  4168. }
  4169. /**
  4170. * Function that returns the total amount HT of discounts applied for all lines.
  4171. *
  4172. * @return float|string Total amout of discount
  4173. */
  4174. public function getTotalDiscount()
  4175. {
  4176. if (!empty($this->table_element_line) ) {
  4177. $total_discount = 0.00;
  4178. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  4179. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  4180. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  4181. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  4182. $resql = $this->db->query($sql);
  4183. if ($resql) {
  4184. $num = $this->db->num_rows($resql);
  4185. $i = 0;
  4186. while ($i < $num) {
  4187. $obj = $this->db->fetch_object($resql);
  4188. $pu_ht = $obj->pu_ht;
  4189. $qty = $obj->qty;
  4190. $total_ht = $obj->total_ht;
  4191. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  4192. $total_discount += $total_discount_line;
  4193. $i++;
  4194. }
  4195. }
  4196. //print $total_discount; exit;
  4197. return price2num($total_discount);
  4198. }
  4199. return null;
  4200. }
  4201. /**
  4202. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  4203. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  4204. *
  4205. * @return array array('weight'=>...,'volume'=>...)
  4206. */
  4207. public function getTotalWeightVolume()
  4208. {
  4209. $totalWeight = 0;
  4210. $totalVolume = 0;
  4211. // defined for shipment only
  4212. $totalOrdered = '';
  4213. // defined for shipment only
  4214. $totalToShip = '';
  4215. foreach ($this->lines as $line) {
  4216. if (isset($line->qty_asked)) {
  4217. if (empty($totalOrdered)) {
  4218. $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  4219. }
  4220. $totalOrdered += $line->qty_asked; // defined for shipment only
  4221. }
  4222. if (isset($line->qty_shipped)) {
  4223. if (empty($totalToShip)) {
  4224. $totalToShip = 0; // Avoid warning because $totalToShip is ''
  4225. }
  4226. $totalToShip += $line->qty_shipped; // defined for shipment only
  4227. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
  4228. if (empty($totalToShip)) {
  4229. $totalToShip = 0;
  4230. }
  4231. $totalToShip += $line->qty; // defined for reception only
  4232. }
  4233. // Define qty, weight, volume, weight_units, volume_units
  4234. if ($this->element == 'shipping') {
  4235. // for shipments
  4236. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  4237. } else {
  4238. $qty = $line->qty ? $line->qty : 0;
  4239. }
  4240. $weight = !empty($line->weight) ? $line->weight : 0;
  4241. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  4242. $volume = !empty($line->volume) ? $line->volume : 0;
  4243. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  4244. $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
  4245. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  4246. $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
  4247. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  4248. $weightUnit = 0;
  4249. $volumeUnit = 0;
  4250. if (!empty($weight_units)) {
  4251. $weightUnit = $weight_units;
  4252. }
  4253. if (!empty($volume_units)) {
  4254. $volumeUnit = $volume_units;
  4255. }
  4256. if (empty($totalWeight)) {
  4257. $totalWeight = 0; // Avoid warning because $totalWeight is ''
  4258. }
  4259. if (empty($totalVolume)) {
  4260. $totalVolume = 0; // Avoid warning because $totalVolume is ''
  4261. }
  4262. //var_dump($line->volume_units);
  4263. if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4264. $trueWeightUnit = pow(10, $weightUnit);
  4265. $totalWeight += $weight * $qty * $trueWeightUnit;
  4266. } else {
  4267. if ($weight_units == 99) {
  4268. // conversion 1 Pound = 0.45359237 KG
  4269. $trueWeightUnit = 0.45359237;
  4270. $totalWeight += $weight * $qty * $trueWeightUnit;
  4271. } elseif ($weight_units == 98) {
  4272. // conversion 1 Ounce = 0.0283495 KG
  4273. $trueWeightUnit = 0.0283495;
  4274. $totalWeight += $weight * $qty * $trueWeightUnit;
  4275. } else {
  4276. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  4277. }
  4278. }
  4279. if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4280. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  4281. $trueVolumeUnit = pow(10, $volumeUnit);
  4282. //print $line->volume;
  4283. $totalVolume += $volume * $qty * $trueVolumeUnit;
  4284. } else {
  4285. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  4286. }
  4287. }
  4288. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  4289. }
  4290. /**
  4291. * Set extra parameters
  4292. *
  4293. * @return int <0 if KO, >0 if OK
  4294. */
  4295. public function setExtraParameters()
  4296. {
  4297. $this->db->begin();
  4298. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  4299. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  4300. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  4301. $sql .= " WHERE rowid = ".((int) $this->id);
  4302. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  4303. $resql = $this->db->query($sql);
  4304. if (!$resql) {
  4305. $this->error = $this->db->lasterror();
  4306. $this->db->rollback();
  4307. return -1;
  4308. } else {
  4309. $this->db->commit();
  4310. return 1;
  4311. }
  4312. }
  4313. // --------------------
  4314. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  4315. // --------------------
  4316. /* This is to show add lines */
  4317. /**
  4318. * Show add free and predefined products/services form
  4319. *
  4320. * @param int $dateSelector 1=Show also date range input fields
  4321. * @param Societe $seller Object thirdparty who sell
  4322. * @param Societe $buyer Object thirdparty who buy
  4323. * @param string $defaulttpldir Directory where to find the template
  4324. * @return void
  4325. */
  4326. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  4327. {
  4328. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  4329. global $form;
  4330. // Line extrafield
  4331. if (!is_object($extrafields)) {
  4332. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4333. $extrafields = new ExtraFields($this->db);
  4334. }
  4335. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4336. // Output template part (modules that overwrite templates must declare this into descriptor)
  4337. // Use global variables + $dateSelector + $seller and $buyer
  4338. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  4339. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4340. foreach ($dirtpls as $module => $reldir) {
  4341. if (!empty($module)) {
  4342. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  4343. } else {
  4344. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  4345. }
  4346. if (empty($conf->file->strict_mode)) {
  4347. $res = @include $tpl;
  4348. } else {
  4349. $res = include $tpl; // for debug
  4350. }
  4351. if ($res) {
  4352. break;
  4353. }
  4354. }
  4355. }
  4356. /* This is to show array of line of details */
  4357. /**
  4358. * Return HTML table for object lines
  4359. * TODO Move this into an output class file (htmlline.class.php)
  4360. * If lines are into a template, title must also be into a template
  4361. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4362. *
  4363. * @param string $action Action code
  4364. * @param string $seller Object of seller third party
  4365. * @param string $buyer Object of buyer third party
  4366. * @param int $selected Object line selected
  4367. * @param int $dateSelector 1=Show also date range input fields
  4368. * @param string $defaulttpldir Directory where to find the template
  4369. * @return void
  4370. */
  4371. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  4372. {
  4373. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  4374. // TODO We should not use global var for this
  4375. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  4376. // Define usemargins
  4377. $usemargins = 0;
  4378. if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
  4379. $usemargins = 1;
  4380. }
  4381. $num = count($this->lines);
  4382. // Line extrafield
  4383. if (!is_object($extrafields)) {
  4384. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4385. $extrafields = new ExtraFields($this->db);
  4386. }
  4387. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4388. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  4389. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4390. if (empty($reshook)) {
  4391. // Output template part (modules that overwrite templates must declare this into descriptor)
  4392. // Use global variables + $dateSelector + $seller and $buyer
  4393. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  4394. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4395. foreach ($dirtpls as $module => $reldir) {
  4396. if (!empty($module)) {
  4397. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  4398. } else {
  4399. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  4400. }
  4401. if (empty($conf->file->strict_mode)) {
  4402. $res = @include $tpl;
  4403. } else {
  4404. $res = include $tpl; // for debug
  4405. }
  4406. if ($res) {
  4407. break;
  4408. }
  4409. }
  4410. }
  4411. $i = 0;
  4412. print "<!-- begin printObjectLines() --><tbody>\n";
  4413. foreach ($this->lines as $line) {
  4414. //Line extrafield
  4415. $line->fetch_optionals();
  4416. //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  4417. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4418. if (empty($line->fk_parent_line)) {
  4419. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  4420. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4421. } else {
  4422. $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);
  4423. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4424. }
  4425. }
  4426. if (empty($reshook)) {
  4427. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  4428. }
  4429. $i++;
  4430. }
  4431. print "</tbody><!-- end printObjectLines() -->\n";
  4432. }
  4433. /**
  4434. * Return HTML content of a detail line
  4435. * TODO Move this into an output class file (htmlline.class.php)
  4436. *
  4437. * @param string $action GET/POST action
  4438. * @param CommonObjectLine $line Selected object line to output
  4439. * @param string $var Is it a an odd line (true)
  4440. * @param int $num Number of line (0)
  4441. * @param int $i I
  4442. * @param int $dateSelector 1=Show also date range input fields
  4443. * @param string $seller Object of seller third party
  4444. * @param string $buyer Object of buyer third party
  4445. * @param int $selected Object line selected
  4446. * @param Extrafields $extrafields Object of extrafields
  4447. * @param string $defaulttpldir Directory where to find the template (deprecated)
  4448. * @return void
  4449. */
  4450. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  4451. {
  4452. global $conf, $langs, $user, $object, $hookmanager;
  4453. global $form;
  4454. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  4455. $object_rights = $this->getRights();
  4456. $element = $this->element;
  4457. $text = '';
  4458. $description = '';
  4459. // Line in view mode
  4460. if ($action != 'editline' || $selected != $line->id) {
  4461. // Product
  4462. if ($line->fk_product > 0) {
  4463. $product_static = new Product($this->db);
  4464. $product_static->fetch($line->fk_product);
  4465. $product_static->ref = $line->ref; //can change ref in hook
  4466. $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
  4467. $text = $product_static->getNomUrl(1);
  4468. // Define output language and label
  4469. if (!empty($conf->global->MAIN_MULTILANGS)) {
  4470. if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
  4471. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  4472. return;
  4473. }
  4474. $prod = new Product($this->db);
  4475. $prod->fetch($line->fk_product);
  4476. $outputlangs = $langs;
  4477. $newlang = '';
  4478. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  4479. $newlang = GETPOST('lang_id', 'aZ09');
  4480. }
  4481. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
  4482. $newlang = $this->thirdparty->default_lang; // To use language of customer
  4483. }
  4484. if (!empty($newlang)) {
  4485. $outputlangs = new Translate("", $conf);
  4486. $outputlangs->setDefaultLang($newlang);
  4487. }
  4488. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  4489. } else {
  4490. $label = $line->product_label;
  4491. }
  4492. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  4493. $description .= (!empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : (!empty($line->description) ? dol_htmlentitiesbr($line->description) : '')); // Description is what to show on popup. We shown nothing if already into desc.
  4494. }
  4495. $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
  4496. // Output template part (modules that overwrite templates must declare this into descriptor)
  4497. // Use global variables + $dateSelector + $seller and $buyer
  4498. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4499. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4500. foreach ($dirtpls as $module => $reldir) {
  4501. if (!empty($module)) {
  4502. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  4503. } else {
  4504. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  4505. }
  4506. if (empty($conf->file->strict_mode)) {
  4507. $res = @include $tpl;
  4508. } else {
  4509. $res = include $tpl; // for debug
  4510. }
  4511. if ($res) {
  4512. break;
  4513. }
  4514. }
  4515. }
  4516. // Line in update mode
  4517. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
  4518. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  4519. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4520. // Output template part (modules that overwrite templates must declare this into descriptor)
  4521. // Use global variables + $dateSelector + $seller and $buyer
  4522. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4523. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4524. foreach ($dirtpls as $module => $reldir) {
  4525. if (!empty($module)) {
  4526. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  4527. } else {
  4528. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  4529. }
  4530. if (empty($conf->file->strict_mode)) {
  4531. $res = @include $tpl;
  4532. } else {
  4533. $res = include $tpl; // for debug
  4534. }
  4535. if ($res) {
  4536. break;
  4537. }
  4538. }
  4539. }
  4540. }
  4541. /* This is to show array of line of details of source object */
  4542. /**
  4543. * Return HTML table table of source object lines
  4544. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4545. * If lines are into a template, title must also be into a template
  4546. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  4547. *
  4548. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  4549. * @param array $selectedLines Array of lines id for selected lines
  4550. * @return void
  4551. */
  4552. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  4553. {
  4554. global $langs, $hookmanager, $conf, $form, $action;
  4555. print '<tr class="liste_titre">';
  4556. print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
  4557. print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
  4558. print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
  4559. print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
  4560. if (!empty($conf->multicurrency->enabled)) {
  4561. print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
  4562. }
  4563. print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
  4564. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4565. print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
  4566. }
  4567. print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
  4568. print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
  4569. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  4570. print '</tr>';
  4571. $i = 0;
  4572. if (!empty($this->lines)) {
  4573. foreach ($this->lines as $line) {
  4574. $reshook = 0;
  4575. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
  4576. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4577. $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
  4578. if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
  4579. $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4580. }
  4581. if (empty($reshook)) {
  4582. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  4583. }
  4584. $i++;
  4585. }
  4586. }
  4587. }
  4588. /**
  4589. * Return HTML with a line of table array of source object lines
  4590. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4591. * If lines are into a template, title must also be into a template
  4592. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4593. *
  4594. * @param CommonObjectLine $line Line
  4595. * @param string $var Var
  4596. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  4597. * @param string $defaulttpldir Directory where to find the template
  4598. * @param array $selectedLines Array of lines id for selected lines
  4599. * @return void
  4600. */
  4601. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  4602. {
  4603. global $langs, $conf;
  4604. //var_dump($line);
  4605. if (!empty($line->date_start)) {
  4606. $date_start = $line->date_start;
  4607. } else {
  4608. $date_start = $line->date_debut_prevue;
  4609. if ($line->date_debut_reel) {
  4610. $date_start = $line->date_debut_reel;
  4611. }
  4612. }
  4613. if (!empty($line->date_end)) {
  4614. $date_end = $line->date_end;
  4615. } else {
  4616. $date_end = $line->date_fin_prevue;
  4617. if ($line->date_fin_reel) {
  4618. $date_end = $line->date_fin_reel;
  4619. }
  4620. }
  4621. $this->tpl['id'] = $line->id;
  4622. $this->tpl['label'] = '';
  4623. if (!empty($line->fk_parent_line)) {
  4624. $this->tpl['label'] .= img_picto('', 'rightarrow');
  4625. }
  4626. if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
  4627. $discount = new DiscountAbsolute($this->db);
  4628. $discount->fk_soc = $this->socid;
  4629. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  4630. } elseif (!empty($line->fk_product)) {
  4631. $productstatic = new Product($this->db);
  4632. $productstatic->id = $line->fk_product;
  4633. $productstatic->ref = $line->ref;
  4634. $productstatic->type = $line->fk_product_type;
  4635. if (empty($productstatic->ref)) {
  4636. $line->fetch_product();
  4637. $productstatic = $line->product;
  4638. }
  4639. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  4640. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  4641. // Dates
  4642. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4643. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4644. }
  4645. } else {
  4646. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  4647. if (!empty($line->desc)) {
  4648. $this->tpl['label'] .= $line->desc;
  4649. } else {
  4650. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  4651. }
  4652. // Dates
  4653. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4654. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4655. }
  4656. }
  4657. if (!empty($line->desc)) {
  4658. if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
  4659. $discount = new DiscountAbsolute($this->db);
  4660. $discount->fetch($line->fk_remise_except);
  4661. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  4662. } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
  4663. $discount = new DiscountAbsolute($this->db);
  4664. $discount->fetch($line->fk_remise_except);
  4665. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  4666. } elseif ($line->desc == '(EXCESS RECEIVED)') {
  4667. $discount = new DiscountAbsolute($this->db);
  4668. $discount->fetch($line->fk_remise_except);
  4669. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  4670. } elseif ($line->desc == '(EXCESS PAID)') {
  4671. $discount = new DiscountAbsolute($this->db);
  4672. $discount->fetch($line->fk_remise_except);
  4673. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  4674. } else {
  4675. $this->tpl['description'] = dol_trunc($line->desc, 60);
  4676. }
  4677. } else {
  4678. $this->tpl['description'] = '&nbsp;';
  4679. }
  4680. // VAT Rate
  4681. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  4682. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  4683. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
  4684. $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  4685. }
  4686. $this->tpl['price'] = price($line->subprice);
  4687. $this->tpl['total_ht'] = price($line->total_ht);
  4688. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  4689. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  4690. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4691. $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  4692. }
  4693. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  4694. // Is the line strike or not
  4695. $this->tpl['strike'] = 0;
  4696. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
  4697. $this->tpl['strike'] = 1;
  4698. }
  4699. // Output template part (modules that overwrite templates must declare this into descriptor)
  4700. // Use global variables + $dateSelector + $seller and $buyer
  4701. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4702. foreach ($dirtpls as $module => $reldir) {
  4703. if (!empty($module)) {
  4704. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  4705. } else {
  4706. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  4707. }
  4708. if (empty($conf->file->strict_mode)) {
  4709. $res = @include $tpl;
  4710. } else {
  4711. $res = include $tpl; // for debug
  4712. }
  4713. if ($res) {
  4714. break;
  4715. }
  4716. }
  4717. }
  4718. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4719. /**
  4720. * Add resources to the current object : add entry into llx_element_resources
  4721. * Need $this->element & $this->id
  4722. *
  4723. * @param int $resource_id Resource id
  4724. * @param string $resource_type 'resource'
  4725. * @param int $busy Busy or not
  4726. * @param int $mandatory Mandatory or not
  4727. * @return int <=0 if KO, >0 if OK
  4728. */
  4729. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  4730. {
  4731. // phpcs:enable
  4732. $this->db->begin();
  4733. $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
  4734. $sql .= "resource_id";
  4735. $sql .= ", resource_type";
  4736. $sql .= ", element_id";
  4737. $sql .= ", element_type";
  4738. $sql .= ", busy";
  4739. $sql .= ", mandatory";
  4740. $sql .= ") VALUES (";
  4741. $sql .= $resource_id;
  4742. $sql .= ", '".$this->db->escape($resource_type)."'";
  4743. $sql .= ", '".$this->db->escape($this->id)."'";
  4744. $sql .= ", '".$this->db->escape($this->element)."'";
  4745. $sql .= ", '".$this->db->escape($busy)."'";
  4746. $sql .= ", '".$this->db->escape($mandatory)."'";
  4747. $sql .= ")";
  4748. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  4749. if ($this->db->query($sql)) {
  4750. $this->db->commit();
  4751. return 1;
  4752. } else {
  4753. $this->error = $this->db->lasterror();
  4754. $this->db->rollback();
  4755. return 0;
  4756. }
  4757. }
  4758. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4759. /**
  4760. * Delete a link to resource line
  4761. *
  4762. * @param int $rowid Id of resource line to delete
  4763. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  4764. * @param int $notrigger Disable all triggers
  4765. * @return int >0 if OK, <0 if KO
  4766. */
  4767. public function delete_resource($rowid, $element, $notrigger = 0)
  4768. {
  4769. // phpcs:enable
  4770. global $user;
  4771. $this->db->begin();
  4772. $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
  4773. $sql .= " WHERE rowid = ".((int) $rowid);
  4774. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  4775. $resql = $this->db->query($sql);
  4776. if (!$resql) {
  4777. $this->error = $this->db->lasterror();
  4778. $this->db->rollback();
  4779. return -1;
  4780. } else {
  4781. if (!$notrigger) {
  4782. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  4783. if ($result < 0) {
  4784. $this->db->rollback();
  4785. return -1;
  4786. }
  4787. }
  4788. $this->db->commit();
  4789. return 1;
  4790. }
  4791. }
  4792. /**
  4793. * Overwrite magic function to solve problem of cloning object that are kept as references
  4794. *
  4795. * @return void
  4796. */
  4797. public function __clone()
  4798. {
  4799. // Force a copy of this->lines, otherwise it will point to same object.
  4800. if (isset($this->lines) && is_array($this->lines)) {
  4801. $nboflines = count($this->lines);
  4802. for ($i = 0; $i < $nboflines; $i++) {
  4803. $this->lines[$i] = clone $this->lines[$i];
  4804. }
  4805. }
  4806. }
  4807. /**
  4808. * Common function for all objects extending CommonObject for generating documents
  4809. *
  4810. * @param string $modelspath Relative folder where generators are placed
  4811. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4812. * @param Translate $outputlangs Output language to use
  4813. * @param int $hidedetails 1 to hide details. 0 by default
  4814. * @param int $hidedesc 1 to hide product description. 0 by default
  4815. * @param int $hideref 1 to hide product reference. 0 by default
  4816. * @param null|array $moreparams Array to provide more information
  4817. * @return int >0 if OK, <0 if KO
  4818. * @see addFileIntoDatabaseIndex()
  4819. */
  4820. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4821. {
  4822. global $conf, $langs, $user, $hookmanager, $action;
  4823. $srctemplatepath = '';
  4824. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  4825. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4826. if (empty($reshook)) {
  4827. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4828. if (empty($modele)) {
  4829. $this->error = 'BadValueForParameterModele';
  4830. return -1;
  4831. }
  4832. // Increase limit for PDF build
  4833. $err = error_reporting();
  4834. error_reporting(0);
  4835. @set_time_limit(120);
  4836. error_reporting($err);
  4837. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4838. $tmp = explode(':', $modele, 2);
  4839. if (!empty($tmp[1])) {
  4840. $modele = $tmp[0];
  4841. $srctemplatepath = $tmp[1];
  4842. }
  4843. // Search template files
  4844. $file = '';
  4845. $classname = '';
  4846. $filefound = '';
  4847. $dirmodels = array('/');
  4848. if (is_array($conf->modules_parts['models'])) {
  4849. $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4850. }
  4851. foreach ($dirmodels as $reldir) {
  4852. foreach (array('doc', 'pdf') as $prefix) {
  4853. if (in_array(get_class($this), array('Adherent'))) {
  4854. // Member module use prefix_modele.class.php
  4855. $file = $prefix."_".$modele.".class.php";
  4856. } else {
  4857. // Other module use prefix_modele.modules.php
  4858. $file = $prefix."_".$modele.".modules.php";
  4859. }
  4860. // On verifie l'emplacement du modele
  4861. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  4862. if (file_exists($file)) {
  4863. $filefound = $file;
  4864. $classname = $prefix.'_'.$modele;
  4865. break;
  4866. }
  4867. }
  4868. if ($filefound) {
  4869. break;
  4870. }
  4871. }
  4872. // If generator was found
  4873. if ($filefound) {
  4874. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4875. require_once $file;
  4876. $obj = new $classname($this->db);
  4877. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4878. if ($obj->type == 'odt' && empty($srctemplatepath)) {
  4879. $varfortemplatedir = $obj->scandir;
  4880. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
  4881. $dirtoscan = $conf->global->$varfortemplatedir;
  4882. $listoffiles = array();
  4883. // Now we add first model found in directories scanned
  4884. $listofdir = explode(',', $dirtoscan);
  4885. foreach ($listofdir as $key => $tmpdir) {
  4886. $tmpdir = trim($tmpdir);
  4887. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4888. if (!$tmpdir) {
  4889. unset($listofdir[$key]);
  4890. continue;
  4891. }
  4892. if (is_dir($tmpdir)) {
  4893. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4894. if (count($tmpfiles)) {
  4895. $listoffiles = array_merge($listoffiles, $tmpfiles);
  4896. }
  4897. }
  4898. }
  4899. if (count($listoffiles)) {
  4900. foreach ($listoffiles as $record) {
  4901. $srctemplatepath = $record['fullname'];
  4902. break;
  4903. }
  4904. }
  4905. }
  4906. if (empty($srctemplatepath)) {
  4907. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4908. return -1;
  4909. }
  4910. }
  4911. if ($obj->type == 'odt' && !empty($srctemplatepath)) {
  4912. if (!dol_is_file($srctemplatepath)) {
  4913. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  4914. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4915. return -1;
  4916. }
  4917. }
  4918. // We save charset_output to restore it because write_file can change it if needed for
  4919. // output format that does not support UTF8.
  4920. $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
  4921. if (in_array(get_class($this), array('Adherent'))) {
  4922. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
  4923. } else {
  4924. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4925. }
  4926. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4927. if ($resultwritefile > 0) {
  4928. $outputlangs->charset_output = $sav_charset_output;
  4929. // We delete old preview
  4930. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4931. dol_delete_preview($this);
  4932. // Index file in database
  4933. if (!empty($obj->result['fullpath'])) {
  4934. $destfull = $obj->result['fullpath'];
  4935. // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
  4936. $update_main_doc_field = 0;
  4937. if (!empty($obj->update_main_doc_field)) {
  4938. $update_main_doc_field = 1;
  4939. }
  4940. $this->indexFile($destfull, $update_main_doc_field);
  4941. } else {
  4942. 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);
  4943. }
  4944. // Success in building document. We build meta file.
  4945. dol_meta_create($this);
  4946. return 1;
  4947. } else {
  4948. $outputlangs->charset_output = $sav_charset_output;
  4949. $this->error = $obj->error;
  4950. $this->errors = $obj->errors;
  4951. dol_syslog("Error generating document for ".__CLASS__.". Error: ".$obj->error, LOG_ERR);
  4952. return -1;
  4953. }
  4954. } else {
  4955. if (!$filefound) {
  4956. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4957. $this->errors[] = $this->error;
  4958. dol_syslog($this->error, LOG_ERR);
  4959. } else {
  4960. $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
  4961. $this->errors[] = $this->error;
  4962. dol_syslog($this->error, LOG_ERR);
  4963. }
  4964. return -1;
  4965. }
  4966. } else {
  4967. return $reshook;
  4968. }
  4969. }
  4970. /**
  4971. * Index a file into the ECM database
  4972. *
  4973. * @param string $destfull Full path of file to index
  4974. * @param int $update_main_doc_field Update field main_doc fied into the table of object.
  4975. * This param is set when called for a document generation if document generator hase
  4976. * ->update_main_doc_field set and returns ->result['fullpath'].
  4977. * @return int <0 if KO, >0 if OK
  4978. */
  4979. public function indexFile($destfull, $update_main_doc_field)
  4980. {
  4981. global $conf, $user;
  4982. $upload_dir = dirname($destfull);
  4983. $destfile = basename($destfull);
  4984. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  4985. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  4986. $filename = basename($destfile);
  4987. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4988. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4989. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4990. $ecmfile = new EcmFiles($this->db);
  4991. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  4992. // Set the public "share" key
  4993. $setsharekey = false;
  4994. if ($this->element == 'propal' || $this->element == 'proposal') {
  4995. if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
  4996. $setsharekey = true; // feature to make online signature is not set or set to on (default)
  4997. }
  4998. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4999. $setsharekey = true;
  5000. }
  5001. }
  5002. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  5003. $setsharekey = true;
  5004. }
  5005. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  5006. $setsharekey = true;
  5007. }
  5008. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  5009. $setsharekey = true;
  5010. }
  5011. if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
  5012. $setsharekey = true;
  5013. }
  5014. if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  5015. $setsharekey = true;
  5016. }
  5017. if ($setsharekey) {
  5018. if (empty($ecmfile->share)) { // Because object not found or share not set yet
  5019. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  5020. $ecmfile->share = getRandomPassword(true);
  5021. }
  5022. }
  5023. if ($result > 0) {
  5024. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  5025. $ecmfile->fullpath_orig = '';
  5026. $ecmfile->gen_or_uploaded = 'generated';
  5027. $ecmfile->description = ''; // indexed content
  5028. $ecmfile->keywords = ''; // keyword content
  5029. $result = $ecmfile->update($user);
  5030. if ($result < 0) {
  5031. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  5032. return -1;
  5033. }
  5034. } else {
  5035. $ecmfile->entity = $conf->entity;
  5036. $ecmfile->filepath = $rel_dir;
  5037. $ecmfile->filename = $filename;
  5038. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  5039. $ecmfile->fullpath_orig = '';
  5040. $ecmfile->gen_or_uploaded = 'generated';
  5041. $ecmfile->description = ''; // indexed content
  5042. $ecmfile->keywords = ''; // keyword content
  5043. $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
  5044. $ecmfile->src_object_id = $this->id;
  5045. $result = $ecmfile->create($user);
  5046. if ($result < 0) {
  5047. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  5048. return -1;
  5049. }
  5050. }
  5051. /*$this->result['fullname']=$destfull;
  5052. $this->result['filepath']=$ecmfile->filepath;
  5053. $this->result['filename']=$ecmfile->filename;*/
  5054. //var_dump($obj->update_main_doc_field);exit;
  5055. if ($update_main_doc_field && !empty($this->table_element)) {
  5056. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
  5057. $sql .= " WHERE rowid = ".((int) $this->id);
  5058. $resql = $this->db->query($sql);
  5059. if (!$resql) {
  5060. dol_print_error($this->db);
  5061. return -1;
  5062. } else {
  5063. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  5064. }
  5065. }
  5066. }
  5067. return 1;
  5068. }
  5069. /**
  5070. * Build thumb
  5071. * @todo Move this into files.lib.php
  5072. *
  5073. * @param string $file Path file in UTF8 to original file to create thumbs from.
  5074. * @return void
  5075. */
  5076. public function addThumbs($file)
  5077. {
  5078. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  5079. $tmparraysize = getDefaultImageSizes();
  5080. $maxwidthsmall = $tmparraysize['maxwidthsmall'];
  5081. $maxheightsmall = $tmparraysize['maxheightsmall'];
  5082. $maxwidthmini = $tmparraysize['maxwidthmini'];
  5083. $maxheightmini = $tmparraysize['maxheightmini'];
  5084. //$quality = $tmparraysize['quality'];
  5085. $quality = 50; // For thumbs, we force quality to 50
  5086. $file_osencoded = dol_osencode($file);
  5087. if (file_exists($file_osencoded)) {
  5088. // Create small thumbs for company (Ratio is near 16/9)
  5089. // Used on logon for example
  5090. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  5091. // Create mini thumbs for company (Ratio is near 16/9)
  5092. // Used on menu or for setup page for example
  5093. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  5094. }
  5095. }
  5096. /* Functions common to commonobject and commonobjectline */
  5097. /* For default values */
  5098. /**
  5099. * Return the default value to use for a field when showing the create form of object.
  5100. * Return values in this order:
  5101. * 1) If parameter is available into POST, we return it first.
  5102. * 2) If not but an alternate value was provided as parameter of function, we return it.
  5103. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  5104. * 4) Return value found into database (TODO No yet implemented)
  5105. *
  5106. * @param string $fieldname Name of field
  5107. * @param string $alternatevalue Alternate value to use
  5108. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  5109. **/
  5110. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
  5111. {
  5112. global $conf, $_POST;
  5113. // If param here has been posted, we use this value first.
  5114. if (GETPOSTISSET($fieldname)) {
  5115. return GETPOST($fieldname, 'alphanohtml', 3);
  5116. }
  5117. if (isset($alternatevalue)) {
  5118. return $alternatevalue;
  5119. }
  5120. $newelement = $this->element;
  5121. if ($newelement == 'facture') {
  5122. $newelement = 'invoice';
  5123. }
  5124. if ($newelement == 'commande') {
  5125. $newelement = 'order';
  5126. }
  5127. if (empty($newelement)) {
  5128. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  5129. return '';
  5130. }
  5131. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  5132. //var_dump($keyforfieldname);
  5133. if (isset($conf->global->$keyforfieldname)) {
  5134. return $conf->global->$keyforfieldname;
  5135. }
  5136. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  5137. }
  5138. /* For triggers */
  5139. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5140. /**
  5141. * Call trigger based on this instance.
  5142. * Some context information may also be provided into array property this->context.
  5143. * NB: Error from trigger are stacked in interface->errors
  5144. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  5145. *
  5146. * @param string $triggerName trigger's name to execute
  5147. * @param User $user Object user
  5148. * @return int Result of run_triggers
  5149. */
  5150. public function call_trigger($triggerName, $user)
  5151. {
  5152. // phpcs:enable
  5153. global $langs, $conf;
  5154. if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
  5155. dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.');
  5156. exit;
  5157. }
  5158. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  5159. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  5160. $langs = new Translate('', $conf);
  5161. }
  5162. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  5163. $interface = new Interfaces($this->db);
  5164. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  5165. if ($result < 0) {
  5166. if (!empty($this->errors)) {
  5167. $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.
  5168. } else {
  5169. $this->errors = $interface->errors;
  5170. }
  5171. }
  5172. return $result;
  5173. }
  5174. /* Functions for data in other language */
  5175. /**
  5176. * Function to get alternative languages of a data into $this->array_languages
  5177. * This method is NOT called by method fetch of objects but must be called separately.
  5178. *
  5179. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  5180. * @see fetch_optionnals()
  5181. */
  5182. public function fetchValuesForExtraLanguages()
  5183. {
  5184. // To avoid SQL errors. Probably not the better solution though
  5185. if (!$this->element) {
  5186. return 0;
  5187. }
  5188. if (!($this->id > 0)) {
  5189. return 0;
  5190. }
  5191. if (is_array($this->array_languages)) {
  5192. return 1;
  5193. }
  5194. $this->array_languages = array();
  5195. $element = $this->element;
  5196. if ($element == 'categorie') {
  5197. $element = 'categories'; // For compatibility
  5198. }
  5199. // Request to get translation values for object
  5200. $sql = "SELECT rowid, property, lang , value";
  5201. $sql .= " FROM ".$this->db->prefix()."object_lang";
  5202. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  5203. $sql .= " AND fk_object = ".((int) $this->id);
  5204. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5205. $resql = $this->db->query($sql);
  5206. if ($resql) {
  5207. $numrows = $this->db->num_rows($resql);
  5208. if ($numrows) {
  5209. $i = 0;
  5210. while ($i < $numrows) {
  5211. $obj = $this->db->fetch_object($resql);
  5212. $key = $obj->property;
  5213. $value = $obj->value;
  5214. $codelang = $obj->lang;
  5215. $type = $this->fields[$key]['type'];
  5216. // we can add this attribute to object
  5217. if (preg_match('/date/', $type)) {
  5218. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  5219. } else {
  5220. $this->array_languages[$key][$codelang] = $value;
  5221. }
  5222. $i++;
  5223. }
  5224. }
  5225. $this->db->free($resql);
  5226. if ($numrows) {
  5227. return $numrows;
  5228. } else {
  5229. return 0;
  5230. }
  5231. } else {
  5232. dol_print_error($this->db);
  5233. return -1;
  5234. }
  5235. }
  5236. /**
  5237. * Fill array_options property of object by extrafields value (using for data sent by forms)
  5238. *
  5239. * @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.
  5240. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  5241. */
  5242. public function setValuesForExtraLanguages($onlykey = '')
  5243. {
  5244. global $_POST, $langs;
  5245. // Get extra fields
  5246. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  5247. $tmparray = explode('-', $postfieldkey);
  5248. if ($tmparray[0] != 'field') {
  5249. continue;
  5250. }
  5251. $element = $tmparray[1];
  5252. $key = $tmparray[2];
  5253. $codelang = $tmparray[3];
  5254. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  5255. if (!empty($onlykey) && $key != $onlykey) {
  5256. continue;
  5257. }
  5258. if ($element != $this->element) {
  5259. continue;
  5260. }
  5261. $key_type = $this->fields[$key]['type'];
  5262. $enabled = 1;
  5263. if (isset($this->fields[$key]['enabled'])) {
  5264. $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
  5265. }
  5266. /*$perms = 1;
  5267. if (isset($this->fields[$key]['perms']))
  5268. {
  5269. $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
  5270. }*/
  5271. if (empty($enabled)) {
  5272. continue;
  5273. }
  5274. //if (empty($perms)) continue;
  5275. if (in_array($key_type, array('date'))) {
  5276. // Clean parameters
  5277. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5278. $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
  5279. } elseif (in_array($key_type, array('datetime'))) {
  5280. // Clean parameters
  5281. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5282. $value_key = dol_mktime(GETPOST($postfieldkey."hour", 'int'), GETPOST($postfieldkey."min", 'int'), 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
  5283. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  5284. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  5285. if (!empty($value_arr)) {
  5286. $value_key = implode(',', $value_arr);
  5287. } else {
  5288. $value_key = '';
  5289. }
  5290. } elseif (in_array($key_type, array('price', 'double'))) {
  5291. $value_arr = GETPOST($postfieldkey, 'alpha');
  5292. $value_key = price2num($value_arr);
  5293. } else {
  5294. $value_key = GETPOST($postfieldkey);
  5295. if (in_array($key_type, array('link')) && $value_key == '-1') {
  5296. $value_key = '';
  5297. }
  5298. }
  5299. $this->array_languages[$key][$codelang] = $value_key;
  5300. /*if ($nofillrequired) {
  5301. $langs->load('errors');
  5302. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  5303. return -1;
  5304. }*/
  5305. }
  5306. return 1;
  5307. }
  5308. /* Functions for extrafields */
  5309. /**
  5310. * Function to make a fetch but set environment to avoid to load computed values before.
  5311. *
  5312. * @param int $id ID of object
  5313. * @return int >0 if OK, 0 if not found, <0 if KO
  5314. */
  5315. public function fetchNoCompute($id)
  5316. {
  5317. global $conf;
  5318. $savDisableCompute = $conf->disable_compute;
  5319. $conf->disable_compute = 1;
  5320. $ret = $this->fetch($id);
  5321. $conf->disable_compute = $savDisableCompute;
  5322. return $ret;
  5323. }
  5324. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5325. /**
  5326. * Function to get extra fields of an object into $this->array_options
  5327. * This method is in most cases called by method fetch of objects but you can call it separately.
  5328. *
  5329. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  5330. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  5331. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  5332. * @see fetchValuesForExtraLanguages()
  5333. */
  5334. public function fetch_optionals($rowid = null, $optionsArray = null)
  5335. {
  5336. // phpcs:enable
  5337. global $conf, $extrafields;
  5338. if (empty($rowid)) {
  5339. $rowid = $this->id;
  5340. }
  5341. if (empty($rowid) && isset($this->rowid)) {
  5342. $rowid = $this->rowid; // deprecated
  5343. }
  5344. // To avoid SQL errors. Probably not the better solution though
  5345. if (!$this->table_element) {
  5346. return 0;
  5347. }
  5348. $this->array_options = array();
  5349. if (!is_array($optionsArray)) {
  5350. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  5351. if (!isset($extrafields) || !is_object($extrafields)) {
  5352. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5353. $extrafields = new ExtraFields($this->db);
  5354. }
  5355. // Load array of extrafields for elementype = $this->table_element
  5356. if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
  5357. $extrafields->fetch_name_optionals_label($this->table_element);
  5358. }
  5359. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  5360. } else {
  5361. global $extrafields;
  5362. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  5363. }
  5364. $table_element = $this->table_element;
  5365. if ($table_element == 'categorie') {
  5366. $table_element = 'categories'; // For compatibility
  5367. }
  5368. // Request to get complementary values
  5369. if (is_array($optionsArray) && count($optionsArray) > 0) {
  5370. $sql = "SELECT rowid";
  5371. foreach ($optionsArray as $name => $label) {
  5372. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
  5373. $sql .= ", ".$name;
  5374. }
  5375. }
  5376. $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
  5377. $sql .= " WHERE fk_object = ".((int) $rowid);
  5378. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5379. $resql = $this->db->query($sql);
  5380. if ($resql) {
  5381. $numrows = $this->db->num_rows($resql);
  5382. if ($numrows) {
  5383. $tab = $this->db->fetch_array($resql);
  5384. foreach ($tab as $key => $value) {
  5385. // 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)
  5386. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
  5387. // we can add this attribute to object
  5388. if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
  5389. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  5390. $this->array_options["options_".$key] = $this->db->jdate($value);
  5391. } else {
  5392. $this->array_options["options_".$key] = $value;
  5393. }
  5394. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  5395. }
  5396. }
  5397. }
  5398. // If field is a computed field, value must become result of compute (regardless of whether a row exists
  5399. // in the element's extrafields table)
  5400. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
  5401. if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
  5402. //var_dump($conf->disable_compute);
  5403. if (empty($conf->disable_compute)) {
  5404. global $objectoffield; // We set a global variable to $objectoffield so
  5405. $objectoffield = $this; // we can use it inside computed formula
  5406. $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
  5407. }
  5408. }
  5409. }
  5410. $this->db->free($resql);
  5411. if ($numrows) {
  5412. return $numrows;
  5413. } else {
  5414. return 0;
  5415. }
  5416. } else {
  5417. $this->errors[]=$this->db->lasterror;
  5418. return -1;
  5419. }
  5420. }
  5421. return 0;
  5422. }
  5423. /**
  5424. * Delete all extra fields values for the current object.
  5425. *
  5426. * @return int <0 if KO, >0 if OK
  5427. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  5428. */
  5429. public function deleteExtraFields()
  5430. {
  5431. global $conf;
  5432. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5433. return 0;
  5434. }
  5435. $this->db->begin();
  5436. $table_element = $this->table_element;
  5437. if ($table_element == 'categorie') {
  5438. $table_element = 'categories'; // For compatibility
  5439. }
  5440. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  5441. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5442. $resql = $this->db->query($sql_del);
  5443. if (!$resql) {
  5444. $this->error = $this->db->lasterror();
  5445. $this->db->rollback();
  5446. return -1;
  5447. } else {
  5448. $this->db->commit();
  5449. return 1;
  5450. }
  5451. }
  5452. /**
  5453. * Add/Update all extra fields values for the current object.
  5454. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5455. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5456. *
  5457. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5458. * @param User $userused Object user
  5459. * @return int -1=error, O=did nothing, 1=OK
  5460. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  5461. */
  5462. public function insertExtraFields($trigger = '', $userused = null)
  5463. {
  5464. global $conf, $langs, $user;
  5465. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5466. return 0;
  5467. }
  5468. if (empty($userused)) {
  5469. $userused = $user;
  5470. }
  5471. $error = 0;
  5472. if (!empty($this->array_options)) {
  5473. // Check parameters
  5474. $langs->load('admin');
  5475. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5476. $extrafields = new ExtraFields($this->db);
  5477. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  5478. // Eliminate copied source object extra fields that do not exist in target object
  5479. $new_array_options = array();
  5480. foreach ($this->array_options as $key => $value) {
  5481. if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
  5482. $new_array_options[$key] = $value;
  5483. } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
  5484. $new_array_options['options_'.$key] = $value;
  5485. }
  5486. }
  5487. foreach ($new_array_options as $key => $value) {
  5488. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5489. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  5490. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  5491. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  5492. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  5493. $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
  5494. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  5495. // If we clone, we have to clean unique extrafields to prevent duplicates.
  5496. // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
  5497. if (! empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && ! empty($attributeUnique)) {
  5498. $new_array_options[$key] = null;
  5499. }
  5500. // Similar code than into insertExtraFields
  5501. if ($attributeRequired) {
  5502. $mandatorypb = false;
  5503. if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
  5504. $mandatorypb = true;
  5505. }
  5506. if ($this->array_options[$key] === '') {
  5507. $mandatorypb = true;
  5508. }
  5509. if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
  5510. $mandatorypb = true;
  5511. }
  5512. if ($mandatorypb) {
  5513. $langs->load("errors");
  5514. dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
  5515. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5516. return -1;
  5517. }
  5518. }
  5519. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5520. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5521. if (!empty($attrfieldcomputed)) {
  5522. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5523. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5524. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5525. $new_array_options[$key] = $value;
  5526. } else {
  5527. $new_array_options[$key] = null;
  5528. }
  5529. }
  5530. switch ($attributeType) {
  5531. case 'int':
  5532. if (!is_numeric($value) && $value != '') {
  5533. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5534. return -1;
  5535. } elseif ($value == '') {
  5536. $new_array_options[$key] = null;
  5537. }
  5538. break;
  5539. case 'price':
  5540. case 'double':
  5541. $value = price2num($value);
  5542. if (!is_numeric($value) && $value != '') {
  5543. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5544. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5545. return -1;
  5546. } elseif ($value == '') {
  5547. $value = null;
  5548. }
  5549. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5550. $new_array_options[$key] = $value;
  5551. break;
  5552. /*case 'select': // Not required, we chosed value='0' for undefined values
  5553. if ($value=='-1')
  5554. {
  5555. $this->array_options[$key] = null;
  5556. }
  5557. break;*/
  5558. case 'password':
  5559. $algo = '';
  5560. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
  5561. // If there is an encryption choice, we use it to crypt data before insert
  5562. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  5563. $algo = reset($tmparrays);
  5564. if ($algo != '') {
  5565. //global $action; // $action may be 'create', 'update', 'update_extras'...
  5566. //var_dump($action);
  5567. //var_dump($this->oldcopy);exit;
  5568. 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
  5569. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  5570. if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) { // If old value crypted in database is same than submited new value, it means we don't change it, so we don't update.
  5571. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5572. } else {
  5573. // var_dump($algo);
  5574. $newvalue = dol_hash($this->array_options[$key], $algo);
  5575. $new_array_options[$key] = $newvalue;
  5576. }
  5577. } else {
  5578. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5579. }
  5580. }
  5581. } else // Common usage
  5582. {
  5583. $new_array_options[$key] = $this->array_options[$key];
  5584. }
  5585. break;
  5586. case 'date':
  5587. case 'datetime':
  5588. // If data is a string instead of a timestamp, we convert it
  5589. if (!is_int($this->array_options[$key])) {
  5590. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5591. }
  5592. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  5593. break;
  5594. case 'link':
  5595. $param_list = array_keys($attributeParam['options']);
  5596. // 0 : ObjectName
  5597. // 1 : classPath
  5598. $InfoFieldList = explode(":", $param_list[0]);
  5599. dol_include_once($InfoFieldList[1]);
  5600. if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
  5601. if ($value == '-1') { // -1 is key for no defined in combo list of objects
  5602. $new_array_options[$key] = '';
  5603. } elseif ($value) {
  5604. $object = new $InfoFieldList[0]($this->db);
  5605. if (is_numeric($value)) {
  5606. $res = $object->fetch($value); // Common case
  5607. } else {
  5608. $res = $object->fetch('', $value); // For compatibility
  5609. }
  5610. if ($res > 0) {
  5611. $new_array_options[$key] = $object->id;
  5612. } else {
  5613. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  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. $table_element = $this->table_element;
  5625. if ($table_element == 'categorie') {
  5626. $table_element = 'categories'; // For compatibility
  5627. }
  5628. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  5629. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5630. $this->db->query($sql_del);
  5631. $sql = "INSERT INTO ".$this->db->prefix().$table_element."_extrafields (fk_object";
  5632. foreach ($new_array_options as $key => $value) {
  5633. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5634. // Add field of attribut
  5635. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
  5636. $sql .= ",".$attributeKey;
  5637. }
  5638. }
  5639. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5640. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5641. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5642. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5643. $sql .= ",".$tmpkey;
  5644. }
  5645. }
  5646. }
  5647. $sql .= ") VALUES (".$this->id;
  5648. foreach ($new_array_options as $key => $value) {
  5649. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5650. // Add field of attribute
  5651. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
  5652. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
  5653. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  5654. } else {
  5655. $sql .= ",null";
  5656. }
  5657. }
  5658. }
  5659. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5660. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5661. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5662. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5663. if (in_array($tmpval, array('int', 'double', 'price'))) {
  5664. $sql .= ", 0";
  5665. } else {
  5666. $sql .= ", ''";
  5667. }
  5668. }
  5669. }
  5670. }
  5671. $sql .= ")";
  5672. $resql = $this->db->query($sql);
  5673. if (!$resql) {
  5674. $this->error = $this->db->lasterror();
  5675. $error++;
  5676. }
  5677. if (!$error && $trigger) {
  5678. // Call trigger
  5679. $this->context = array('extrafieldaddupdate'=>1);
  5680. $result = $this->call_trigger($trigger, $userused);
  5681. if ($result < 0) {
  5682. $error++;
  5683. }
  5684. // End call trigger
  5685. }
  5686. if ($error) {
  5687. $this->db->rollback();
  5688. return -1;
  5689. } else {
  5690. $this->db->commit();
  5691. return 1;
  5692. }
  5693. } else {
  5694. return 0;
  5695. }
  5696. }
  5697. /**
  5698. * Add/Update all extra fields values for the current object.
  5699. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5700. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5701. *
  5702. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5703. * @param User $userused Object user
  5704. * @return int -1=error, O=did nothing, 1=OK
  5705. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  5706. */
  5707. public function insertExtraLanguages($trigger = '', $userused = null)
  5708. {
  5709. global $conf, $langs, $user;
  5710. if (empty($userused)) {
  5711. $userused = $user;
  5712. }
  5713. $error = 0;
  5714. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5715. return 0; // For avoid conflicts if trigger used
  5716. }
  5717. if (is_array($this->array_languages)) {
  5718. $new_array_languages = $this->array_languages;
  5719. foreach ($new_array_languages as $key => $value) {
  5720. $attributeKey = $key;
  5721. $attributeType = $this->fields[$attributeKey]['type'];
  5722. $attributeLabel = $this->fields[$attributeKey]['label'];
  5723. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5724. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5725. switch ($attributeType) {
  5726. case 'int':
  5727. if (!is_numeric($value) && $value != '') {
  5728. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5729. return -1;
  5730. } elseif ($value == '') {
  5731. $new_array_languages[$key] = null;
  5732. }
  5733. break;
  5734. case 'double':
  5735. $value = price2num($value);
  5736. if (!is_numeric($value) && $value != '') {
  5737. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5738. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5739. return -1;
  5740. } elseif ($value == '') {
  5741. $new_array_languages[$key] = null;
  5742. }
  5743. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5744. $new_array_languages[$key] = $value;
  5745. break;
  5746. /*case 'select': // Not required, we chosed value='0' for undefined values
  5747. if ($value=='-1')
  5748. {
  5749. $this->array_options[$key] = null;
  5750. }
  5751. break;*/
  5752. }
  5753. }
  5754. $this->db->begin();
  5755. $table_element = $this->table_element;
  5756. if ($table_element == 'categorie') {
  5757. $table_element = 'categories'; // For compatibility
  5758. }
  5759. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  5760. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  5761. foreach ($langcodearray as $langcode => $value) {
  5762. $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
  5763. $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  5764. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  5765. $this->db->query($sql_del);
  5766. if ($value !== '') {
  5767. $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
  5768. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  5769. $sql .= ")";
  5770. $resql = $this->db->query($sql);
  5771. if (!$resql) {
  5772. $this->error = $this->db->lasterror();
  5773. $error++;
  5774. break;
  5775. }
  5776. }
  5777. }
  5778. }
  5779. if (!$error && $trigger) {
  5780. // Call trigger
  5781. $this->context = array('extralanguagesaddupdate'=>1);
  5782. $result = $this->call_trigger($trigger, $userused);
  5783. if ($result < 0) {
  5784. $error++;
  5785. }
  5786. // End call trigger
  5787. }
  5788. if ($error) {
  5789. $this->db->rollback();
  5790. return -1;
  5791. } else {
  5792. $this->db->commit();
  5793. return 1;
  5794. }
  5795. } else {
  5796. return 0;
  5797. }
  5798. }
  5799. /**
  5800. * Update 1 extra field value for the current object. Keep other fields unchanged.
  5801. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5802. *
  5803. * @param string $key Key of the extrafield to update (without starting 'options_')
  5804. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5805. * @param User $userused Object user
  5806. * @return int -1=error, O=did nothing, 1=OK
  5807. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  5808. */
  5809. public function updateExtraField($key, $trigger = null, $userused = null)
  5810. {
  5811. global $conf, $langs, $user;
  5812. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5813. return 0;
  5814. }
  5815. if (empty($userused)) {
  5816. $userused = $user;
  5817. }
  5818. $error = 0;
  5819. if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
  5820. // Check parameters
  5821. $langs->load('admin');
  5822. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5823. $extrafields = new ExtraFields($this->db);
  5824. $extrafields->fetch_name_optionals_label($this->table_element);
  5825. $value = $this->array_options["options_".$key];
  5826. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  5827. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  5828. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  5829. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  5830. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  5831. // Similar code than into insertExtraFields
  5832. if ($attributeRequired) {
  5833. $mandatorypb = false;
  5834. if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
  5835. $mandatorypb = true;
  5836. }
  5837. if ($this->array_options["options_".$key] === '') {
  5838. $mandatorypb = true;
  5839. }
  5840. if ($mandatorypb) {
  5841. $langs->load("errors");
  5842. dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
  5843. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5844. return -1;
  5845. }
  5846. }
  5847. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5848. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5849. if (!empty($attrfieldcomputed)) {
  5850. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5851. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5852. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5853. $this->array_options["options_".$key] = $value;
  5854. } else {
  5855. $this->array_options["options_".$key] = null;
  5856. }
  5857. }
  5858. switch ($attributeType) {
  5859. case 'int':
  5860. if (!is_numeric($value) && $value != '') {
  5861. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5862. return -1;
  5863. } elseif ($value === '') {
  5864. $this->array_options["options_".$key] = null;
  5865. }
  5866. break;
  5867. case 'double':
  5868. $value = price2num($value);
  5869. if (!is_numeric($value) && $value != '') {
  5870. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5871. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5872. return -1;
  5873. } elseif ($value === '') {
  5874. $value = null;
  5875. }
  5876. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5877. $this->array_options["options_".$key] = $value;
  5878. break;
  5879. /*case 'select': // Not required, we chosed value='0' for undefined values
  5880. if ($value=='-1')
  5881. {
  5882. $this->array_options[$key] = null;
  5883. }
  5884. break;*/
  5885. case 'price':
  5886. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  5887. break;
  5888. case 'date':
  5889. case 'datetime':
  5890. if (empty($this->array_options["options_".$key])) {
  5891. $this->array_options["options_".$key] = null;
  5892. } else {
  5893. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5894. }
  5895. break;
  5896. case 'boolean':
  5897. if (empty($this->array_options["options_".$key])) {
  5898. $this->array_options["options_".$key] = null;
  5899. }
  5900. break;
  5901. /*
  5902. case 'link':
  5903. $param_list = array_keys($attributeParam['options']);
  5904. // 0 : ObjectName
  5905. // 1 : classPath
  5906. $InfoFieldList = explode(":", $param_list[0]);
  5907. dol_include_once($InfoFieldList[1]);
  5908. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  5909. {
  5910. if ($value == '-1') // -1 is key for no defined in combo list of objects
  5911. {
  5912. $new_array_options[$key] = '';
  5913. } elseif ($value) {
  5914. $object = new $InfoFieldList[0]($this->db);
  5915. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  5916. else $res = $object->fetch('', $value); // For compatibility
  5917. if ($res > 0) $new_array_options[$key] = $object->id;
  5918. else {
  5919. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5920. $this->db->rollback();
  5921. return -1;
  5922. }
  5923. }
  5924. } else {
  5925. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5926. }
  5927. break;
  5928. */
  5929. }
  5930. $this->db->begin();
  5931. $linealreadyfound = 0;
  5932. // 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)
  5933. $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5934. $resql = $this->db->query($sql);
  5935. if ($resql) {
  5936. $tmpobj = $this->db->fetch_object($resql);
  5937. if ($tmpobj) {
  5938. $linealreadyfound = $tmpobj->nb;
  5939. }
  5940. }
  5941. if ($linealreadyfound) {
  5942. if ($this->array_options["options_".$key] === null) {
  5943. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = null";
  5944. } else {
  5945. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
  5946. }
  5947. $sql .= " WHERE fk_object = ".((int) $this->id);
  5948. } else {
  5949. $result = $this->insertExtraFields('', $user);
  5950. if ($result < 0) {
  5951. $error++;
  5952. }
  5953. }
  5954. $resql = $this->db->query($sql);
  5955. if (!$resql) {
  5956. $error++;
  5957. $this->error = $this->db->lasterror();
  5958. }
  5959. if (!$error && $trigger) {
  5960. // Call trigger
  5961. $this->context = array('extrafieldupdate'=>1);
  5962. $result = $this->call_trigger($trigger, $userused);
  5963. if ($result < 0) {
  5964. $error++;
  5965. }
  5966. // End call trigger
  5967. }
  5968. if ($error) {
  5969. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  5970. $this->db->rollback();
  5971. return -1;
  5972. } else {
  5973. $this->db->commit();
  5974. return 1;
  5975. }
  5976. } else {
  5977. return 0;
  5978. }
  5979. }
  5980. /**
  5981. * Update an extra language value for the current object.
  5982. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5983. *
  5984. * @param string $key Key of the extrafield (without starting 'options_')
  5985. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5986. * @param User $userused Object user
  5987. * @return int -1=error, O=did nothing, 1=OK
  5988. * @see updateExtraFields(), insertExtraLanguages()
  5989. */
  5990. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  5991. {
  5992. global $conf, $langs, $user;
  5993. if (empty($userused)) {
  5994. $userused = $user;
  5995. }
  5996. $error = 0;
  5997. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5998. return 0; // For avoid conflicts if trigger used
  5999. }
  6000. return 0;
  6001. }
  6002. /**
  6003. * Return HTML string to put an input field into a page
  6004. * Code very similar with showInputField of extra fields
  6005. *
  6006. * @param array $val Array of properties for field to show (used only if ->fields not defined)
  6007. * @param string $key Key of attribute
  6008. * @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)
  6009. * @param string $moreparam To add more parameters on html input tag
  6010. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6011. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6012. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  6013. * @param int $nonewbutton Force to not show the new button on field that are links to object
  6014. * @return string
  6015. */
  6016. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  6017. {
  6018. global $conf, $langs, $form;
  6019. if (!is_object($form)) {
  6020. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6021. $form = new Form($this->db);
  6022. }
  6023. if (!empty($this->fields)) {
  6024. $val = $this->fields[$key];
  6025. }
  6026. // Validation tests and output
  6027. $fieldValidationErrorMsg = '';
  6028. $validationClass = '';
  6029. $fieldValidationErrorMsg = $this->getFieldError($key);
  6030. if (!empty($fieldValidationErrorMsg)) {
  6031. $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
  6032. } else {
  6033. $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
  6034. }
  6035. $out = '';
  6036. $type = '';
  6037. $isDependList = 0;
  6038. $param = array();
  6039. $param['options'] = array();
  6040. $reg = array();
  6041. $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
  6042. // Because we work on extrafields
  6043. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6044. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  6045. $type = 'link';
  6046. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6047. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6048. $type = 'link';
  6049. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  6050. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  6051. $type = 'link';
  6052. } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6053. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  6054. $type = 'sellist';
  6055. } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6056. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6057. $type = 'sellist';
  6058. } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
  6059. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  6060. $type = 'sellist';
  6061. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  6062. $param['options'] = array();
  6063. $type = 'varchar';
  6064. $size = $reg[1];
  6065. } elseif (preg_match('/varchar/', $val['type'])) {
  6066. $param['options'] = array();
  6067. $type = 'varchar';
  6068. } else {
  6069. $param['options'] = array();
  6070. $type = $this->fields[$key]['type'];
  6071. }
  6072. // Special case that force options and type ($type can be integer, varchar, ...)
  6073. if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
  6074. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  6075. $type = 'select';
  6076. }
  6077. $label = $this->fields[$key]['label'];
  6078. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  6079. $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
  6080. $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
  6081. $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
  6082. $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
  6083. $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
  6084. $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
  6085. $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
  6086. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  6087. $objectid = $this->id;
  6088. if ($computed) {
  6089. if (!preg_match('/^search_/', $keyprefix)) {
  6090. return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  6091. } else {
  6092. return '';
  6093. }
  6094. }
  6095. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  6096. if (empty($morecss) && !empty($val['css'])) {
  6097. $morecss = $val['css'];
  6098. } elseif (empty($morecss)) {
  6099. if ($type == 'date') {
  6100. $morecss = 'minwidth100imp';
  6101. } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
  6102. $morecss = 'minwidth200imp';
  6103. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  6104. $morecss = 'maxwidth75';
  6105. } elseif ($type == 'url') {
  6106. $morecss = 'minwidth400';
  6107. } elseif ($type == 'boolean') {
  6108. $morecss = '';
  6109. } else {
  6110. if (round($size) < 12) {
  6111. $morecss = 'minwidth100';
  6112. } elseif (round($size) <= 48) {
  6113. $morecss = 'minwidth200';
  6114. } else {
  6115. $morecss = 'minwidth400';
  6116. }
  6117. }
  6118. }
  6119. // Add validation state class
  6120. if (!empty($validationClass)) {
  6121. $morecss.= $validationClass;
  6122. }
  6123. if (in_array($type, array('date'))) {
  6124. $tmp = explode(',', $size);
  6125. $newsize = $tmp[0];
  6126. $showtime = 0;
  6127. // Do not show current date when field not required (see selectDate() method)
  6128. if (!$required && $value == '') {
  6129. $value = '-1';
  6130. }
  6131. // TODO Must also support $moreparam
  6132. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  6133. } elseif (in_array($type, array('datetime'))) {
  6134. $tmp = explode(',', $size);
  6135. $newsize = $tmp[0];
  6136. $showtime = 1;
  6137. // Do not show current date when field not required (see selectDate() method)
  6138. if (!$required && $value == '') $value = '-1';
  6139. // TODO Must also support $moreparam
  6140. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
  6141. } elseif (in_array($type, array('duration'))) {
  6142. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  6143. } elseif (in_array($type, array('int', 'integer'))) {
  6144. $tmp = explode(',', $size);
  6145. $newsize = $tmp[0];
  6146. $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' : '').'>';
  6147. } elseif (in_array($type, array('real'))) {
  6148. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6149. } elseif (preg_match('/varchar/', $type)) {
  6150. $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' : '').'>';
  6151. } elseif (in_array($type, array('email', 'mail', 'phone', 'url'))) {
  6152. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6153. } elseif (preg_match('/^text/', $type)) {
  6154. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6155. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  6156. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  6157. $out = $doleditor->Create(1);
  6158. } else {
  6159. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  6160. }
  6161. } elseif (preg_match('/^html/', $type)) {
  6162. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6163. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  6164. $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%');
  6165. $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
  6166. } else {
  6167. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  6168. }
  6169. } elseif ($type == 'boolean') {
  6170. $checked = '';
  6171. if (!empty($value)) {
  6172. $checked = ' checked value="1" ';
  6173. } else {
  6174. $checked = ' value="1" ';
  6175. }
  6176. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  6177. } elseif ($type == 'price') {
  6178. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6179. $value = price($value);
  6180. }
  6181. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  6182. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  6183. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6184. $value = price($value);
  6185. }
  6186. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  6187. } elseif ($type == 'select') {
  6188. $out = '';
  6189. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6190. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6191. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6192. }
  6193. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6194. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
  6195. $out .= '<option value="0">&nbsp;</option>';
  6196. }
  6197. foreach ($param['options'] as $keyb => $valb) {
  6198. if ((string) $keyb == '') {
  6199. continue;
  6200. }
  6201. if (strpos($valb, "|") !== false) {
  6202. list($valb, $parent) = explode('|', $valb);
  6203. }
  6204. $out .= '<option value="'.$keyb.'"';
  6205. $out .= (((string) $value == (string) $keyb) ? ' selected' : '');
  6206. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6207. $out .= '>'.$valb.'</option>';
  6208. }
  6209. $out .= '</select>';
  6210. } elseif ($type == 'sellist') {
  6211. $out = '';
  6212. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6213. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6214. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6215. }
  6216. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6217. if (is_array($param['options'])) {
  6218. $param_list = array_keys($param['options']);
  6219. $InfoFieldList = explode(":", $param_list[0]);
  6220. $parentName = '';
  6221. $parentField = '';
  6222. // 0 : tableName
  6223. // 1 : label field name
  6224. // 2 : key fields name (if differ of rowid)
  6225. // 3 : key field parent (for dependent lists)
  6226. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6227. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6228. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6229. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6230. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6231. } else {
  6232. $keyList = $InfoFieldList[2].' as rowid';
  6233. }
  6234. }
  6235. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6236. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6237. $keyList .= ', '.$parentField;
  6238. }
  6239. $fields_label = explode('|', $InfoFieldList[1]);
  6240. if (is_array($fields_label)) {
  6241. $keyList .= ', ';
  6242. $keyList .= implode(', ', $fields_label);
  6243. }
  6244. $sqlwhere = '';
  6245. $sql = "SELECT ".$keyList;
  6246. $sql .= " FROM ".$this->db->prefix().$InfoFieldList[0];
  6247. if (!empty($InfoFieldList[4])) {
  6248. // can use SELECT request
  6249. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6250. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6251. }
  6252. // current object id can be use into filter
  6253. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6254. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6255. } else {
  6256. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6257. }
  6258. //We have to join on extrafield table
  6259. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6260. $sql .= " as main, ".$this->db->prefix().$InfoFieldList[0]."_extrafields as extra";
  6261. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  6262. } else {
  6263. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  6264. }
  6265. } else {
  6266. $sqlwhere .= ' WHERE 1=1';
  6267. }
  6268. // Some tables may have field, some other not. For the moment we disable it.
  6269. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6270. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  6271. }
  6272. $sql .= $sqlwhere;
  6273. //print $sql;
  6274. $sql .= ' ORDER BY '.implode(', ', $fields_label);
  6275. dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
  6276. $resql = $this->db->query($sql);
  6277. if ($resql) {
  6278. $out .= '<option value="0">&nbsp;</option>';
  6279. $num = $this->db->num_rows($resql);
  6280. $i = 0;
  6281. while ($i < $num) {
  6282. $labeltoshow = '';
  6283. $obj = $this->db->fetch_object($resql);
  6284. // Several field into label (eq table:code|libelle:rowid)
  6285. $notrans = false;
  6286. $fields_label = explode('|', $InfoFieldList[1]);
  6287. if (count($fields_label) > 1) {
  6288. $notrans = true;
  6289. foreach ($fields_label as $field_toshow) {
  6290. $labeltoshow .= $obj->$field_toshow.' ';
  6291. }
  6292. } else {
  6293. $labeltoshow = $obj->{$InfoFieldList[1]};
  6294. }
  6295. $labeltoshow = dol_trunc($labeltoshow, 45);
  6296. if ($value == $obj->rowid) {
  6297. foreach ($fields_label as $field_toshow) {
  6298. $translabel = $langs->trans($obj->$field_toshow);
  6299. if ($translabel != $obj->$field_toshow) {
  6300. $labeltoshow = dol_trunc($translabel).' ';
  6301. } else {
  6302. $labeltoshow = dol_trunc($obj->$field_toshow).' ';
  6303. }
  6304. }
  6305. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6306. } else {
  6307. if (!$notrans) {
  6308. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6309. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6310. $labeltoshow = dol_trunc($translabel, 18);
  6311. } else {
  6312. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
  6313. }
  6314. }
  6315. if (empty($labeltoshow)) {
  6316. $labeltoshow = '(not defined)';
  6317. }
  6318. if ($value == $obj->rowid) {
  6319. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6320. }
  6321. if (!empty($InfoFieldList[3]) && $parentField) {
  6322. $parent = $parentName.':'.$obj->{$parentField};
  6323. $isDependList = 1;
  6324. }
  6325. $out .= '<option value="'.$obj->rowid.'"';
  6326. $out .= ($value == $obj->rowid ? ' selected' : '');
  6327. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6328. $out .= '>'.$labeltoshow.'</option>';
  6329. }
  6330. $i++;
  6331. }
  6332. $this->db->free($resql);
  6333. } else {
  6334. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6335. }
  6336. }
  6337. $out .= '</select>';
  6338. } elseif ($type == 'checkbox') {
  6339. $value_arr = explode(',', $value);
  6340. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, $morecss, 0, '100%');
  6341. } elseif ($type == 'radio') {
  6342. $out = '';
  6343. foreach ($param['options'] as $keyopt => $valopt) {
  6344. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  6345. $out .= ' value="'.$keyopt.'"';
  6346. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  6347. $out .= ($value == $keyopt ? 'checked' : '');
  6348. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$valopt.'</label><br>';
  6349. }
  6350. } elseif ($type == 'chkbxlst') {
  6351. if (is_array($value)) {
  6352. $value_arr = $value;
  6353. } else {
  6354. $value_arr = explode(',', $value);
  6355. }
  6356. if (is_array($param['options'])) {
  6357. $param_list = array_keys($param['options']);
  6358. $InfoFieldList = explode(":", $param_list[0]);
  6359. $parentName = '';
  6360. $parentField = '';
  6361. // 0 : tableName
  6362. // 1 : label field name
  6363. // 2 : key fields name (if differ of rowid)
  6364. // 3 : key field parent (for dependent lists)
  6365. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6366. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6367. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6368. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6369. $keyList .= ', '.$parentField;
  6370. }
  6371. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6372. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6373. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6374. } else {
  6375. $keyList = $InfoFieldList[2].' as rowid';
  6376. }
  6377. }
  6378. $fields_label = explode('|', $InfoFieldList[1]);
  6379. if (is_array($fields_label)) {
  6380. $keyList .= ', ';
  6381. $keyList .= implode(', ', $fields_label);
  6382. }
  6383. $sqlwhere = '';
  6384. $sql = "SELECT ".$keyList;
  6385. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6386. if (!empty($InfoFieldList[4])) {
  6387. // can use SELECT request
  6388. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6389. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6390. }
  6391. // current object id can be use into filter
  6392. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6393. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6394. } else {
  6395. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6396. }
  6397. // We have to join on extrafield table
  6398. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6399. $sql .= ' as main, '.$this->db->prefix().$InfoFieldList[0].'_extrafields as extra';
  6400. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  6401. } else {
  6402. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  6403. }
  6404. } else {
  6405. $sqlwhere .= ' WHERE 1=1';
  6406. }
  6407. // Some tables may have field, some other not. For the moment we disable it.
  6408. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6409. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  6410. }
  6411. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  6412. // print $sql;
  6413. $sql .= $sqlwhere;
  6414. dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
  6415. $resql = $this->db->query($sql);
  6416. if ($resql) {
  6417. $num = $this->db->num_rows($resql);
  6418. $i = 0;
  6419. $data = array();
  6420. while ($i < $num) {
  6421. $labeltoshow = '';
  6422. $obj = $this->db->fetch_object($resql);
  6423. $notrans = false;
  6424. // Several field into label (eq table:code|libelle:rowid)
  6425. $fields_label = explode('|', $InfoFieldList[1]);
  6426. if (count($fields_label) > 1) {
  6427. $notrans = true;
  6428. foreach ($fields_label as $field_toshow) {
  6429. $labeltoshow .= $obj->$field_toshow.' ';
  6430. }
  6431. } else {
  6432. $labeltoshow = $obj->{$InfoFieldList[1]};
  6433. }
  6434. $labeltoshow = dol_trunc($labeltoshow, 45);
  6435. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6436. foreach ($fields_label as $field_toshow) {
  6437. $translabel = $langs->trans($obj->$field_toshow);
  6438. if ($translabel != $obj->$field_toshow) {
  6439. $labeltoshow = dol_trunc($translabel, 18).' ';
  6440. } else {
  6441. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  6442. }
  6443. }
  6444. $data[$obj->rowid] = $labeltoshow;
  6445. } else {
  6446. if (!$notrans) {
  6447. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6448. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6449. $labeltoshow = dol_trunc($translabel, 18);
  6450. } else {
  6451. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  6452. }
  6453. }
  6454. if (empty($labeltoshow)) {
  6455. $labeltoshow = '(not defined)';
  6456. }
  6457. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6458. $data[$obj->rowid] = $labeltoshow;
  6459. }
  6460. if (!empty($InfoFieldList[3]) && $parentField) {
  6461. $parent = $parentName.':'.$obj->{$parentField};
  6462. $isDependList = 1;
  6463. }
  6464. $data[$obj->rowid] = $labeltoshow;
  6465. }
  6466. $i++;
  6467. }
  6468. $this->db->free($resql);
  6469. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
  6470. } else {
  6471. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6472. }
  6473. }
  6474. } elseif ($type == 'link') {
  6475. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
  6476. $param_list_array = explode(':', $param_list[0]);
  6477. $showempty = (($required && $default != '') ? 0 : 1);
  6478. if (!preg_match('/search_/', $keyprefix)) {
  6479. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6480. if (!empty($this->fields[$key]['picto'])) {
  6481. $morecss .= ' widthcentpercentminusxx';
  6482. } else {
  6483. $morecss .= ' widthcentpercentminusx';
  6484. }
  6485. } else {
  6486. if (!empty($this->fields[$key]['picto'])) {
  6487. $morecss .= ' widthcentpercentminusx';
  6488. }
  6489. }
  6490. }
  6491. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  6492. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6493. 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".
  6494. list($class, $classfile) = explode(':', $param_list[0]);
  6495. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
  6496. $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  6497. } else {
  6498. $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  6499. }
  6500. $paramforthenewlink = '';
  6501. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  6502. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  6503. $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin='.GETPOST('origin', 'aZ09') : '');
  6504. $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid='.GETPOST('originid', 'int') : '');
  6505. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  6506. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  6507. $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>';
  6508. }
  6509. }
  6510. } elseif ($type == 'password') {
  6511. // If prefix is 'search_', field is used as a filter, we use a common text field.
  6512. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  6513. } elseif ($type == 'array') {
  6514. $newval = $val;
  6515. $newval['type'] = 'varchar(256)';
  6516. $out = '';
  6517. if (!empty($value)) {
  6518. foreach ($value as $option) {
  6519. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6520. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  6521. }
  6522. }
  6523. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6524. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6525. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  6526. if (!empty($conf->use_javascript_ajax)) {
  6527. $out .= '
  6528. <script>
  6529. $(document).ready(function() {
  6530. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  6531. $("'.dol_escape_js($newInput).'").insertBefore(this);
  6532. });
  6533. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  6534. $(this).parent().remove();
  6535. });
  6536. });
  6537. </script>';
  6538. }
  6539. }
  6540. if (!empty($hidden)) {
  6541. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  6542. }
  6543. if ($isDependList==1) {
  6544. $out .= $this->getJSListDependancies('_common');
  6545. }
  6546. /* Add comments
  6547. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  6548. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  6549. */
  6550. // Display error message for field
  6551. if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
  6552. $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
  6553. }
  6554. return $out;
  6555. }
  6556. /**
  6557. * Return HTML string to show a field into a page
  6558. * Code very similar with showOutputField of extra fields
  6559. *
  6560. * @param array $val Array of properties of field to show
  6561. * @param string $key Key of attribute
  6562. * @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)
  6563. * @param string $moreparam To add more parametes on html input tag
  6564. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6565. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6566. * @param mixed $morecss Value for css to define size. May also be a numeric.
  6567. * @return string
  6568. */
  6569. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  6570. {
  6571. global $conf, $langs, $form;
  6572. if (!is_object($form)) {
  6573. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6574. $form = new Form($this->db);
  6575. }
  6576. $objectid = $this->id; // Not used ???
  6577. $label = empty($val['label']) ? '' : $val['label'];
  6578. $type = empty($val['type']) ? '' : $val['type'];
  6579. $size = empty($val['css']) ? '' : $val['css'];
  6580. $reg = array();
  6581. // Convert var to be able to share same code than showOutputField of extrafields
  6582. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6583. $type = 'varchar'; // convert varchar(xx) int varchar
  6584. $size = $reg[1];
  6585. } elseif (preg_match('/varchar/', $type)) {
  6586. $type = 'varchar'; // convert varchar(xx) int varchar
  6587. }
  6588. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6589. $type = 'select';
  6590. }
  6591. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6592. $type = 'link';
  6593. }
  6594. $default = empty($val['default']) ? '' : $val['default'];
  6595. $computed = empty($val['computed']) ? '' : $val['computed'];
  6596. $unique = empty($val['unique']) ? '' : $val['unique'];
  6597. $required = empty($val['required']) ? '' : $val['required'];
  6598. $param = array();
  6599. $param['options'] = array();
  6600. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6601. $param['options'] = $val['arrayofkeyval'];
  6602. }
  6603. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6604. $type = 'link';
  6605. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6606. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6607. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6608. $type = 'sellist';
  6609. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6610. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6611. $type = 'sellist';
  6612. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6613. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6614. $type = 'sellist';
  6615. }
  6616. $langfile = empty($val['langfile']) ? '' : $val['langfile'];
  6617. $list = (empty($val['list']) ? '' : $val['list']);
  6618. $help = (empty($val['help']) ? '' : $val['help']);
  6619. $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)
  6620. if ($hidden) {
  6621. return '';
  6622. }
  6623. // If field is a computed field, value must become result of compute
  6624. if ($computed) {
  6625. // Make the eval of compute string
  6626. //var_dump($computed);
  6627. $value = dol_eval($computed, 1, 0, '');
  6628. }
  6629. if (empty($morecss)) {
  6630. if ($type == 'date') {
  6631. $morecss = 'minwidth100imp';
  6632. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6633. $morecss = 'minwidth200imp';
  6634. } elseif (in_array($type, array('int', 'double', 'price'))) {
  6635. $morecss = 'maxwidth75';
  6636. } elseif ($type == 'url') {
  6637. $morecss = 'minwidth400';
  6638. } elseif ($type == 'boolean') {
  6639. $morecss = '';
  6640. } else {
  6641. if (is_numeric($size) && round($size) < 12) {
  6642. $morecss = 'minwidth100';
  6643. } elseif (is_numeric($size) && round($size) <= 48) {
  6644. $morecss = 'minwidth200';
  6645. } else {
  6646. $morecss = 'minwidth400';
  6647. }
  6648. }
  6649. }
  6650. // Format output value differently according to properties of field
  6651. if (in_array($key, array('rowid', 'ref')) && method_exists($this, 'getNomUrl')) {
  6652. if ($key != 'rowid' || empty($this->fields['ref'])) { // If we want ref field or if we want ID and there is no ref field, we show the link.
  6653. $value = $this->getNomUrl(1, '', 0, '', 1);
  6654. }
  6655. } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
  6656. $value = $this->getLibStatut(3);
  6657. } elseif ($type == 'date') {
  6658. if (!empty($value)) {
  6659. $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
  6660. } else {
  6661. $value = '';
  6662. }
  6663. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6664. if (!empty($value)) {
  6665. $value = dol_print_date($value, 'dayhour', 'tzuserrel');
  6666. } else {
  6667. $value = '';
  6668. }
  6669. } elseif ($type == 'duration') {
  6670. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6671. if (!is_null($value) && $value !== '') {
  6672. $value = convertSecondToTime($value, 'allhourmin');
  6673. }
  6674. } elseif ($type == 'double' || $type == 'real') {
  6675. if (!is_null($value) && $value !== '') {
  6676. $value = price($value);
  6677. }
  6678. } elseif ($type == 'boolean') {
  6679. $checked = '';
  6680. if (!empty($value)) {
  6681. $checked = ' checked ';
  6682. }
  6683. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  6684. } elseif ($type == 'mail' || $type == 'email') {
  6685. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  6686. } elseif ($type == 'url') {
  6687. $value = dol_print_url($value, '_blank', 32, 1);
  6688. } elseif ($type == 'phone') {
  6689. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 'phone');
  6690. } elseif ($type == 'price') {
  6691. if (!is_null($value) && $value !== '') {
  6692. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  6693. }
  6694. } elseif ($type == 'select') {
  6695. $value = isset($param['options'][$value])?$param['options'][$value]:'';
  6696. } elseif ($type == 'sellist') {
  6697. $param_list = array_keys($param['options']);
  6698. $InfoFieldList = explode(":", $param_list[0]);
  6699. $selectkey = "rowid";
  6700. $keyList = 'rowid';
  6701. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6702. $selectkey = $InfoFieldList[2];
  6703. $keyList = $InfoFieldList[2].' as rowid';
  6704. }
  6705. $fields_label = explode('|', $InfoFieldList[1]);
  6706. if (is_array($fields_label)) {
  6707. $keyList .= ', ';
  6708. $keyList .= implode(', ', $fields_label);
  6709. }
  6710. $sql = "SELECT ".$keyList;
  6711. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6712. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6713. $sql .= ' as main';
  6714. }
  6715. if ($selectkey == 'rowid' && empty($value)) {
  6716. $sql .= " WHERE ".$selectkey." = 0";
  6717. } elseif ($selectkey == 'rowid') {
  6718. $sql .= " WHERE ".$selectkey." = ".((int) $value);
  6719. } else {
  6720. $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
  6721. }
  6722. //$sql.= ' AND entity = '.$conf->entity;
  6723. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  6724. $resql = $this->db->query($sql);
  6725. if ($resql) {
  6726. $value = ''; // value was used, so now we reste it to use it to build final output
  6727. $numrows = $this->db->num_rows($resql);
  6728. if ($numrows) {
  6729. $obj = $this->db->fetch_object($resql);
  6730. // Several field into label (eq table:code|libelle:rowid)
  6731. $fields_label = explode('|', $InfoFieldList[1]);
  6732. if (is_array($fields_label) && count($fields_label) > 1) {
  6733. foreach ($fields_label as $field_toshow) {
  6734. $translabel = '';
  6735. if (!empty($obj->$field_toshow)) {
  6736. $translabel = $langs->trans($obj->$field_toshow);
  6737. }
  6738. if ($translabel != $field_toshow) {
  6739. $value .= dol_trunc($translabel, 18).' ';
  6740. } else {
  6741. $value .= $obj->$field_toshow.' ';
  6742. }
  6743. }
  6744. } else {
  6745. $translabel = '';
  6746. if (!empty($obj->{$InfoFieldList[1]})) {
  6747. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6748. }
  6749. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6750. $value = dol_trunc($translabel, 18);
  6751. } else {
  6752. $value = $obj->{$InfoFieldList[1]};
  6753. }
  6754. }
  6755. }
  6756. } else {
  6757. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6758. }
  6759. } elseif ($type == 'radio') {
  6760. $value = $param['options'][$value];
  6761. } elseif ($type == 'checkbox') {
  6762. $value_arr = explode(',', $value);
  6763. $value = '';
  6764. if (is_array($value_arr) && count($value_arr) > 0) {
  6765. $toprint = array();
  6766. foreach ($value_arr as $keyval => $valueval) {
  6767. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  6768. }
  6769. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6770. }
  6771. } elseif ($type == 'chkbxlst') {
  6772. $value_arr = explode(',', $value);
  6773. $param_list = array_keys($param['options']);
  6774. $InfoFieldList = explode(":", $param_list[0]);
  6775. $selectkey = "rowid";
  6776. $keyList = 'rowid';
  6777. if (count($InfoFieldList) >= 3) {
  6778. $selectkey = $InfoFieldList[2];
  6779. $keyList = $InfoFieldList[2].' as rowid';
  6780. }
  6781. $fields_label = explode('|', $InfoFieldList[1]);
  6782. if (is_array($fields_label)) {
  6783. $keyList .= ', ';
  6784. $keyList .= implode(', ', $fields_label);
  6785. }
  6786. $sql = "SELECT ".$keyList;
  6787. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6788. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6789. $sql .= ' as main';
  6790. }
  6791. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  6792. // $sql.= ' AND entity = '.$conf->entity;
  6793. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  6794. $resql = $this->db->query($sql);
  6795. if ($resql) {
  6796. $value = ''; // value was used, so now we reste it to use it to build final output
  6797. $toprint = array();
  6798. while ($obj = $this->db->fetch_object($resql)) {
  6799. // Several field into label (eq table:code|libelle:rowid)
  6800. $fields_label = explode('|', $InfoFieldList[1]);
  6801. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6802. if (is_array($fields_label) && count($fields_label) > 1) {
  6803. foreach ($fields_label as $field_toshow) {
  6804. $translabel = '';
  6805. if (!empty($obj->$field_toshow)) {
  6806. $translabel = $langs->trans($obj->$field_toshow);
  6807. }
  6808. if ($translabel != $field_toshow) {
  6809. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6810. } else {
  6811. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->$field_toshow.'</li>';
  6812. }
  6813. }
  6814. } else {
  6815. $translabel = '';
  6816. if (!empty($obj->{$InfoFieldList[1]})) {
  6817. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6818. }
  6819. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6820. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6821. } else {
  6822. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->{$InfoFieldList[1]}.'</li>';
  6823. }
  6824. }
  6825. }
  6826. }
  6827. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6828. } else {
  6829. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6830. }
  6831. } elseif ($type == 'link') {
  6832. $out = '';
  6833. // only if something to display (perf)
  6834. if ($value) {
  6835. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6836. $InfoFieldList = explode(":", $param_list[0]);
  6837. $classname = $InfoFieldList[0];
  6838. $classpath = $InfoFieldList[1];
  6839. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  6840. $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
  6841. if (!empty($classpath)) {
  6842. dol_include_once($InfoFieldList[1]);
  6843. if ($classname && class_exists($classname)) {
  6844. $object = new $classname($this->db);
  6845. if ($object->element === 'product') { // Special cas for product because default valut of fetch are wrong
  6846. $result = $object->fetch($value, '', '', '', 0, 1, 1);
  6847. } else {
  6848. $result = $object->fetch($value);
  6849. }
  6850. if ($result > 0) {
  6851. $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
  6852. } else {
  6853. $value = '';
  6854. }
  6855. }
  6856. } else {
  6857. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  6858. return 'Error bad setup of extrafield';
  6859. }
  6860. } else {
  6861. $value = '';
  6862. }
  6863. } elseif ($type == 'password') {
  6864. $value = preg_replace('/./i', '*', $value);
  6865. } elseif ($type == 'array') {
  6866. $value = implode('<br>', $value);
  6867. } else { // text|html|varchar
  6868. $value = dol_htmlentitiesbr($value);
  6869. }
  6870. //print $type.'-'.$size.'-'.$value;
  6871. $out = $value;
  6872. return $out;
  6873. }
  6874. /**
  6875. * clear validation message result for a field
  6876. *
  6877. * @param string $fieldKey Key of attribute to clear
  6878. * @return null
  6879. */
  6880. public function clearFieldError($fieldKey)
  6881. {
  6882. $this->error = '';
  6883. unset($this->validateFieldsErrors[$fieldKey]);
  6884. }
  6885. /**
  6886. * set validation error message a field
  6887. *
  6888. * @param string $fieldKey Key of attribute
  6889. * @param string $msg the field error message
  6890. * @return null
  6891. */
  6892. public function setFieldError($fieldKey, $msg = '')
  6893. {
  6894. global $langs;
  6895. if (empty($msg)) { $msg = $langs->trans("UnknowError"); }
  6896. $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
  6897. }
  6898. /**
  6899. * get field error message
  6900. *
  6901. * @param string $fieldKey Key of attribute
  6902. * @return string
  6903. */
  6904. public function getFieldError($fieldKey)
  6905. {
  6906. if (!empty($this->validateFieldsErrors[$fieldKey])) {
  6907. return $this->validateFieldsErrors[$fieldKey];
  6908. }
  6909. return '';
  6910. }
  6911. /**
  6912. * Return validation test result for a field
  6913. *
  6914. * @param array $val Array of properties of field to show
  6915. * @param string $fieldKey Key of attribute
  6916. * @param string $fieldValue value of attribute
  6917. * @return bool return false if fail true on success, see $this->error for error message
  6918. */
  6919. public function validateField($val, $fieldKey, $fieldValue)
  6920. {
  6921. global $langs;
  6922. if (!class_exists('Validate')) { require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php'; }
  6923. $this->clearFieldError($fieldKey);
  6924. if (!isset($val[$fieldKey])) {
  6925. $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
  6926. return false;
  6927. }
  6928. $param = array();
  6929. $param['options'] = array();
  6930. $type = $val[$fieldKey]['type'];
  6931. $required = false;
  6932. if (isset($val[$fieldKey]['notnull']) && $val[$fieldKey]['notnull'] === 1) {
  6933. // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  6934. $required = true;
  6935. }
  6936. $maxSize = 0;
  6937. $minSize = 0;
  6938. //
  6939. // PREPARE Elements
  6940. //
  6941. // Convert var to be able to share same code than showOutputField of extrafields
  6942. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6943. $type = 'varchar'; // convert varchar(xx) int varchar
  6944. $maxSize = $reg[1];
  6945. } elseif (preg_match('/varchar/', $type)) {
  6946. $type = 'varchar'; // convert varchar(xx) int varchar
  6947. }
  6948. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6949. $type = 'select';
  6950. }
  6951. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6952. $type = 'link';
  6953. }
  6954. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6955. $param['options'] = $val['arrayofkeyval'];
  6956. }
  6957. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6958. $type = 'link';
  6959. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6960. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6961. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6962. $type = 'sellist';
  6963. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6964. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6965. $type = 'sellist';
  6966. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6967. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6968. $type = 'sellist';
  6969. }
  6970. //
  6971. // TEST Value
  6972. //
  6973. // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
  6974. $validate = new Validate($this->db, $langs);
  6975. // little trick : to perform tests with good performances sort tests by quick to low
  6976. //
  6977. // COMMON TESTS
  6978. //
  6979. // Required test and empty value
  6980. if ($required && !$validate->isNotEmptyString($fieldValue)) {
  6981. $this->setFieldError($fieldKey, $validate->error);
  6982. return false;
  6983. } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
  6984. // if no value sent and the field is not mandatory, no need to perform tests
  6985. return true;
  6986. }
  6987. // MAX Size test
  6988. if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
  6989. $this->setFieldError($fieldKey, $validate->error);
  6990. return false;
  6991. }
  6992. // MIN Size test
  6993. if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
  6994. $this->setFieldError($fieldKey, $validate->error);
  6995. return false;
  6996. }
  6997. //
  6998. // TESTS for TYPE
  6999. //
  7000. if (in_array($type, array('date', 'datetime', 'timestamp'))) {
  7001. if (!$validate->isTimestamp($fieldValue)) {
  7002. $this->setFieldError($fieldKey, $validate->error);
  7003. return false;
  7004. } else { return true; }
  7005. } elseif ($type == 'duration') {
  7006. if (!$validate->isDuration($fieldValue)) {
  7007. $this->setFieldError($fieldKey, $validate->error);
  7008. return false;
  7009. } else { return true; }
  7010. } elseif (in_array($type, array('double', 'real', 'price'))) {
  7011. // is numeric
  7012. if (!$validate->isNumeric($fieldValue)) {
  7013. $this->setFieldError($fieldKey, $validate->error);
  7014. return false;
  7015. } else { return true; }
  7016. } elseif ($type == 'boolean') {
  7017. if (!$validate->isBool($fieldValue)) {
  7018. $this->setFieldError($fieldKey, $validate->error);
  7019. return false;
  7020. } else { return true; }
  7021. } elseif ($type == 'mail') {
  7022. if (!$validate->isEmail($fieldValue)) {
  7023. $this->setFieldError($fieldKey, $validate->error);
  7024. return false;
  7025. }
  7026. } elseif ($type == 'url') {
  7027. if (!$validate->isUrl($fieldValue)) {
  7028. $this->setFieldError($fieldKey, $validate->error);
  7029. return false;
  7030. } else { return true; }
  7031. } elseif ($type == 'phone') {
  7032. if (!$validate->isPhone($fieldValue)) {
  7033. $this->setFieldError($fieldKey, $validate->error);
  7034. return false;
  7035. } else { return true; }
  7036. } elseif ($type == 'select' || $type == 'radio') {
  7037. if (!isset($param['options'][$fieldValue])) {
  7038. $this->error = $langs->trans('RequireValidValue');
  7039. return false;
  7040. } else { return true; }
  7041. } elseif ($type == 'sellist' || $type == 'chkbxlst') {
  7042. $param_list = array_keys($param['options']);
  7043. $InfoFieldList = explode(":", $param_list[0]);
  7044. $value_arr = explode(',', $fieldValue);
  7045. $value_arr = array_map(array($this->db, 'escape'), $value_arr);
  7046. $selectkey = "rowid";
  7047. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  7048. $selectkey = $InfoFieldList[2];
  7049. }
  7050. if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
  7051. $this->setFieldError($fieldKey, $validate->error);
  7052. return false;
  7053. } else { return true; }
  7054. } elseif ($type == 'link') {
  7055. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  7056. $InfoFieldList = explode(":", $param_list[0]);
  7057. $classname = $InfoFieldList[0];
  7058. $classpath = $InfoFieldList[1];
  7059. if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
  7060. $this->setFieldError($fieldKey, $validate->error);
  7061. return false;
  7062. } else { return true; }
  7063. }
  7064. // if no test failled all is ok
  7065. return true;
  7066. }
  7067. /**
  7068. * Function to show lines of extrafields with output datas.
  7069. * 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
  7070. *
  7071. * @param Extrafields $extrafields Extrafield Object
  7072. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  7073. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  7074. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  7075. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  7076. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  7077. * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...)
  7078. * @return string String with html content to show
  7079. */
  7080. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
  7081. {
  7082. global $db, $conf, $langs, $action, $form, $hookmanager;
  7083. if (!is_object($form)) {
  7084. $form = new Form($db);
  7085. }
  7086. if (!is_object($extrafields)) {
  7087. dol_syslog('Bad parameter extrafields for showOptionals', LOG_ERR);
  7088. return 'Bad parameter extrafields for showOptionals';
  7089. }
  7090. if (!is_array($extrafields->attributes[$this->table_element])) {
  7091. dol_syslog("extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
  7092. }
  7093. $out = '';
  7094. $parameters = array();
  7095. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  7096. if (empty($reshook)) {
  7097. if (is_array($extrafields->attributes[$this->table_element]) && key_exists('label', $extrafields->attributes[$this->table_element]) && is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0) {
  7098. $out .= "\n";
  7099. $out .= '<!-- commonobject:showOptionals --> ';
  7100. $out .= "\n";
  7101. $extrafields_collapse_num = '';
  7102. $e = 0;
  7103. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
  7104. // Show only the key field in params
  7105. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
  7106. continue;
  7107. }
  7108. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  7109. $enabled = 1;
  7110. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  7111. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '1');
  7112. }
  7113. if (empty($enabled)) {
  7114. continue;
  7115. }
  7116. $visibility = 1;
  7117. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  7118. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '1');
  7119. }
  7120. $perms = 1;
  7121. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  7122. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '1');
  7123. }
  7124. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
  7125. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  7126. } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
  7127. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  7128. } elseif ($mode == 'view' && empty($visibility)) {
  7129. continue;
  7130. }
  7131. if (empty($perms)) {
  7132. continue;
  7133. }
  7134. // Load language if required
  7135. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  7136. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  7137. }
  7138. $colspan = 0;
  7139. if (is_array($params) && count($params) > 0 && $display_type=='card') {
  7140. if (array_key_exists('cols', $params)) {
  7141. $colspan = $params['cols'];
  7142. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  7143. $reg = array();
  7144. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  7145. $colspan = $reg[1];
  7146. } else {
  7147. $colspan = $params['colspan'];
  7148. }
  7149. }
  7150. }
  7151. $colspan = intval($colspan);
  7152. switch ($mode) {
  7153. case "view":
  7154. $value = ((!empty($this->array_options) && array_key_exists("options_".$key.$keysuffix, $this->array_options)) ? $this->array_options["options_".$key.$keysuffix] : null); // Value may be cleaned or formated later
  7155. break;
  7156. case "create":
  7157. case "edit":
  7158. // We get the value of property found with GETPOST so it takes into account:
  7159. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  7160. $check = 'alphanohtml';
  7161. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  7162. $check = 'restricthtml';
  7163. }
  7164. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  7165. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  7166. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
  7167. if (is_array($getposttemp)) {
  7168. // $getposttemp is an array but following code expects a comma separated string
  7169. $value = implode(",", $getposttemp);
  7170. } else {
  7171. $value = $getposttemp;
  7172. }
  7173. } else {
  7174. $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.
  7175. }
  7176. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  7177. break;
  7178. }
  7179. // Output value of the current field
  7180. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  7181. $extrafields_collapse_num = '';
  7182. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  7183. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  7184. $extrafield_param_list = array_keys($extrafield_param['options']);
  7185. if (count($extrafield_param_list) > 0) {
  7186. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  7187. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  7188. $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  7189. }
  7190. }
  7191. }
  7192. // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
  7193. $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
  7194. } else {
  7195. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  7196. $csstyle = '';
  7197. if (is_array($params) && count($params) > 0) {
  7198. if (array_key_exists('class', $params)) {
  7199. $class .= $params['class'].' ';
  7200. }
  7201. if (array_key_exists('style', $params)) {
  7202. $csstyle = $params['style'];
  7203. }
  7204. }
  7205. // add html5 elements
  7206. $domData = ' data-element="extrafield"';
  7207. $domData .= ' data-targetelement="'.$this->element.'"';
  7208. $domData .= ' data-targetid="'.$this->id.'"';
  7209. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  7210. if ($display_type=='card') {
  7211. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
  7212. $colspan = 0;
  7213. }
  7214. if ($action == 'selectlines') {
  7215. $colspan++;
  7216. }
  7217. }
  7218. // Convert date into timestamp format (value in memory must be a timestamp)
  7219. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
  7220. $datenotinstring = null;
  7221. if (array_key_exists('options_'.$key, $this->array_options)) {
  7222. $datenotinstring = $this->array_options['options_'.$key];
  7223. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7224. $datenotinstring = $this->db->jdate($datenotinstring);
  7225. }
  7226. }
  7227. $datekey = $keyprefix.'options_'.$key.$keysuffix;
  7228. $value = (GETPOSTISSET($datekey)) ? dol_mktime(12, 0, 0, GETPOST($datekey.'month', 'int', 3), GETPOST($datekey.'day', 'int', 3), GETPOST($datekey.'year', 'int', 3)) : $datenotinstring;
  7229. }
  7230. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
  7231. $datenotinstring = null;
  7232. if (array_key_exists('options_'.$key, $this->array_options)) {
  7233. $datenotinstring = $this->array_options['options_'.$key];
  7234. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7235. $datenotinstring = $this->db->jdate($datenotinstring);
  7236. }
  7237. }
  7238. $timekey = $keyprefix.'options_'.$key.$keysuffix;
  7239. $value = (GETPOSTISSET($timekey)) ? dol_mktime(GETPOST($timekey.'hour', 'int', 3), GETPOST($timekey.'min', 'int', 3), GETPOST($timekey.'sec', 'int', 3), GETPOST($timekey.'month', 'int', 3), GETPOST($timekey.'day', 'int', 3), GETPOST($timekey.'year', 'int', 3), 'tzuserrel') : $datenotinstring;
  7240. }
  7241. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  7242. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
  7243. if (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) {
  7244. $value = price2num($value);
  7245. } elseif (isset($this->array_options['options_'.$key])) {
  7246. $value = $this->array_options['options_'.$key];
  7247. }
  7248. }
  7249. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  7250. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int', 'boolean'))) {
  7251. if ($action == 'create') {
  7252. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  7253. }
  7254. }
  7255. $labeltoshow = $langs->trans($label);
  7256. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  7257. if ($display_type == 'card') {
  7258. $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="field_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >';
  7259. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action == 'view' || $action == 'valid' || $action == 'editline' || $action == 'confirm_valid' || $action == 'confirm_cancel')) {
  7260. $out .= '<td></td>';
  7261. }
  7262. $out .= '<td class="titlefieldcreate wordbreak';
  7263. } elseif ($display_type == 'line') {
  7264. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="fieldline_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >';
  7265. $out .= '<div style="display: inline-block; padding-right:4px" class="titlefieldcreate wordbreak';
  7266. }
  7267. //$out .= "titlefield";
  7268. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  7269. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  7270. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  7271. if ($tpl_context != "public") { // Public page : red dot instead of fieldrequired characters
  7272. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7273. $out .= ' fieldrequired';
  7274. }
  7275. }
  7276. $out .= '">';
  7277. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  7278. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7279. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7280. } else {
  7281. $out .= $labeltoshow;
  7282. }
  7283. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7284. $out .= '&nbsp;<span style="color: red">*</span>';
  7285. }
  7286. } else {
  7287. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7288. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7289. } else {
  7290. $out .= $labeltoshow;
  7291. }
  7292. }
  7293. $out .= ($display_type == 'card' ? '</td>' : '</div>');
  7294. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  7295. if ($display_type == 'card') {
  7296. // a first td column was already output (and may be another on before if MAIN_VIEW_LINE_NUMBER set), so this td is the next one
  7297. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="valuefieldcreate '.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  7298. } elseif ($display_type == 'line') {
  7299. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').' style="display: inline-block" class="valuefieldcreate '.$this->element.'_extras_'.$key.' extra_inline_'.$extrafields->attributes[$this->table_element]['type'][$key].'">';
  7300. }
  7301. switch ($mode) {
  7302. case "view":
  7303. $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
  7304. break;
  7305. case "create":
  7306. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7307. break;
  7308. case "edit":
  7309. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7310. break;
  7311. }
  7312. $out .= ($display_type=='card' ? '</td>' : '</div>');
  7313. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
  7314. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7315. } else {
  7316. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7317. }
  7318. $e++;
  7319. }
  7320. }
  7321. $out .= "\n";
  7322. // Add code to manage list depending on others
  7323. if (!empty($conf->use_javascript_ajax)) {
  7324. $out .= $this->getJSListDependancies();
  7325. }
  7326. $out .= '<!-- commonobject:showOptionals end --> '."\n";
  7327. }
  7328. }
  7329. $out .= $hookmanager->resPrint;
  7330. return $out;
  7331. }
  7332. /**
  7333. * @param string $type Type for prefix
  7334. * @return string Javacript code to manage dependency
  7335. */
  7336. public function getJSListDependancies($type = '_extra')
  7337. {
  7338. $out = '
  7339. <script>
  7340. jQuery(document).ready(function() {
  7341. function showOptions'.$type.'(child_list, parent_list, orig_select)
  7342. {
  7343. var val = $("select[name=\""+parent_list+"\"]").val();
  7344. var parentVal = parent_list + ":" + val;
  7345. if(typeof val == "string"){
  7346. if(val != "") {
  7347. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7348. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7349. $("select[name=\""+child_list+"\"]").append(options);
  7350. } else {
  7351. var options = orig_select.find("option[parent]").clone();
  7352. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7353. $("select[name=\""+child_list+"\"]").append(options);
  7354. }
  7355. } else if(val > 0) {
  7356. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7357. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7358. $("select[name=\""+child_list+"\"]").append(options);
  7359. } else {
  7360. var options = orig_select.find("option[parent]").clone();
  7361. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7362. $("select[name=\""+child_list+"\"]").append(options);
  7363. }
  7364. }
  7365. function setListDependencies'.$type.'() {
  7366. jQuery("select option[parent]").parent().each(function() {
  7367. var orig_select = {};
  7368. var child_list = $(this).attr("name");
  7369. orig_select[child_list] = $(this).clone();
  7370. var parent = $(this).find("option[parent]:first").attr("parent");
  7371. var infos = parent.split(":");
  7372. var parent_list = infos[0];
  7373. //Hide daughters lists
  7374. if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
  7375. $("#"+child_list).hide();
  7376. //Show mother lists
  7377. } else if ($("#"+parent_list).val() != 0){
  7378. $("#"+parent_list).show();
  7379. }
  7380. //Show the child list if the parent list value is selected
  7381. $("select[name=\""+parent_list+"\"]").click(function() {
  7382. if ($(this).val() != 0){
  7383. $("#"+child_list).show()
  7384. }
  7385. });
  7386. //When we change parent list
  7387. $("select[name=\""+parent_list+"\"]").change(function() {
  7388. showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
  7389. //Select the value 0 on child list after a change on the parent list
  7390. $("#"+child_list).val(0).trigger("change");
  7391. //Hide child lists if the parent value is set to 0
  7392. if ($(this).val() == 0){
  7393. $("#"+child_list).hide();
  7394. }
  7395. });
  7396. });
  7397. }
  7398. setListDependencies'.$type.'();
  7399. });
  7400. </script>'."\n";
  7401. return $out;
  7402. }
  7403. /**
  7404. * Returns the rights used for this class
  7405. * @return stdClass
  7406. */
  7407. public function getRights()
  7408. {
  7409. global $user;
  7410. $element = $this->element;
  7411. if ($element == 'facturerec') {
  7412. $element = 'facture';
  7413. } elseif ($element == 'invoice_supplier_rec') {
  7414. return $user->rights->fournisseur->facture;
  7415. }
  7416. return $user->rights->{$element};
  7417. }
  7418. /**
  7419. * Function used to replace a thirdparty id with another one.
  7420. * This function is meant to be called from replaceThirdparty with the appropriate tables
  7421. * Column name fk_soc MUST be used to identify thirdparties
  7422. *
  7423. * @param DoliDB $db Database handler
  7424. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  7425. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  7426. * @param string[] $tables Tables that need to be changed
  7427. * @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)
  7428. * @return bool True if success, False if error
  7429. */
  7430. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7431. {
  7432. foreach ($tables as $table) {
  7433. $sql = 'UPDATE '.$db->prefix().$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
  7434. if (!$db->query($sql)) {
  7435. if ($ignoreerrors) {
  7436. return true; // TODO Not enough. If there is A-B on kept thirdparty and B-C on old one, we must get A-B-C after merge. Not A-B.
  7437. }
  7438. //$this->errors = $db->lasterror();
  7439. return false;
  7440. }
  7441. }
  7442. return true;
  7443. }
  7444. /**
  7445. * Function used to replace a product id with another one.
  7446. * This function is meant to be called from replaceProduct with the appropriate tables
  7447. * Column name fk_product MUST be used to identify products
  7448. *
  7449. * @param DoliDB $db Database handler
  7450. * @param int $origin_id Old product id (the product to delete)
  7451. * @param int $dest_id New product id (the product that will received element of the other)
  7452. * @param string[] $tables Tables that need to be changed
  7453. * @param int $ignoreerrors Ignore errors. Return true even if errors. We need this when replacement can fails like for categories (categorie of old product may already exists on new one)
  7454. * @return bool True if success, False if error
  7455. */
  7456. public static function commonReplaceProduct(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7457. {
  7458. foreach ($tables as $table) {
  7459. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_product = '.((int) $dest_id).' WHERE fk_product = '.((int) $origin_id);
  7460. if (!$db->query($sql)) {
  7461. if ($ignoreerrors) {
  7462. return true; // TODO Not enough. If there is A-B on kept product and B-C on old one, we must get A-B-C after merge. Not A-B.
  7463. }
  7464. //$this->errors = $db->lasterror();
  7465. return false;
  7466. }
  7467. }
  7468. return true;
  7469. }
  7470. /**
  7471. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  7472. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  7473. * elseif calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  7474. * elseif calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  7475. * else set min buy price as buy price
  7476. *
  7477. * @param float $unitPrice Product unit price
  7478. * @param float $discountPercent Line discount percent
  7479. * @param int $fk_product Product id
  7480. * @return float <0 if KO, buyprice if OK
  7481. */
  7482. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  7483. {
  7484. global $conf;
  7485. $buyPrice = 0;
  7486. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
  7487. // When ForceBuyingPriceIfNull is set
  7488. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  7489. } else {
  7490. // Get cost price for margin calculation
  7491. if (!empty($fk_product) && $fk_product > 0) {
  7492. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
  7493. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7494. $product = new Product($this->db);
  7495. $result = $product->fetch($fk_product);
  7496. if ($result <= 0) {
  7497. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7498. return -1;
  7499. }
  7500. if ($product->cost_price > 0) {
  7501. $buyPrice = $product->cost_price;
  7502. } elseif ($product->pmp > 0) {
  7503. $buyPrice = $product->pmp;
  7504. }
  7505. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
  7506. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7507. $product = new Product($this->db);
  7508. $result = $product->fetch($fk_product);
  7509. if ($result <= 0) {
  7510. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7511. return -1;
  7512. }
  7513. if ($product->pmp > 0) {
  7514. $buyPrice = $product->pmp;
  7515. }
  7516. }
  7517. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
  7518. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  7519. $productFournisseur = new ProductFournisseur($this->db);
  7520. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
  7521. $buyPrice = $productFournisseur->fourn_unitprice;
  7522. } elseif ($result < 0) {
  7523. $this->errors[] = $productFournisseur->error;
  7524. return -2;
  7525. }
  7526. }
  7527. }
  7528. }
  7529. return $buyPrice;
  7530. }
  7531. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7532. /**
  7533. * Show photos of an object (nbmax maximum), into several columns
  7534. *
  7535. * @param string $modulepart 'product', 'ticket', ...
  7536. * @param string $sdir Directory to scan (full absolute path)
  7537. * @param int $size 0=original size, 1='small' use thumbnail if possible
  7538. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  7539. * @param int $nbbyrow Number of image per line or -1 to use div separator or 0 to use no separator. Used only if size=1 or 'small'.
  7540. * @param int $showfilename 1=Show filename
  7541. * @param int $showaction 1=Show icon with action links (resize, delete)
  7542. * @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.
  7543. * @param int $maxWidth Max width of original image when size='small'
  7544. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  7545. * @param int $notitle Do not add title tag on image
  7546. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  7547. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  7548. */
  7549. 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)
  7550. {
  7551. // phpcs:enable
  7552. global $conf, $user, $langs;
  7553. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7554. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  7555. $sortfield = 'position_name';
  7556. $sortorder = 'asc';
  7557. $dir = $sdir.'/';
  7558. $pdir = '/';
  7559. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7560. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7561. // For backward compatibility
  7562. if ($modulepart == 'product') {
  7563. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  7564. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7565. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7566. }
  7567. }
  7568. // Defined relative dir to DOL_DATA_ROOT
  7569. $relativedir = '';
  7570. if ($dir) {
  7571. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  7572. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  7573. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  7574. }
  7575. $dirthumb = $dir.'thumbs/';
  7576. $pdirthumb = $pdir.'thumbs/';
  7577. $return = '<!-- Photo -->'."\n";
  7578. $nbphoto = 0;
  7579. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  7580. /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
  7581. {
  7582. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  7583. $filearray=array_merge($filearray, $filearrayold);
  7584. }*/
  7585. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  7586. if (count($filearray)) {
  7587. if ($sortfield && $sortorder) {
  7588. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  7589. }
  7590. foreach ($filearray as $key => $val) {
  7591. $photo = '';
  7592. $file = $val['name'];
  7593. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  7594. if (image_format_supported($file) >= 0) {
  7595. $nbphoto++;
  7596. $photo = $file;
  7597. $viewfilename = $file;
  7598. if ($size == 1 || $size == 'small') { // Format vignette
  7599. // Find name of thumb file
  7600. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  7601. if (!dol_is_file($dirthumb.$photo_vignette)) {
  7602. $photo_vignette = '';
  7603. }
  7604. // Get filesize of original file
  7605. $imgarray = dol_getImageSize($dir.$photo);
  7606. if ($nbbyrow > 0) {
  7607. if ($nbphoto == 1) {
  7608. $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  7609. }
  7610. if ($nbphoto % $nbbyrow == 1) {
  7611. $return .= '<tr class="center valignmiddle" style="border: 1px">';
  7612. }
  7613. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
  7614. } elseif ($nbbyrow < 0) {
  7615. $return .= '<div class="inline-block">';
  7616. }
  7617. $return .= "\n";
  7618. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  7619. if (empty($nolink)) {
  7620. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  7621. if ($urladvanced) {
  7622. $return .= '<a href="'.$urladvanced.'">';
  7623. } else {
  7624. $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
  7625. }
  7626. }
  7627. // Show image (width height=$maxHeight)
  7628. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  7629. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  7630. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  7631. if ($notitle) {
  7632. $alt = '';
  7633. }
  7634. $addphotorefcss = 1;
  7635. if ($usesharelink) {
  7636. if ($val['share']) {
  7637. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7638. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  7639. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7640. } else {
  7641. $return .= '<!-- Show original file -->';
  7642. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7643. }
  7644. } else {
  7645. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  7646. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  7647. }
  7648. } else {
  7649. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7650. $return .= '<!-- Show thumb -->';
  7651. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').' maxwidth150onsmartphone maxwidth200" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdirthumb.$photo_vignette).'" title="'.dol_escape_htmltag($alt).'">';
  7652. } else {
  7653. $return .= '<!-- Show original file -->';
  7654. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" title="'.dol_escape_htmltag($alt).'">';
  7655. }
  7656. }
  7657. if (empty($nolink)) {
  7658. $return .= '</a>';
  7659. }
  7660. $return .= "\n";
  7661. if ($showfilename) {
  7662. $return .= '<br>'.$viewfilename;
  7663. }
  7664. if ($showaction) {
  7665. $return .= '<br>';
  7666. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  7667. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
  7668. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=addthumb&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'), 'refresh').'&nbsp;&nbsp;</a>';
  7669. }
  7670. // Special cas for product
  7671. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7672. // Link to resize
  7673. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  7674. // Link to delete
  7675. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7676. $return .= img_delete().'</a>';
  7677. }
  7678. }
  7679. $return .= "\n";
  7680. if ($nbbyrow > 0) {
  7681. $return .= '</td>';
  7682. if (($nbphoto % $nbbyrow) == 0) {
  7683. $return .= '</tr>';
  7684. }
  7685. } elseif ($nbbyrow < 0) {
  7686. $return .= '</div>';
  7687. }
  7688. }
  7689. if (empty($size)) { // Format origine
  7690. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  7691. if ($showfilename) {
  7692. $return .= '<br>'.$viewfilename;
  7693. }
  7694. if ($showaction) {
  7695. // Special case for product
  7696. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7697. // Link to resize
  7698. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  7699. // Link to delete
  7700. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7701. $return .= img_delete().'</a>';
  7702. }
  7703. }
  7704. }
  7705. // On continue ou on arrete de boucler ?
  7706. if ($nbmax && $nbphoto >= $nbmax) {
  7707. break;
  7708. }
  7709. }
  7710. }
  7711. if ($size == 1 || $size == 'small') {
  7712. if ($nbbyrow > 0) {
  7713. // Ferme tableau
  7714. while ($nbphoto % $nbbyrow) {
  7715. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  7716. $nbphoto++;
  7717. }
  7718. if ($nbphoto) {
  7719. $return .= '</table>';
  7720. }
  7721. }
  7722. }
  7723. }
  7724. $this->nbphoto = $nbphoto;
  7725. return $return;
  7726. }
  7727. /**
  7728. * Function test if type is array
  7729. *
  7730. * @param array $info content informations of field
  7731. * @return bool true if array
  7732. */
  7733. protected function isArray($info)
  7734. {
  7735. if (is_array($info)) {
  7736. if (isset($info['type']) && $info['type'] == 'array') {
  7737. return true;
  7738. } else {
  7739. return false;
  7740. }
  7741. }
  7742. return false;
  7743. }
  7744. /**
  7745. * Function test if type is date
  7746. *
  7747. * @param array $info content informations of field
  7748. * @return bool true if date
  7749. */
  7750. public function isDate($info)
  7751. {
  7752. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
  7753. return true;
  7754. }
  7755. return false;
  7756. }
  7757. /**
  7758. * Function test if type is duration
  7759. *
  7760. * @param array $info content informations of field
  7761. * @return bool true if field of type duration
  7762. */
  7763. public function isDuration($info)
  7764. {
  7765. if (is_array($info)) {
  7766. if (isset($info['type']) && ($info['type'] == 'duration')) {
  7767. return true;
  7768. } else {
  7769. return false;
  7770. }
  7771. } else {
  7772. return false;
  7773. }
  7774. }
  7775. /**
  7776. * Function test if type is integer
  7777. *
  7778. * @param array $info content informations of field
  7779. * @return bool true if integer
  7780. */
  7781. public function isInt($info)
  7782. {
  7783. if (is_array($info)) {
  7784. if (isset($info['type']) && (preg_match('/(^int|int$)/i', $info['type']))) {
  7785. return true;
  7786. } else {
  7787. return false;
  7788. }
  7789. } else {
  7790. return false;
  7791. }
  7792. }
  7793. /**
  7794. * Function test if type is float
  7795. *
  7796. * @param array $info content informations of field
  7797. * @return bool true if float
  7798. */
  7799. public function isFloat($info)
  7800. {
  7801. if (is_array($info)) {
  7802. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
  7803. return true;
  7804. } else {
  7805. return false;
  7806. }
  7807. }
  7808. return false;
  7809. }
  7810. /**
  7811. * Function test if type is text
  7812. *
  7813. * @param array $info content informations of field
  7814. * @return bool true if type text
  7815. */
  7816. public function isText($info)
  7817. {
  7818. if (is_array($info)) {
  7819. if (isset($info['type']) && $info['type'] == 'text') {
  7820. return true;
  7821. } else {
  7822. return false;
  7823. }
  7824. }
  7825. return false;
  7826. }
  7827. /**
  7828. * Function test if field can be null
  7829. *
  7830. * @param array $info content informations of field
  7831. * @return bool true if it can be null
  7832. */
  7833. protected function canBeNull($info)
  7834. {
  7835. if (is_array($info)) {
  7836. if (isset($info['notnull']) && $info['notnull'] != '1') {
  7837. return true;
  7838. } else {
  7839. return false;
  7840. }
  7841. }
  7842. return true;
  7843. }
  7844. /**
  7845. * Function test if field is forced to null if zero or empty
  7846. *
  7847. * @param array $info content informations of field
  7848. * @return bool true if forced to null
  7849. */
  7850. protected function isForcedToNullIfZero($info)
  7851. {
  7852. if (is_array($info)) {
  7853. if (isset($info['notnull']) && $info['notnull'] == '-1') {
  7854. return true;
  7855. } else {
  7856. return false;
  7857. }
  7858. }
  7859. return false;
  7860. }
  7861. /**
  7862. * Function test if is indexed
  7863. *
  7864. * @param array $info content informations of field
  7865. * @return bool
  7866. */
  7867. protected function isIndex($info)
  7868. {
  7869. if (is_array($info)) {
  7870. if (isset($info['index']) && $info['index'] == true) {
  7871. return true;
  7872. } else {
  7873. return false;
  7874. }
  7875. }
  7876. return false;
  7877. }
  7878. /**
  7879. * Function to prepare a part of the query for insert.
  7880. * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
  7881. * $this->${field} should be a clean value. The page can run
  7882. *
  7883. * @return array
  7884. */
  7885. protected function setSaveQuery()
  7886. {
  7887. global $conf;
  7888. $queryarray = array();
  7889. foreach ($this->fields as $field => $info) { // Loop on definition of fields
  7890. // Depending on field type ('datetime', ...)
  7891. if ($this->isDate($info)) {
  7892. if (empty($this->{$field})) {
  7893. $queryarray[$field] = null;
  7894. } else {
  7895. $queryarray[$field] = $this->db->idate($this->{$field});
  7896. }
  7897. } elseif ($this->isDuration($info)) {
  7898. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7899. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7900. if (!isset($this->{$field})) {
  7901. if (!empty($info['default'])) {
  7902. $queryarray[$field] = $info['default'];
  7903. } else {
  7904. $queryarray[$field] = 0;
  7905. }
  7906. } else {
  7907. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7908. }
  7909. } else {
  7910. $queryarray[$field] = null;
  7911. }
  7912. } elseif ($this->isInt($info) || $this->isFloat($info)) {
  7913. if ($field == 'entity' && is_null($this->{$field})) {
  7914. $queryarray[$field] = $conf->entity;
  7915. } else {
  7916. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7917. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7918. if (!isset($this->{$field})) {
  7919. $queryarray[$field] = 0;
  7920. } elseif ($this->isInt($info)) {
  7921. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7922. } elseif ($this->isFloat($info)) {
  7923. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7924. }
  7925. } else {
  7926. $queryarray[$field] = null;
  7927. }
  7928. }
  7929. } else {
  7930. // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
  7931. // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
  7932. $queryarray[$field] = $this->{$field};
  7933. }
  7934. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
  7935. unset($queryarray[$field]);
  7936. }
  7937. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
  7938. $queryarray[$field] = null; // May force 0 to null
  7939. }
  7940. }
  7941. return $queryarray;
  7942. }
  7943. /**
  7944. * Function to load data from a SQL pointer into properties of current object $this
  7945. *
  7946. * @param stdClass $obj Contain data of object from database
  7947. * @return void
  7948. */
  7949. public function setVarsFromFetchObj(&$obj)
  7950. {
  7951. global $db;
  7952. foreach ($this->fields as $field => $info) {
  7953. if ($this->isDate($info)) {
  7954. if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
  7955. $this->{$field} = '';
  7956. } else {
  7957. $this->{$field} = $db->jdate($obj->{$field});
  7958. }
  7959. } elseif ($this->isInt($info)) {
  7960. if ($field == 'rowid') {
  7961. $this->id = (int) $obj->{$field};
  7962. } else {
  7963. if ($this->isForcedToNullIfZero($info)) {
  7964. if (empty($obj->{$field})) {
  7965. $this->{$field} = null;
  7966. } else {
  7967. $this->{$field} = (double) $obj->{$field};
  7968. }
  7969. } else {
  7970. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7971. $this->{$field} = (int) $obj->{$field};
  7972. } else {
  7973. $this->{$field} = null;
  7974. }
  7975. }
  7976. }
  7977. } elseif ($this->isFloat($info)) {
  7978. if ($this->isForcedToNullIfZero($info)) {
  7979. if (empty($obj->{$field})) {
  7980. $this->{$field} = null;
  7981. } else {
  7982. $this->{$field} = (double) $obj->{$field};
  7983. }
  7984. } else {
  7985. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7986. $this->{$field} = (double) $obj->{$field};
  7987. } else {
  7988. $this->{$field} = null;
  7989. }
  7990. }
  7991. } else {
  7992. $this->{$field} = isset($obj->{$field}) ? $obj->{$field} : null;
  7993. }
  7994. }
  7995. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  7996. if (!isset($this->fields['ref']) && isset($this->id)) {
  7997. $this->ref = $this->id;
  7998. }
  7999. }
  8000. /**
  8001. * Function to concat keys of fields
  8002. *
  8003. * @param string $alias String of alias of table for fields. For example 't'.
  8004. * @return string list of alias fields
  8005. */
  8006. public function getFieldList($alias = '')
  8007. {
  8008. $keys = array_keys($this->fields);
  8009. if (!empty($alias)) {
  8010. $keys_with_alias = array();
  8011. foreach ($keys as $fieldname) {
  8012. $keys_with_alias[] = $alias . '.' . $fieldname;
  8013. }
  8014. return implode(',', $keys_with_alias);
  8015. } else {
  8016. return implode(',', $keys);
  8017. }
  8018. }
  8019. /**
  8020. * Add quote to field value if necessary
  8021. *
  8022. * @param string|int $value Value to protect
  8023. * @param array $fieldsentry Properties of field
  8024. * @return string
  8025. */
  8026. protected function quote($value, $fieldsentry)
  8027. {
  8028. if (is_null($value)) {
  8029. return 'NULL';
  8030. } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
  8031. return price2num("$value");
  8032. } elseif (preg_match('/int$/i', $fieldsentry['type'])) {
  8033. return (int) $value;
  8034. } elseif ($fieldsentry['type'] == 'boolean') {
  8035. if ($value) {
  8036. return 'true';
  8037. } else {
  8038. return 'false';
  8039. }
  8040. } else {
  8041. return "'".$this->db->escape($value)."'";
  8042. }
  8043. }
  8044. /**
  8045. * Create object into database
  8046. *
  8047. * @param User $user User that creates
  8048. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8049. * @return int <0 if KO, Id of created object if OK
  8050. */
  8051. public function createCommon(User $user, $notrigger = false)
  8052. {
  8053. global $langs;
  8054. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  8055. $error = 0;
  8056. $now = dol_now();
  8057. $fieldvalues = $this->setSaveQuery();
  8058. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
  8059. $fieldvalues['date_creation'] = $this->db->idate($now);
  8060. }
  8061. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
  8062. $fieldvalues['fk_user_creat'] = $user->id;
  8063. }
  8064. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  8065. if (array_key_exists('ref', $fieldvalues)) {
  8066. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8067. }
  8068. $keys = array();
  8069. $values = array(); // Array to store string forged for SQL syntax
  8070. foreach ($fieldvalues as $k => $v) {
  8071. $keys[$k] = $k;
  8072. $value = $this->fields[$k];
  8073. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  8074. }
  8075. // Clean and check mandatory
  8076. foreach ($keys as $key) {
  8077. // If field is an implicit foreign key field (so type = 'integer:...')
  8078. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8079. $values[$key] = '';
  8080. }
  8081. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8082. $values[$key] = '';
  8083. }
  8084. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
  8085. $error++;
  8086. $langs->load("errors");
  8087. dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
  8088. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8089. }
  8090. // If value is null and there is a default value for field
  8091. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
  8092. $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
  8093. }
  8094. // If field is an implicit foreign key field (so type = 'integer:...')
  8095. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  8096. if (isset($this->fields[$key]['default'])) {
  8097. $values[$key] = ((int) $this->fields[$key]['default']);
  8098. } else {
  8099. $values[$key] = 'null';
  8100. }
  8101. }
  8102. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
  8103. $values[$key] = 'null';
  8104. }
  8105. }
  8106. if ($error) {
  8107. return -1;
  8108. }
  8109. $this->db->begin();
  8110. if (!$error) {
  8111. $sql = "INSERT INTO ".$this->db->prefix().$this->table_element;
  8112. $sql .= " (".implode(", ", $keys).')';
  8113. $sql .= " VALUES (".implode(", ", $values).")"; // $values can contains 'abc' or 123
  8114. $res = $this->db->query($sql);
  8115. if (!$res) {
  8116. $error++;
  8117. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  8118. $this->errors[] = "ErrorRefAlreadyExists";
  8119. } else {
  8120. $this->errors[] = $this->db->lasterror();
  8121. }
  8122. }
  8123. }
  8124. if (!$error) {
  8125. $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
  8126. }
  8127. // If we have a field ref with a default value of (PROV)
  8128. if (!$error) {
  8129. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
  8130. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
  8131. $resqlupdate = $this->db->query($sql);
  8132. if ($resqlupdate === false) {
  8133. $error++;
  8134. $this->errors[] = $this->db->lasterror();
  8135. } else {
  8136. $this->ref = '(PROV'.$this->id.')';
  8137. }
  8138. }
  8139. }
  8140. // Create extrafields
  8141. if (!$error) {
  8142. $result = $this->insertExtraFields();
  8143. if ($result < 0) {
  8144. $error++;
  8145. }
  8146. }
  8147. // Create lines
  8148. if (!empty($this->table_element_line) && !empty($this->fk_element)) {
  8149. $num = (is_array($this->lines) ? count($this->lines) : 0);
  8150. for ($i = 0; $i < $num; $i++) {
  8151. $line = $this->lines[$i];
  8152. $keyforparent = $this->fk_element;
  8153. $line->$keyforparent = $this->id;
  8154. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  8155. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  8156. if (!is_object($line)) {
  8157. $line = (object) $line;
  8158. }
  8159. $result = $line->create($user, 1);
  8160. if ($result < 0) {
  8161. $this->error = $line->error;
  8162. $this->db->rollback();
  8163. return -1;
  8164. }
  8165. }
  8166. }
  8167. // Triggers
  8168. if (!$error && !$notrigger) {
  8169. // Call triggers
  8170. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  8171. if ($result < 0) {
  8172. $error++;
  8173. }
  8174. // End call triggers
  8175. }
  8176. // Commit or rollback
  8177. if ($error) {
  8178. $this->db->rollback();
  8179. return -1;
  8180. } else {
  8181. $this->db->commit();
  8182. return $this->id;
  8183. }
  8184. }
  8185. /**
  8186. * Load object in memory from the database
  8187. *
  8188. * @param int $id Id object
  8189. * @param string $ref Ref
  8190. * @param string $morewhere More SQL filters (' AND ...')
  8191. * @return int <0 if KO, 0 if not found, >0 if OK
  8192. */
  8193. public function fetchCommon($id, $ref = null, $morewhere = '')
  8194. {
  8195. if (empty($id) && empty($ref) && empty($morewhere)) {
  8196. return -1;
  8197. }
  8198. $fieldlist = $this->getFieldList('t');
  8199. if (empty($fieldlist)) {
  8200. return 0;
  8201. }
  8202. $sql = "SELECT ".$fieldlist;
  8203. $sql .= " FROM ".$this->db->prefix().$this->table_element.' as t';
  8204. if (!empty($id)) {
  8205. $sql .= ' WHERE t.rowid = '.((int) $id);
  8206. } elseif (!empty($ref)) {
  8207. $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
  8208. } else {
  8209. $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  8210. }
  8211. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  8212. $sql .= ' AND t.entity IN ('.getEntity($this->table_element).')';
  8213. }
  8214. if ($morewhere) {
  8215. $sql .= $morewhere;
  8216. }
  8217. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  8218. $res = $this->db->query($sql);
  8219. if ($res) {
  8220. $obj = $this->db->fetch_object($res);
  8221. if ($obj) {
  8222. $this->setVarsFromFetchObj($obj);
  8223. // Retrieve all extrafield
  8224. // fetch optionals attributes and labels
  8225. $this->fetch_optionals();
  8226. return $this->id;
  8227. } else {
  8228. return 0;
  8229. }
  8230. } else {
  8231. $this->error = $this->db->lasterror();
  8232. $this->errors[] = $this->error;
  8233. return -1;
  8234. }
  8235. }
  8236. /**
  8237. * Load object in memory from the database
  8238. *
  8239. * @param string $morewhere More SQL filters (' AND ...')
  8240. * @return int <0 if KO, 0 if not found, >0 if OK
  8241. */
  8242. public function fetchLinesCommon($morewhere = '')
  8243. {
  8244. $objectlineclassname = get_class($this).'Line';
  8245. if (!class_exists($objectlineclassname)) {
  8246. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  8247. return -1;
  8248. }
  8249. $objectline = new $objectlineclassname($this->db);
  8250. $sql = "SELECT ".$objectline->getFieldList('l');
  8251. $sql .= " FROM ".$this->db->prefix().$objectline->table_element." as l";
  8252. $sql .= " WHERE l.fk_".$this->db->escape($this->element)." = ".((int) $this->id);
  8253. if ($morewhere) {
  8254. $sql .= $morewhere;
  8255. }
  8256. if (isset($objectline->fields['position'])) {
  8257. $sql .= $this->db->order('position', 'ASC');
  8258. }
  8259. $resql = $this->db->query($sql);
  8260. if ($resql) {
  8261. $num_rows = $this->db->num_rows($resql);
  8262. $i = 0;
  8263. while ($i < $num_rows) {
  8264. $obj = $this->db->fetch_object($resql);
  8265. if ($obj) {
  8266. $newline = new $objectlineclassname($this->db);
  8267. $newline->setVarsFromFetchObj($obj);
  8268. $this->lines[] = $newline;
  8269. }
  8270. $i++;
  8271. }
  8272. return 1;
  8273. } else {
  8274. $this->error = $this->db->lasterror();
  8275. $this->errors[] = $this->error;
  8276. return -1;
  8277. }
  8278. }
  8279. /**
  8280. * Update object into database
  8281. *
  8282. * @param User $user User that modifies
  8283. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8284. * @return int <0 if KO, >0 if OK
  8285. */
  8286. public function updateCommon(User $user, $notrigger = false)
  8287. {
  8288. global $conf, $langs;
  8289. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  8290. $error = 0;
  8291. $now = dol_now();
  8292. $fieldvalues = $this->setSaveQuery();
  8293. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
  8294. $fieldvalues['date_modification'] = $this->db->idate($now);
  8295. }
  8296. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
  8297. $fieldvalues['fk_user_modif'] = $user->id;
  8298. }
  8299. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  8300. if (array_key_exists('ref', $fieldvalues)) {
  8301. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8302. }
  8303. // Add quotes and escape on fields with type string
  8304. $keys = array();
  8305. $values = array();
  8306. $tmp = array();
  8307. foreach ($fieldvalues as $k => $v) {
  8308. $keys[$k] = $k;
  8309. $value = $this->fields[$k];
  8310. $values[$k] = $this->quote($v, $value);
  8311. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  8312. }
  8313. // Clean and check mandatory fields
  8314. foreach ($keys as $key) {
  8315. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8316. $values[$key] = ''; // This is an implicit foreign key field
  8317. }
  8318. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8319. $values[$key] = ''; // This is an explicit foreign key field
  8320. }
  8321. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  8322. /*
  8323. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  8324. {
  8325. $error++;
  8326. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8327. }*/
  8328. }
  8329. $sql = 'UPDATE '.$this->db->prefix().$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
  8330. $this->db->begin();
  8331. if (!$error) {
  8332. $res = $this->db->query($sql);
  8333. if (!$res) {
  8334. $error++;
  8335. $this->errors[] = $this->db->lasterror();
  8336. }
  8337. }
  8338. // Update extrafield
  8339. if (!$error) {
  8340. $result = $this->insertExtraFields();
  8341. if ($result < 0) {
  8342. $error++;
  8343. }
  8344. }
  8345. // Triggers
  8346. if (!$error && !$notrigger) {
  8347. // Call triggers
  8348. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  8349. if ($result < 0) {
  8350. $error++;
  8351. } //Do also here what you must do to rollback action if trigger fail
  8352. // End call triggers
  8353. }
  8354. // Commit or rollback
  8355. if ($error) {
  8356. $this->db->rollback();
  8357. return -1;
  8358. } else {
  8359. $this->db->commit();
  8360. return $this->id;
  8361. }
  8362. }
  8363. /**
  8364. * Delete object in database
  8365. *
  8366. * @param User $user User that deletes
  8367. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8368. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  8369. * @return int <=0 if KO, 0=Nothing done because object has child, >0 if OK
  8370. */
  8371. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  8372. {
  8373. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  8374. $error = 0;
  8375. $this->db->begin();
  8376. if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
  8377. foreach ($this->childtables as $table) {
  8378. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8379. $resql = $this->db->query($sql);
  8380. if (!$resql) {
  8381. $this->error = $this->db->lasterror();
  8382. $this->errors[] = $this->error;
  8383. $this->db->rollback();
  8384. return -1;
  8385. }
  8386. }
  8387. } elseif (!empty($this->fk_element) && !empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
  8388. $objectisused = $this->isObjectUsed($this->id);
  8389. if (!empty($objectisused)) {
  8390. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  8391. $this->error = 'ErrorRecordHasChildren';
  8392. $this->errors[] = $this->error;
  8393. $this->db->rollback();
  8394. return 0;
  8395. }
  8396. }
  8397. // Delete cascade first
  8398. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  8399. foreach ($this->childtablesoncascade as $table) {
  8400. $deleteFromObject = explode(':', $table);
  8401. if (count($deleteFromObject) >= 2) {
  8402. $className = str_replace('@', '', $deleteFromObject[0]);
  8403. $filePath = $deleteFromObject[1];
  8404. $columnName = $deleteFromObject[2];
  8405. $TMoreSQL = array();
  8406. $more_sql = $deleteFromObject[3];
  8407. if (!empty($more_sql)) {
  8408. $TMoreSQL['customsql'] = $more_sql;
  8409. }
  8410. if (dol_include_once($filePath)) {
  8411. $childObject = new $className($this->db);
  8412. if (method_exists($childObject, 'deleteByParentField')) {
  8413. $result = $childObject->deleteByParentField($this->id, $columnName, $TMoreSQL);
  8414. if ($result < 0) {
  8415. $error++;
  8416. $this->errors[] = $childObject->error;
  8417. break;
  8418. }
  8419. } else {
  8420. $error++;
  8421. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  8422. break;
  8423. }
  8424. } else {
  8425. $error++;
  8426. $this->errors[] = 'Cannot include child class file '.$filePath;
  8427. break;
  8428. }
  8429. } else {
  8430. // Delete record in child table
  8431. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8432. $resql = $this->db->query($sql);
  8433. if (!$resql) {
  8434. $error++;
  8435. $this->error = $this->db->lasterror();
  8436. $this->errors[] = $this->error;
  8437. break;
  8438. }
  8439. }
  8440. }
  8441. }
  8442. if (!$error) {
  8443. if (!$notrigger) {
  8444. // Call triggers
  8445. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  8446. if ($result < 0) {
  8447. $error++;
  8448. } // Do also here what you must do to rollback action if trigger fail
  8449. // End call triggers
  8450. }
  8451. }
  8452. // Delete llx_ecm_files
  8453. if (!$error) {
  8454. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  8455. if (!$res) {
  8456. $error++;
  8457. }
  8458. }
  8459. // Delete linked object
  8460. $res = $this->deleteObjectLinked();
  8461. if ($res < 0) {
  8462. $error++;
  8463. }
  8464. if (!$error && !empty($this->isextrafieldmanaged)) {
  8465. $result = $this->deleteExtraFields();
  8466. if ($result < 0) {
  8467. $error++;
  8468. }
  8469. }
  8470. if (!$error) {
  8471. $sql = 'DELETE FROM '.$this->db->prefix().$this->table_element.' WHERE rowid='.((int) $this->id);
  8472. $resql = $this->db->query($sql);
  8473. if (!$resql) {
  8474. $error++;
  8475. $this->errors[] = $this->db->lasterror();
  8476. }
  8477. }
  8478. // Commit or rollback
  8479. if ($error) {
  8480. $this->db->rollback();
  8481. return -1;
  8482. } else {
  8483. $this->db->commit();
  8484. return 1;
  8485. }
  8486. }
  8487. /**
  8488. * Delete all child object from a parent ID
  8489. *
  8490. * @param int $parentId Parent Id
  8491. * @param string $parentField Name of Foreign key parent column
  8492. * @param array $filter an array filter
  8493. * @param string $filtermode AND or OR
  8494. * @return int <0 if KO, >0 if OK
  8495. * @throws Exception
  8496. */
  8497. public function deleteByParentField($parentId = 0, $parentField = '', $filter = array(), $filtermode = "AND")
  8498. {
  8499. global $user;
  8500. $error = 0;
  8501. $deleted = 0;
  8502. if (!empty($parentId) && !empty($parentField)) {
  8503. $this->db->begin();
  8504. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
  8505. $sql .= " WHERE ".$parentField." = ".(int) $parentId;
  8506. // Manage filters
  8507. $sqlwhere = array();
  8508. if (count($filter) > 0) {
  8509. foreach ($filter as $key => $value) {
  8510. if ($key == 'customsql') {
  8511. $sqlwhere[] = $value;
  8512. } elseif (strpos($value, '%') === false) {
  8513. $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
  8514. } else {
  8515. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  8516. }
  8517. }
  8518. }
  8519. if (count($sqlwhere) > 0) {
  8520. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  8521. }
  8522. $resql = $this->db->query($sql);
  8523. if (!$resql) {
  8524. $this->errors[] = $this->db->lasterror();
  8525. $error++;
  8526. } else {
  8527. while ($obj = $this->db->fetch_object($resql)) {
  8528. $result = $this->fetch($obj->rowid);
  8529. if ($result < 0) {
  8530. $error++;
  8531. $this->errors[] = $this->error;
  8532. } else {
  8533. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  8534. $result = $this->delete();
  8535. } else {
  8536. $result = $this->delete($user);
  8537. }
  8538. if ($result < 0) {
  8539. $error++;
  8540. $this->errors[] = $this->error;
  8541. } else {
  8542. $deleted++;
  8543. }
  8544. }
  8545. }
  8546. }
  8547. if (empty($error)) {
  8548. $this->db->commit();
  8549. return $deleted;
  8550. } else {
  8551. $this->error = implode(', ', $this->errors);
  8552. $this->db->rollback();
  8553. return $error * -1;
  8554. }
  8555. }
  8556. return $deleted;
  8557. }
  8558. /**
  8559. * Delete a line of object in database
  8560. *
  8561. * @param User $user User that delete
  8562. * @param int $idline Id of line to delete
  8563. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8564. * @return int >0 if OK, <0 if KO
  8565. */
  8566. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  8567. {
  8568. global $conf;
  8569. $error = 0;
  8570. $tmpforobjectclass = get_class($this);
  8571. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  8572. // Call trigger
  8573. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  8574. if ($result < 0) {
  8575. return -1;
  8576. }
  8577. // End call triggers
  8578. $this->db->begin();
  8579. $sql = "DELETE FROM ".$this->db->prefix().$this->table_element_line;
  8580. $sql .= " WHERE rowid = ".((int) $idline);
  8581. dol_syslog(get_class($this)."::deleteLineCommon", LOG_DEBUG);
  8582. $resql = $this->db->query($sql);
  8583. if (!$resql) {
  8584. $this->error = "Error ".$this->db->lasterror();
  8585. $error++;
  8586. }
  8587. if (empty($error)) {
  8588. // Remove extrafields
  8589. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  8590. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  8591. $tmpobjectline->id = $idline;
  8592. $result = $tmpobjectline->deleteExtraFields();
  8593. if ($result < 0) {
  8594. $error++;
  8595. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  8596. }
  8597. }
  8598. }
  8599. if (empty($error)) {
  8600. $this->db->commit();
  8601. return 1;
  8602. } else {
  8603. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  8604. $this->db->rollback();
  8605. return -1;
  8606. }
  8607. }
  8608. /**
  8609. * Set to a status
  8610. *
  8611. * @param User $user Object user that modify
  8612. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  8613. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  8614. * @param string $triggercode Trigger code to use
  8615. * @return int <0 if KO, >0 if OK
  8616. */
  8617. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  8618. {
  8619. $error = 0;
  8620. $this->db->begin();
  8621. $statusfield = 'status';
  8622. if ($this->element == 'don' || $this->element == 'donation') {
  8623. $statusfield = 'fk_statut';
  8624. }
  8625. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  8626. $sql .= " SET ".$statusfield." = ".((int) $status);
  8627. $sql .= " WHERE rowid = ".((int) $this->id);
  8628. if ($this->db->query($sql)) {
  8629. if (!$error) {
  8630. $this->oldcopy = clone $this;
  8631. }
  8632. if (!$error && !$notrigger) {
  8633. // Call trigger
  8634. $result = $this->call_trigger($triggercode, $user);
  8635. if ($result < 0) {
  8636. $error++;
  8637. }
  8638. }
  8639. if (!$error) {
  8640. $this->status = $status;
  8641. $this->db->commit();
  8642. return 1;
  8643. } else {
  8644. $this->db->rollback();
  8645. return -1;
  8646. }
  8647. } else {
  8648. $this->error = $this->db->error();
  8649. $this->db->rollback();
  8650. return -1;
  8651. }
  8652. }
  8653. /**
  8654. * Initialise object with example values
  8655. * Id must be 0 if object instance is a specimen
  8656. *
  8657. * @return int
  8658. */
  8659. public function initAsSpecimenCommon()
  8660. {
  8661. global $user;
  8662. $this->id = 0;
  8663. $this->specimen = 1;
  8664. $fields = array(
  8665. 'label' => 'This is label',
  8666. 'ref' => 'ABCD1234',
  8667. 'description' => 'This is a description',
  8668. 'qty' => 123.12,
  8669. 'note_public' => 'Public note',
  8670. 'note_private' => 'Private note',
  8671. 'date_creation' => (dol_now() - 3600 * 48),
  8672. 'date_modification' => (dol_now() - 3600 * 24),
  8673. 'fk_user_creat' => $user->id,
  8674. 'fk_user_modif' => $user->id,
  8675. 'date' => dol_now(),
  8676. );
  8677. foreach ($fields as $key => $value) {
  8678. if (array_key_exists($key, $this->fields)) {
  8679. $this->{$key} = $value;
  8680. }
  8681. }
  8682. return 1;
  8683. }
  8684. /* Part for comments */
  8685. /**
  8686. * Load comments linked with current task
  8687. * @return boolean 1 if ok
  8688. */
  8689. public function fetchComments()
  8690. {
  8691. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  8692. $comment = new Comment($this->db);
  8693. $result = $comment->fetchAllFor($this->element, $this->id);
  8694. if ($result < 0) {
  8695. $this->errors = array_merge($this->errors, $comment->errors);
  8696. return -1;
  8697. } else {
  8698. $this->comments = $comment->comments;
  8699. }
  8700. return count($this->comments);
  8701. }
  8702. /**
  8703. * Return nb comments already posted
  8704. *
  8705. * @return int
  8706. */
  8707. public function getNbComments()
  8708. {
  8709. return count($this->comments);
  8710. }
  8711. /**
  8712. * Trim object parameters
  8713. *
  8714. * @param string[] $parameters array of parameters to trim
  8715. * @return void
  8716. */
  8717. public function trimParameters($parameters)
  8718. {
  8719. if (!is_array($parameters)) {
  8720. return;
  8721. }
  8722. foreach ($parameters as $parameter) {
  8723. if (isset($this->$parameter)) {
  8724. $this->$parameter = trim($this->$parameter);
  8725. }
  8726. }
  8727. }
  8728. /* Part for categories/tags */
  8729. /**
  8730. * Sets object to given categories.
  8731. *
  8732. * Deletes object from existing categories not supplied.
  8733. * Adds it to non existing supplied categories.
  8734. * Existing categories are left untouch.
  8735. *
  8736. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  8737. * @return int Array of category objects or < 0 if KO
  8738. */
  8739. public function getCategoriesCommon($type_categ)
  8740. {
  8741. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8742. // Get current categories
  8743. $c = new Categorie($this->db);
  8744. $existing = $c->containing($this->id, $type_categ, 'id');
  8745. return $existing;
  8746. }
  8747. /**
  8748. * Sets object to given categories.
  8749. *
  8750. * Adds it to non existing supplied categories.
  8751. * Deletes object from existing categories not supplied (if remove_existing==true).
  8752. * Existing categories are left untouch.
  8753. *
  8754. * @param int[]|int $categories Category ID or array of Categories IDs
  8755. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) definied into const class Categorie type
  8756. * @param boolean $remove_existing True: Remove existings categories from Object if not supplies by $categories, False: let them
  8757. * @return int <0 if KO, >0 if OK
  8758. */
  8759. public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
  8760. {
  8761. // Handle single category
  8762. if (!is_array($categories)) {
  8763. $categories = array($categories);
  8764. }
  8765. dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
  8766. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8767. if (empty($type_categ)) {
  8768. dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
  8769. return -1;
  8770. }
  8771. // Get current categories
  8772. $c = new Categorie($this->db);
  8773. $existing = $c->containing($this->id, $type_categ, 'id');
  8774. if ($remove_existing) {
  8775. // Diff
  8776. if (is_array($existing)) {
  8777. $to_del = array_diff($existing, $categories);
  8778. $to_add = array_diff($categories, $existing);
  8779. } else {
  8780. $to_del = array(); // Nothing to delete
  8781. $to_add = $categories;
  8782. }
  8783. } else {
  8784. $to_del = array(); // Nothing to delete
  8785. $to_add = array_diff($categories, $existing);
  8786. }
  8787. $error = 0;
  8788. $ok = 0;
  8789. // Process
  8790. foreach ($to_del as $del) {
  8791. if ($c->fetch($del) > 0) {
  8792. $result=$c->del_type($this, $type_categ);
  8793. if ($result < 0) {
  8794. $error++;
  8795. $this->error = $c->error;
  8796. $this->errors = $c->errors;
  8797. break;
  8798. } else {
  8799. $ok += $result;
  8800. }
  8801. }
  8802. }
  8803. foreach ($to_add as $add) {
  8804. if ($c->fetch($add) > 0) {
  8805. $result = $c->add_type($this, $type_categ);
  8806. if ($result < 0) {
  8807. $error++;
  8808. $this->error = $c->error;
  8809. $this->errors = $c->errors;
  8810. break;
  8811. } else {
  8812. $ok += $result;
  8813. }
  8814. }
  8815. }
  8816. return $error ? -1 * $error : $ok;
  8817. }
  8818. /**
  8819. * Copy related categories to another object
  8820. *
  8821. * @param int $fromId Id object source
  8822. * @param int $toId Id object cible
  8823. * @param string $type Type of category ('product', ...)
  8824. * @return int < 0 if error, > 0 if ok
  8825. */
  8826. public function cloneCategories($fromId, $toId, $type = '')
  8827. {
  8828. $this->db->begin();
  8829. if (empty($type)) {
  8830. $type = $this->table_element;
  8831. }
  8832. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8833. $categorystatic = new Categorie($this->db);
  8834. $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  8835. $sql .= " SELECT fk_categorie, $toId FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  8836. $sql .= " WHERE fk_product = ".((int) $fromId);
  8837. if (!$this->db->query($sql)) {
  8838. $this->error = $this->db->lasterror();
  8839. $this->db->rollback();
  8840. return -1;
  8841. }
  8842. $this->db->commit();
  8843. return 1;
  8844. }
  8845. /**
  8846. * Delete related files of object in database
  8847. *
  8848. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  8849. * @return bool True if OK, False if KO
  8850. */
  8851. public function deleteEcmFiles($mode = 0)
  8852. {
  8853. global $conf;
  8854. $this->db->begin();
  8855. // Delete in database with mode 0
  8856. if ($mode == 0) {
  8857. switch ($this->element) {
  8858. case 'propal':
  8859. $element = 'propale';
  8860. break;
  8861. case 'product':
  8862. $element = 'produit';
  8863. break;
  8864. case 'order_supplier':
  8865. $element = 'fournisseur/commande';
  8866. break;
  8867. case 'invoice_supplier':
  8868. $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  8869. break;
  8870. case 'shipping':
  8871. $element = 'expedition/sending';
  8872. break;
  8873. default:
  8874. $element = $this->element;
  8875. }
  8876. // Delete ecm_files extrafields
  8877. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files_extrafields WHERE fk_object IN (";
  8878. $sql .= " SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8879. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  8880. $sql .= ")";
  8881. if (!$this->db->query($sql)) {
  8882. $this->error = $this->db->lasterror();
  8883. $this->db->rollback();
  8884. return false;
  8885. }
  8886. // Delete ecm_files
  8887. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files";
  8888. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8889. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  8890. if (!$this->db->query($sql)) {
  8891. $this->error = $this->db->lasterror();
  8892. $this->db->rollback();
  8893. return false;
  8894. }
  8895. }
  8896. // Delete in database with mode 1
  8897. if ($mode == 1) {
  8898. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files_extrafields";
  8899. $sql .= " WHERE fk_object IN (SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id).")";
  8900. $resql = $this->db->query($sql);
  8901. if (!$resql) {
  8902. $this->error = $this->db->lasterror();
  8903. $this->db->rollback();
  8904. return false;
  8905. }
  8906. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files";
  8907. $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
  8908. $resql = $this->db->query($sql);
  8909. if (!$resql) {
  8910. $this->error = $this->db->lasterror();
  8911. $this->db->rollback();
  8912. return false;
  8913. }
  8914. }
  8915. $this->db->commit();
  8916. return true;
  8917. }
  8918. /**
  8919. * Get linked objects ids
  8920. * @author MMI Mathieu Moulin iProspective
  8921. *
  8922. * @return Array
  8923. */
  8924. public function fetchObjectLinkedIDs($object_class=true)
  8925. {
  8926. $classname = strtolower(get_class($this));
  8927. $sql = 'SELECT e.sourcetype object_type, e.fk_source fk_object
  8928. FROM '.MAIN_DB_PREFIX.'element_element e
  8929. WHERE e.targettype="'.$classname.'" AND e.fk_target="'.$this->id.'"
  8930. UNION
  8931. SELECT e.targettype object_type, e.fk_target fk_object
  8932. FROM '.MAIN_DB_PREFIX.'element_element e
  8933. WHERE e.sourcetype="'.$classname.'" AND e.fk_source="'.$this->id.'"';
  8934. //echo $sql;
  8935. $resql = $this->db->query($sql);
  8936. if (!$resql)
  8937. return;
  8938. $l = [];
  8939. while ($obj = $this->db->fetch_object($resql)) {
  8940. //var_dump($obj);
  8941. $l[] = [$obj->object_type, $obj->fk_object];
  8942. }
  8943. return $l;
  8944. }
  8945. /**
  8946. * Get total amount already paid
  8947. * @author MMI Mathieu Moulin iProspective
  8948. *
  8949. * @return []
  8950. */
  8951. public function getPaiements()
  8952. {
  8953. $classname = strtolower(get_class($this));
  8954. $ol = $this->fetchObjectLinkedIDs();
  8955. //var_dump($ol);
  8956. if (!is_array($ol))
  8957. $ol = [];
  8958. $ol[] = [$classname, $this->id];
  8959. $sql_w = [];
  8960. foreach($ol as $o) {
  8961. if ($o[0]=='facture')
  8962. $sql_w[] = "(pf.`fk_facture`='".$o[1]."')";
  8963. $sql_w[] = "(po.`objecttype`='".$o[0]."' AND po.`fk_object`='".$o[1]."')";
  8964. }
  8965. $sql = "SELECT DISTINCT p2.*, p.*
  8966. FROM ".MAIN_DB_PREFIX."paiement p
  8967. LEFT JOIN ".MAIN_DB_PREFIX."paiement_extrafields p2 ON p2.fk_object=p.rowid
  8968. LEFT JOIN ".MAIN_DB_PREFIX."paiement_object po ON po.fk_paiement=p.rowid
  8969. LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture pf ON pf.fk_paiement=p.rowid
  8970. WHERE ".implode(' OR ', $sql_w);
  8971. //echo $sql;
  8972. $resql = $this->db->query($sql);
  8973. if (!$resql)
  8974. return;
  8975. $l = [];
  8976. while ($obj = $this->db->fetch_object($resql)) {
  8977. //var_dump($obj);
  8978. $l[$obj->rowid] = $obj;
  8979. }
  8980. return $l;
  8981. }
  8982. /**
  8983. * Get total amount already paid
  8984. * @author MMI Mathieu Moulin iProspective
  8985. *
  8986. * @return float
  8987. */
  8988. public function getSommePaiement()
  8989. {
  8990. $mt = 0;
  8991. $l = $this->getPaiements();
  8992. foreach($l as $p) {
  8993. $mt += $p->amount;
  8994. }
  8995. //echo $mt;
  8996. return $mt;
  8997. }
  8998. /**
  8999. * Get filename for PDF
  9000. * @author MMI Mathieu Moulin iProspective
  9001. *
  9002. * @return string
  9003. */
  9004. public function pdf_filename()
  9005. {
  9006. global $conf;
  9007. if (empty($conf->global->MMIDOCUMENT_PDF_RENAME))
  9008. return;
  9009. $thirdparty = $this->thirdparty;
  9010. $file_e = [];
  9011. $file_e[] = dol_sanitizeFileName($this->ref);
  9012. if (!empty($conf->global->MMIDOCUMENT_PDF_RENAME_MYSOC)) {
  9013. global $mysoc;
  9014. $file_e[] = $mysoc->name;
  9015. }
  9016. if (!empty($conf->global->MMIDOCUMENT_PDF_RENAME_THIRDPARTY)) {
  9017. $file_e[] = $thirdparty->name;
  9018. }
  9019. if (!empty($conf->global->MMIDOCUMENT_PDF_RENAME_REF_CUSTOMER) && !empty($this->ref_customer)) {
  9020. $file_e[] = $this->ref_customer;
  9021. }
  9022. $filename = preg_replace('/[^A-Za-z0-9\-]/', '', str_replace(' ', '-', iconv('UTF-8','ASCII//TRANSLIT', implode('-', $file_e))));
  9023. return !empty($conf->global->MMIDOCUMENT_PDF_RENAME_UPPERCASE) ?strtoupper($filename) :$filename;
  9024. }
  9025. /**
  9026. * Get total amount already paid
  9027. * @author MMI Mathieu Moulin iProspective
  9028. *
  9029. * @return float
  9030. */
  9031. public function paye()
  9032. {
  9033. return $this->getSommePaiement() >= $this->total_ttc;
  9034. }
  9035. }