commonobject.class.php 243 KB

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