commonobject.class.php 357 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336
  1. <?php
  2. /* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
  5. * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
  6. * Copyright (C) 2011-2022 Philippe Grand <philippe.grand@atoo-net.com>
  7. * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
  8. * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  9. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  10. * Copyright (C) 2015-2022 Alexandre Spangaro <aspangaro@open-dsi.fr>
  11. * Copyright (C) 2016 Bahfir abbes <dolipar@dolipar.org>
  12. * Copyright (C) 2017 ATM Consulting <support@atm-consulting.fr>
  13. * Copyright (C) 2017-2019 Nicolas ZABOURI <info@inovea-conseil.com>
  14. * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
  15. * Copyright (C) 2018-2023 Frédéric France <frederic.france@netlogic.fr>
  16. * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
  17. * Copyright (C) 2023 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  18. * Copyright (C) 2021 Grégory Blémand <gregory.blemand@atm-consulting.fr>
  19. * Copyright (C) 2023 Lenin Rivas <lenin.rivas777@gmail.com>
  20. *
  21. * This program is free software; you can redistribute it and/or modify
  22. * it under the terms of the GNU General Public License as published by
  23. * the Free Software Foundation; either version 3 of the License, or
  24. * (at your option) any later version.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU General Public License
  32. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  33. */
  34. /**
  35. * \file htdocs/core/class/commonobject.class.php
  36. * \ingroup core
  37. * \brief File of parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  38. */
  39. /**
  40. * Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  41. */
  42. abstract class CommonObject
  43. {
  44. const TRIGGER_PREFIX = ''; // to be overriden in child class implementations, i.e. 'BILL', 'TASK', 'PROPAL', etc.
  45. /**
  46. * @var DoliDb Database handler (result of a new DoliDB)
  47. */
  48. public $db;
  49. /**
  50. * @var int The object identifier
  51. */
  52. public $id;
  53. /**
  54. * @var int The environment ID when using a multicompany module
  55. */
  56. public $entity;
  57. /**
  58. * @var string Error string
  59. * @see $errors
  60. */
  61. public $error;
  62. /**
  63. * @var string Error string that is hidden but can be used to store complementatry technical code.
  64. */
  65. public $errorhidden;
  66. /**
  67. * @var string[] Array of error strings
  68. */
  69. public $errors = array();
  70. /**
  71. * @var array To store error results of ->validateField()
  72. */
  73. private $validateFieldsErrors = array();
  74. /**
  75. * @var string ID to identify managed object
  76. */
  77. public $element;
  78. /**
  79. * @var int The related element
  80. */
  81. public $fk_element;
  82. /**
  83. * @var string Name to use for 'features' parameter to check module permissions user->rights->feature with restrictedArea().
  84. * Undefined means same value than $element. Can be use to force a check on another element for example for class of line, we mention here the parent element.
  85. */
  86. public $element_for_permission;
  87. /**
  88. * @var string Name of table without prefix where object is stored
  89. */
  90. public $table_element;
  91. /**
  92. * @var string Name of subtable line
  93. */
  94. public $table_element_line = '';
  95. /**
  96. * @var string Key value used to track if data is coming from import wizard
  97. */
  98. public $import_key;
  99. /**
  100. * @var mixed Contains data to manage extrafields
  101. */
  102. public $array_options = array();
  103. /**
  104. * @var mixed Array to store alternative languages values of object
  105. */
  106. public $array_languages = null; // Value is array() when load already tried
  107. /**
  108. * @var array To store result of ->liste_contact()
  109. */
  110. public $contacts_ids;
  111. /**
  112. * @var mixed Array of linked objects, set and used when calling ->create() to be able to create links during the creation of object
  113. */
  114. public $linked_objects;
  115. /**
  116. * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked
  117. */
  118. public $linkedObjectsIds;
  119. /**
  120. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  121. */
  122. public $linkedObjects;
  123. /**
  124. * @var boolean[] Array of boolean with object id as key and value as true if linkedObjects full loaded for object id. Loaded by ->fetchObjectLinked. Important for pdf generation time reduction.
  125. */
  126. private $linkedObjectsFullLoaded = array();
  127. /**
  128. * @var CommonObject To store a cloned copy of object before to edit it and keep track of old properties
  129. */
  130. public $oldcopy;
  131. /**
  132. * @var string Column name of the ref field.
  133. */
  134. protected $table_ref_field = '';
  135. /**
  136. * @var integer 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user
  137. */
  138. public $restrictiononfksoc = 0;
  139. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  140. /**
  141. * @var array<string,mixed> Can be used to pass information when only object is provided to method
  142. */
  143. public $context = array();
  144. /**
  145. * @var string Contains canvas name if record is an alternative canvas record
  146. */
  147. public $canvas;
  148. /**
  149. * @var Project The related project object
  150. * @see fetch_projet()
  151. */
  152. public $project;
  153. /**
  154. * @var int The related project ID
  155. * @see setProject(), project
  156. */
  157. public $fk_project;
  158. /**
  159. * @var Project The related project object
  160. * @deprecated
  161. * @see project
  162. */
  163. public $projet;
  164. /**
  165. * @deprecated
  166. * @see $fk_project
  167. */
  168. public $fk_projet;
  169. /**
  170. * @var Contact A related contact object
  171. * @see fetch_contact()
  172. */
  173. public $contact;
  174. /**
  175. * @var int The related contact ID
  176. * @see fetch_contact()
  177. */
  178. public $contact_id;
  179. /**
  180. * @var Societe A related thirdparty object
  181. * @see fetch_thirdparty()
  182. */
  183. public $thirdparty;
  184. /**
  185. * @var User A related user
  186. * @see fetch_user()
  187. */
  188. public $user;
  189. /**
  190. * @var string The type of originating object ('commande', 'facture', ...). Note: on some object this field is called $origin_type
  191. * @see fetch_origin()
  192. */
  193. public $origin;
  194. /**
  195. * @var int The id of originating object
  196. * @see fetch_origin()
  197. */
  198. public $origin_id;
  199. /**
  200. * @var string The object's reference
  201. */
  202. public $ref;
  203. /**
  204. * @var string An external reference for the object
  205. */
  206. public $ref_ext;
  207. /**
  208. * @var string The object's previous reference
  209. */
  210. public $ref_previous;
  211. /**
  212. * @var string The object's next reference
  213. */
  214. public $ref_next;
  215. /**
  216. * @var string Ref to store on object to save the new ref to use for example when making a validate() of an object
  217. */
  218. public $newref;
  219. /**
  220. * @var int The object's status. Prefer use of status.
  221. * @see setStatut()
  222. */
  223. public $statut;
  224. /**
  225. * @var int The object's status
  226. * @see setStatut()
  227. */
  228. public $status;
  229. /**
  230. * @var string
  231. * @see getFullAddress()
  232. */
  233. public $country;
  234. /**
  235. * @var int
  236. * @see getFullAddress(), country
  237. */
  238. public $country_id;
  239. /**
  240. * @var string The ISO country code on 2 chars.
  241. * @see getFullAddress(), isInEEC(), country
  242. */
  243. public $country_code;
  244. /**
  245. * @var string
  246. * @see getFullAddress()
  247. */
  248. public $state;
  249. /**
  250. * @var int
  251. * @see getFullAddress(), state
  252. */
  253. public $state_id;
  254. /**
  255. * @var string
  256. * @see getFullAddress(), $state
  257. */
  258. public $state_code;
  259. /**
  260. * @var int
  261. * @see getFullAddress(), $region_code, $region
  262. */
  263. public $region_id;
  264. /**
  265. * @var string
  266. * @see getFullAddress(), $region_id, $region
  267. */
  268. public $region_code;
  269. /**
  270. * @var string
  271. * @see getFullAddress(), $region_id, $region_code
  272. */
  273. public $region;
  274. /**
  275. * @var int
  276. * @see fetch_barcode()
  277. */
  278. public $barcode_type;
  279. /**
  280. * @var string
  281. * @see fetch_barcode(), barcode_type
  282. */
  283. public $barcode_type_code;
  284. /**
  285. * @var string
  286. * @see fetch_barcode(), barcode_type
  287. */
  288. public $barcode_type_label;
  289. /**
  290. * @var string
  291. * @see fetch_barcode(), barcode_type
  292. */
  293. public $barcode_type_coder;
  294. /**
  295. * @var int Payment method ID (cheque, cash, ...)
  296. * @see setPaymentMethods()
  297. */
  298. public $mode_reglement_id;
  299. /**
  300. * @var int Payment terms ID
  301. * @see setPaymentTerms()
  302. */
  303. public $cond_reglement_id;
  304. /**
  305. * @var int Demand reason ID
  306. */
  307. public $demand_reason_id;
  308. /**
  309. * @var int Transport mode ID (For module intracomm report)
  310. * @see setTransportMode()
  311. */
  312. public $transport_mode_id;
  313. /**
  314. * @var int Payment terms ID
  315. * @deprecated Kept for compatibility
  316. * @see cond_reglement_id;
  317. */
  318. public $cond_reglement;
  319. /**
  320. * @var int Delivery address ID
  321. * @see setDeliveryAddress()
  322. * @deprecated
  323. */
  324. public $fk_delivery_address;
  325. /**
  326. * @var int Shipping method ID
  327. * @see setShippingMethod()
  328. */
  329. public $shipping_method_id;
  330. /**
  331. * @var string Shipping method label
  332. * @see setShippingMethod()
  333. */
  334. public $shipping_method;
  335. /**
  336. * @var string multicurrency code
  337. */
  338. public $multicurrency_code;
  339. /**
  340. * @var string multicurrency tx
  341. */
  342. public $multicurrency_tx;
  343. /**
  344. * @var string
  345. * @see SetDocModel()
  346. */
  347. public $model_pdf;
  348. /**
  349. * @var string
  350. * @deprecated
  351. * @see $model_pdf
  352. */
  353. public $modelpdf;
  354. /**
  355. * @var string
  356. * Contains relative path of last generated main file
  357. */
  358. public $last_main_doc;
  359. /**
  360. * @var int Bank account ID sometimes, ID of record into llx_bank sometimes
  361. * @deprecated
  362. * @see $fk_account
  363. */
  364. public $fk_bank;
  365. /**
  366. * @var int Bank account ID
  367. * @see SetBankAccount()
  368. */
  369. public $fk_account;
  370. /**
  371. * @var string Open ID
  372. */
  373. public $openid;
  374. /**
  375. * @var string Public note
  376. * @see update_note()
  377. */
  378. public $note_public;
  379. /**
  380. * @var string Private note
  381. * @see update_note()
  382. */
  383. public $note_private;
  384. /**
  385. * @deprecated
  386. * @see $note_private
  387. */
  388. public $note;
  389. /**
  390. * @var float Total amount before taxes
  391. * @see update_price()
  392. */
  393. public $total_ht;
  394. /**
  395. * @var float Total VAT amount
  396. * @see update_price()
  397. */
  398. public $total_tva;
  399. /**
  400. * @var float Total local tax 1 amount
  401. * @see update_price()
  402. */
  403. public $total_localtax1;
  404. /**
  405. * @var float Total local tax 2 amount
  406. * @see update_price()
  407. */
  408. public $total_localtax2;
  409. /**
  410. * @var float Total amount with taxes
  411. * @see update_price()
  412. */
  413. public $total_ttc;
  414. /**
  415. * @var CommonObjectLine[]
  416. */
  417. public $lines;
  418. /**
  419. * @var mixed Contains comments
  420. * @see fetchComments()
  421. */
  422. public $comments = array();
  423. /**
  424. * @var string The name
  425. */
  426. public $name;
  427. /**
  428. * @var string The lastname
  429. */
  430. public $lastname;
  431. /**
  432. * @var string The firstname
  433. */
  434. public $firstname;
  435. /**
  436. * @var string The civility code, not an integer
  437. */
  438. public $civility_id;
  439. // Dates
  440. /**
  441. * @var integer|string date_creation
  442. */
  443. public $date_creation;
  444. /**
  445. * @var integer|string $date_validation;
  446. */
  447. public $date_validation; // Date validation
  448. /**
  449. * @var integer|string $date_modification;
  450. */
  451. public $date_modification; // Date last change (tms field)
  452. /**
  453. * @var integer|string $date_cloture;
  454. */
  455. public $date_cloture; // Date closing (tms field)
  456. /**
  457. * @var User|int User author/creation
  458. * @TODO Merge with user_creation
  459. */
  460. public $user_author;
  461. /**
  462. * @var User|int User author/creation
  463. * @TODO Remove type id
  464. */
  465. public $user_creation;
  466. /**
  467. * @var int User id author/creation
  468. */
  469. public $user_creation_id;
  470. /**
  471. * @var User|int User of validation
  472. * @TODO Merge with user_validation
  473. */
  474. public $user_valid;
  475. /**
  476. * @var User|int User of validation
  477. * @TODO Remove type id
  478. */
  479. public $user_validation;
  480. /**
  481. * @var int User id of validation
  482. */
  483. public $user_validation_id;
  484. /**
  485. * @var int User id closing object
  486. */
  487. public $user_closing_id;
  488. /**
  489. * @var User|int User last modifier
  490. * @TODO Remove type id
  491. */
  492. public $user_modification;
  493. /**
  494. * @var int User id last modifier
  495. */
  496. public $user_modification_id;
  497. public $next_prev_filter;
  498. /**
  499. * @var int 1 if object is specimen
  500. */
  501. public $specimen = 0;
  502. /**
  503. * @var int Id of contact to send object (used by the trigger of module Agenda)
  504. */
  505. public $sendtoid;
  506. /**
  507. * @var float Amount already paid (used to show correct status)
  508. */
  509. public $alreadypaid;
  510. protected $labelStatus;
  511. protected $labelStatusShort;
  512. /**
  513. * @var int showphoto_on_popup
  514. */
  515. public $showphoto_on_popup;
  516. /**
  517. * @var array nb used in load_stateboard
  518. */
  519. public $nb = array();
  520. /**
  521. * @var string output
  522. */
  523. public $output;
  524. /**
  525. * @var array List of child tables. To test if we can delete object.
  526. */
  527. protected $childtables = array();
  528. /**
  529. * @var array List of child tables. To know object to delete on cascade.
  530. * If name is like '@ClassName:FilePathClass:ParentFkFieldName', it will
  531. * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object.
  532. */
  533. protected $childtablesoncascade = array();
  534. // No constructor as it is an abstract class
  535. /**
  536. * Check an object id/ref exists
  537. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  538. *
  539. * @param string $element String of element ('product', 'facture', ...)
  540. * @param int $id Id of object
  541. * @param string $ref Ref of object to check
  542. * @param string $ref_ext Ref ext of object to check
  543. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  544. */
  545. public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
  546. {
  547. global $db, $conf;
  548. $sql = "SELECT rowid, ref, ref_ext";
  549. $sql .= " FROM ".$db->prefix().$element;
  550. $sql .= " WHERE entity IN (".getEntity($element).")";
  551. if ($id > 0) {
  552. $sql .= " AND rowid = ".((int) $id);
  553. } elseif ($ref) {
  554. $sql .= " AND ref = '".$db->escape($ref)."'";
  555. } elseif ($ref_ext) {
  556. $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
  557. } else {
  558. $error = 'ErrorWrongParameters';
  559. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  560. return -1;
  561. }
  562. if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
  563. $sql .= " AND entity = ".((int) $conf->entity);
  564. }
  565. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  566. $resql = $db->query($sql);
  567. if ($resql) {
  568. $num = $db->num_rows($resql);
  569. if ($num > 0) {
  570. return 1;
  571. } else {
  572. return 0;
  573. }
  574. }
  575. return -1;
  576. }
  577. /**
  578. * setErrorsFromObject
  579. *
  580. * @param CommonObject $object commonobject
  581. * @return void
  582. */
  583. public function setErrorsFromObject($object)
  584. {
  585. if (!empty($object->error)) {
  586. $this->error = $object->error;
  587. }
  588. if (!empty($object->errors)) {
  589. $this->errors = array_merge($this->errors, $object->errors);
  590. }
  591. }
  592. /**
  593. * getTooltipContentArray
  594. *
  595. * @since v18
  596. * @param array $params params to construct tooltip data
  597. * @return array
  598. */
  599. public function getTooltipContentArray($params)
  600. {
  601. return [];
  602. }
  603. /**
  604. * getTooltipContent
  605. *
  606. * @param array $params params
  607. * @since v18
  608. * @return string
  609. */
  610. public function getTooltipContent($params)
  611. {
  612. global $action, $extrafields, $langs, $hookmanager;
  613. $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP = 5; // If there is too much extrafields, we do not include them into tooltip
  614. $datas = $this->getTooltipContentArray($params);
  615. // Add extrafields
  616. if (!empty($extrafields->attributes[$this->table_element]['label'])) {
  617. if (count($extrafields->attributes[$this->table_element]['label']) < $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP) {
  618. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
  619. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  620. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  621. }
  622. $labelextra = $langs->trans((string) $extrafields->attributes[$this->table_element]['label'][$key]);
  623. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  624. $datas[$key]= '<br><b><u>'. $labelextra . '</u></b>';
  625. } else {
  626. $value = (empty($this->array_options['options_' . $key]) ? '' : $this->array_options['options_' . $key]);
  627. $datas[$key]= '<br><b>'. $labelextra . ':</b> ' . $extrafields->showOutputField($key, $value, '', $this->table_element);
  628. }
  629. }
  630. }
  631. }
  632. $hookmanager->initHooks(array($this->element . 'dao'));
  633. $parameters = array(
  634. 'tooltipcontentarray' => &$datas
  635. );
  636. // Note that $action and $object may have been modified by some hooks
  637. $hookmanager->executeHooks('getTooltipContent', $parameters, $this, $action);
  638. $label = implode($datas);
  639. return $label;
  640. }
  641. /**
  642. * Method to output saved errors
  643. *
  644. * @return string String with errors
  645. */
  646. public function errorsToString()
  647. {
  648. return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
  649. }
  650. /**
  651. * Return customer ref for screen output.
  652. *
  653. * @param string $objref Customer ref
  654. * @return string Customer ref formated
  655. */
  656. public function getFormatedCustomerRef($objref)
  657. {
  658. global $hookmanager;
  659. $parameters = array('objref'=>$objref);
  660. $action = '';
  661. $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  662. if ($reshook > 0) {
  663. return $hookmanager->resArray['objref'];
  664. }
  665. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  666. }
  667. /**
  668. * Return supplier ref for screen output.
  669. *
  670. * @param string $objref Supplier ref
  671. * @return string Supplier ref formated
  672. */
  673. public function getFormatedSupplierRef($objref)
  674. {
  675. global $hookmanager;
  676. $parameters = array('objref'=>$objref);
  677. $action = '';
  678. $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  679. if ($reshook > 0) {
  680. return $hookmanager->resArray['objref'];
  681. }
  682. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  683. }
  684. /**
  685. * Return full name (civility+' '+name+' '+lastname)
  686. *
  687. * @param Translate $langs Language object for translation of civility (used only if option is 1)
  688. * @param int $option 0=No option, 1=Add civility
  689. * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname, 3=Firstname if defined else lastname, 4=Lastname, 5=Lastname if defined else firstname
  690. * @param int $maxlen Maximum length
  691. * @return string String with full name
  692. */
  693. public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
  694. {
  695. //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
  696. $lastname = $this->lastname;
  697. $firstname = $this->firstname;
  698. if (empty($lastname)) {
  699. $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 : '')))));
  700. }
  701. $ret = '';
  702. if (!empty($option) && !empty($this->civility_code)) {
  703. if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) {
  704. $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
  705. } else {
  706. $ret .= $this->civility_code.' ';
  707. }
  708. }
  709. $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
  710. return dol_trunc($ret, $maxlen);
  711. }
  712. /**
  713. * Set to upper or ucwords/lower if needed
  714. *
  715. * @return void;
  716. */
  717. public function setUpperOrLowerCase()
  718. {
  719. global $conf;
  720. if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
  721. $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
  722. $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
  723. $this->name = dol_ucwords(dol_strtolower($this->name));
  724. $this->name_alias = isset($this->name_alias)?dol_ucwords(dol_strtolower($this->name_alias)):'';
  725. }
  726. if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
  727. $this->lastname = dol_strtoupper($this->lastname);
  728. $this->name = dol_strtoupper($this->name);
  729. $this->name_alias = dol_strtoupper($this->name_alias);
  730. }
  731. if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
  732. $this->address = dol_strtoupper($this->address);
  733. $this->town = dol_strtoupper($this->town);
  734. }
  735. if (isset($this->email)) {
  736. $this->email = dol_strtolower($this->email);
  737. }
  738. if (isset($this->personal_email)) {
  739. $this->personal_email = dol_strtolower($this->personal_email);
  740. }
  741. }
  742. /**
  743. * Return full address of contact
  744. *
  745. * @param int $withcountry 1=Add country into address string
  746. * @param string $sep Separator to use to build string
  747. * @param int $withregion 1=Add region into address string
  748. * @param string $extralangcode User extralanguages as value
  749. * @return string Full address string
  750. */
  751. public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
  752. {
  753. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
  754. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  755. $tmparray = getCountry($this->country_id, 'all');
  756. $this->country_code = $tmparray['code'];
  757. $this->country = $tmparray['label'];
  758. }
  759. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
  760. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  761. $tmparray = getState($this->state_id, 'all', 0, 1);
  762. $this->state_code = $tmparray['code'];
  763. $this->state = $tmparray['label'];
  764. $this->region_code = $tmparray['region_code'];
  765. $this->region = $tmparray['region'];
  766. }
  767. return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
  768. }
  769. /**
  770. * Return full address for banner
  771. *
  772. * @param string $htmlkey HTML id to make banner content unique
  773. * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member)
  774. * @return string Full address string
  775. */
  776. public function getBannerAddress($htmlkey, $object)
  777. {
  778. global $conf, $langs, $form, $extralanguages;
  779. $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
  780. $contactid = 0;
  781. $thirdpartyid = 0;
  782. $elementforaltlanguage = $this->element;
  783. if ($this->element == 'societe') {
  784. $thirdpartyid = $this->id;
  785. }
  786. if ($this->element == 'contact') {
  787. $contactid = $this->id;
  788. $thirdpartyid = empty($this->fk_soc) ? 0 : $this->fk_soc;
  789. }
  790. if ($this->element == 'user') {
  791. $contactid = $this->contact_id;
  792. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  793. }
  794. $out = '';
  795. $outdone = 0;
  796. $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
  797. if ($coords) {
  798. if (!empty($conf->use_javascript_ajax)) {
  799. // Add picto with tooltip on map
  800. $namecoords = '';
  801. if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
  802. $namecoords .= $object->name.'<br>';
  803. }
  804. $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
  805. // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
  806. $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
  807. $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
  808. $out .= '</a> ';
  809. }
  810. $address = dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  811. if ($address) {
  812. $out .= $address;
  813. $outdone++;
  814. }
  815. $outdone++;
  816. // List of extra languages
  817. $arrayoflangcode = array();
  818. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  819. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  820. }
  821. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  822. if (!is_object($extralanguages)) {
  823. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  824. $extralanguages = new ExtraLanguages($this->db);
  825. }
  826. $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
  827. if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
  828. $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
  829. $this->fetchValuesForExtraLanguages();
  830. if (!is_object($form)) {
  831. $form = new Form($this->db);
  832. }
  833. $htmltext = '';
  834. // If there is extra languages
  835. foreach ($arrayoflangcode as $extralangcode) {
  836. $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  837. // This also call dol_format_address()
  838. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
  839. $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  840. }
  841. $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  842. }
  843. }
  844. }
  845. // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
  846. if (!in_array($this->country_code, $countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)
  847. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
  848. if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
  849. $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
  850. } else {
  851. $out .= ($outdone ? ' - ' : '').$this->state;
  852. }
  853. $outdone++;
  854. }
  855. if ($outdone) {
  856. $out = '<div class="address inline-block">'.$out.'</div>';
  857. }
  858. 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)) {
  859. $out .= ($outdone ? '<br>' : '');
  860. }
  861. if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  862. $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  863. $outdone++;
  864. }
  865. if (!empty($this->phone_pro)) {
  866. $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  867. $outdone++;
  868. }
  869. if (!empty($this->phone_mobile)) {
  870. $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  871. $outdone++;
  872. }
  873. if (!empty($this->phone_perso)) {
  874. $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
  875. $outdone++;
  876. }
  877. if (!empty($this->office_phone)) {
  878. $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  879. $outdone++;
  880. }
  881. if (!empty($this->user_mobile)) {
  882. $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  883. $outdone++;
  884. }
  885. if (!empty($this->fax)) {
  886. $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  887. $outdone++;
  888. }
  889. if (!empty($this->office_fax)) {
  890. $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  891. $outdone++;
  892. }
  893. if ($out) {
  894. $out .= '<div style="clear: both;"></div>';
  895. }
  896. $outdone = 0;
  897. if (!empty($this->email)) {
  898. $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
  899. $outdone++;
  900. }
  901. if (!empty($this->url)) {
  902. //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
  903. $out .= dol_print_url($this->url, '_blank', 0, 1);
  904. $outdone++;
  905. }
  906. if (isModEnabled('socialnetworks')) {
  907. $outsocialnetwork = '';
  908. if (!empty($this->socialnetworks) && is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
  909. $socialnetworksdict = getArrayOfSocialNetworks();
  910. foreach ($this->socialnetworks as $key => $value) {
  911. if ($value) {
  912. $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
  913. }
  914. $outdone++;
  915. }
  916. }
  917. if ($outsocialnetwork) {
  918. $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
  919. }
  920. }
  921. if ($out) {
  922. return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
  923. } else {
  924. return '';
  925. }
  926. }
  927. /**
  928. * Return the link of last main doc file for direct public download.
  929. *
  930. * @param string $modulepart Module related to document
  931. * @param int $initsharekey Init the share key if it was not yet defined
  932. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  933. * @return string Link or empty string if there is no download link
  934. */
  935. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  936. {
  937. global $user, $dolibarr_main_url_root;
  938. if (empty($this->last_main_doc)) {
  939. return ''; // No way to known which document name to use
  940. }
  941. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  942. $ecmfile = new EcmFiles($this->db);
  943. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  944. if ($result < 0) {
  945. $this->error = $ecmfile->error;
  946. $this->errors = $ecmfile->errors;
  947. return -1;
  948. }
  949. if (empty($ecmfile->id)) {
  950. // Add entry into index
  951. if ($initsharekey) {
  952. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  953. // TODO We can't, we dont' have full path of file, only last_main_doc and ->element, so we must first rebuild full path $destfull
  954. /*
  955. $ecmfile->filepath = $rel_dir;
  956. $ecmfile->filename = $filename;
  957. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  958. $ecmfile->fullpath_orig = '';
  959. $ecmfile->gen_or_uploaded = 'generated';
  960. $ecmfile->description = ''; // indexed content
  961. $ecmfile->keywords = ''; // keyword content
  962. $ecmfile->share = getRandomPassword(true);
  963. $result = $ecmfile->create($user);
  964. if ($result < 0)
  965. {
  966. $this->error = $ecmfile->error;
  967. $this->errors = $ecmfile->errors;
  968. }
  969. */
  970. } else {
  971. return '';
  972. }
  973. } elseif (empty($ecmfile->share)) {
  974. // Add entry into index
  975. if ($initsharekey) {
  976. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  977. $ecmfile->share = getRandomPassword(true);
  978. $ecmfile->update($user);
  979. } else {
  980. return '';
  981. }
  982. }
  983. // Define $urlwithroot
  984. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  985. // This is to use external domain name found into config file
  986. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  987. //else
  988. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  989. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  990. $forcedownload = 0;
  991. $paramlink = '';
  992. //if (!empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  993. //if (!empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  994. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  995. if (!empty($ecmfile->share)) {
  996. $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
  997. }
  998. if ($forcedownload) {
  999. $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  1000. }
  1001. if ($relativelink) {
  1002. $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
  1003. } else {
  1004. $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  1005. }
  1006. // Here $ecmfile->share is defined
  1007. return $linktoreturn;
  1008. }
  1009. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1010. /**
  1011. * Add a link between element $this->element and a contact
  1012. *
  1013. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  1014. * @param int|string $type_contact Type of contact (code or id). Must be id or code found into table llx_c_type_contact. For example: SALESREPFOLL
  1015. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  1016. * @param int $notrigger Disable all triggers
  1017. * @return int <0 if KO, 0 if already added, >0 if OK
  1018. */
  1019. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  1020. {
  1021. // phpcs:enable
  1022. global $user, $langs;
  1023. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  1024. // Check parameters
  1025. if ($fk_socpeople <= 0) {
  1026. $langs->load("errors");
  1027. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  1028. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  1029. return -1;
  1030. }
  1031. if (!$type_contact) {
  1032. $langs->load("errors");
  1033. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  1034. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  1035. return -2;
  1036. }
  1037. $id_type_contact = 0;
  1038. if (is_numeric($type_contact)) {
  1039. $id_type_contact = $type_contact;
  1040. } else {
  1041. // We look for id type_contact
  1042. $sql = "SELECT tc.rowid";
  1043. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1044. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1045. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1046. $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  1047. //print $sql;
  1048. $resql = $this->db->query($sql);
  1049. if ($resql) {
  1050. $obj = $this->db->fetch_object($resql);
  1051. if ($obj) {
  1052. $id_type_contact = $obj->rowid;
  1053. }
  1054. }
  1055. }
  1056. if ($id_type_contact == 0) {
  1057. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  1058. 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");
  1059. return -3;
  1060. }
  1061. $datecreate = dol_now();
  1062. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  1063. $TListeContacts = $this->liste_contact(-1, $source);
  1064. $already_added = false;
  1065. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  1066. foreach ($TListeContacts as $array_contact) {
  1067. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  1068. $already_added = true;
  1069. break;
  1070. }
  1071. }
  1072. }
  1073. if (!$already_added) {
  1074. $this->db->begin();
  1075. // Insert into database
  1076. $sql = "INSERT INTO ".$this->db->prefix()."element_contact";
  1077. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  1078. $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
  1079. $sql .= "'".$this->db->idate($datecreate)."'";
  1080. $sql .= ", 4, ".((int) $id_type_contact);
  1081. $sql .= ")";
  1082. $resql = $this->db->query($sql);
  1083. if ($resql) {
  1084. if (!$notrigger) {
  1085. $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  1086. if ($result < 0) {
  1087. $this->db->rollback();
  1088. return -1;
  1089. }
  1090. }
  1091. $this->db->commit();
  1092. return 1;
  1093. } else {
  1094. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1095. $this->error = $this->db->errno();
  1096. $this->db->rollback();
  1097. return -2;
  1098. } else {
  1099. $this->error = $this->db->lasterror();
  1100. $this->db->rollback();
  1101. return -1;
  1102. }
  1103. }
  1104. } else {
  1105. return 0;
  1106. }
  1107. }
  1108. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1109. /**
  1110. * Copy contact from one element to current
  1111. *
  1112. * @param CommonObject $objFrom Source element
  1113. * @param string $source Nature of contact ('internal' or 'external')
  1114. * @return int >0 if OK, <0 if KO
  1115. */
  1116. public function copy_linked_contact($objFrom, $source = 'internal')
  1117. {
  1118. // phpcs:enable
  1119. $contacts = $objFrom->liste_contact(-1, $source);
  1120. foreach ($contacts as $contact) {
  1121. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
  1122. return -1;
  1123. }
  1124. }
  1125. return 1;
  1126. }
  1127. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1128. /**
  1129. * Update a link to contact line
  1130. *
  1131. * @param int $rowid Id of line contact-element
  1132. * @param int $statut New status of link
  1133. * @param int $type_contact_id Id of contact type (not modified if 0)
  1134. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  1135. * @return int <0 if KO, >= 0 if OK
  1136. */
  1137. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  1138. {
  1139. // phpcs:enable
  1140. // Insert into database
  1141. $sql = "UPDATE ".$this->db->prefix()."element_contact set";
  1142. $sql .= " statut = ".$statut;
  1143. if ($type_contact_id) {
  1144. $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
  1145. }
  1146. if ($fk_socpeople) {
  1147. $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
  1148. }
  1149. $sql .= " where rowid = ".((int) $rowid);
  1150. $resql = $this->db->query($sql);
  1151. if ($resql) {
  1152. return 0;
  1153. } else {
  1154. $this->error = $this->db->lasterror();
  1155. return -1;
  1156. }
  1157. }
  1158. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1159. /**
  1160. * Delete a link to contact line
  1161. *
  1162. * @param int $rowid Id of contact link line to delete
  1163. * @param int $notrigger Disable all triggers
  1164. * @return int >0 if OK, <0 if KO
  1165. */
  1166. public function delete_contact($rowid, $notrigger = 0)
  1167. {
  1168. // phpcs:enable
  1169. global $user;
  1170. $this->db->begin();
  1171. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1172. $sql .= " WHERE rowid = ".((int) $rowid);
  1173. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  1174. if ($this->db->query($sql)) {
  1175. if (!$notrigger) {
  1176. $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  1177. if ($result < 0) {
  1178. $this->db->rollback();
  1179. return -1;
  1180. }
  1181. }
  1182. $this->db->commit();
  1183. return 1;
  1184. } else {
  1185. $this->error = $this->db->lasterror();
  1186. $this->db->rollback();
  1187. return -1;
  1188. }
  1189. }
  1190. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1191. /**
  1192. * Delete all links between an object $this and all its contacts in llx_element_contact
  1193. *
  1194. * @param string $source '' or 'internal' or 'external'
  1195. * @param string $code Type of contact (code or id)
  1196. * @return int <0 if KO, 0=Nothing done, >0 if OK
  1197. */
  1198. public function delete_linked_contact($source = '', $code = '')
  1199. {
  1200. // phpcs:enable
  1201. $listId = '';
  1202. $temp = array();
  1203. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  1204. if (!empty($typeContact)) {
  1205. foreach ($typeContact as $key => $value) {
  1206. array_push($temp, $key);
  1207. }
  1208. $listId = implode(",", $temp);
  1209. }
  1210. // If $listId is empty, we have not criteria on fk_c_type_contact so we will delete record on element_id for
  1211. // any type or record instead of only the ones of the current object. So we do nothing in such a case.
  1212. if (empty($listId)) {
  1213. return 0;
  1214. }
  1215. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1216. $sql .= " WHERE element_id = ".((int) $this->id);
  1217. $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
  1218. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  1219. if ($this->db->query($sql)) {
  1220. return 1;
  1221. } else {
  1222. $this->error = $this->db->lasterror();
  1223. return -1;
  1224. }
  1225. }
  1226. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1227. /**
  1228. * Get array of all contacts for an object
  1229. *
  1230. * @param int $statusoflink Status of links to get (-1=all). Not used.
  1231. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  1232. * @param int $list 0:Returned array contains all properties, 1:Return array contains just id
  1233. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1234. * @param int $status Status of user or company
  1235. * @param array $arrayoftcids Array with ID of type of contacts. If we provide this, we can make a ec.fk_c_type_contact in ($arrayoftcids) to avoid link on tc table. TODO Not implemented.
  1236. * @return array|int Array of contacts, -1 if error
  1237. */
  1238. public function liste_contact($statusoflink = -1, $source = 'external', $list = 0, $code = '', $status = -1, $arrayoftcids = array())
  1239. {
  1240. // phpcs:enable
  1241. global $langs;
  1242. $tab = array();
  1243. $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
  1244. if ($source == 'internal') {
  1245. $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  1246. }
  1247. if ($source == 'external' || $source == 'thirdparty') {
  1248. $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1249. }
  1250. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  1251. $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
  1252. $sql .= " FROM ".$this->db->prefix()."c_type_contact tc,";
  1253. $sql .= " ".$this->db->prefix()."element_contact ec";
  1254. if ($source == 'internal') { // internal contact (user)
  1255. $sql .= " LEFT JOIN ".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid";
  1256. }
  1257. if ($source == 'external' || $source == 'thirdparty') { // external contact (socpeople)
  1258. $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid";
  1259. }
  1260. $sql .= " WHERE ec.element_id = ".((int) $this->id);
  1261. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1262. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1263. if ($code) {
  1264. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1265. }
  1266. if ($source == 'internal') {
  1267. $sql .= " AND tc.source = 'internal'";
  1268. if ($status >= 0) {
  1269. $sql .= " AND t.statut = ".((int) $status);
  1270. }
  1271. }
  1272. if ($source == 'external' || $source == 'thirdparty') {
  1273. $sql .= " AND tc.source = 'external'";
  1274. if ($status >= 0) {
  1275. $sql .= " AND t.statut = ".((int) $status); // t is llx_socpeople
  1276. }
  1277. }
  1278. $sql .= " AND tc.active = 1";
  1279. if ($statusoflink >= 0) {
  1280. $sql .= " AND ec.statut = ".((int) $statusoflink);
  1281. }
  1282. $sql .= " ORDER BY t.lastname ASC";
  1283. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  1284. $resql = $this->db->query($sql);
  1285. if ($resql) {
  1286. $num = $this->db->num_rows($resql);
  1287. $i = 0;
  1288. while ($i < $num) {
  1289. $obj = $this->db->fetch_object($resql);
  1290. if (!$list) {
  1291. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1292. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1293. $tab[$i] = array(
  1294. 'parentId' => $this->id,
  1295. 'source' => $obj->source,
  1296. 'socid' => $obj->socid,
  1297. 'id' => $obj->id,
  1298. 'nom' => $obj->lastname, // For backward compatibility
  1299. 'civility' => $obj->civility,
  1300. 'lastname' => $obj->lastname,
  1301. 'firstname' => $obj->firstname,
  1302. 'email'=>$obj->email,
  1303. 'login'=> (empty($obj->login) ? '' : $obj->login),
  1304. 'photo' => (empty($obj->photo) ? '' : $obj->photo),
  1305. 'statuscontact' => $obj->statuscontact,
  1306. 'rowid' => $obj->rowid,
  1307. 'code' => $obj->code,
  1308. 'libelle' => $libelle_type,
  1309. 'status' => $obj->statuslink,
  1310. 'fk_c_type_contact' => $obj->fk_c_type_contact
  1311. );
  1312. } else {
  1313. $tab[$i] = $obj->id;
  1314. }
  1315. $i++;
  1316. }
  1317. return $tab;
  1318. } else {
  1319. $this->error = $this->db->lasterror();
  1320. dol_print_error($this->db);
  1321. return -1;
  1322. }
  1323. }
  1324. /**
  1325. * Update status of a contact linked to object
  1326. *
  1327. * @param int $rowid Id of link between object and contact
  1328. * @return int <0 if KO, >=0 if OK
  1329. */
  1330. public function swapContactStatus($rowid)
  1331. {
  1332. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1333. $sql .= " tc.code, tc.libelle";
  1334. $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
  1335. $sql .= " WHERE ec.rowid =".((int) $rowid);
  1336. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1337. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1338. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  1339. $resql = $this->db->query($sql);
  1340. if ($resql) {
  1341. $obj = $this->db->fetch_object($resql);
  1342. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1343. $result = $this->update_contact($rowid, $newstatut);
  1344. $this->db->free($resql);
  1345. return $result;
  1346. } else {
  1347. $this->error = $this->db->error();
  1348. dol_print_error($this->db);
  1349. return -1;
  1350. }
  1351. }
  1352. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1353. /**
  1354. * Return array with list of possible values for type of contacts
  1355. *
  1356. * @param string $source 'internal', 'external' or 'all'
  1357. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  1358. * @param int $option 0=Return array id->label, 1=Return array code->label
  1359. * @param int $activeonly 0=all status of contact, 1=only the active
  1360. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1361. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1362. */
  1363. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1364. {
  1365. // phpcs:enable
  1366. global $langs;
  1367. if (empty($order)) {
  1368. $order = 'position';
  1369. }
  1370. if ($order == 'position') {
  1371. $order .= ',code';
  1372. }
  1373. $tab = array();
  1374. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  1375. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1376. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1377. if ($activeonly == 1) {
  1378. $sql .= " AND tc.active=1"; // only the active types
  1379. }
  1380. if (!empty($source) && $source != 'all') {
  1381. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1382. }
  1383. if (!empty($code)) {
  1384. $sql .= " AND tc.code='".$this->db->escape($code)."'";
  1385. }
  1386. $sql .= $this->db->order($order, 'ASC');
  1387. //print "sql=".$sql;
  1388. $resql = $this->db->query($sql);
  1389. if ($resql) {
  1390. $num = $this->db->num_rows($resql);
  1391. $i = 0;
  1392. while ($i < $num) {
  1393. $obj = $this->db->fetch_object($resql);
  1394. $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
  1395. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1396. if (empty($option)) {
  1397. $tab[$obj->rowid] = $libelle_type;
  1398. } else {
  1399. $tab[$obj->code] = $libelle_type;
  1400. }
  1401. $i++;
  1402. }
  1403. return $tab;
  1404. } else {
  1405. $this->error = $this->db->lasterror();
  1406. //dol_print_error($this->db);
  1407. return null;
  1408. }
  1409. }
  1410. /**
  1411. * Return array with list of possible values for type of contacts
  1412. *
  1413. * @param string $source 'internal', 'external' or 'all'
  1414. * @param int $option 0=Return array id->label, 1=Return array code->label
  1415. * @param int $activeonly 0=all status of contact, 1=only the active
  1416. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1417. * @param string $element Filter on 1 element type
  1418. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1419. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1420. */
  1421. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1422. {
  1423. global $langs, $conf;
  1424. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1425. $tab = array();
  1426. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
  1427. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1428. $sqlWhere = array();
  1429. if (!empty($element)) {
  1430. $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
  1431. }
  1432. if (!empty($excludeelement)) {
  1433. $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
  1434. }
  1435. if ($activeonly == 1) {
  1436. $sqlWhere[] = " tc.active=1"; // only the active types
  1437. }
  1438. if (!empty($source) && $source != 'all') {
  1439. $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
  1440. }
  1441. if (!empty($code)) {
  1442. $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
  1443. }
  1444. if (count($sqlWhere) > 0) {
  1445. $sql .= " WHERE ".implode(' AND ', $sqlWhere);
  1446. }
  1447. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1448. dol_syslog(__METHOD__, LOG_DEBUG);
  1449. $resql = $this->db->query($sql);
  1450. if ($resql) {
  1451. $num = $this->db->num_rows($resql);
  1452. if ($num > 0) {
  1453. $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
  1454. while ($obj = $this->db->fetch_object($resql)) {
  1455. $modulename = $obj->element;
  1456. if (strpos($obj->element, 'project') !== false) {
  1457. $modulename = 'projet';
  1458. } elseif ($obj->element == 'contrat') {
  1459. $element = 'contract';
  1460. } elseif ($obj->element == 'action') {
  1461. $modulename = 'agenda';
  1462. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1463. $modulename = 'fournisseur';
  1464. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1465. $modulename = 'fournisseur';
  1466. }
  1467. if (!empty($conf->{$modulename}->enabled)) {
  1468. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1469. $tmpelement = $obj->element;
  1470. $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
  1471. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1472. if (empty($option)) {
  1473. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1474. } else {
  1475. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1476. }
  1477. }
  1478. }
  1479. }
  1480. return $tab;
  1481. } else {
  1482. $this->error = $this->db->lasterror();
  1483. return null;
  1484. }
  1485. }
  1486. /**
  1487. * Return id of contacts for a source and a contact code.
  1488. * Example: contact client de facturation ('external', 'BILLING')
  1489. * Example: contact client de livraison ('external', 'SHIPPING')
  1490. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1491. *
  1492. * @param string $source 'external' or 'internal'
  1493. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1494. * @param int $status limited to a certain status
  1495. * @return array List of id for such contacts
  1496. */
  1497. public function getIdContact($source, $code, $status = 0)
  1498. {
  1499. global $conf;
  1500. $result = array();
  1501. $i = 0;
  1502. //cas particulier pour les expeditions
  1503. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1504. $id = $this->origin_id;
  1505. $element = 'commande';
  1506. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1507. $id = $this->origin_id;
  1508. $element = 'order_supplier';
  1509. } else {
  1510. $id = $this->id;
  1511. $element = $this->element;
  1512. }
  1513. $sql = "SELECT ec.fk_socpeople";
  1514. $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
  1515. if ($source == 'internal') {
  1516. $sql .= " ".$this->db->prefix()."user as c,";
  1517. }
  1518. if ($source == 'external') {
  1519. $sql .= " ".$this->db->prefix()."socpeople as c,";
  1520. }
  1521. $sql .= " ".$this->db->prefix()."c_type_contact as tc";
  1522. $sql .= " WHERE ec.element_id = ".((int) $id);
  1523. $sql .= " AND ec.fk_socpeople = c.rowid";
  1524. if ($source == 'internal') {
  1525. $sql .= " AND c.entity IN (".getEntity('user').")";
  1526. }
  1527. if ($source == 'external') {
  1528. $sql .= " AND c.entity IN (".getEntity('societe').")";
  1529. }
  1530. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1531. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1532. $sql .= " AND tc.source = '".$this->db->escape($source)."'";
  1533. if ($code) {
  1534. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1535. }
  1536. $sql .= " AND tc.active = 1";
  1537. if ($status) {
  1538. $sql .= " AND ec.statut = ".((int) $status);
  1539. }
  1540. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1541. $resql = $this->db->query($sql);
  1542. if ($resql) {
  1543. while ($obj = $this->db->fetch_object($resql)) {
  1544. $result[$i] = $obj->fk_socpeople;
  1545. $i++;
  1546. }
  1547. } else {
  1548. $this->error = $this->db->error();
  1549. return null;
  1550. }
  1551. return $result;
  1552. }
  1553. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1554. /**
  1555. * Load object contact with id=$this->contact_id into $this->contact
  1556. *
  1557. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1558. * @return int <0 if KO, >0 if OK
  1559. */
  1560. public function fetch_contact($contactid = null)
  1561. {
  1562. // phpcs:enable
  1563. if (empty($contactid)) {
  1564. $contactid = $this->contact_id;
  1565. }
  1566. if (empty($contactid)) {
  1567. return 0;
  1568. }
  1569. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1570. $contact = new Contact($this->db);
  1571. $result = $contact->fetch($contactid);
  1572. $this->contact = $contact;
  1573. return $result;
  1574. }
  1575. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1576. /**
  1577. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1578. *
  1579. * @param int $force_thirdparty_id Force thirdparty id
  1580. * @return int <0 if KO, >0 if OK
  1581. */
  1582. public function fetch_thirdparty($force_thirdparty_id = 0)
  1583. {
  1584. // phpcs:enable
  1585. global $conf;
  1586. if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
  1587. return 0;
  1588. }
  1589. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1590. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
  1591. if ($force_thirdparty_id) {
  1592. $idtofetch = $force_thirdparty_id;
  1593. }
  1594. if ($idtofetch) {
  1595. $thirdparty = new Societe($this->db);
  1596. $result = $thirdparty->fetch($idtofetch);
  1597. if ($result<0) {
  1598. $this->errors=array_merge($this->errors, $thirdparty->errors);
  1599. }
  1600. $this->thirdparty = $thirdparty;
  1601. // Use first price level if level not defined for third party
  1602. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1603. $this->thirdparty->price_level = 1;
  1604. }
  1605. return $result;
  1606. } else {
  1607. return -1;
  1608. }
  1609. }
  1610. /**
  1611. * Looks for an object with ref matching the wildcard provided
  1612. * It does only work when $this->table_ref_field is set
  1613. *
  1614. * @param string $ref Wildcard
  1615. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1616. */
  1617. public function fetchOneLike($ref)
  1618. {
  1619. if (!$this->table_ref_field) {
  1620. return 0;
  1621. }
  1622. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element." WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."' LIMIT 1";
  1623. $query = $this->db->query($sql);
  1624. if (!$this->db->num_rows($query)) {
  1625. return 0;
  1626. }
  1627. $result = $this->db->fetch_object($query);
  1628. return $this->fetch($result->rowid);
  1629. }
  1630. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1631. /**
  1632. * Load data for barcode into properties ->barcode_type*
  1633. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1634. * if it is not defined, ->element must be defined to know default barcode type.
  1635. *
  1636. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1637. */
  1638. public function fetch_barcode()
  1639. {
  1640. // phpcs:enable
  1641. global $conf;
  1642. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1643. $idtype = $this->barcode_type;
  1644. 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
  1645. if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
  1646. $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1647. } elseif ($this->element == 'societe') {
  1648. $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1649. } else {
  1650. dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1651. }
  1652. }
  1653. if ($idtype > 0) {
  1654. 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
  1655. $sql = "SELECT rowid, code, libelle as label, coder";
  1656. $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
  1657. $sql .= " WHERE rowid = ".((int) $idtype);
  1658. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1659. $resql = $this->db->query($sql);
  1660. if ($resql) {
  1661. $obj = $this->db->fetch_object($resql);
  1662. $this->barcode_type = $obj->rowid;
  1663. $this->barcode_type_code = $obj->code;
  1664. $this->barcode_type_label = $obj->label;
  1665. $this->barcode_type_coder = $obj->coder;
  1666. return 1;
  1667. } else {
  1668. dol_print_error($this->db);
  1669. return -1;
  1670. }
  1671. }
  1672. }
  1673. return 0;
  1674. }
  1675. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1676. /**
  1677. * Load the project with id $this->fk_project into this->project
  1678. *
  1679. * @return int <0 if KO, >=0 if OK
  1680. */
  1681. public function fetch_project()
  1682. {
  1683. // phpcs:enable
  1684. return $this->fetch_projet();
  1685. }
  1686. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1687. /**
  1688. * Load the project with id $this->fk_project into this->project
  1689. *
  1690. * @return int <0 if KO, >=0 if OK
  1691. */
  1692. public function fetch_projet()
  1693. {
  1694. // phpcs:enable
  1695. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1696. if (empty($this->fk_project) && !empty($this->fk_projet)) {
  1697. $this->fk_project = $this->fk_projet; // For backward compatibility
  1698. }
  1699. if (empty($this->fk_project)) {
  1700. return 0;
  1701. }
  1702. $project = new Project($this->db);
  1703. $result = $project->fetch($this->fk_project);
  1704. $this->projet = $project; // deprecated
  1705. $this->project = $project;
  1706. return $result;
  1707. }
  1708. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1709. /**
  1710. * Load the product with id $this->fk_product into this->product
  1711. *
  1712. * @return int <0 if KO, >=0 if OK
  1713. */
  1714. public function fetch_product()
  1715. {
  1716. // phpcs:enable
  1717. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1718. if (empty($this->fk_product)) {
  1719. return 0;
  1720. }
  1721. $product = new Product($this->db);
  1722. $result = $product->fetch($this->fk_product);
  1723. $this->product = $product;
  1724. return $result;
  1725. }
  1726. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1727. /**
  1728. * Load the user with id $userid into this->user
  1729. *
  1730. * @param int $userid Id du contact
  1731. * @return int <0 if KO, >0 if OK
  1732. */
  1733. public function fetch_user($userid)
  1734. {
  1735. // phpcs:enable
  1736. $user = new User($this->db);
  1737. $result = $user->fetch($userid);
  1738. $this->user = $user;
  1739. return $result;
  1740. }
  1741. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1742. /**
  1743. * Read linked origin object
  1744. *
  1745. * @return void
  1746. */
  1747. public function fetch_origin()
  1748. {
  1749. // phpcs:enable
  1750. if ($this->origin == 'shipping') {
  1751. $this->origin = 'expedition';
  1752. }
  1753. if ($this->origin == 'delivery') {
  1754. $this->origin = 'livraison';
  1755. }
  1756. if ($this->origin == 'order_supplier') {
  1757. $this->origin = 'commandeFournisseur';
  1758. }
  1759. $origin = $this->origin;
  1760. $classname = ucfirst($origin);
  1761. $this->$origin = new $classname($this->db);
  1762. $this->$origin->fetch($this->origin_id);
  1763. }
  1764. /**
  1765. * Load object from specific field
  1766. *
  1767. * @param string $table Table element or element line
  1768. * @param string $field Field selected
  1769. * @param string $key Import key
  1770. * @param string $element Element name
  1771. * @return int <0 if KO, >0 if OK
  1772. */
  1773. public function fetchObjectFrom($table, $field, $key, $element = null)
  1774. {
  1775. global $conf;
  1776. $result = false;
  1777. $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
  1778. $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
  1779. if (!empty($element)) {
  1780. $sql .= " AND entity IN (".getEntity($element).")";
  1781. } else {
  1782. $sql .= " AND entity = ".((int) $conf->entity);
  1783. }
  1784. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1785. $resql = $this->db->query($sql);
  1786. if ($resql) {
  1787. $row = $this->db->fetch_row($resql);
  1788. // Test for avoid error -1
  1789. if ($row[0] > 0) {
  1790. $result = $this->fetch($row[0]);
  1791. }
  1792. }
  1793. return $result;
  1794. }
  1795. /**
  1796. * Getter generic. Load value from a specific field
  1797. *
  1798. * @param string $table Table of element or element line
  1799. * @param int $id Element id
  1800. * @param string $field Field selected
  1801. * @return int <0 if KO, >0 if OK
  1802. */
  1803. public function getValueFrom($table, $id, $field)
  1804. {
  1805. $result = false;
  1806. if (!empty($id) && !empty($field) && !empty($table)) {
  1807. $sql = "SELECT ".$field." FROM ".$this->db->prefix().$table;
  1808. $sql .= " WHERE rowid = ".((int) $id);
  1809. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1810. $resql = $this->db->query($sql);
  1811. if ($resql) {
  1812. $row = $this->db->fetch_row($resql);
  1813. $result = $row[0];
  1814. }
  1815. }
  1816. return $result;
  1817. }
  1818. /**
  1819. * Setter generic. Update a specific field into database.
  1820. * Warning: Trigger is run only if param trigkey is provided.
  1821. *
  1822. * @param string $field Field to update
  1823. * @param mixed $value New value
  1824. * @param string $table To force other table element or element line (should not be used)
  1825. * @param int $id To force other object id (should not be used)
  1826. * @param string $format Data format ('text', 'int', 'date'). 'text' is used if not defined
  1827. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1828. * @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'
  1829. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1830. * @param string $fk_user_field Name of field to save user id making change
  1831. * @return int <0 if KO, >0 if OK
  1832. * @see updateExtraField()
  1833. */
  1834. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1835. {
  1836. global $user, $langs, $conf;
  1837. if (empty($table)) {
  1838. $table = $this->table_element;
  1839. }
  1840. if (empty($id)) {
  1841. $id = $this->id;
  1842. }
  1843. if (empty($format)) {
  1844. $format = 'text';
  1845. }
  1846. if (empty($id_field)) {
  1847. $id_field = 'rowid';
  1848. }
  1849. // Special case
  1850. if ($table == 'product' && $field == 'note_private') {
  1851. $field = 'note';
  1852. }
  1853. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  1854. $fk_user_field = 'fk_user_mod';
  1855. }
  1856. if ($trigkey) {
  1857. $oldvalue = null;
  1858. $sql = "SELECT " . $field;
  1859. $sql .= " FROM " . MAIN_DB_PREFIX . $table;
  1860. $sql .= " WHERE " . $id_field . " = " . ((int) $id);
  1861. $resql = $this->db->query($sql);
  1862. if ($resql) {
  1863. if ($obj = $this->db->fetch_object($resql)) {
  1864. if ($format == 'date') {
  1865. $oldvalue = $this->db->jdate($obj->$field);
  1866. } else {
  1867. $oldvalue = $obj->$field;
  1868. }
  1869. }
  1870. } else {
  1871. $this->error = $this->db->lasterror();
  1872. return -1;
  1873. }
  1874. }
  1875. $error = 0;
  1876. dol_syslog(__METHOD__, LOG_DEBUG);
  1877. $this->db->begin();
  1878. $sql = "UPDATE ".$this->db->prefix().$table." SET ";
  1879. if ($format == 'text') {
  1880. $sql .= $field." = '".$this->db->escape($value)."'";
  1881. } elseif ($format == 'int') {
  1882. $sql .= $field." = ".((int) $value);
  1883. } elseif ($format == 'date') {
  1884. $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1885. } elseif ($format == 'dategmt') {
  1886. $sql .= $field." = ".($value ? "'".$this->db->idate($value, 'gmt')."'" : "null");
  1887. }
  1888. if ($fk_user_field) {
  1889. if (!empty($fuser) && is_object($fuser)) {
  1890. $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
  1891. } elseif (empty($fuser) || $fuser != 'none') {
  1892. $sql .= ", ".$fk_user_field." = ".((int) $user->id);
  1893. }
  1894. }
  1895. $sql .= " WHERE ".$id_field." = ".((int) $id);
  1896. $resql = $this->db->query($sql);
  1897. if ($resql) {
  1898. if ($trigkey) {
  1899. // call trigger with updated object values
  1900. if (method_exists($this, 'fetch')) {
  1901. $result = $this->fetch($id);
  1902. } else {
  1903. $result = $this->fetchCommon($id);
  1904. }
  1905. $this->oldcopy = clone $this;
  1906. if (property_exists($this->oldcopy, $field)) {
  1907. $this->oldcopy->$field = $oldvalue;
  1908. }
  1909. if ($result >= 0) {
  1910. $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1911. }
  1912. if ($result < 0) {
  1913. $error++;
  1914. }
  1915. }
  1916. if (!$error) {
  1917. if (property_exists($this, $field)) {
  1918. $this->$field = $value;
  1919. }
  1920. $this->db->commit();
  1921. return 1;
  1922. } else {
  1923. $this->db->rollback();
  1924. return -2;
  1925. }
  1926. } else {
  1927. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1928. $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
  1929. } else {
  1930. $this->error = $this->db->lasterror();
  1931. }
  1932. $this->db->rollback();
  1933. return -1;
  1934. }
  1935. }
  1936. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1937. /**
  1938. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1939. *
  1940. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')". Do not allow user input data here.
  1941. * @param string $fieldid Name of field to use for the select MAX and MIN
  1942. * @param int $nodbprefix Do not include DB prefix to forge table name
  1943. * @return int <0 if KO, >0 if OK
  1944. */
  1945. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1946. {
  1947. // phpcs:enable
  1948. global $conf, $user;
  1949. if (!$this->table_element) {
  1950. dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1951. return -1;
  1952. }
  1953. if ($fieldid == 'none') {
  1954. return 1;
  1955. }
  1956. // For backward compatibility
  1957. if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
  1958. $fieldid = 'titre';
  1959. }
  1960. // Security on socid
  1961. $socid = 0;
  1962. if ($user->socid > 0) {
  1963. $socid = $user->socid;
  1964. }
  1965. // this->ismultientitymanaged contains
  1966. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1967. $aliastablesociete = 's';
  1968. if ($this->element == 'societe') {
  1969. $aliastablesociete = 'te'; // te as table_element
  1970. }
  1971. $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
  1972. $sql = "SELECT MAX(te.".$fieldid.")";
  1973. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1974. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1975. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1976. }
  1977. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1978. $tmparray = explode('@', $this->ismultientitymanaged);
  1979. $sql .= ", ".$this->db->prefix().$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1980. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1981. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1982. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1983. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1984. }
  1985. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1986. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1987. }
  1988. $sql .= " WHERE te.".$fieldid." < '".$this->db->escape($fieldid == 'rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
  1989. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1990. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1991. }
  1992. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1993. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1994. }
  1995. if (!empty($filter)) {
  1996. if (!preg_match('/^\s*AND/i', $filter)) {
  1997. $sql .= " AND "; // For backward compatibility
  1998. }
  1999. $sql .= $filter;
  2000. }
  2001. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  2002. $tmparray = explode('@', $this->ismultientitymanaged);
  2003. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  2004. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  2005. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  2006. }
  2007. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  2008. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  2009. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  2010. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  2011. } else {
  2012. $sql .= " AND ug.fk_user = te.rowid";
  2013. $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
  2014. }
  2015. } else {
  2016. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  2017. }
  2018. }
  2019. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  2020. $tmparray = explode('@', $this->ismultientitymanaged);
  2021. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  2022. }
  2023. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  2024. $sql .= ' AND te.fk_soc = '.((int) $socid);
  2025. }
  2026. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  2027. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  2028. }
  2029. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  2030. $sql .= ' AND te.rowid = '.((int) $socid);
  2031. }
  2032. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  2033. $result = $this->db->query($sql);
  2034. if (!$result) {
  2035. $this->error = $this->db->lasterror();
  2036. return -1;
  2037. }
  2038. $row = $this->db->fetch_row($result);
  2039. $this->ref_previous = $row[0];
  2040. $sql = "SELECT MIN(te.".$fieldid.")";
  2041. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  2042. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  2043. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  2044. }
  2045. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  2046. $tmparray = explode('@', $this->ismultientitymanaged);
  2047. $sql .= ", ".$this->db->prefix().$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  2048. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  2049. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  2050. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  2051. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  2052. }
  2053. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  2054. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  2055. }
  2056. $sql .= " WHERE te.".$fieldid." > '".$this->db->escape($fieldid == 'rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
  2057. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  2058. $sql .= " AND sc.fk_user = ".((int) $user->id);
  2059. }
  2060. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  2061. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  2062. }
  2063. if (!empty($filter)) {
  2064. if (!preg_match('/^\s*AND/i', $filter)) {
  2065. $sql .= " AND "; // For backward compatibility
  2066. }
  2067. $sql .= $filter;
  2068. }
  2069. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  2070. $tmparray = explode('@', $this->ismultientitymanaged);
  2071. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  2072. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  2073. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  2074. }
  2075. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  2076. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  2077. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  2078. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  2079. } else {
  2080. $sql .= " AND ug.fk_user = te.rowid";
  2081. $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
  2082. }
  2083. } else {
  2084. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  2085. }
  2086. }
  2087. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  2088. $tmparray = explode('@', $this->ismultientitymanaged);
  2089. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  2090. }
  2091. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  2092. $sql .= ' AND te.fk_soc = '.((int) $socid);
  2093. }
  2094. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  2095. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  2096. }
  2097. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  2098. $sql .= ' AND te.rowid = '.((int) $socid);
  2099. }
  2100. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  2101. // 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
  2102. $result = $this->db->query($sql);
  2103. if (!$result) {
  2104. $this->error = $this->db->lasterror();
  2105. return -2;
  2106. }
  2107. $row = $this->db->fetch_row($result);
  2108. $this->ref_next = $row[0];
  2109. return 1;
  2110. }
  2111. /**
  2112. * Return list of id of contacts of object
  2113. *
  2114. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  2115. * @return array Array of id of contacts (if source=external or internal)
  2116. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  2117. */
  2118. public function getListContactId($source = 'external')
  2119. {
  2120. $contactAlreadySelected = array();
  2121. $tab = $this->liste_contact(-1, $source);
  2122. $num = count($tab);
  2123. $i = 0;
  2124. while ($i < $num) {
  2125. if ($source == 'thirdparty') {
  2126. $contactAlreadySelected[$i] = $tab[$i]['socid'];
  2127. } else {
  2128. $contactAlreadySelected[$i] = $tab[$i]['id'];
  2129. }
  2130. $i++;
  2131. }
  2132. return $contactAlreadySelected;
  2133. }
  2134. /**
  2135. * Link element with a project
  2136. *
  2137. * @param int $projectid Project id to link element to
  2138. * @param int $notrigger Disable the trigger
  2139. * @return int <0 if KO, >0 if OK
  2140. */
  2141. public function setProject($projectid, $notrigger = 0)
  2142. {
  2143. global $user;
  2144. $error = 0;
  2145. if (!$this->table_element) {
  2146. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  2147. return -1;
  2148. }
  2149. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2150. if (!empty($this->fields['fk_project'])) { // Common case
  2151. if ($projectid) {
  2152. $sql .= " SET fk_project = ".((int) $projectid);
  2153. } else {
  2154. $sql .= " SET fk_project = NULL";
  2155. }
  2156. $sql .= ' WHERE rowid = '.((int) $this->id);
  2157. } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
  2158. if ($projectid) {
  2159. $sql .= " SET fk_project = ".((int) $projectid);
  2160. } else {
  2161. $sql .= " SET fk_project = NULL";
  2162. }
  2163. $sql .= ' WHERE id = '.((int) $this->id);
  2164. } else // Special case for old architecture objects
  2165. {
  2166. if ($projectid) {
  2167. $sql .= ' SET fk_projet = '.((int) $projectid);
  2168. } else {
  2169. $sql .= ' SET fk_projet = NULL';
  2170. }
  2171. $sql .= " WHERE rowid = ".((int) $this->id);
  2172. }
  2173. $this->db->begin();
  2174. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  2175. if ($this->db->query($sql)) {
  2176. $this->fk_project = ((int) $projectid);
  2177. } else {
  2178. dol_print_error($this->db);
  2179. $error++;
  2180. }
  2181. // Triggers
  2182. if (!$error && !$notrigger) {
  2183. // Call triggers
  2184. $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
  2185. if ($result < 0) {
  2186. $error++;
  2187. } //Do also here what you must do to rollback action if trigger fail
  2188. // End call triggers
  2189. }
  2190. // Commit or rollback
  2191. if ($error) {
  2192. $this->db->rollback();
  2193. return -1;
  2194. } else {
  2195. $this->db->commit();
  2196. return 1;
  2197. }
  2198. }
  2199. /**
  2200. * Change the payments methods
  2201. *
  2202. * @param int $id Id of new payment method
  2203. * @return int >0 if OK, <0 if KO
  2204. */
  2205. public function setPaymentMethods($id)
  2206. {
  2207. global $user;
  2208. $error = 0; $notrigger = 0;
  2209. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  2210. if ($this->statut >= 0 || $this->element == 'societe') {
  2211. // TODO uniformize field name
  2212. $fieldname = 'fk_mode_reglement';
  2213. if ($this->element == 'societe') {
  2214. $fieldname = 'mode_reglement';
  2215. }
  2216. if (get_class($this) == 'Fournisseur') {
  2217. $fieldname = 'mode_reglement_supplier';
  2218. }
  2219. if (get_class($this) == 'Tva') {
  2220. $fieldname = 'fk_typepayment';
  2221. }
  2222. if (get_class($this) == 'Salary') {
  2223. $fieldname = 'fk_typepayment';
  2224. }
  2225. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2226. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2227. $sql .= ' WHERE rowid='.((int) $this->id);
  2228. if ($this->db->query($sql)) {
  2229. $this->mode_reglement_id = $id;
  2230. // for supplier
  2231. if (get_class($this) == 'Fournisseur') {
  2232. $this->mode_reglement_supplier_id = $id;
  2233. }
  2234. // Triggers
  2235. if (!$error && !$notrigger) {
  2236. // Call triggers
  2237. if (get_class($this) == 'Commande') {
  2238. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2239. } else {
  2240. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  2241. }
  2242. if ($result < 0) {
  2243. $error++;
  2244. }
  2245. // End call triggers
  2246. }
  2247. return 1;
  2248. } else {
  2249. dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
  2250. $this->error = $this->db->error();
  2251. return -1;
  2252. }
  2253. } else {
  2254. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  2255. $this->error = 'Status of the object is incompatible '.$this->statut;
  2256. return -2;
  2257. }
  2258. }
  2259. /**
  2260. * Change the multicurrency code
  2261. *
  2262. * @param string $code multicurrency code
  2263. * @return int >0 if OK, <0 if KO
  2264. */
  2265. public function setMulticurrencyCode($code)
  2266. {
  2267. dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
  2268. if ($this->statut >= 0 || $this->element == 'societe') {
  2269. $fieldname = 'multicurrency_code';
  2270. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2271. $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
  2272. $sql .= ' WHERE rowid='.((int) $this->id);
  2273. if ($this->db->query($sql)) {
  2274. $this->multicurrency_code = $code;
  2275. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  2276. if ($rate) {
  2277. $this->setMulticurrencyRate($rate, 2);
  2278. }
  2279. return 1;
  2280. } else {
  2281. dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
  2282. $this->error = $this->db->error();
  2283. return -1;
  2284. }
  2285. } else {
  2286. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  2287. $this->error = 'Status of the object is incompatible '.$this->statut;
  2288. return -2;
  2289. }
  2290. }
  2291. /**
  2292. * Change the multicurrency rate
  2293. *
  2294. * @param double $rate multicurrency rate
  2295. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  2296. * @return int >0 if OK, <0 if KO
  2297. */
  2298. public function setMulticurrencyRate($rate, $mode = 1)
  2299. {
  2300. dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
  2301. if ($this->statut >= 0 || $this->element == 'societe') {
  2302. $fieldname = 'multicurrency_tx';
  2303. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2304. $sql .= " SET ".$fieldname." = ".((float) $rate);
  2305. $sql .= ' WHERE rowid='.((int) $this->id);
  2306. if ($this->db->query($sql)) {
  2307. $this->multicurrency_tx = $rate;
  2308. // Update line price
  2309. if (!empty($this->lines)) {
  2310. foreach ($this->lines as &$line) {
  2311. // Amounts in company currency will be recalculated
  2312. if ($mode == 1) {
  2313. $line->subprice = 0;
  2314. }
  2315. // Amounts in foreign currency will be recalculated
  2316. if ($mode == 2) {
  2317. $line->multicurrency_subprice = 0;
  2318. }
  2319. switch ($this->element) {
  2320. case 'propal':
  2321. $this->updateline(
  2322. $line->id,
  2323. $line->subprice,
  2324. $line->qty,
  2325. $line->remise_percent,
  2326. $line->tva_tx,
  2327. $line->localtax1_tx,
  2328. $line->localtax2_tx,
  2329. ($line->description ? $line->description : $line->desc),
  2330. 'HT',
  2331. $line->info_bits,
  2332. $line->special_code,
  2333. $line->fk_parent_line,
  2334. $line->skip_update_total,
  2335. $line->fk_fournprice,
  2336. $line->pa_ht,
  2337. $line->label,
  2338. $line->product_type,
  2339. $line->date_start,
  2340. $line->date_end,
  2341. $line->array_options,
  2342. $line->fk_unit,
  2343. $line->multicurrency_subprice
  2344. );
  2345. break;
  2346. case 'commande':
  2347. $this->updateline(
  2348. $line->id,
  2349. ($line->description ? $line->description : $line->desc),
  2350. $line->subprice,
  2351. $line->qty,
  2352. $line->remise_percent,
  2353. $line->tva_tx,
  2354. $line->localtax1_tx,
  2355. $line->localtax2_tx,
  2356. 'HT',
  2357. $line->info_bits,
  2358. $line->date_start,
  2359. $line->date_end,
  2360. $line->product_type,
  2361. $line->fk_parent_line,
  2362. $line->skip_update_total,
  2363. $line->fk_fournprice,
  2364. $line->pa_ht,
  2365. $line->label,
  2366. $line->special_code,
  2367. $line->array_options,
  2368. $line->fk_unit,
  2369. $line->multicurrency_subprice
  2370. );
  2371. break;
  2372. case 'facture':
  2373. $this->updateline(
  2374. $line->id,
  2375. ($line->description ? $line->description : $line->desc),
  2376. $line->subprice,
  2377. $line->qty,
  2378. $line->remise_percent,
  2379. $line->date_start,
  2380. $line->date_end,
  2381. $line->tva_tx,
  2382. $line->localtax1_tx,
  2383. $line->localtax2_tx,
  2384. 'HT',
  2385. $line->info_bits,
  2386. $line->product_type,
  2387. $line->fk_parent_line,
  2388. $line->skip_update_total,
  2389. $line->fk_fournprice,
  2390. $line->pa_ht,
  2391. $line->label,
  2392. $line->special_code,
  2393. $line->array_options,
  2394. $line->situation_percent,
  2395. $line->fk_unit,
  2396. $line->multicurrency_subprice
  2397. );
  2398. break;
  2399. case 'supplier_proposal':
  2400. $this->updateline(
  2401. $line->id,
  2402. $line->subprice,
  2403. $line->qty,
  2404. $line->remise_percent,
  2405. $line->tva_tx,
  2406. $line->localtax1_tx,
  2407. $line->localtax2_tx,
  2408. ($line->description ? $line->description : $line->desc),
  2409. 'HT',
  2410. $line->info_bits,
  2411. $line->special_code,
  2412. $line->fk_parent_line,
  2413. $line->skip_update_total,
  2414. $line->fk_fournprice,
  2415. $line->pa_ht,
  2416. $line->label,
  2417. $line->product_type,
  2418. $line->array_options,
  2419. $line->ref_fourn,
  2420. $line->multicurrency_subprice
  2421. );
  2422. break;
  2423. case 'order_supplier':
  2424. $this->updateline(
  2425. $line->id,
  2426. ($line->description ? $line->description : $line->desc),
  2427. $line->subprice,
  2428. $line->qty,
  2429. $line->remise_percent,
  2430. $line->tva_tx,
  2431. $line->localtax1_tx,
  2432. $line->localtax2_tx,
  2433. 'HT',
  2434. $line->info_bits,
  2435. $line->product_type,
  2436. false,
  2437. $line->date_start,
  2438. $line->date_end,
  2439. $line->array_options,
  2440. $line->fk_unit,
  2441. $line->multicurrency_subprice,
  2442. $line->ref_supplier
  2443. );
  2444. break;
  2445. case 'invoice_supplier':
  2446. $this->updateline(
  2447. $line->id,
  2448. ($line->description ? $line->description : $line->desc),
  2449. $line->subprice,
  2450. $line->tva_tx,
  2451. $line->localtax1_tx,
  2452. $line->localtax2_tx,
  2453. $line->qty,
  2454. 0,
  2455. 'HT',
  2456. $line->info_bits,
  2457. $line->product_type,
  2458. $line->remise_percent,
  2459. false,
  2460. $line->date_start,
  2461. $line->date_end,
  2462. $line->array_options,
  2463. $line->fk_unit,
  2464. $line->multicurrency_subprice,
  2465. $line->ref_supplier
  2466. );
  2467. break;
  2468. default:
  2469. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  2470. break;
  2471. }
  2472. }
  2473. }
  2474. return 1;
  2475. } else {
  2476. dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
  2477. $this->error = $this->db->error();
  2478. return -1;
  2479. }
  2480. } else {
  2481. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  2482. $this->error = 'Status of the object is incompatible '.$this->statut;
  2483. return -2;
  2484. }
  2485. }
  2486. /**
  2487. * Change the payments terms
  2488. *
  2489. * @param int $id Id of new payment terms
  2490. * @param string $deposit_percent % of deposit if needed by payment terms
  2491. * @return int >0 if OK, <0 if KO
  2492. */
  2493. public function setPaymentTerms($id, $deposit_percent = null)
  2494. {
  2495. dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
  2496. if ($this->statut >= 0 || $this->element == 'societe') {
  2497. // TODO uniformize field name
  2498. $fieldname = 'fk_cond_reglement';
  2499. if ($this->element == 'societe') {
  2500. $fieldname = 'cond_reglement';
  2501. }
  2502. if (get_class($this) == 'Fournisseur') {
  2503. $fieldname = 'cond_reglement_supplier';
  2504. }
  2505. if (empty($deposit_percent) || $deposit_percent < 0) {
  2506. $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id);
  2507. }
  2508. if ($deposit_percent > 100) {
  2509. $deposit_percent = 100;
  2510. }
  2511. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2512. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2513. if (in_array($this->table_element, array('propal', 'commande'))) {
  2514. $sql .= " , deposit_percent = " . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'");
  2515. }
  2516. $sql .= ' WHERE rowid='.((int) $this->id);
  2517. if ($this->db->query($sql)) {
  2518. $this->cond_reglement_id = $id;
  2519. // for supplier
  2520. if (get_class($this) == 'Fournisseur') {
  2521. $this->cond_reglement_supplier_id = $id;
  2522. }
  2523. $this->cond_reglement = $id; // for compatibility
  2524. $this->deposit_percent = $deposit_percent;
  2525. return 1;
  2526. } else {
  2527. dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
  2528. $this->error = $this->db->error();
  2529. return -1;
  2530. }
  2531. } else {
  2532. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  2533. $this->error = 'Status of the object is incompatible '.$this->statut;
  2534. return -2;
  2535. }
  2536. }
  2537. /**
  2538. * Change the transport mode methods
  2539. *
  2540. * @param int $id Id of transport mode
  2541. * @return int >0 if OK, <0 if KO
  2542. */
  2543. public function setTransportMode($id)
  2544. {
  2545. dol_syslog(get_class($this).'::setTransportMode('.$id.')');
  2546. if ($this->statut >= 0 || $this->element == 'societe') {
  2547. $fieldname = 'fk_transport_mode';
  2548. if ($this->element == 'societe') {
  2549. $fieldname = 'transport_mode';
  2550. }
  2551. if (get_class($this) == 'Fournisseur') {
  2552. $fieldname = 'transport_mode_supplier';
  2553. }
  2554. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2555. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2556. $sql .= ' WHERE rowid='.((int) $this->id);
  2557. if ($this->db->query($sql)) {
  2558. $this->transport_mode_id = $id;
  2559. // for supplier
  2560. if (get_class($this) == 'Fournisseur') {
  2561. $this->transport_mode_supplier_id = $id;
  2562. }
  2563. return 1;
  2564. } else {
  2565. dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
  2566. $this->error = $this->db->error();
  2567. return -1;
  2568. }
  2569. } else {
  2570. dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
  2571. $this->error = 'Status of the object is incompatible '.$this->statut;
  2572. return -2;
  2573. }
  2574. }
  2575. /**
  2576. * Change the retained warranty payments terms
  2577. *
  2578. * @param int $id Id of new payment terms
  2579. * @return int >0 if OK, <0 if KO
  2580. */
  2581. public function setRetainedWarrantyPaymentTerms($id)
  2582. {
  2583. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
  2584. if ($this->statut >= 0 || $this->element == 'societe') {
  2585. $fieldname = 'retained_warranty_fk_cond_reglement';
  2586. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2587. $sql .= " SET ".$fieldname." = ".((int) $id);
  2588. $sql .= ' WHERE rowid='.((int) $this->id);
  2589. if ($this->db->query($sql)) {
  2590. $this->retained_warranty_fk_cond_reglement = $id;
  2591. return 1;
  2592. } else {
  2593. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
  2594. $this->error = $this->db->error();
  2595. return -1;
  2596. }
  2597. } else {
  2598. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  2599. $this->error = 'Status of the object is incompatible '.$this->statut;
  2600. return -2;
  2601. }
  2602. }
  2603. /**
  2604. * Define delivery address
  2605. * @deprecated
  2606. *
  2607. * @param int $id Address id
  2608. * @return int <0 si ko, >0 si ok
  2609. */
  2610. public function setDeliveryAddress($id)
  2611. {
  2612. $fieldname = 'fk_delivery_address';
  2613. if ($this->element == 'delivery' || $this->element == 'shipping') {
  2614. $fieldname = 'fk_address';
  2615. }
  2616. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$fieldname." = ".((int) $id);
  2617. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
  2618. if ($this->db->query($sql)) {
  2619. $this->fk_delivery_address = $id;
  2620. return 1;
  2621. } else {
  2622. $this->error = $this->db->error();
  2623. dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
  2624. return -1;
  2625. }
  2626. }
  2627. /**
  2628. * Change the shipping method
  2629. *
  2630. * @param int $shipping_method_id Id of shipping method
  2631. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2632. * @param User $userused Object user
  2633. *
  2634. * @return int 1 if OK, 0 if KO
  2635. */
  2636. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  2637. {
  2638. global $user;
  2639. if (empty($userused)) {
  2640. $userused = $user;
  2641. }
  2642. $error = 0;
  2643. if (!$this->table_element) {
  2644. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2645. return -1;
  2646. }
  2647. $this->db->begin();
  2648. if ($shipping_method_id < 0) {
  2649. $shipping_method_id = 'NULL';
  2650. }
  2651. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  2652. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2653. $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
  2654. $sql .= " WHERE rowid=".((int) $this->id);
  2655. $resql = $this->db->query($sql);
  2656. if (!$resql) {
  2657. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  2658. $this->error = $this->db->lasterror();
  2659. $error++;
  2660. } else {
  2661. if (!$notrigger) {
  2662. // Call trigger
  2663. $this->context = array('shippingmethodupdate'=>1);
  2664. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2665. if ($result < 0) {
  2666. $error++;
  2667. }
  2668. // End call trigger
  2669. }
  2670. }
  2671. if ($error) {
  2672. $this->db->rollback();
  2673. return -1;
  2674. } else {
  2675. $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
  2676. $this->db->commit();
  2677. return 1;
  2678. }
  2679. }
  2680. /**
  2681. * Change the warehouse
  2682. *
  2683. * @param int $warehouse_id Id of warehouse
  2684. * @return int 1 if OK, 0 if KO
  2685. */
  2686. public function setWarehouse($warehouse_id)
  2687. {
  2688. if (!$this->table_element) {
  2689. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2690. return -1;
  2691. }
  2692. if ($warehouse_id < 0) {
  2693. $warehouse_id = 'NULL';
  2694. }
  2695. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  2696. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2697. $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
  2698. $sql .= " WHERE rowid=".((int) $this->id);
  2699. if ($this->db->query($sql)) {
  2700. $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
  2701. return 1;
  2702. } else {
  2703. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  2704. $this->error = $this->db->error();
  2705. return 0;
  2706. }
  2707. }
  2708. /**
  2709. * Set last model used by doc generator
  2710. *
  2711. * @param User $user User object that make change
  2712. * @param string $modelpdf Modele name
  2713. * @return int <0 if KO, >0 if OK
  2714. */
  2715. public function setDocModel($user, $modelpdf)
  2716. {
  2717. if (!$this->table_element) {
  2718. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2719. return -1;
  2720. }
  2721. $newmodelpdf = dol_trunc($modelpdf, 255);
  2722. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2723. $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  2724. $sql .= " WHERE rowid = ".((int) $this->id);
  2725. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  2726. $resql = $this->db->query($sql);
  2727. if ($resql) {
  2728. $this->model_pdf = $modelpdf;
  2729. $this->modelpdf = $modelpdf; // For bakward compatibility
  2730. return 1;
  2731. } else {
  2732. dol_print_error($this->db);
  2733. return 0;
  2734. }
  2735. }
  2736. /**
  2737. * Change the bank account
  2738. *
  2739. * @param int $fk_account Id of bank account
  2740. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2741. * @param User $userused Object user
  2742. * @return int 1 if OK, 0 if KO
  2743. */
  2744. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2745. {
  2746. global $user;
  2747. if (empty($userused)) {
  2748. $userused = $user;
  2749. }
  2750. $error = 0;
  2751. if (!$this->table_element) {
  2752. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2753. return -1;
  2754. }
  2755. $this->db->begin();
  2756. if ($fk_account < 0) {
  2757. $fk_account = 'NULL';
  2758. }
  2759. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  2760. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2761. $sql .= " SET fk_account = ".((int) $fk_account);
  2762. $sql .= " WHERE rowid=".((int) $this->id);
  2763. $resql = $this->db->query($sql);
  2764. if (!$resql) {
  2765. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  2766. $this->error = $this->db->lasterror();
  2767. $error++;
  2768. } else {
  2769. if (!$notrigger) {
  2770. // Call trigger
  2771. $this->context = array('bankaccountupdate'=>1);
  2772. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2773. if ($result < 0) {
  2774. $error++;
  2775. }
  2776. // End call trigger
  2777. }
  2778. }
  2779. if ($error) {
  2780. $this->db->rollback();
  2781. return -1;
  2782. } else {
  2783. $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
  2784. $this->db->commit();
  2785. return 1;
  2786. }
  2787. }
  2788. // TODO: Move line related operations to CommonObjectLine?
  2789. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2790. /**
  2791. * Save a new position (field rang) for details lines.
  2792. * You can choose to set position for lines with already a position or lines without any position defined.
  2793. *
  2794. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2795. * @param string $rowidorder ASC or DESC
  2796. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2797. * @return int <0 if KO, >0 if OK
  2798. */
  2799. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2800. {
  2801. // phpcs:enable
  2802. if (!$this->table_element_line) {
  2803. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2804. return -1;
  2805. }
  2806. if (!$this->fk_element) {
  2807. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2808. return -1;
  2809. }
  2810. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2811. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2812. $fieldposition = 'position';
  2813. }
  2814. // Count number of lines to reorder (according to choice $renum)
  2815. $nl = 0;
  2816. $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
  2817. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2818. if (!$renum) {
  2819. $sql .= " AND " . $fieldposition . " = 0";
  2820. }
  2821. if ($renum) {
  2822. $sql .= " AND " . $fieldposition . " <> 0";
  2823. }
  2824. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  2825. $resql = $this->db->query($sql);
  2826. if ($resql) {
  2827. $row = $this->db->fetch_row($resql);
  2828. $nl = $row[0];
  2829. } else {
  2830. dol_print_error($this->db);
  2831. }
  2832. if ($nl > 0) {
  2833. // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
  2834. $rows = array();
  2835. // We first search all lines that are parent lines (for multilevel details lines)
  2836. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2837. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2838. if ($fk_parent_line) {
  2839. $sql .= ' AND fk_parent_line IS NULL';
  2840. }
  2841. $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder;
  2842. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  2843. $resql = $this->db->query($sql);
  2844. if ($resql) {
  2845. $i = 0;
  2846. $num = $this->db->num_rows($resql);
  2847. while ($i < $num) {
  2848. $row = $this->db->fetch_row($resql);
  2849. $rows[] = $row[0]; // Add parent line into array rows
  2850. $childrens = $this->getChildrenOfLine($row[0]);
  2851. if (!empty($childrens)) {
  2852. foreach ($childrens as $child) {
  2853. array_push($rows, $child);
  2854. }
  2855. }
  2856. $i++;
  2857. }
  2858. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2859. if (!empty($rows)) {
  2860. foreach ($rows as $key => $row) {
  2861. $this->updateRangOfLine($row, ($key + 1));
  2862. }
  2863. }
  2864. } else {
  2865. dol_print_error($this->db);
  2866. }
  2867. }
  2868. return 1;
  2869. }
  2870. /**
  2871. * Get children of line
  2872. *
  2873. * @param int $id Id of parent line
  2874. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2875. * @return array Array with list of children lines id
  2876. */
  2877. public function getChildrenOfLine($id, $includealltree = 0)
  2878. {
  2879. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2880. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2881. $fieldposition = 'position';
  2882. }
  2883. $rows = array();
  2884. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2885. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2886. $sql .= ' AND fk_parent_line = '.((int) $id);
  2887. $sql .= " ORDER BY " . $fieldposition . " ASC";
  2888. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
  2889. $resql = $this->db->query($sql);
  2890. if ($resql) {
  2891. if ($this->db->num_rows($resql) > 0) {
  2892. while ($row = $this->db->fetch_row($resql)) {
  2893. $rows[] = $row[0];
  2894. if (!empty($includealltree)) {
  2895. $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2896. }
  2897. }
  2898. }
  2899. }
  2900. return $rows;
  2901. }
  2902. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2903. /**
  2904. * Update a line to have a lower rank
  2905. *
  2906. * @param int $rowid Id of line
  2907. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2908. * @return void
  2909. */
  2910. public function line_up($rowid, $fk_parent_line = true)
  2911. {
  2912. // phpcs:enable
  2913. $this->line_order(false, 'ASC', $fk_parent_line);
  2914. // Get rang of line
  2915. $rang = $this->getRangOfLine($rowid);
  2916. // Update position of line
  2917. $this->updateLineUp($rowid, $rang);
  2918. }
  2919. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2920. /**
  2921. * Update a line to have a higher rank
  2922. *
  2923. * @param int $rowid Id of line
  2924. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2925. * @return void
  2926. */
  2927. public function line_down($rowid, $fk_parent_line = true)
  2928. {
  2929. // phpcs:enable
  2930. $this->line_order(false, 'ASC', $fk_parent_line);
  2931. // Get rang of line
  2932. $rang = $this->getRangOfLine($rowid);
  2933. // Get max value for rang
  2934. $max = $this->line_max();
  2935. // Update position of line
  2936. $this->updateLineDown($rowid, $rang, $max);
  2937. }
  2938. /**
  2939. * Update position of line (rang)
  2940. *
  2941. * @param int $rowid Id of line
  2942. * @param int $rang Position
  2943. * @return int <0 if KO, >0 if OK
  2944. */
  2945. public function updateRangOfLine($rowid, $rang)
  2946. {
  2947. global $hookmanager;
  2948. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2949. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2950. $fieldposition = 'position';
  2951. }
  2952. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2953. $sql .= ' WHERE rowid = '.((int) $rowid);
  2954. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2955. if (!$this->db->query($sql)) {
  2956. dol_print_error($this->db);
  2957. return -1;
  2958. } else {
  2959. $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
  2960. $action='';
  2961. $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
  2962. return 1;
  2963. }
  2964. }
  2965. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2966. /**
  2967. * Update position of line with ajax (rang)
  2968. *
  2969. * @param array $rows Array of rows
  2970. * @return void
  2971. */
  2972. public function line_ajaxorder($rows)
  2973. {
  2974. // phpcs:enable
  2975. $num = count($rows);
  2976. for ($i = 0; $i < $num; $i++) {
  2977. $this->updateRangOfLine($rows[$i], ($i + 1));
  2978. }
  2979. }
  2980. /**
  2981. * Update position of line up (rang)
  2982. *
  2983. * @param int $rowid Id of line
  2984. * @param int $rang Position
  2985. * @return void
  2986. */
  2987. public function updateLineUp($rowid, $rang)
  2988. {
  2989. if ($rang > 1) {
  2990. $fieldposition = 'rang';
  2991. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2992. $fieldposition = 'position';
  2993. }
  2994. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2995. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2996. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1));
  2997. if ($this->db->query($sql)) {
  2998. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
  2999. $sql .= ' WHERE rowid = '.((int) $rowid);
  3000. if (!$this->db->query($sql)) {
  3001. dol_print_error($this->db);
  3002. }
  3003. } else {
  3004. dol_print_error($this->db);
  3005. }
  3006. }
  3007. }
  3008. /**
  3009. * Update position of line down (rang)
  3010. *
  3011. * @param int $rowid Id of line
  3012. * @param int $rang Position
  3013. * @param int $max Max
  3014. * @return void
  3015. */
  3016. public function updateLineDown($rowid, $rang, $max)
  3017. {
  3018. if ($rang < $max) {
  3019. $fieldposition = 'rang';
  3020. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  3021. $fieldposition = 'position';
  3022. }
  3023. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  3024. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3025. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1));
  3026. if ($this->db->query($sql)) {
  3027. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
  3028. $sql .= ' WHERE rowid = '.((int) $rowid);
  3029. if (!$this->db->query($sql)) {
  3030. dol_print_error($this->db);
  3031. }
  3032. } else {
  3033. dol_print_error($this->db);
  3034. }
  3035. }
  3036. }
  3037. /**
  3038. * Get position of line (rang)
  3039. *
  3040. * @param int $rowid Id of line
  3041. * @return int Value of rang in table of lines
  3042. */
  3043. public function getRangOfLine($rowid)
  3044. {
  3045. $fieldposition = 'rang';
  3046. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  3047. $fieldposition = 'position';
  3048. }
  3049. $sql = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line;
  3050. $sql .= " WHERE rowid = ".((int) $rowid);
  3051. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  3052. $resql = $this->db->query($sql);
  3053. if ($resql) {
  3054. $row = $this->db->fetch_row($resql);
  3055. return $row[0];
  3056. }
  3057. return 0;
  3058. }
  3059. /**
  3060. * Get rowid of the line relative to its position
  3061. *
  3062. * @param int $rang Rang value
  3063. * @return int Rowid of the line
  3064. */
  3065. public function getIdOfLine($rang)
  3066. {
  3067. $fieldposition = 'rang';
  3068. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  3069. $fieldposition = 'position';
  3070. }
  3071. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  3072. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3073. $sql .= " AND " . $fieldposition . " = ".((int) $rang);
  3074. $resql = $this->db->query($sql);
  3075. if ($resql) {
  3076. $row = $this->db->fetch_row($resql);
  3077. return $row[0];
  3078. }
  3079. return 0;
  3080. }
  3081. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3082. /**
  3083. * Get max value used for position of line (rang)
  3084. *
  3085. * @param int $fk_parent_line Parent line id
  3086. * @return int Max value of rang in table of lines
  3087. */
  3088. public function line_max($fk_parent_line = 0)
  3089. {
  3090. // phpcs:enable
  3091. $positionfield = 'rang';
  3092. if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
  3093. $positionfield = 'position';
  3094. }
  3095. // Search the last rang with fk_parent_line
  3096. if ($fk_parent_line) {
  3097. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  3098. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3099. $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
  3100. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  3101. $resql = $this->db->query($sql);
  3102. if ($resql) {
  3103. $row = $this->db->fetch_row($resql);
  3104. if (!empty($row[0])) {
  3105. return $row[0];
  3106. } else {
  3107. return $this->getRangOfLine($fk_parent_line);
  3108. }
  3109. }
  3110. } else {
  3111. // If not, search the last rang of element
  3112. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  3113. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3114. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  3115. $resql = $this->db->query($sql);
  3116. if ($resql) {
  3117. $row = $this->db->fetch_row($resql);
  3118. return $row[0];
  3119. }
  3120. }
  3121. return 0;
  3122. }
  3123. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3124. /**
  3125. * Update external ref of element
  3126. *
  3127. * @param string $ref_ext Update field ref_ext
  3128. * @return int <0 if KO, >0 if OK
  3129. */
  3130. public function update_ref_ext($ref_ext)
  3131. {
  3132. // phpcs:enable
  3133. if (!$this->table_element) {
  3134. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  3135. return -1;
  3136. }
  3137. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  3138. $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  3139. $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
  3140. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  3141. if ($this->db->query($sql)) {
  3142. $this->ref_ext = $ref_ext;
  3143. return 1;
  3144. } else {
  3145. $this->error = $this->db->error();
  3146. return -1;
  3147. }
  3148. }
  3149. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3150. /**
  3151. * Update note of element
  3152. *
  3153. * @param string $note New value for note
  3154. * @param string $suffix '', '_public' or '_private'
  3155. * @return int <0 if KO, >0 if OK
  3156. */
  3157. public function update_note($note, $suffix = '')
  3158. {
  3159. // phpcs:enable
  3160. global $user;
  3161. if (!$this->table_element) {
  3162. $this->error = 'update_note was called on objet with property table_element not defined';
  3163. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  3164. return -1;
  3165. }
  3166. if (!in_array($suffix, array('', '_public', '_private'))) {
  3167. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  3168. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  3169. return -2;
  3170. }
  3171. $newsuffix = $suffix;
  3172. // Special cas
  3173. if ($this->table_element == 'product' && $newsuffix == '_private') {
  3174. $newsuffix = '';
  3175. }
  3176. if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  3177. $fieldusermod = "fk_user_mod";
  3178. } elseif ($this->table_element == 'ecm_files') {
  3179. $fieldusermod = "fk_user_m";
  3180. } else {
  3181. $fieldusermod = "fk_user_modif";
  3182. }
  3183. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  3184. $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
  3185. $sql .= ", ".$fieldusermod." = ".((int) $user->id);
  3186. $sql .= " WHERE rowid = ".((int) $this->id);
  3187. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  3188. if ($this->db->query($sql)) {
  3189. if ($suffix == '_public') {
  3190. $this->note_public = $note;
  3191. } elseif ($suffix == '_private') {
  3192. $this->note_private = $note;
  3193. } else {
  3194. $this->note = $note; // deprecated
  3195. $this->note_private = $note;
  3196. }
  3197. return 1;
  3198. } else {
  3199. $this->error = $this->db->lasterror();
  3200. return -1;
  3201. }
  3202. }
  3203. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3204. /**
  3205. * Update public note (kept for backward compatibility)
  3206. *
  3207. * @param string $note New value for note
  3208. * @return int <0 if KO, >0 if OK
  3209. * @deprecated
  3210. * @see update_note()
  3211. */
  3212. public function update_note_public($note)
  3213. {
  3214. // phpcs:enable
  3215. return $this->update_note($note, '_public');
  3216. }
  3217. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3218. /**
  3219. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  3220. * Must be called at end of methods addline or updateline.
  3221. *
  3222. * @param int $exclspec >0 = Exclude special product (product_type=9)
  3223. * @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
  3224. * @param int $nodatabaseupdate 1=Do not update database total fields of the main object. Update only properties in memory. Can be used to save SQL when this method is called several times, so we can do it only once at end.
  3225. * @param Societe $seller If roundingadjust is '0' or '1' or maybe 'auto', it means we recalculate total for lines before calculating total for object and for this, we need seller object (used to analyze lines to check corrupted data).
  3226. * @return int <0 if KO, >0 if OK
  3227. */
  3228. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  3229. {
  3230. // phpcs:enable
  3231. global $conf, $hookmanager, $action;
  3232. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  3233. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3234. if ($reshook > 0) {
  3235. return 1; // replacement code
  3236. } elseif ($reshook < 0) {
  3237. return -1; // failure
  3238. } // reshook = 0 => execute normal code
  3239. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  3240. $MODULE = "";
  3241. if ($this->element == 'propal') {
  3242. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  3243. } elseif ($this->element == 'commande' || $this->element == 'order') {
  3244. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  3245. } elseif ($this->element == 'facture' || $this->element == 'invoice') {
  3246. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  3247. } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
  3248. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  3249. } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
  3250. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  3251. } elseif ($this->element == 'supplier_proposal') {
  3252. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  3253. }
  3254. if (!empty($MODULE)) {
  3255. if (!empty($conf->global->$MODULE)) {
  3256. $modsactivated = explode(',', $conf->global->$MODULE);
  3257. foreach ($modsactivated as $mod) {
  3258. if (isModEnabled($mod)) {
  3259. return 1; // update was disabled by specific setup
  3260. }
  3261. }
  3262. }
  3263. }
  3264. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  3265. $forcedroundingmode = $roundingadjust;
  3266. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
  3267. $forcedroundingmode = getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND');
  3268. } elseif ($forcedroundingmode == 'auto') {
  3269. $forcedroundingmode = '0';
  3270. }
  3271. $error = 0;
  3272. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  3273. // Define constants to find lines to sum (field name int the table_element_line not into table_element)
  3274. $fieldtva = 'total_tva';
  3275. $fieldlocaltax1 = 'total_localtax1';
  3276. $fieldlocaltax2 = 'total_localtax2';
  3277. $fieldup = 'subprice';
  3278. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3279. $fieldtva = 'tva';
  3280. $fieldup = 'pu_ht';
  3281. }
  3282. if ($this->element == 'invoice_supplier_rec') {
  3283. $fieldup = 'pu_ht';
  3284. }
  3285. if ($this->element == 'expensereport') {
  3286. $fieldup = 'value_unit';
  3287. }
  3288. $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,";
  3289. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  3290. if ($this->table_element_line == 'facturedet') {
  3291. $sql .= ', situation_percent';
  3292. }
  3293. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3294. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  3295. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3296. if ($exclspec) {
  3297. $product_field = 'product_type';
  3298. if ($this->table_element_line == 'contratdet') {
  3299. $product_field = ''; // contratdet table has no product_type field
  3300. }
  3301. if ($product_field) {
  3302. $sql .= " AND ".$product_field." <> 9";
  3303. }
  3304. }
  3305. $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
  3306. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3307. $resql = $this->db->query($sql);
  3308. if ($resql) {
  3309. $this->total_ht = 0;
  3310. $this->total_tva = 0;
  3311. $this->total_localtax1 = 0;
  3312. $this->total_localtax2 = 0;
  3313. $this->total_ttc = 0;
  3314. $total_ht_by_vats = array();
  3315. $total_tva_by_vats = array();
  3316. $total_ttc_by_vats = array();
  3317. $this->multicurrency_total_ht = 0;
  3318. $this->multicurrency_total_tva = 0;
  3319. $this->multicurrency_total_ttc = 0;
  3320. $num = $this->db->num_rows($resql);
  3321. $i = 0;
  3322. while ($i < $num) {
  3323. $obj = $this->db->fetch_object($resql);
  3324. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  3325. $parameters = array('fk_element' => $obj->rowid);
  3326. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3327. 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'
  3328. // This part of code is to fix data. We should not call it too often.
  3329. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  3330. $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);
  3331. $diff_when_using_price_ht = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); // If price was set with tax price and unit price HT has a low number of digits, then we may have a diff on recalculation from unit price HT.
  3332. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  3333. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' => '.$obj->total_ttc);
  3334. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  3335. if ($diff_on_current_total) {
  3336. // This should not happen, we should always have in table: total_ttc = total_ht + total_vat + total_localtax1 + total_localtax2
  3337. $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2])." WHERE rowid = ".((int) $obj->rowid);
  3338. dol_syslog('We found unconsistent data into detailed line (diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (ht=".$obj->total_ht." vat=".$obj->total_tva." tax1=".$obj->total_localtax1." tax2=".$obj->total_localtax2." ttc=".$obj->total_ttc."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix, LOG_WARNING);
  3339. $resqlfix = $this->db->query($sqlfix);
  3340. if (!$resqlfix) {
  3341. dol_print_error($this->db, 'Failed to update line');
  3342. }
  3343. $obj->total_tva = $tmpcal[1];
  3344. $obj->total_ttc = $tmpcal[2];
  3345. } elseif ($diff_when_using_price_ht && $roundingadjust == '0') {
  3346. // After calculation from HT, total is consistent but we have found a difference between VAT part in calculation and into database and
  3347. // we ask to force the use of rounding on line (like done on calculation) so we force update of line
  3348. $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2])." WHERE rowid = ".((int) $obj->rowid);
  3349. dol_syslog('We found a line with different rounding data into detailed line (diff_when_using_price_ht = '.$diff_when_using_price_ht.' and diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (total vat of line calculated=".$tmpcal[1].", database=".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix);
  3350. $resqlfix = $this->db->query($sqlfix);
  3351. if (!$resqlfix) {
  3352. dol_print_error($this->db, 'Failed to update line');
  3353. }
  3354. $obj->total_tva = $tmpcal[1];
  3355. $obj->total_ttc = $tmpcal[2];
  3356. }
  3357. }
  3358. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  3359. $this->total_tva += $obj->total_tva;
  3360. $this->total_localtax1 += $obj->total_localtax1;
  3361. $this->total_localtax2 += $obj->total_localtax2;
  3362. $this->total_ttc += $obj->total_ttc;
  3363. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  3364. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  3365. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  3366. if (!isset($total_ht_by_vats[$obj->vatrate])) {
  3367. $total_ht_by_vats[$obj->vatrate] = 0;
  3368. }
  3369. if (!isset($total_tva_by_vats[$obj->vatrate])) {
  3370. $total_tva_by_vats[$obj->vatrate] = 0;
  3371. }
  3372. if (!isset($total_ttc_by_vats[$obj->vatrate])) {
  3373. $total_ttc_by_vats[$obj->vatrate] = 0;
  3374. }
  3375. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  3376. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  3377. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  3378. if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  3379. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  3380. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  3381. //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";
  3382. if ($diff) {
  3383. if (abs($diff) > 0.1) {
  3384. $errmsg = 'A rounding difference was detected into TOTAL but is too high to be corrected. Some data in your line may be corrupted. Try to edit each line manually.';
  3385. dol_syslog($errmsg, LOG_WARNING);
  3386. dol_print_error('', $errmsg);
  3387. exit;
  3388. }
  3389. $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num($obj->total_tva - $diff).", total_ttc = ".price2num($obj->total_ttc - $diff)." WHERE rowid = ".((int) $obj->rowid);
  3390. 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);
  3391. $resqlfix = $this->db->query($sqlfix);
  3392. if (!$resqlfix) {
  3393. dol_print_error($this->db, 'Failed to update line');
  3394. }
  3395. $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1);
  3396. $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1);
  3397. $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1);
  3398. $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1);
  3399. }
  3400. }
  3401. $i++;
  3402. }
  3403. // Add revenue stamp to total
  3404. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  3405. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  3406. // Situations totals
  3407. if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
  3408. $prev_sits = $this->get_prev_sits();
  3409. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  3410. $this->total_ht -= $sit->total_ht;
  3411. $this->total_tva -= $sit->total_tva;
  3412. $this->total_localtax1 -= $sit->total_localtax1;
  3413. $this->total_localtax2 -= $sit->total_localtax2;
  3414. $this->total_ttc -= $sit->total_ttc;
  3415. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  3416. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  3417. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  3418. }
  3419. }
  3420. // Clean total
  3421. $this->total_ht = (float) price2num($this->total_ht);
  3422. $this->total_tva = (float) price2num($this->total_tva);
  3423. $this->total_localtax1 = (float) price2num($this->total_localtax1);
  3424. $this->total_localtax2 = (float) price2num($this->total_localtax2);
  3425. $this->total_ttc = (float) price2num($this->total_ttc);
  3426. $this->db->free($resql);
  3427. // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_* of main object
  3428. $fieldht = 'total_ht';
  3429. $fieldtva = 'tva';
  3430. $fieldlocaltax1 = 'localtax1';
  3431. $fieldlocaltax2 = 'localtax2';
  3432. $fieldttc = 'total_ttc';
  3433. // Specific code for backward compatibility with old field names
  3434. if (in_array($this->element, array('propal', 'commande', 'facture', 'facturerec', 'supplier_proposal', 'order_supplier', 'facture_fourn', 'invoice_supplier', 'invoice_supplier_rec', 'expensereport'))) {
  3435. $fieldtva = 'total_tva';
  3436. }
  3437. if (empty($nodatabaseupdate)) {
  3438. $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
  3439. $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht, 'MT', 1)).",";
  3440. $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva, 'MT', 1)).",";
  3441. $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1, 'MT', 1)).",";
  3442. $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2, 'MT', 1)).",";
  3443. $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc, 'MT', 1));
  3444. $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
  3445. $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
  3446. $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
  3447. $sql .= " WHERE rowid = ".((int) $this->id);
  3448. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3449. $resql = $this->db->query($sql);
  3450. if (!$resql) {
  3451. $error++;
  3452. $this->error = $this->db->lasterror();
  3453. $this->errors[] = $this->db->lasterror();
  3454. }
  3455. }
  3456. if (!$error) {
  3457. return 1;
  3458. } else {
  3459. return -1;
  3460. }
  3461. } else {
  3462. dol_print_error($this->db, 'Bad request in update_price');
  3463. return -1;
  3464. }
  3465. }
  3466. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3467. /**
  3468. * Add an object link into llx_element_element.
  3469. *
  3470. * @param string $origin Linked element type
  3471. * @param int $origin_id Linked element id
  3472. * @param User $f_user User that create
  3473. * @param int $notrigger 1=Does not execute triggers, 0=execute triggers
  3474. * @return int <=0 if KO, >0 if OK
  3475. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  3476. */
  3477. public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
  3478. {
  3479. // phpcs:enable
  3480. global $user, $hookmanager, $action;
  3481. $origin = (!empty($origin) ? $origin : $this->origin);
  3482. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  3483. $f_user = isset($f_user) ? $f_user : $user;
  3484. // Special case
  3485. if ($origin == 'order') {
  3486. $origin = 'commande';
  3487. }
  3488. if ($origin == 'invoice') {
  3489. $origin = 'facture';
  3490. }
  3491. if ($origin == 'invoice_template') {
  3492. $origin = 'facturerec';
  3493. }
  3494. if ($origin == 'supplierorder') {
  3495. $origin = 'order_supplier';
  3496. }
  3497. // Elements of the core modules which have `$module` property but may to which we don't want to prefix module part to the element name for finding the linked object in llx_element_element.
  3498. // It's because an entry for this element may be exist in llx_element_element before this modification (version <=14.2) and ave named only with their element name in fk_source or fk_target.
  3499. $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
  3500. // Add module part to target type if object has $module property and isn't in core modules.
  3501. $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
  3502. $parameters = array('targettype'=>$targettype);
  3503. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3504. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3505. if ($reshook > 0) {
  3506. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3507. }
  3508. $this->db->begin();
  3509. $error = 0;
  3510. $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
  3511. $sql .= "fk_source";
  3512. $sql .= ", sourcetype";
  3513. $sql .= ", fk_target";
  3514. $sql .= ", targettype";
  3515. $sql .= ") VALUES (";
  3516. $sql .= ((int) $origin_id);
  3517. $sql .= ", '" . $this->db->escape($origin) . "'";
  3518. $sql .= ", " . ((int) $this->id);
  3519. $sql .= ", '" . $this->db->escape($targettype) . "'";
  3520. $sql .= ")";
  3521. dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
  3522. if ($this->db->query($sql)) {
  3523. if (!$notrigger) {
  3524. // Call trigger
  3525. $this->context['link_origin'] = $origin;
  3526. $this->context['link_origin_id'] = $origin_id;
  3527. $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
  3528. if ($result < 0) {
  3529. $error++;
  3530. }
  3531. // End call triggers
  3532. }
  3533. } else {
  3534. $this->error = $this->db->lasterror();
  3535. $error++;
  3536. }
  3537. if (!$error) {
  3538. $this->db->commit();
  3539. return 1;
  3540. } else {
  3541. $this->db->rollback();
  3542. return 0;
  3543. }
  3544. }
  3545. /**
  3546. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  3547. * this->linkedObjectsIds array +
  3548. * this->linkedObjects array if $loadalsoobjects = 1 or $loadalsoobjects = type
  3549. * Possible usage for parameters:
  3550. * - all parameters empty -> we look all link to current object (current object can be source or target)
  3551. * - source id+type -> will get list of targets linked to source
  3552. * - target id+type -> will get list of sources linked to target
  3553. * - source id+type + target type -> will get list of targets of the type linked to source
  3554. * - target id+type + source type -> will get list of sources of the type linked to target
  3555. *
  3556. * @param int $sourceid Object source id (if not defined, id of object)
  3557. * @param string $sourcetype Object source type (if not defined, element name of object)
  3558. * @param int $targetid Object target id (if not defined, id of object)
  3559. * @param string $targettype Object target type (if not defined, element name of object)
  3560. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  3561. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  3562. * @param string $orderby SQL 'ORDER BY' clause
  3563. * @param int|string $loadalsoobjects Load also array this->linkedObjects. Use 0 to increase performances, Use 1 to load all, Use value of type ('facture', 'facturerec', ...) to load only a type of object.
  3564. * @return int <0 if KO, >0 if OK
  3565. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  3566. */
  3567. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  3568. {
  3569. global $conf, $hookmanager, $action;
  3570. // Important for pdf generation time reduction
  3571. // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
  3572. if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
  3573. return 1;
  3574. }
  3575. $this->linkedObjectsIds = array();
  3576. $this->linkedObjects = array();
  3577. $justsource = false;
  3578. $justtarget = false;
  3579. $withtargettype = false;
  3580. $withsourcetype = false;
  3581. $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
  3582. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3583. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3584. if ($reshook > 0) {
  3585. if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
  3586. if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
  3587. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3588. if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
  3589. }
  3590. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
  3591. $justsource = true; // the source (id and type) is a search criteria
  3592. if (!empty($targettype)) {
  3593. $withtargettype = true;
  3594. }
  3595. }
  3596. if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
  3597. $justtarget = true; // the target (id and type) is a search criteria
  3598. if (!empty($sourcetype)) {
  3599. $withsourcetype = true;
  3600. }
  3601. }
  3602. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3603. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3604. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3605. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3606. /*if (empty($sourceid) && empty($targetid))
  3607. {
  3608. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  3609. return -1;
  3610. }*/
  3611. // Links between objects are stored in table element_element
  3612. $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
  3613. $sql .= " FROM ".$this->db->prefix()."element_element";
  3614. $sql .= " WHERE ";
  3615. if ($justsource || $justtarget) {
  3616. if ($justsource) {
  3617. $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3618. if ($withtargettype) {
  3619. $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
  3620. }
  3621. } elseif ($justtarget) {
  3622. $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
  3623. if ($withsourcetype) {
  3624. $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3625. }
  3626. }
  3627. } else {
  3628. $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
  3629. $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
  3630. if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
  3631. $this->linkedObjectsFullLoaded[$this->id] = true;
  3632. }
  3633. }
  3634. $sql .= " ORDER BY ".$orderby;
  3635. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  3636. $resql = $this->db->query($sql);
  3637. if ($resql) {
  3638. $num = $this->db->num_rows($resql);
  3639. $i = 0;
  3640. while ($i < $num) {
  3641. $obj = $this->db->fetch_object($resql);
  3642. if ($justsource || $justtarget) {
  3643. if ($justsource) {
  3644. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3645. } elseif ($justtarget) {
  3646. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3647. }
  3648. } else {
  3649. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
  3650. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3651. }
  3652. if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
  3653. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3654. }
  3655. }
  3656. $i++;
  3657. }
  3658. if (!empty($this->linkedObjectsIds)) {
  3659. $tmparray = $this->linkedObjectsIds;
  3660. foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  3661. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  3662. $module = $element = $subelement = $objecttype;
  3663. $regs = array();
  3664. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  3665. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  3666. $module = $element = $regs[1];
  3667. $subelement = $regs[2];
  3668. }
  3669. $classpath = $element.'/class';
  3670. // To work with non standard classpath or module name
  3671. if ($objecttype == 'facture') {
  3672. $classpath = 'compta/facture/class';
  3673. } elseif ($objecttype == 'facturerec') {
  3674. $classpath = 'compta/facture/class';
  3675. $module = 'facture';
  3676. } elseif ($objecttype == 'propal') {
  3677. $classpath = 'comm/propal/class';
  3678. } elseif ($objecttype == 'supplier_proposal') {
  3679. $classpath = 'supplier_proposal/class';
  3680. } elseif ($objecttype == 'shipping') {
  3681. $classpath = 'expedition/class';
  3682. $subelement = 'expedition';
  3683. $module = 'expedition';
  3684. } elseif ($objecttype == 'delivery') {
  3685. $classpath = 'delivery/class';
  3686. $subelement = 'delivery';
  3687. $module = 'delivery_note';
  3688. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  3689. $classpath = 'fourn/class';
  3690. $module = 'fournisseur';
  3691. } elseif ($objecttype == 'fichinter') {
  3692. $classpath = 'fichinter/class';
  3693. $subelement = 'fichinter';
  3694. $module = 'ficheinter';
  3695. } elseif ($objecttype == 'subscription') {
  3696. $classpath = 'adherents/class';
  3697. $module = 'adherent';
  3698. } elseif ($objecttype == 'contact') {
  3699. $module = 'societe';
  3700. }
  3701. // Set classfile
  3702. $classfile = strtolower($subelement);
  3703. $classname = ucfirst($subelement);
  3704. if ($objecttype == 'order') {
  3705. $classfile = 'commande';
  3706. $classname = 'Commande';
  3707. } elseif ($objecttype == 'invoice_supplier') {
  3708. $classfile = 'fournisseur.facture';
  3709. $classname = 'FactureFournisseur';
  3710. } elseif ($objecttype == 'order_supplier') {
  3711. $classfile = 'fournisseur.commande';
  3712. $classname = 'CommandeFournisseur';
  3713. } elseif ($objecttype == 'supplier_proposal') {
  3714. $classfile = 'supplier_proposal';
  3715. $classname = 'SupplierProposal';
  3716. } elseif ($objecttype == 'facturerec') {
  3717. $classfile = 'facture-rec';
  3718. $classname = 'FactureRec';
  3719. } elseif ($objecttype == 'subscription') {
  3720. $classfile = 'subscription';
  3721. $classname = 'Subscription';
  3722. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  3723. $classpath = 'projet/class';
  3724. $classfile = 'project';
  3725. $classname = 'Project';
  3726. } elseif ($objecttype == 'conferenceorboothattendee') {
  3727. $classpath = 'eventorganization/class';
  3728. $classfile = 'conferenceorboothattendee';
  3729. $classname = 'ConferenceOrBoothAttendee';
  3730. $module = 'eventorganization';
  3731. } elseif ($objecttype == 'conferenceorbooth') {
  3732. $classpath = 'eventorganization/class';
  3733. $classfile = 'conferenceorbooth';
  3734. $classname = 'ConferenceOrBooth';
  3735. $module = 'eventorganization';
  3736. } elseif ($objecttype == 'mo') {
  3737. $classpath = 'mrp/class';
  3738. $classfile = 'mo';
  3739. $classname = 'Mo';
  3740. $module = 'mrp';
  3741. }
  3742. // Here $module, $classfile and $classname are set, we can use them.
  3743. if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
  3744. if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
  3745. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  3746. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  3747. if (class_exists($classname)) {
  3748. foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
  3749. $object = new $classname($this->db);
  3750. $ret = $object->fetch($objectid);
  3751. if ($ret >= 0) {
  3752. $this->linkedObjects[$objecttype][$i] = $object;
  3753. }
  3754. }
  3755. }
  3756. }
  3757. } else {
  3758. unset($this->linkedObjectsIds[$objecttype]);
  3759. }
  3760. }
  3761. }
  3762. return 1;
  3763. } else {
  3764. dol_print_error($this->db);
  3765. return -1;
  3766. }
  3767. }
  3768. /**
  3769. * Clear the cache saying that all linked object were already loaded. So next fetchObjectLinked will reload all links.
  3770. *
  3771. * @return int <0 if KO, >0 if OK
  3772. * @see fetchObjectLinked()
  3773. */
  3774. public function clearObjectLinkedCache()
  3775. {
  3776. if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
  3777. unset($this->linkedObjectsFullLoaded[$this->id]);
  3778. }
  3779. return 1;
  3780. }
  3781. /**
  3782. * Update object linked of a current object
  3783. *
  3784. * @param int $sourceid Object source id
  3785. * @param string $sourcetype Object source type
  3786. * @param int $targetid Object target id
  3787. * @param string $targettype Object target type
  3788. * @param User $f_user User that create
  3789. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3790. * @return int >0 if OK, <0 if KO
  3791. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3792. */
  3793. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
  3794. {
  3795. global $user;
  3796. $updatesource = false;
  3797. $updatetarget = false;
  3798. $f_user = isset($f_user) ? $f_user : $user;
  3799. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3800. $updatesource = true;
  3801. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3802. $updatetarget = true;
  3803. }
  3804. $this->db->begin();
  3805. $error = 0;
  3806. $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
  3807. if ($updatesource) {
  3808. $sql .= "fk_source = " . ((int) $sourceid);
  3809. $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3810. $sql .= " WHERE fk_target = " . ((int) $this->id);
  3811. $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
  3812. } elseif ($updatetarget) {
  3813. $sql .= "fk_target = " . ((int) $targetid);
  3814. $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
  3815. $sql .= " WHERE fk_source = " . ((int) $this->id);
  3816. $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3817. }
  3818. dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
  3819. if ($this->db->query($sql)) {
  3820. if (!$notrigger) {
  3821. // Call trigger
  3822. $this->context['link_source_id'] = $sourceid;
  3823. $this->context['link_source_type'] = $sourcetype;
  3824. $this->context['link_target_id'] = $targetid;
  3825. $this->context['link_target_type'] = $targettype;
  3826. $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
  3827. if ($result < 0) {
  3828. $error++;
  3829. }
  3830. // End call triggers
  3831. }
  3832. } else {
  3833. $this->error = $this->db->lasterror();
  3834. $error++;
  3835. }
  3836. if (!$error) {
  3837. $this->db->commit();
  3838. return 1;
  3839. } else {
  3840. $this->db->rollback();
  3841. return -1;
  3842. }
  3843. }
  3844. /**
  3845. * Delete all links between an object $this
  3846. *
  3847. * @param int $sourceid Object source id
  3848. * @param string $sourcetype Object source type
  3849. * @param int $targetid Object target id
  3850. * @param string $targettype Object target type
  3851. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3852. * @param User $f_user User that create
  3853. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3854. * @return int >0 if OK, <0 if KO
  3855. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3856. */
  3857. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
  3858. {
  3859. global $user;
  3860. $deletesource = false;
  3861. $deletetarget = false;
  3862. $f_user = isset($f_user) ? $f_user : $user;
  3863. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3864. $deletesource = true;
  3865. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3866. $deletetarget = true;
  3867. }
  3868. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3869. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3870. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3871. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3872. $this->db->begin();
  3873. $error = 0;
  3874. if (!$notrigger) {
  3875. // Call trigger
  3876. $this->context['link_id'] = $rowid;
  3877. $this->context['link_source_id'] = $sourceid;
  3878. $this->context['link_source_type'] = $sourcetype;
  3879. $this->context['link_target_id'] = $targetid;
  3880. $this->context['link_target_type'] = $targettype;
  3881. $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
  3882. if ($result < 0) {
  3883. $error++;
  3884. }
  3885. // End call triggers
  3886. }
  3887. if (!$error) {
  3888. $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
  3889. $sql .= " WHERE";
  3890. if ($rowid > 0) {
  3891. $sql .= " rowid = " . ((int) $rowid);
  3892. } else {
  3893. if ($deletesource) {
  3894. $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3895. $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
  3896. } elseif ($deletetarget) {
  3897. $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
  3898. $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3899. } else {
  3900. $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
  3901. $sql .= " OR";
  3902. $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
  3903. }
  3904. }
  3905. dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
  3906. if (!$this->db->query($sql)) {
  3907. $this->error = $this->db->lasterror();
  3908. $this->errors[] = $this->error;
  3909. $error++;
  3910. }
  3911. }
  3912. if (!$error) {
  3913. $this->db->commit();
  3914. return 1;
  3915. } else {
  3916. $this->db->rollback();
  3917. return 0;
  3918. }
  3919. }
  3920. /**
  3921. * Function used to get an array with all items linked to an object id in association table
  3922. *
  3923. * @param int $fk_object_where id of object we need to get linked items
  3924. * @param string $field_select name of field we need to get a list
  3925. * @param string $field_where name of field of object we need to get linked items
  3926. * @param string $table_element name of association table
  3927. * @return array|int Array of record, -1 if empty
  3928. */
  3929. public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
  3930. {
  3931. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3932. return -1;
  3933. }
  3934. global $db;
  3935. $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3936. $resql = $db->query($sql);
  3937. $TRes = array();
  3938. if (!empty($resql)) {
  3939. while ($res = $db->fetch_object($resql)) {
  3940. $TRes[] = $res->{$field_select};
  3941. }
  3942. }
  3943. return $TRes;
  3944. }
  3945. /**
  3946. * Function used to remove all items linked to an object id in association table
  3947. *
  3948. * @param int $fk_object_where id of object we need to remove linked items
  3949. * @param string $field_where name of field of object we need to delete linked items
  3950. * @param string $table_element name of association table
  3951. * @return int <0 if KO, 0 if nothing done, >0 if OK and something done
  3952. */
  3953. public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
  3954. {
  3955. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3956. return -1;
  3957. }
  3958. global $db;
  3959. $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3960. $resql = $db->query($sql);
  3961. if (empty($resql)) {
  3962. return 0;
  3963. }
  3964. return 1;
  3965. }
  3966. /**
  3967. * Set status of an object.
  3968. *
  3969. * @param int $status Status to set
  3970. * @param int $elementId Id of element to force (use this->id by default if null)
  3971. * @param string $elementType Type of element to force (use this->table_element by default)
  3972. * @param string $trigkey Trigger key to use for trigger. Use '' means automatic but it is not recommended and is deprecated.
  3973. * @param string $fieldstatus Name of status field in this->table_element
  3974. * @return int <0 if KO, >0 if OK
  3975. */
  3976. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
  3977. {
  3978. global $user, $langs, $conf;
  3979. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3980. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3981. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3982. $this->db->begin();
  3983. if ($elementTable == 'facture_rec') {
  3984. $fieldstatus = "suspended";
  3985. }
  3986. if ($elementTable == 'mailing') {
  3987. $fieldstatus = "statut";
  3988. }
  3989. if ($elementTable == 'cronjob') {
  3990. $fieldstatus = "status";
  3991. }
  3992. if ($elementTable == 'user') {
  3993. $fieldstatus = "statut";
  3994. }
  3995. if ($elementTable == 'expensereport') {
  3996. $fieldstatus = "fk_statut";
  3997. }
  3998. if ($elementTable == 'commande_fournisseur_dispatch') {
  3999. $fieldstatus = "status";
  4000. }
  4001. if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
  4002. $fieldstatus = 'status';
  4003. }
  4004. $sql = "UPDATE ".$this->db->prefix().$elementTable;
  4005. $sql .= " SET ".$fieldstatus." = ".((int) $status);
  4006. // If status = 1 = validated, update also fk_user_valid
  4007. // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
  4008. if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
  4009. $sql .= ", fk_user_valid = ".((int) $user->id);
  4010. }
  4011. if ($status == 1 && in_array($elementTable, array('expensereport'))) {
  4012. $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
  4013. }
  4014. if ($status == 1 && in_array($elementTable, array('inventory'))) {
  4015. $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
  4016. }
  4017. $sql .= " WHERE rowid = ".((int) $elementId);
  4018. $sql .= " AND ".$fieldstatus." <> ".((int) $status); // We avoid update if status already correct
  4019. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  4020. $resql = $this->db->query($sql);
  4021. if ($resql) {
  4022. $error = 0;
  4023. $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
  4024. if ($nb_rows_affected > 0) {
  4025. if (empty($trigkey)) {
  4026. // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
  4027. if ($this->element == 'supplier_proposal' && $status == 2) {
  4028. $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  4029. }
  4030. if ($this->element == 'supplier_proposal' && $status == 3) {
  4031. $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  4032. }
  4033. if ($this->element == 'supplier_proposal' && $status == 4) {
  4034. $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  4035. }
  4036. if ($this->element == 'fichinter' && $status == 3) {
  4037. $trigkey = 'FICHINTER_CLASSIFY_DONE';
  4038. }
  4039. if ($this->element == 'fichinter' && $status == 2) {
  4040. $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  4041. }
  4042. if ($this->element == 'fichinter' && $status == 1) {
  4043. $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  4044. }
  4045. }
  4046. if ($trigkey) {
  4047. // Call trigger
  4048. $result = $this->call_trigger($trigkey, $user);
  4049. if ($result < 0) {
  4050. $error++;
  4051. }
  4052. // End call triggers
  4053. }
  4054. } else {
  4055. // The status was probably already good. We do nothing more, no triggers.
  4056. }
  4057. if (!$error) {
  4058. $this->db->commit();
  4059. if (empty($savElementId)) {
  4060. // If the element we update is $this (so $elementId was provided as null)
  4061. if ($fieldstatus == 'tosell') {
  4062. $this->status = $status;
  4063. } elseif ($fieldstatus == 'tobuy') {
  4064. $this->status_buy = $status;
  4065. } else {
  4066. $this->statut = $status;
  4067. $this->status = $status;
  4068. }
  4069. }
  4070. return 1;
  4071. } else {
  4072. $this->db->rollback();
  4073. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  4074. return -1;
  4075. }
  4076. } else {
  4077. $this->error = $this->db->lasterror();
  4078. $this->db->rollback();
  4079. return -1;
  4080. }
  4081. }
  4082. /**
  4083. * Load type of canvas of an object if it exists
  4084. *
  4085. * @param int $id Record id
  4086. * @param string $ref Record ref
  4087. * @return int <0 if KO, 0 if nothing done, >0 if OK
  4088. */
  4089. public function getCanvas($id = 0, $ref = '')
  4090. {
  4091. global $conf;
  4092. if (empty($id) && empty($ref)) {
  4093. return 0;
  4094. }
  4095. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
  4096. return 0; // To increase speed. Not enabled by default.
  4097. }
  4098. // Clean parameters
  4099. $ref = trim($ref);
  4100. $sql = "SELECT rowid, canvas";
  4101. $sql .= " FROM ".$this->db->prefix().$this->table_element;
  4102. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  4103. if (!empty($id)) {
  4104. $sql .= " AND rowid = ".((int) $id);
  4105. }
  4106. if (!empty($ref)) {
  4107. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  4108. }
  4109. $resql = $this->db->query($sql);
  4110. if ($resql) {
  4111. $obj = $this->db->fetch_object($resql);
  4112. if ($obj) {
  4113. $this->canvas = $obj->canvas;
  4114. return 1;
  4115. } else {
  4116. return 0;
  4117. }
  4118. } else {
  4119. dol_print_error($this->db);
  4120. return -1;
  4121. }
  4122. }
  4123. /**
  4124. * Get special code of a line
  4125. *
  4126. * @param int $lineid Id of line
  4127. * @return int Special code
  4128. */
  4129. public function getSpecialCode($lineid)
  4130. {
  4131. $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
  4132. $sql .= " WHERE rowid = ".((int) $lineid);
  4133. $resql = $this->db->query($sql);
  4134. if ($resql) {
  4135. $row = $this->db->fetch_row($resql);
  4136. return $row[0];
  4137. }
  4138. return 0;
  4139. }
  4140. /**
  4141. * Function to check if an object is used by others (by children).
  4142. * Check is done into this->childtables. There is no check into llx_element_element.
  4143. *
  4144. * @param int $id Force id of object
  4145. * @param int $entity Force entity to check
  4146. * @return int <0 if KO, 0 if not used, >0 if already used
  4147. */
  4148. public function isObjectUsed($id = 0, $entity = 0)
  4149. {
  4150. global $langs;
  4151. if (empty($id)) {
  4152. $id = $this->id;
  4153. }
  4154. // Check parameters
  4155. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
  4156. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  4157. return -1;
  4158. }
  4159. $arraytoscan = $this->childtables; // array('tablename'=>array('fk_element'=>'parentfield'), ...) or array('tablename'=>array('parent'=>table_parent, 'parentkey'=>'nameoffieldforparentfkkey'), ...)
  4160. // For backward compatibility, we check if array is old format array('tablename1', 'tablename2', ...)
  4161. $tmparray = array_keys($this->childtables);
  4162. if (is_numeric($tmparray[0])) {
  4163. $arraytoscan = array_flip($this->childtables);
  4164. }
  4165. // Test if child exists
  4166. $haschild = 0;
  4167. foreach ($arraytoscan as $table => $element) {
  4168. //print $id.'-'.$table.'-'.$elementname.'<br>';
  4169. // Check if element can be deleted
  4170. $sql = "SELECT COUNT(*) as nb";
  4171. $sql.= " FROM ".$this->db->prefix().$table." as c";
  4172. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4173. $sql.= ", ".$this->db->prefix().$element['parent']." as p";
  4174. }
  4175. if (!empty($element['fk_element'])) {
  4176. $sql.= " WHERE c.".$element['fk_element']." = ".((int) $id);
  4177. } else {
  4178. $sql.= " WHERE c.".$this->fk_element." = ".((int) $id);
  4179. }
  4180. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4181. $sql.= " AND c.".$element['parentkey']." = p.rowid";
  4182. }
  4183. if (!empty($element['parent']) && !empty($element['parenttypefield']) && !empty($element['parenttypevalue'])) {
  4184. $sql.= " AND c.".$element['parenttypefield']." = '".$this->db->escape($element['parenttypevalue'])."'";
  4185. }
  4186. if (!empty($entity)) {
  4187. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4188. $sql.= " AND p.entity = ".((int) $entity);
  4189. } else {
  4190. $sql.= " AND c.entity = ".((int) $entity);
  4191. }
  4192. }
  4193. $resql = $this->db->query($sql);
  4194. if ($resql) {
  4195. $obj = $this->db->fetch_object($resql);
  4196. if ($obj->nb > 0) {
  4197. $langs->load("errors");
  4198. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  4199. $haschild += $obj->nb;
  4200. if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
  4201. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
  4202. } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
  4203. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
  4204. } else { // new usage: $element['name']=Translation key
  4205. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
  4206. }
  4207. break; // We found at least one, we stop here
  4208. }
  4209. } else {
  4210. $this->errors[] = $this->db->lasterror();
  4211. return -1;
  4212. }
  4213. }
  4214. if ($haschild > 0) {
  4215. $this->errors[] = "ErrorRecordHasChildren";
  4216. return $haschild;
  4217. } else {
  4218. return 0;
  4219. }
  4220. }
  4221. /**
  4222. * Function to say how many lines object contains
  4223. *
  4224. * @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
  4225. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  4226. */
  4227. public function hasProductsOrServices($predefined = -1)
  4228. {
  4229. $nb = 0;
  4230. foreach ($this->lines as $key => $val) {
  4231. $qualified = 0;
  4232. if ($predefined == -1) {
  4233. $qualified = 1;
  4234. }
  4235. if ($predefined == 1 && $val->fk_product > 0) {
  4236. $qualified = 1;
  4237. }
  4238. if ($predefined == 0 && $val->fk_product <= 0) {
  4239. $qualified = 1;
  4240. }
  4241. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
  4242. $qualified = 1;
  4243. }
  4244. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
  4245. $qualified = 1;
  4246. }
  4247. if ($qualified) {
  4248. $nb++;
  4249. }
  4250. }
  4251. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  4252. return $nb;
  4253. }
  4254. /**
  4255. * Function that returns the total amount HT of discounts applied for all lines.
  4256. *
  4257. * @return float|string Total amout of discount
  4258. */
  4259. public function getTotalDiscount()
  4260. {
  4261. if (!empty($this->table_element_line) ) {
  4262. $total_discount = 0.00;
  4263. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  4264. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  4265. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  4266. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  4267. $resql = $this->db->query($sql);
  4268. if ($resql) {
  4269. $num = $this->db->num_rows($resql);
  4270. $i = 0;
  4271. while ($i < $num) {
  4272. $obj = $this->db->fetch_object($resql);
  4273. $pu_ht = $obj->pu_ht;
  4274. $qty = $obj->qty;
  4275. $total_ht = $obj->total_ht;
  4276. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  4277. $total_discount += $total_discount_line;
  4278. $i++;
  4279. }
  4280. }
  4281. //print $total_discount; exit;
  4282. return price2num($total_discount);
  4283. }
  4284. return null;
  4285. }
  4286. /**
  4287. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  4288. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  4289. *
  4290. * @return array array('weight'=>...,'volume'=>...)
  4291. */
  4292. public function getTotalWeightVolume()
  4293. {
  4294. $totalWeight = 0;
  4295. $totalVolume = 0;
  4296. // defined for shipment only
  4297. $totalOrdered = '';
  4298. // defined for shipment only
  4299. $totalToShip = '';
  4300. foreach ($this->lines as $line) {
  4301. if (isset($line->qty_asked)) {
  4302. if (empty($totalOrdered)) {
  4303. $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  4304. }
  4305. $totalOrdered += $line->qty_asked; // defined for shipment only
  4306. }
  4307. if (isset($line->qty_shipped)) {
  4308. if (empty($totalToShip)) {
  4309. $totalToShip = 0; // Avoid warning because $totalToShip is ''
  4310. }
  4311. $totalToShip += $line->qty_shipped; // defined for shipment only
  4312. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
  4313. if (empty($totalToShip)) {
  4314. $totalToShip = 0;
  4315. }
  4316. $totalToShip += $line->qty; // defined for reception only
  4317. }
  4318. // Define qty, weight, volume, weight_units, volume_units
  4319. if ($this->element == 'shipping') {
  4320. // for shipments
  4321. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  4322. } else {
  4323. $qty = $line->qty ? $line->qty : 0;
  4324. }
  4325. $weight = !empty($line->weight) ? $line->weight : 0;
  4326. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  4327. $volume = !empty($line->volume) ? $line->volume : 0;
  4328. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  4329. $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
  4330. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  4331. $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
  4332. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  4333. $weightUnit = 0;
  4334. $volumeUnit = 0;
  4335. if (!empty($weight_units)) {
  4336. $weightUnit = $weight_units;
  4337. }
  4338. if (!empty($volume_units)) {
  4339. $volumeUnit = $volume_units;
  4340. }
  4341. if (empty($totalWeight)) {
  4342. $totalWeight = 0; // Avoid warning because $totalWeight is ''
  4343. }
  4344. if (empty($totalVolume)) {
  4345. $totalVolume = 0; // Avoid warning because $totalVolume is ''
  4346. }
  4347. //var_dump($line->volume_units);
  4348. if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4349. $trueWeightUnit = pow(10, $weightUnit);
  4350. $totalWeight += $weight * $qty * $trueWeightUnit;
  4351. } else {
  4352. if ($weight_units == 99) {
  4353. // conversion 1 Pound = 0.45359237 KG
  4354. $trueWeightUnit = 0.45359237;
  4355. $totalWeight += $weight * $qty * $trueWeightUnit;
  4356. } elseif ($weight_units == 98) {
  4357. // conversion 1 Ounce = 0.0283495 KG
  4358. $trueWeightUnit = 0.0283495;
  4359. $totalWeight += $weight * $qty * $trueWeightUnit;
  4360. } else {
  4361. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  4362. }
  4363. }
  4364. if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4365. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  4366. $trueVolumeUnit = pow(10, $volumeUnit);
  4367. //print $line->volume;
  4368. $totalVolume += $volume * $qty * $trueVolumeUnit;
  4369. } else {
  4370. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  4371. }
  4372. }
  4373. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  4374. }
  4375. /**
  4376. * Set extra parameters
  4377. *
  4378. * @return int <0 if KO, >0 if OK
  4379. */
  4380. public function setExtraParameters()
  4381. {
  4382. $this->db->begin();
  4383. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  4384. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  4385. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  4386. $sql .= " WHERE rowid = ".((int) $this->id);
  4387. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  4388. $resql = $this->db->query($sql);
  4389. if (!$resql) {
  4390. $this->error = $this->db->lasterror();
  4391. $this->db->rollback();
  4392. return -1;
  4393. } else {
  4394. $this->db->commit();
  4395. return 1;
  4396. }
  4397. }
  4398. // --------------------
  4399. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  4400. // --------------------
  4401. /* This is to show add lines */
  4402. /**
  4403. * Show add free and predefined products/services form
  4404. *
  4405. * @param int $dateSelector 1=Show also date range input fields
  4406. * @param Societe $seller Object thirdparty who sell
  4407. * @param Societe $buyer Object thirdparty who buy
  4408. * @param string $defaulttpldir Directory where to find the template
  4409. * @return void
  4410. */
  4411. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  4412. {
  4413. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  4414. global $form;
  4415. // Line extrafield
  4416. if (!is_object($extrafields)) {
  4417. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4418. $extrafields = new ExtraFields($this->db);
  4419. }
  4420. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4421. // Output template part (modules that overwrite templates must declare this into descriptor)
  4422. // Use global variables + $dateSelector + $seller and $buyer
  4423. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  4424. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4425. foreach ($dirtpls as $module => $reldir) {
  4426. if (!empty($module)) {
  4427. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  4428. } else {
  4429. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  4430. }
  4431. if (empty($conf->file->strict_mode)) {
  4432. $res = @include $tpl;
  4433. } else {
  4434. $res = include $tpl; // for debug
  4435. }
  4436. if ($res) {
  4437. break;
  4438. }
  4439. }
  4440. }
  4441. /* This is to show array of line of details */
  4442. /**
  4443. * Return HTML table for object lines
  4444. * TODO Move this into an output class file (htmlline.class.php)
  4445. * If lines are into a template, title must also be into a template
  4446. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4447. *
  4448. * @param string $action Action code
  4449. * @param Societe $seller Object of seller third party
  4450. * @param Societe $buyer Object of buyer third party
  4451. * @param int $selected ID line selected
  4452. * @param int $dateSelector 1=Show also date range input fields
  4453. * @param string $defaulttpldir Directory where to find the template
  4454. * @return void
  4455. */
  4456. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  4457. {
  4458. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  4459. // TODO We should not use global var for this
  4460. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  4461. // Define usemargins
  4462. $usemargins = 0;
  4463. if (isModEnabled('margin') && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
  4464. $usemargins = 1;
  4465. }
  4466. $num = count($this->lines);
  4467. // Line extrafield
  4468. if (!is_object($extrafields)) {
  4469. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4470. $extrafields = new ExtraFields($this->db);
  4471. }
  4472. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4473. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  4474. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4475. if (empty($reshook)) {
  4476. // Output template part (modules that overwrite templates must declare this into descriptor)
  4477. // Use global variables + $dateSelector + $seller and $buyer
  4478. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  4479. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4480. foreach ($dirtpls as $module => $reldir) {
  4481. $res = 0;
  4482. if (!empty($module)) {
  4483. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  4484. } else {
  4485. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  4486. }
  4487. if (file_exists($tpl)) {
  4488. if (empty($conf->file->strict_mode)) {
  4489. $res = @include $tpl;
  4490. } else {
  4491. $res = include $tpl; // for debug
  4492. }
  4493. }
  4494. if ($res) {
  4495. break;
  4496. }
  4497. }
  4498. }
  4499. $i = 0;
  4500. print "<!-- begin printObjectLines() --><tbody>\n";
  4501. foreach ($this->lines as $line) {
  4502. //Line extrafield
  4503. $line->fetch_optionals();
  4504. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line)))
  4505. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4506. if (empty($line->fk_parent_line)) {
  4507. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  4508. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4509. } else {
  4510. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element, 'fk_parent_line'=>$line->fk_parent_line);
  4511. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4512. }
  4513. }
  4514. if (empty($reshook)) {
  4515. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  4516. }
  4517. $i++;
  4518. }
  4519. print "</tbody><!-- end printObjectLines() -->\n";
  4520. }
  4521. /**
  4522. * Return HTML content of a detail line
  4523. * TODO Move this into an output class file (htmlline.class.php)
  4524. *
  4525. * @param string $action GET/POST action
  4526. * @param CommonObjectLine $line Selected object line to output
  4527. * @param string $var Not used
  4528. * @param int $num Number of line (0)
  4529. * @param int $i I
  4530. * @param int $dateSelector 1=Show also date range input fields
  4531. * @param Societe $seller Object of seller third party
  4532. * @param Societe $buyer Object of buyer third party
  4533. * @param int $selected ID line selected
  4534. * @param Extrafields $extrafields Object of extrafields
  4535. * @param string $defaulttpldir Directory where to find the template (deprecated)
  4536. * @return void
  4537. */
  4538. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  4539. {
  4540. global $conf, $langs, $user, $object, $hookmanager;
  4541. global $form;
  4542. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  4543. $object_rights = $this->getRights();
  4544. $text = '';
  4545. $description = '';
  4546. // Line in view mode
  4547. if ($action != 'editline' || $selected != $line->id) {
  4548. // Product
  4549. if (!empty($line->fk_product) && $line->fk_product > 0) {
  4550. $product_static = new Product($this->db);
  4551. $product_static->fetch($line->fk_product);
  4552. $product_static->ref = $line->ref; //can change ref in hook
  4553. $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
  4554. $text = $product_static->getNomUrl(1);
  4555. // Define output language and label
  4556. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  4557. if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
  4558. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  4559. return;
  4560. }
  4561. $prod = new Product($this->db);
  4562. $prod->fetch($line->fk_product);
  4563. $outputlangs = $langs;
  4564. $newlang = '';
  4565. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  4566. $newlang = GETPOST('lang_id', 'aZ09');
  4567. }
  4568. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
  4569. $newlang = $this->thirdparty->default_lang; // To use language of customer
  4570. }
  4571. if (!empty($newlang)) {
  4572. $outputlangs = new Translate("", $conf);
  4573. $outputlangs->setDefaultLang($newlang);
  4574. }
  4575. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  4576. } else {
  4577. $label = $line->product_label;
  4578. }
  4579. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  4580. $description .= (getDolGlobalInt('PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ? '' : (!empty($line->description) ? dol_htmlentitiesbr($line->description) : '')); // Description is what to show on popup. We shown nothing if already into desc.
  4581. }
  4582. $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
  4583. // Output template part (modules that overwrite templates must declare this into descriptor)
  4584. // Use global variables + $dateSelector + $seller and $buyer
  4585. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4586. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4587. foreach ($dirtpls as $module => $reldir) {
  4588. $res = 0;
  4589. if (!empty($module)) {
  4590. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  4591. } else {
  4592. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  4593. }
  4594. if (file_exists($tpl)) {
  4595. if (empty($conf->file->strict_mode)) {
  4596. $res = @include $tpl;
  4597. } else {
  4598. $res = include $tpl; // for debug
  4599. }
  4600. }
  4601. if ($res) {
  4602. break;
  4603. }
  4604. }
  4605. }
  4606. // Line in update mode
  4607. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
  4608. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  4609. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4610. // Output template part (modules that overwrite templates must declare this into descriptor)
  4611. // Use global variables + $dateSelector + $seller and $buyer
  4612. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4613. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4614. foreach ($dirtpls as $module => $reldir) {
  4615. if (!empty($module)) {
  4616. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  4617. } else {
  4618. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  4619. }
  4620. if (empty($conf->file->strict_mode)) {
  4621. $res = @include $tpl;
  4622. } else {
  4623. $res = include $tpl; // for debug
  4624. }
  4625. if ($res) {
  4626. break;
  4627. }
  4628. }
  4629. }
  4630. }
  4631. /* This is to show array of line of details of source object */
  4632. /**
  4633. * Return HTML table table of source object lines
  4634. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4635. * If lines are into a template, title must also be into a template
  4636. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  4637. *
  4638. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  4639. * @param array $selectedLines Array of lines id for selected lines
  4640. * @return void
  4641. */
  4642. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  4643. {
  4644. global $langs, $hookmanager, $conf, $form, $action;
  4645. print '<tr class="liste_titre">';
  4646. print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
  4647. print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
  4648. print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
  4649. print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
  4650. if (isModEnabled("multicurrency")) {
  4651. print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
  4652. }
  4653. print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
  4654. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  4655. print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
  4656. }
  4657. print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
  4658. print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
  4659. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  4660. print '</tr>';
  4661. $i = 0;
  4662. if (!empty($this->lines)) {
  4663. foreach ($this->lines as $line) {
  4664. $reshook = 0;
  4665. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
  4666. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4667. $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
  4668. if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
  4669. $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4670. }
  4671. if (empty($reshook)) {
  4672. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  4673. }
  4674. $i++;
  4675. }
  4676. }
  4677. }
  4678. /**
  4679. * Return HTML with a line of table array of source object lines
  4680. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4681. * If lines are into a template, title must also be into a template
  4682. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4683. *
  4684. * @param CommonObjectLine $line Line
  4685. * @param string $var Var
  4686. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  4687. * @param string $defaulttpldir Directory where to find the template
  4688. * @param array $selectedLines Array of lines id for selected lines
  4689. * @return void
  4690. */
  4691. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  4692. {
  4693. global $langs, $conf;
  4694. //var_dump($line);
  4695. if (!empty($line->date_start)) {
  4696. $date_start = $line->date_start;
  4697. } else {
  4698. $date_start = $line->date_debut_prevue;
  4699. if ($line->date_debut_reel) {
  4700. $date_start = $line->date_debut_reel;
  4701. }
  4702. }
  4703. if (!empty($line->date_end)) {
  4704. $date_end = $line->date_end;
  4705. } else {
  4706. $date_end = $line->date_fin_prevue;
  4707. if ($line->date_fin_reel) {
  4708. $date_end = $line->date_fin_reel;
  4709. }
  4710. }
  4711. $this->tpl['id'] = $line->id;
  4712. $this->tpl['label'] = '';
  4713. if (!empty($line->fk_parent_line)) {
  4714. $this->tpl['label'] .= img_picto('', 'rightarrow');
  4715. }
  4716. if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
  4717. $discount = new DiscountAbsolute($this->db);
  4718. $discount->fk_soc = $this->socid;
  4719. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  4720. } elseif (!empty($line->fk_product)) {
  4721. $productstatic = new Product($this->db);
  4722. $productstatic->id = $line->fk_product;
  4723. $productstatic->ref = $line->ref;
  4724. $productstatic->type = $line->fk_product_type;
  4725. if (empty($productstatic->ref)) {
  4726. $line->fetch_product();
  4727. $productstatic = $line->product;
  4728. }
  4729. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  4730. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  4731. // Dates
  4732. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4733. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4734. }
  4735. } else {
  4736. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  4737. if (!empty($line->desc)) {
  4738. $this->tpl['label'] .= $line->desc;
  4739. } else {
  4740. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  4741. }
  4742. // Dates
  4743. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4744. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4745. }
  4746. }
  4747. if (!empty($line->desc)) {
  4748. if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
  4749. $discount = new DiscountAbsolute($this->db);
  4750. $discount->fetch($line->fk_remise_except);
  4751. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  4752. } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
  4753. $discount = new DiscountAbsolute($this->db);
  4754. $discount->fetch($line->fk_remise_except);
  4755. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  4756. } elseif ($line->desc == '(EXCESS RECEIVED)') {
  4757. $discount = new DiscountAbsolute($this->db);
  4758. $discount->fetch($line->fk_remise_except);
  4759. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  4760. } elseif ($line->desc == '(EXCESS PAID)') {
  4761. $discount = new DiscountAbsolute($this->db);
  4762. $discount->fetch($line->fk_remise_except);
  4763. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  4764. } else {
  4765. $this->tpl['description'] = dol_trunc($line->desc, 60);
  4766. }
  4767. } else {
  4768. $this->tpl['description'] = '&nbsp;';
  4769. }
  4770. // VAT Rate
  4771. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  4772. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  4773. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
  4774. $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  4775. }
  4776. $this->tpl['price'] = price($line->subprice);
  4777. $this->tpl['total_ht'] = price($line->total_ht);
  4778. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  4779. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  4780. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  4781. $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  4782. }
  4783. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  4784. // Is the line strike or not
  4785. $this->tpl['strike'] = 0;
  4786. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
  4787. $this->tpl['strike'] = 1;
  4788. }
  4789. // Output template part (modules that overwrite templates must declare this into descriptor)
  4790. // Use global variables + $dateSelector + $seller and $buyer
  4791. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4792. foreach ($dirtpls as $module => $reldir) {
  4793. if (!empty($module)) {
  4794. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  4795. } else {
  4796. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  4797. }
  4798. if (empty($conf->file->strict_mode)) {
  4799. $res = @include $tpl;
  4800. } else {
  4801. $res = include $tpl; // for debug
  4802. }
  4803. if ($res) {
  4804. break;
  4805. }
  4806. }
  4807. }
  4808. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4809. /**
  4810. * Add resources to the current object : add entry into llx_element_resources
  4811. * Need $this->element & $this->id
  4812. *
  4813. * @param int $resource_id Resource id
  4814. * @param string $resource_type 'resource'
  4815. * @param int $busy Busy or not
  4816. * @param int $mandatory Mandatory or not
  4817. * @return int <=0 if KO, >0 if OK
  4818. */
  4819. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  4820. {
  4821. // phpcs:enable
  4822. $this->db->begin();
  4823. $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
  4824. $sql .= "resource_id";
  4825. $sql .= ", resource_type";
  4826. $sql .= ", element_id";
  4827. $sql .= ", element_type";
  4828. $sql .= ", busy";
  4829. $sql .= ", mandatory";
  4830. $sql .= ") VALUES (";
  4831. $sql .= ((int) $resource_id);
  4832. $sql .= ", '".$this->db->escape($resource_type)."'";
  4833. $sql .= ", '".$this->db->escape($this->id)."'";
  4834. $sql .= ", '".$this->db->escape($this->element)."'";
  4835. $sql .= ", '".$this->db->escape($busy)."'";
  4836. $sql .= ", '".$this->db->escape($mandatory)."'";
  4837. $sql .= ")";
  4838. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  4839. if ($this->db->query($sql)) {
  4840. $this->db->commit();
  4841. return 1;
  4842. } else {
  4843. $this->error = $this->db->lasterror();
  4844. $this->db->rollback();
  4845. return 0;
  4846. }
  4847. }
  4848. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4849. /**
  4850. * Delete a link to resource line
  4851. *
  4852. * @param int $rowid Id of resource line to delete
  4853. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  4854. * @param int $notrigger Disable all triggers
  4855. * @return int >0 if OK, <0 if KO
  4856. */
  4857. public function delete_resource($rowid, $element, $notrigger = 0)
  4858. {
  4859. // phpcs:enable
  4860. global $user;
  4861. $this->db->begin();
  4862. $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
  4863. $sql .= " WHERE rowid = ".((int) $rowid);
  4864. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  4865. $resql = $this->db->query($sql);
  4866. if (!$resql) {
  4867. $this->error = $this->db->lasterror();
  4868. $this->db->rollback();
  4869. return -1;
  4870. } else {
  4871. if (!$notrigger) {
  4872. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  4873. if ($result < 0) {
  4874. $this->db->rollback();
  4875. return -1;
  4876. }
  4877. }
  4878. $this->db->commit();
  4879. return 1;
  4880. }
  4881. }
  4882. /**
  4883. * Overwrite magic function to solve problem of cloning object that are kept as references
  4884. *
  4885. * @return void
  4886. */
  4887. public function __clone()
  4888. {
  4889. // Force a copy of this->lines, otherwise it will point to same object.
  4890. if (isset($this->lines) && is_array($this->lines)) {
  4891. $nboflines = count($this->lines);
  4892. for ($i = 0; $i < $nboflines; $i++) {
  4893. $this->lines[$i] = clone $this->lines[$i];
  4894. }
  4895. }
  4896. }
  4897. /**
  4898. * Common function for all objects extending CommonObject for generating documents
  4899. *
  4900. * @param string $modelspath Relative folder where generators are placed
  4901. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4902. * @param Translate $outputlangs Output language to use
  4903. * @param int $hidedetails 1 to hide details. 0 by default
  4904. * @param int $hidedesc 1 to hide product description. 0 by default
  4905. * @param int $hideref 1 to hide product reference. 0 by default
  4906. * @param null|array $moreparams Array to provide more information
  4907. * @return int >0 if OK, <0 if KO
  4908. * @see addFileIntoDatabaseIndex()
  4909. */
  4910. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4911. {
  4912. global $conf, $langs, $user, $hookmanager, $action;
  4913. $srctemplatepath = '';
  4914. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  4915. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4916. if (!empty($reshook)) {
  4917. return $reshook;
  4918. }
  4919. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4920. if (empty($modele)) {
  4921. $this->error = 'BadValueForParameterModele';
  4922. return -1;
  4923. }
  4924. // Increase limit for PDF build
  4925. $err = error_reporting();
  4926. error_reporting(0);
  4927. @set_time_limit(120);
  4928. error_reporting($err);
  4929. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4930. $tmp = explode(':', $modele, 2);
  4931. if (!empty($tmp[1])) {
  4932. $modele = $tmp[0];
  4933. $srctemplatepath = $tmp[1];
  4934. }
  4935. // Search template files
  4936. $file = '';
  4937. $classname = '';
  4938. $filefound = '';
  4939. $dirmodels = array('/');
  4940. if (is_array($conf->modules_parts['models'])) {
  4941. $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4942. }
  4943. foreach ($dirmodels as $reldir) {
  4944. foreach (array('doc', 'pdf') as $prefix) {
  4945. if (in_array(get_class($this), array('Adherent'))) {
  4946. // Member module use prefix_modele.class.php
  4947. $file = $prefix."_".$modele.".class.php";
  4948. } else {
  4949. // Other module use prefix_modele.modules.php
  4950. $file = $prefix."_".$modele.".modules.php";
  4951. }
  4952. // On verifie l'emplacement du modele
  4953. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  4954. if (file_exists($file)) {
  4955. $filefound = $file;
  4956. $classname = $prefix.'_'.$modele;
  4957. break;
  4958. }
  4959. }
  4960. if ($filefound) {
  4961. break;
  4962. }
  4963. }
  4964. if (!$filefound) {
  4965. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4966. $this->errors[] = $this->error;
  4967. dol_syslog($this->error, LOG_ERR);
  4968. return -1;
  4969. }
  4970. // If generator was found
  4971. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4972. require_once $file;
  4973. $obj = new $classname($this->db);
  4974. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4975. if ($obj->type == 'odt' && empty($srctemplatepath)) {
  4976. $varfortemplatedir = $obj->scandir;
  4977. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
  4978. $dirtoscan = $conf->global->$varfortemplatedir;
  4979. $listoffiles = array();
  4980. // Now we add first model found in directories scanned
  4981. $listofdir = explode(',', $dirtoscan);
  4982. foreach ($listofdir as $key => $tmpdir) {
  4983. $tmpdir = trim($tmpdir);
  4984. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4985. if (!$tmpdir) {
  4986. unset($listofdir[$key]);
  4987. continue;
  4988. }
  4989. if (is_dir($tmpdir)) {
  4990. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4991. if (count($tmpfiles)) {
  4992. $listoffiles = array_merge($listoffiles, $tmpfiles);
  4993. }
  4994. }
  4995. }
  4996. if (count($listoffiles)) {
  4997. foreach ($listoffiles as $record) {
  4998. $srctemplatepath = $record['fullname'];
  4999. break;
  5000. }
  5001. }
  5002. }
  5003. if (empty($srctemplatepath)) {
  5004. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  5005. return -1;
  5006. }
  5007. }
  5008. if ($obj->type == 'odt' && !empty($srctemplatepath)) {
  5009. if (!dol_is_file($srctemplatepath)) {
  5010. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  5011. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  5012. return -1;
  5013. }
  5014. }
  5015. // We save charset_output to restore it because write_file can change it if needed for
  5016. // output format that does not support UTF8.
  5017. $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
  5018. if (in_array(get_class($this), array('Adherent'))) {
  5019. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
  5020. } else {
  5021. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  5022. }
  5023. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  5024. if ($resultwritefile > 0) {
  5025. $outputlangs->charset_output = $sav_charset_output;
  5026. // We delete old preview
  5027. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  5028. dol_delete_preview($this);
  5029. // Index file in database
  5030. if (!empty($obj->result['fullpath'])) {
  5031. $destfull = $obj->result['fullpath'];
  5032. // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
  5033. $update_main_doc_field = 0;
  5034. if (!empty($obj->update_main_doc_field)) {
  5035. $update_main_doc_field = 1;
  5036. }
  5037. $this->indexFile($destfull, $update_main_doc_field);
  5038. } else {
  5039. 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);
  5040. }
  5041. // Success in building document. We build meta file.
  5042. dol_meta_create($this);
  5043. return 1;
  5044. } else {
  5045. $outputlangs->charset_output = $sav_charset_output;
  5046. $this->error = $obj->error;
  5047. $this->errors = $obj->errors;
  5048. dol_syslog("Error generating document for ".__CLASS__.". Error: ".$obj->error, LOG_ERR);
  5049. return -1;
  5050. }
  5051. }
  5052. /**
  5053. * Index a file into the ECM database
  5054. *
  5055. * @param string $destfull Full path of file to index
  5056. * @param int $update_main_doc_field Update field main_doc fied into the table of object.
  5057. * This param is set when called for a document generation if document generator hase
  5058. * ->update_main_doc_field set and returns ->result['fullpath'].
  5059. * @return int <0 if KO, >0 if OK
  5060. */
  5061. public function indexFile($destfull, $update_main_doc_field)
  5062. {
  5063. global $conf, $user;
  5064. $upload_dir = dirname($destfull);
  5065. $destfile = basename($destfull);
  5066. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  5067. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  5068. $filename = basename($destfile);
  5069. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  5070. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  5071. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  5072. $ecmfile = new EcmFiles($this->db);
  5073. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  5074. // Set the public "share" key
  5075. $setsharekey = false;
  5076. if ($this->element == 'propal' || $this->element == 'proposal') {
  5077. if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
  5078. $setsharekey = true; // feature to make online signature is not set or set to on (default)
  5079. }
  5080. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  5081. $setsharekey = true;
  5082. }
  5083. }
  5084. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  5085. $setsharekey = true;
  5086. }
  5087. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  5088. $setsharekey = true;
  5089. }
  5090. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  5091. $setsharekey = true;
  5092. }
  5093. if ($this->element == 'product' && !empty($conf->global->PRODUCT_ALLOW_EXTERNAL_DOWNLOAD)) {
  5094. $setsharekey = true;
  5095. }
  5096. if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
  5097. $setsharekey = true;
  5098. }
  5099. if ($this->element == 'fichinter' && !empty($conf->global->FICHINTER_ALLOW_EXTERNAL_DOWNLOAD)) {
  5100. $setsharekey = true;
  5101. }
  5102. if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  5103. $setsharekey = true;
  5104. }
  5105. if ($setsharekey) {
  5106. if (empty($ecmfile->share)) { // Because object not found or share not set yet
  5107. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  5108. $ecmfile->share = getRandomPassword(true);
  5109. }
  5110. }
  5111. if ($result > 0) {
  5112. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  5113. $ecmfile->fullpath_orig = '';
  5114. $ecmfile->gen_or_uploaded = 'generated';
  5115. $ecmfile->description = ''; // indexed content
  5116. $ecmfile->keywords = ''; // keyword content
  5117. $result = $ecmfile->update($user);
  5118. if ($result < 0) {
  5119. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  5120. return -1;
  5121. }
  5122. } else {
  5123. $ecmfile->entity = $conf->entity;
  5124. $ecmfile->filepath = $rel_dir;
  5125. $ecmfile->filename = $filename;
  5126. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  5127. $ecmfile->fullpath_orig = '';
  5128. $ecmfile->gen_or_uploaded = 'generated';
  5129. $ecmfile->description = ''; // indexed content
  5130. $ecmfile->keywords = ''; // keyword content
  5131. $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
  5132. $ecmfile->src_object_id = $this->id;
  5133. $result = $ecmfile->create($user);
  5134. if ($result < 0) {
  5135. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  5136. return -1;
  5137. }
  5138. }
  5139. /*$this->result['fullname']=$destfull;
  5140. $this->result['filepath']=$ecmfile->filepath;
  5141. $this->result['filename']=$ecmfile->filename;*/
  5142. //var_dump($obj->update_main_doc_field);exit;
  5143. if ($update_main_doc_field && !empty($this->table_element)) {
  5144. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
  5145. $sql .= " WHERE rowid = ".((int) $this->id);
  5146. $resql = $this->db->query($sql);
  5147. if (!$resql) {
  5148. dol_print_error($this->db);
  5149. return -1;
  5150. } else {
  5151. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  5152. }
  5153. }
  5154. }
  5155. return 1;
  5156. }
  5157. /**
  5158. * Build thumb
  5159. * @todo Move this into files.lib.php
  5160. *
  5161. * @param string $file Path file in UTF8 to original file to create thumbs from.
  5162. * @return void
  5163. */
  5164. public function addThumbs($file)
  5165. {
  5166. $file_osencoded = dol_osencode($file);
  5167. if (file_exists($file_osencoded)) {
  5168. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  5169. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  5170. // Create small thumbs for company (Ratio is near 16/9)
  5171. // Used on logon for example
  5172. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  5173. // Create mini thumbs for company (Ratio is near 16/9)
  5174. // Used on menu or for setup page for example
  5175. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  5176. }
  5177. }
  5178. /**
  5179. * Delete thumbs
  5180. * @todo Move this into files.lib.php
  5181. *
  5182. * @param string $file Path file in UTF8 to original file to delete thumbs.
  5183. * @return void
  5184. */
  5185. public function delThumbs($file)
  5186. {
  5187. $imgThumbName = getImageFileNameForSize($file, '_small'); // Full path of thumb file
  5188. dol_delete_file($imgThumbName);
  5189. $imgThumbName = getImageFileNameForSize($file, '_mini'); // Full path of thumb file
  5190. dol_delete_file($imgThumbName);
  5191. }
  5192. /* Functions common to commonobject and commonobjectline */
  5193. /* For default values */
  5194. /**
  5195. * Return the default value to use for a field when showing the create form of object.
  5196. * Return values in this order:
  5197. * 1) If parameter is available into POST, we return it first.
  5198. * 2) If not but an alternate value was provided as parameter of function, we return it.
  5199. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  5200. * 4) Return value found into database (TODO No yet implemented)
  5201. *
  5202. * @param string $fieldname Name of field
  5203. * @param string $alternatevalue Alternate value to use
  5204. * @param string $type Type of data
  5205. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  5206. **/
  5207. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null, $type = 'alphanohtml')
  5208. {
  5209. global $conf, $_POST;
  5210. // If param here has been posted, we use this value first.
  5211. if (GETPOSTISSET($fieldname)) {
  5212. return GETPOST($fieldname, $type, 3);
  5213. }
  5214. if (isset($alternatevalue)) {
  5215. return $alternatevalue;
  5216. }
  5217. $newelement = $this->element;
  5218. if ($newelement == 'facture') {
  5219. $newelement = 'invoice';
  5220. }
  5221. if ($newelement == 'commande') {
  5222. $newelement = 'order';
  5223. }
  5224. if (empty($newelement)) {
  5225. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  5226. return '';
  5227. }
  5228. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  5229. //var_dump($keyforfieldname);
  5230. if (isset($conf->global->$keyforfieldname)) {
  5231. return $conf->global->$keyforfieldname;
  5232. }
  5233. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  5234. // store content into $conf->cache['overwrite_default']
  5235. return '';
  5236. }
  5237. /* For triggers */
  5238. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5239. /**
  5240. * Call trigger based on this instance.
  5241. * Some context information may also be provided into array property this->context.
  5242. * NB: Error from trigger are stacked in interface->errors
  5243. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  5244. *
  5245. * @param string $triggerName trigger's name to execute
  5246. * @param User $user Object user
  5247. * @return int Result of run_triggers
  5248. */
  5249. public function call_trigger($triggerName, $user)
  5250. {
  5251. // phpcs:enable
  5252. global $langs, $conf;
  5253. if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
  5254. dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.');
  5255. exit;
  5256. }
  5257. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  5258. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  5259. $langs = new Translate('', $conf);
  5260. }
  5261. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  5262. $interface = new Interfaces($this->db);
  5263. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  5264. if ($result < 0) {
  5265. if (!empty($this->errors)) {
  5266. $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.
  5267. } else {
  5268. $this->errors = $interface->errors;
  5269. }
  5270. }
  5271. return $result;
  5272. }
  5273. /* Functions for data in other language */
  5274. /**
  5275. * Function to get alternative languages of a data into $this->array_languages
  5276. * This method is NOT called by method fetch of objects but must be called separately.
  5277. *
  5278. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  5279. * @see fetch_optionnals()
  5280. */
  5281. public function fetchValuesForExtraLanguages()
  5282. {
  5283. // To avoid SQL errors. Probably not the better solution though
  5284. if (!$this->element) {
  5285. return 0;
  5286. }
  5287. if (!($this->id > 0)) {
  5288. return 0;
  5289. }
  5290. if (is_array($this->array_languages)) {
  5291. return 1;
  5292. }
  5293. $this->array_languages = array();
  5294. $element = $this->element;
  5295. if ($element == 'categorie') {
  5296. $element = 'categories'; // For compatibility
  5297. }
  5298. // Request to get translation values for object
  5299. $sql = "SELECT rowid, property, lang , value";
  5300. $sql .= " FROM ".$this->db->prefix()."object_lang";
  5301. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  5302. $sql .= " AND fk_object = ".((int) $this->id);
  5303. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5304. $resql = $this->db->query($sql);
  5305. if ($resql) {
  5306. $numrows = $this->db->num_rows($resql);
  5307. if ($numrows) {
  5308. $i = 0;
  5309. while ($i < $numrows) {
  5310. $obj = $this->db->fetch_object($resql);
  5311. $key = $obj->property;
  5312. $value = $obj->value;
  5313. $codelang = $obj->lang;
  5314. $type = $this->fields[$key]['type'];
  5315. // we can add this attribute to object
  5316. if (preg_match('/date/', $type)) {
  5317. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  5318. } else {
  5319. $this->array_languages[$key][$codelang] = $value;
  5320. }
  5321. $i++;
  5322. }
  5323. }
  5324. $this->db->free($resql);
  5325. if ($numrows) {
  5326. return $numrows;
  5327. } else {
  5328. return 0;
  5329. }
  5330. } else {
  5331. dol_print_error($this->db);
  5332. return -1;
  5333. }
  5334. }
  5335. /**
  5336. * Fill array_options property of object by extrafields value (using for data sent by forms)
  5337. *
  5338. * @param string $onlykey Only the following key is filled. When we make update of only one language field ($action = 'update_languages'), calling page must set this to avoid to have other languages being reset.
  5339. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  5340. */
  5341. public function setValuesForExtraLanguages($onlykey = '')
  5342. {
  5343. global $_POST, $langs;
  5344. // Get extra fields
  5345. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  5346. $tmparray = explode('-', $postfieldkey);
  5347. if ($tmparray[0] != 'field') {
  5348. continue;
  5349. }
  5350. $element = $tmparray[1];
  5351. $key = $tmparray[2];
  5352. $codelang = $tmparray[3];
  5353. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  5354. if (!empty($onlykey) && $key != $onlykey) {
  5355. continue;
  5356. }
  5357. if ($element != $this->element) {
  5358. continue;
  5359. }
  5360. $key_type = $this->fields[$key]['type'];
  5361. $enabled = 1;
  5362. if (isset($this->fields[$key]['enabled'])) {
  5363. $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
  5364. }
  5365. /*$perms = 1;
  5366. if (isset($this->fields[$key]['perms']))
  5367. {
  5368. $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
  5369. }*/
  5370. if (empty($enabled)) {
  5371. continue;
  5372. }
  5373. //if (empty($perms)) continue;
  5374. if (in_array($key_type, array('date'))) {
  5375. // Clean parameters
  5376. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5377. $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
  5378. } elseif (in_array($key_type, array('datetime'))) {
  5379. // Clean parameters
  5380. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5381. $value_key = dol_mktime(GETPOST($postfieldkey."hour", 'int'), GETPOST($postfieldkey."min", 'int'), 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
  5382. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  5383. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  5384. if (!empty($value_arr)) {
  5385. $value_key = implode(',', $value_arr);
  5386. } else {
  5387. $value_key = '';
  5388. }
  5389. } elseif (in_array($key_type, array('price', 'double'))) {
  5390. $value_arr = GETPOST($postfieldkey, 'alpha');
  5391. $value_key = price2num($value_arr);
  5392. } else {
  5393. $value_key = GETPOST($postfieldkey);
  5394. if (in_array($key_type, array('link')) && $value_key == '-1') {
  5395. $value_key = '';
  5396. }
  5397. }
  5398. $this->array_languages[$key][$codelang] = $value_key;
  5399. /*if ($nofillrequired) {
  5400. $langs->load('errors');
  5401. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  5402. return -1;
  5403. }*/
  5404. }
  5405. return 1;
  5406. }
  5407. /* Functions for extrafields */
  5408. /**
  5409. * Function to make a fetch but set environment to avoid to load computed values before.
  5410. *
  5411. * @param int $id ID of object
  5412. * @return int >0 if OK, 0 if not found, <0 if KO
  5413. */
  5414. public function fetchNoCompute($id)
  5415. {
  5416. global $conf;
  5417. $savDisableCompute = $conf->disable_compute;
  5418. $conf->disable_compute = 1;
  5419. $ret = $this->fetch($id);
  5420. $conf->disable_compute = $savDisableCompute;
  5421. return $ret;
  5422. }
  5423. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5424. /**
  5425. * Function to get extra fields of an object into $this->array_options
  5426. * This method is in most cases called by method fetch of objects but you can call it separately.
  5427. *
  5428. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  5429. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  5430. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  5431. * @see fetchValuesForExtraLanguages()
  5432. */
  5433. public function fetch_optionals($rowid = null, $optionsArray = null)
  5434. {
  5435. // phpcs:enable
  5436. global $conf, $extrafields;
  5437. if (empty($rowid)) {
  5438. $rowid = $this->id;
  5439. }
  5440. if (empty($rowid) && isset($this->rowid)) {
  5441. $rowid = $this->rowid; // deprecated
  5442. }
  5443. // To avoid SQL errors. Probably not the better solution though
  5444. if (!$this->table_element) {
  5445. return 0;
  5446. }
  5447. $this->array_options = array();
  5448. if (!is_array($optionsArray)) {
  5449. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  5450. if (!isset($extrafields) || !is_object($extrafields)) {
  5451. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5452. $extrafields = new ExtraFields($this->db);
  5453. }
  5454. // Load array of extrafields for elementype = $this->table_element
  5455. if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
  5456. $extrafields->fetch_name_optionals_label($this->table_element);
  5457. }
  5458. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  5459. } else {
  5460. global $extrafields;
  5461. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  5462. }
  5463. $table_element = $this->table_element;
  5464. if ($table_element == 'categorie') {
  5465. $table_element = 'categories'; // For compatibility
  5466. }
  5467. // Request to get complementary values
  5468. if (is_array($optionsArray) && count($optionsArray) > 0) {
  5469. $sql = "SELECT rowid";
  5470. foreach ($optionsArray as $name => $label) {
  5471. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
  5472. $sql .= ", ".$name;
  5473. }
  5474. }
  5475. $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
  5476. $sql .= " WHERE fk_object = ".((int) $rowid);
  5477. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5478. $resql = $this->db->query($sql);
  5479. if ($resql) {
  5480. $numrows = $this->db->num_rows($resql);
  5481. if ($numrows) {
  5482. $tab = $this->db->fetch_array($resql);
  5483. foreach ($tab as $key => $value) {
  5484. // 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)
  5485. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
  5486. // we can add this attribute to object
  5487. if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
  5488. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  5489. $this->array_options["options_".$key] = $this->db->jdate($value);
  5490. } else {
  5491. $this->array_options["options_".$key] = $value;
  5492. }
  5493. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  5494. }
  5495. }
  5496. }
  5497. // If field is a computed field, value must become result of compute (regardless of whether a row exists
  5498. // in the element's extrafields table)
  5499. if (is_array($extrafields->attributes[$this->table_element]['label'])) {
  5500. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
  5501. if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
  5502. //var_dump($conf->disable_compute);
  5503. if (empty($conf->disable_compute)) {
  5504. global $objectoffield; // We set a global variable to $objectoffield so
  5505. $objectoffield = $this; // we can use it inside computed formula
  5506. $this->array_options['options_' . $key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
  5507. }
  5508. }
  5509. }
  5510. }
  5511. $this->db->free($resql);
  5512. if ($numrows) {
  5513. return $numrows;
  5514. } else {
  5515. return 0;
  5516. }
  5517. } else {
  5518. $this->errors[]=$this->db->lasterror;
  5519. return -1;
  5520. }
  5521. }
  5522. return 0;
  5523. }
  5524. /**
  5525. * Delete all extra fields values for the current object.
  5526. *
  5527. * @return int <0 if KO, >0 if OK
  5528. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  5529. */
  5530. public function deleteExtraFields()
  5531. {
  5532. global $conf;
  5533. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5534. return 0;
  5535. }
  5536. $this->db->begin();
  5537. $table_element = $this->table_element;
  5538. if ($table_element == 'categorie') {
  5539. $table_element = 'categories'; // For compatibility
  5540. }
  5541. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  5542. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5543. $resql = $this->db->query($sql_del);
  5544. if (!$resql) {
  5545. $this->error = $this->db->lasterror();
  5546. $this->db->rollback();
  5547. return -1;
  5548. } else {
  5549. $this->db->commit();
  5550. return 1;
  5551. }
  5552. }
  5553. /**
  5554. * Add/Update all extra fields values for the current object.
  5555. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5556. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5557. *
  5558. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5559. * @param User $userused Object user
  5560. * @return int -1=error, O=did nothing, 1=OK
  5561. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  5562. */
  5563. public function insertExtraFields($trigger = '', $userused = null)
  5564. {
  5565. global $conf, $langs, $user;
  5566. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5567. return 0;
  5568. }
  5569. if (empty($userused)) {
  5570. $userused = $user;
  5571. }
  5572. $error = 0;
  5573. if (!empty($this->array_options)) {
  5574. // Check parameters
  5575. $langs->load('admin');
  5576. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5577. $extrafields = new ExtraFields($this->db);
  5578. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  5579. // Eliminate copied source object extra fields that do not exist in target object
  5580. $new_array_options = array();
  5581. foreach ($this->array_options as $key => $value) {
  5582. if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
  5583. $new_array_options[$key] = $value;
  5584. } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
  5585. $new_array_options['options_'.$key] = $value;
  5586. }
  5587. }
  5588. foreach ($new_array_options as $key => $value) {
  5589. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5590. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  5591. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  5592. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  5593. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  5594. $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
  5595. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  5596. // If we clone, we have to clean unique extrafields to prevent duplicates.
  5597. // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
  5598. if (!empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && !empty($attributeUnique)) {
  5599. $new_array_options[$key] = null;
  5600. }
  5601. // Similar code than into insertExtraFields
  5602. if ($attributeRequired) {
  5603. $mandatorypb = false;
  5604. if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
  5605. $mandatorypb = true;
  5606. }
  5607. if ($this->array_options[$key] === '') {
  5608. $mandatorypb = true;
  5609. }
  5610. if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
  5611. $mandatorypb = true;
  5612. }
  5613. if ($mandatorypb) {
  5614. $langs->load("errors");
  5615. dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
  5616. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5617. return -1;
  5618. }
  5619. }
  5620. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5621. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5622. if (!empty($attrfieldcomputed)) {
  5623. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5624. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5625. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5626. $new_array_options[$key] = $value;
  5627. } else {
  5628. $new_array_options[$key] = null;
  5629. }
  5630. }
  5631. switch ($attributeType) {
  5632. case 'int':
  5633. if (!is_numeric($value) && $value != '') {
  5634. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5635. return -1;
  5636. } elseif ($value == '') {
  5637. $new_array_options[$key] = null;
  5638. }
  5639. break;
  5640. case 'price':
  5641. case 'double':
  5642. $value = price2num($value);
  5643. if (!is_numeric($value) && $value != '') {
  5644. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5645. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5646. return -1;
  5647. } elseif ($value == '') {
  5648. $value = null;
  5649. }
  5650. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5651. $new_array_options[$key] = $value;
  5652. break;
  5653. /*case 'select': // Not required, we chosed value='0' for undefined values
  5654. if ($value=='-1')
  5655. {
  5656. $this->array_options[$key] = null;
  5657. }
  5658. break;*/
  5659. case 'password':
  5660. $algo = '';
  5661. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
  5662. // If there is an encryption choice, we use it to crypt data before insert
  5663. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  5664. $algo = reset($tmparrays);
  5665. if ($algo != '') {
  5666. //global $action; // $action may be 'create', 'update', 'update_extras'...
  5667. //var_dump($action);
  5668. //var_dump($this->oldcopy);exit;
  5669. 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
  5670. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  5671. if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) { // If old value crypted in database is same than submited new value, it means we don't change it, so we don't update.
  5672. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5673. } else {
  5674. // var_dump($algo);
  5675. $newvalue = dol_hash($this->array_options[$key], $algo);
  5676. $new_array_options[$key] = $newvalue;
  5677. }
  5678. } else {
  5679. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5680. }
  5681. }
  5682. } else // Common usage
  5683. {
  5684. $new_array_options[$key] = $this->array_options[$key];
  5685. }
  5686. break;
  5687. case 'date':
  5688. case 'datetime':
  5689. // If data is a string instead of a timestamp, we convert it
  5690. if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
  5691. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5692. }
  5693. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  5694. break;
  5695. case 'datetimegmt':
  5696. // If data is a string instead of a timestamp, we convert it
  5697. if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
  5698. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5699. }
  5700. $new_array_options[$key] = $this->db->idate($this->array_options[$key], 'gmt');
  5701. break;
  5702. case 'link':
  5703. $param_list = array_keys($attributeParam['options']);
  5704. // 0 : ObjectName
  5705. // 1 : classPath
  5706. $InfoFieldList = explode(":", $param_list[0]);
  5707. dol_include_once($InfoFieldList[1]);
  5708. if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
  5709. if ($value == '-1') { // -1 is key for no defined in combo list of objects
  5710. $new_array_options[$key] = '';
  5711. } elseif ($value) {
  5712. $object = new $InfoFieldList[0]($this->db);
  5713. if (is_numeric($value)) {
  5714. $res = $object->fetch($value); // Common case
  5715. } else {
  5716. $res = $object->fetch('', $value); // For compatibility
  5717. }
  5718. if ($res > 0) {
  5719. $new_array_options[$key] = $object->id;
  5720. } else {
  5721. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5722. return -1;
  5723. }
  5724. }
  5725. } else {
  5726. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5727. }
  5728. break;
  5729. case 'checkbox':
  5730. case 'chkbxlst':
  5731. if (is_array($this->array_options[$key])) {
  5732. $new_array_options[$key] = implode(',', $this->array_options[$key]);
  5733. } else {
  5734. $new_array_options[$key] = $this->array_options[$key];
  5735. }
  5736. break;
  5737. }
  5738. }
  5739. $this->db->begin();
  5740. $table_element = $this->table_element;
  5741. if ($table_element == 'categorie') {
  5742. $table_element = 'categories'; // For compatibility
  5743. }
  5744. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  5745. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5746. $this->db->query($sql_del);
  5747. $sql = "INSERT INTO ".$this->db->prefix().$table_element."_extrafields (fk_object";
  5748. foreach ($new_array_options as $key => $value) {
  5749. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5750. // Add field of attribut
  5751. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
  5752. $sql .= ",".$attributeKey;
  5753. }
  5754. }
  5755. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5756. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5757. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5758. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5759. $sql .= ",".$tmpkey;
  5760. }
  5761. }
  5762. }
  5763. $sql .= ") VALUES (".$this->id;
  5764. foreach ($new_array_options as $key => $value) {
  5765. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5766. // Add field of attribute
  5767. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
  5768. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
  5769. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  5770. } else {
  5771. $sql .= ",null";
  5772. }
  5773. }
  5774. }
  5775. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5776. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5777. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5778. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5779. if (in_array($tmpval, array('int', 'double', 'price'))) {
  5780. $sql .= ", 0";
  5781. } else {
  5782. $sql .= ", ''";
  5783. }
  5784. }
  5785. }
  5786. }
  5787. $sql .= ")";
  5788. $resql = $this->db->query($sql);
  5789. if (!$resql) {
  5790. $this->error = $this->db->lasterror();
  5791. $error++;
  5792. }
  5793. if (!$error && $trigger) {
  5794. // Call trigger
  5795. $this->context = array('extrafieldaddupdate'=>1);
  5796. $result = $this->call_trigger($trigger, $userused);
  5797. if ($result < 0) {
  5798. $error++;
  5799. }
  5800. // End call trigger
  5801. }
  5802. if ($error) {
  5803. $this->db->rollback();
  5804. return -1;
  5805. } else {
  5806. $this->db->commit();
  5807. return 1;
  5808. }
  5809. } else {
  5810. return 0;
  5811. }
  5812. }
  5813. /**
  5814. * Add/Update all extra fields values for the current object.
  5815. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5816. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5817. *
  5818. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5819. * @param User $userused Object user
  5820. * @return int -1=error, O=did nothing, 1=OK
  5821. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  5822. */
  5823. public function insertExtraLanguages($trigger = '', $userused = null)
  5824. {
  5825. global $conf, $langs, $user;
  5826. if (empty($userused)) {
  5827. $userused = $user;
  5828. }
  5829. $error = 0;
  5830. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5831. return 0; // For avoid conflicts if trigger used
  5832. }
  5833. if (is_array($this->array_languages)) {
  5834. $new_array_languages = $this->array_languages;
  5835. foreach ($new_array_languages as $key => $value) {
  5836. $attributeKey = $key;
  5837. $attributeType = $this->fields[$attributeKey]['type'];
  5838. $attributeLabel = $this->fields[$attributeKey]['label'];
  5839. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5840. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5841. switch ($attributeType) {
  5842. case 'int':
  5843. if (!is_numeric($value) && $value != '') {
  5844. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5845. return -1;
  5846. } elseif ($value == '') {
  5847. $new_array_languages[$key] = null;
  5848. }
  5849. break;
  5850. case 'double':
  5851. $value = price2num($value);
  5852. if (!is_numeric($value) && $value != '') {
  5853. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5854. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5855. return -1;
  5856. } elseif ($value == '') {
  5857. $new_array_languages[$key] = null;
  5858. } else {
  5859. $new_array_languages[$key] = $value;
  5860. }
  5861. break;
  5862. /*case 'select': // Not required, we chosed value='0' for undefined values
  5863. if ($value=='-1')
  5864. {
  5865. $this->array_options[$key] = null;
  5866. }
  5867. break;*/
  5868. }
  5869. }
  5870. $this->db->begin();
  5871. $table_element = $this->table_element;
  5872. if ($table_element == 'categorie') {
  5873. $table_element = 'categories'; // For compatibility
  5874. }
  5875. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  5876. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  5877. foreach ($langcodearray as $langcode => $value) {
  5878. $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
  5879. $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  5880. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  5881. $this->db->query($sql_del);
  5882. if ($value !== '') {
  5883. $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
  5884. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  5885. $sql .= ")";
  5886. $resql = $this->db->query($sql);
  5887. if (!$resql) {
  5888. $this->error = $this->db->lasterror();
  5889. $error++;
  5890. break;
  5891. }
  5892. }
  5893. }
  5894. }
  5895. if (!$error && $trigger) {
  5896. // Call trigger
  5897. $this->context = array('extralanguagesaddupdate'=>1);
  5898. $result = $this->call_trigger($trigger, $userused);
  5899. if ($result < 0) {
  5900. $error++;
  5901. }
  5902. // End call trigger
  5903. }
  5904. if ($error) {
  5905. $this->db->rollback();
  5906. return -1;
  5907. } else {
  5908. $this->db->commit();
  5909. return 1;
  5910. }
  5911. } else {
  5912. return 0;
  5913. }
  5914. }
  5915. /**
  5916. * Update 1 extra field value for the current object. Keep other fields unchanged.
  5917. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5918. *
  5919. * @param string $key Key of the extrafield to update (without starting 'options_')
  5920. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5921. * @param User $userused Object user
  5922. * @return int -1=error, O=did nothing, 1=OK
  5923. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  5924. */
  5925. public function updateExtraField($key, $trigger = null, $userused = null)
  5926. {
  5927. global $conf, $langs, $user;
  5928. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5929. return 0;
  5930. }
  5931. if (empty($userused)) {
  5932. $userused = $user;
  5933. }
  5934. $error = 0;
  5935. if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
  5936. // Check parameters
  5937. $langs->load('admin');
  5938. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5939. $extrafields = new ExtraFields($this->db);
  5940. $extrafields->fetch_name_optionals_label($this->table_element);
  5941. $value = $this->array_options["options_".$key];
  5942. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  5943. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  5944. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  5945. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  5946. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  5947. // Similar code than into insertExtraFields
  5948. if ($attributeRequired) {
  5949. $mandatorypb = false;
  5950. if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
  5951. $mandatorypb = true;
  5952. }
  5953. if ($this->array_options["options_".$key] === '') {
  5954. $mandatorypb = true;
  5955. }
  5956. if ($mandatorypb) {
  5957. $langs->load("errors");
  5958. dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
  5959. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5960. return -1;
  5961. }
  5962. }
  5963. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5964. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5965. if (!empty($attrfieldcomputed)) {
  5966. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5967. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5968. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5969. $this->array_options["options_".$key] = $value;
  5970. } else {
  5971. $this->array_options["options_".$key] = null;
  5972. }
  5973. }
  5974. switch ($attributeType) {
  5975. case 'int':
  5976. if (!is_numeric($value) && $value != '') {
  5977. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5978. return -1;
  5979. } elseif ($value === '') {
  5980. $this->array_options["options_".$key] = null;
  5981. }
  5982. break;
  5983. case 'double':
  5984. $value = price2num($value);
  5985. if (!is_numeric($value) && $value != '') {
  5986. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5987. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5988. return -1;
  5989. } elseif ($value === '') {
  5990. $value = null;
  5991. }
  5992. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5993. $this->array_options["options_".$key] = $value;
  5994. break;
  5995. /*case 'select': // Not required, we chosed value='0' for undefined values
  5996. if ($value=='-1')
  5997. {
  5998. $this->array_options[$key] = null;
  5999. }
  6000. break;*/
  6001. case 'price':
  6002. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  6003. break;
  6004. case 'date':
  6005. case 'datetime':
  6006. if (empty($this->array_options["options_".$key])) {
  6007. $this->array_options["options_".$key] = null;
  6008. } else {
  6009. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  6010. }
  6011. break;
  6012. case 'datetimegmt':
  6013. if (empty($this->array_options["options_".$key])) {
  6014. $this->array_options["options_".$key] = null;
  6015. } else {
  6016. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key], 'gmt');
  6017. }
  6018. break;
  6019. case 'boolean':
  6020. if (empty($this->array_options["options_".$key])) {
  6021. $this->array_options["options_".$key] = null;
  6022. }
  6023. break;
  6024. /*
  6025. case 'link':
  6026. $param_list = array_keys($attributeParam['options']);
  6027. // 0 : ObjectName
  6028. // 1 : classPath
  6029. $InfoFieldList = explode(":", $param_list[0]);
  6030. dol_include_once($InfoFieldList[1]);
  6031. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  6032. {
  6033. if ($value == '-1') // -1 is key for no defined in combo list of objects
  6034. {
  6035. $new_array_options[$key] = '';
  6036. } elseif ($value) {
  6037. $object = new $InfoFieldList[0]($this->db);
  6038. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  6039. else $res = $object->fetch('', $value); // For compatibility
  6040. if ($res > 0) $new_array_options[$key] = $object->id;
  6041. else {
  6042. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  6043. $this->db->rollback();
  6044. return -1;
  6045. }
  6046. }
  6047. } else {
  6048. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  6049. }
  6050. break;
  6051. */
  6052. case 'checkbox':
  6053. case 'chkbxlst':
  6054. if (is_array($this->array_options[$key])) {
  6055. $new_array_options[$key] = implode(',', $this->array_options[$key]);
  6056. } else {
  6057. $new_array_options[$key] = $this->array_options[$key];
  6058. }
  6059. break;
  6060. }
  6061. $this->db->begin();
  6062. $linealreadyfound = 0;
  6063. // Check if there is already a line for this object (in most cases, it is, but sometimes it is not, for example when extra field has been created after), so we must keep this overload)
  6064. $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  6065. $resql = $this->db->query($sql);
  6066. if ($resql) {
  6067. $tmpobj = $this->db->fetch_object($resql);
  6068. if ($tmpobj) {
  6069. $linealreadyfound = $tmpobj->nb;
  6070. }
  6071. }
  6072. if ($linealreadyfound) {
  6073. if ($this->array_options["options_".$key] === null) {
  6074. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = null";
  6075. } else {
  6076. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
  6077. }
  6078. $sql .= " WHERE fk_object = ".((int) $this->id);
  6079. } else {
  6080. $result = $this->insertExtraFields('', $user);
  6081. if ($result < 0) {
  6082. $error++;
  6083. }
  6084. }
  6085. $resql = $this->db->query($sql);
  6086. if (!$resql) {
  6087. $error++;
  6088. $this->error = $this->db->lasterror();
  6089. }
  6090. if (!$error && $trigger) {
  6091. // Call trigger
  6092. $this->context = array('extrafieldupdate'=>1);
  6093. $result = $this->call_trigger($trigger, $userused);
  6094. if ($result < 0) {
  6095. $error++;
  6096. }
  6097. // End call trigger
  6098. }
  6099. if ($error) {
  6100. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  6101. $this->db->rollback();
  6102. return -1;
  6103. } else {
  6104. $this->db->commit();
  6105. return 1;
  6106. }
  6107. } else {
  6108. return 0;
  6109. }
  6110. }
  6111. /**
  6112. * Update an extra language value for the current object.
  6113. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  6114. *
  6115. * @param string $key Key of the extrafield (without starting 'options_')
  6116. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  6117. * @param User $userused Object user
  6118. * @return int -1=error, O=did nothing, 1=OK
  6119. * @see updateExtraFields(), insertExtraLanguages()
  6120. */
  6121. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  6122. {
  6123. global $conf, $langs, $user;
  6124. if (empty($userused)) {
  6125. $userused = $user;
  6126. }
  6127. $error = 0;
  6128. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  6129. return 0; // For avoid conflicts if trigger used
  6130. }
  6131. return 0;
  6132. }
  6133. /**
  6134. * Return HTML string to put an input field into a page
  6135. * Code very similar with showInputField of extra fields
  6136. *
  6137. * @param array $val Array of properties for field to show (used only if ->fields not defined)
  6138. * @param string $key Key of attribute
  6139. * @param string|array $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value, for array type must be array)
  6140. * @param string $moreparam To add more parameters on html input tag
  6141. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6142. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6143. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  6144. * @param int $nonewbutton Force to not show the new button on field that are links to object
  6145. * @return string
  6146. */
  6147. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  6148. {
  6149. global $conf, $langs, $form;
  6150. if (!is_object($form)) {
  6151. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6152. $form = new Form($this->db);
  6153. }
  6154. if (!empty($this->fields)) {
  6155. $val = $this->fields[$key];
  6156. }
  6157. // Validation tests and output
  6158. $fieldValidationErrorMsg = '';
  6159. $validationClass = '';
  6160. $fieldValidationErrorMsg = $this->getFieldError($key);
  6161. if (!empty($fieldValidationErrorMsg)) {
  6162. $validationClass = ' --error'; // the -- is use as class state in css : .--error can't be be defined alone it must be define with another class like .my-class.--error or input.--error
  6163. } else {
  6164. $validationClass = ' --success'; // the -- is use as class state in css : .--success can't be be defined alone it must be define with another class like .my-class.--success or input.--success
  6165. }
  6166. $out = '';
  6167. $type = '';
  6168. $isDependList = 0;
  6169. $param = array();
  6170. $param['options'] = array();
  6171. $reg = array();
  6172. $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
  6173. // Because we work on extrafields
  6174. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6175. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  6176. $type = 'link';
  6177. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6178. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6179. $type = 'link';
  6180. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  6181. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  6182. $type = 'link';
  6183. } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6184. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  6185. $type = 'sellist';
  6186. } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6187. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6188. $type = 'sellist';
  6189. } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
  6190. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  6191. $type = 'sellist';
  6192. } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
  6193. $param['options'] = array($reg[1] => 'N');
  6194. $type = 'chkbxlst';
  6195. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  6196. $param['options'] = array();
  6197. $type = 'varchar';
  6198. $size = $reg[1];
  6199. } elseif (preg_match('/varchar/', $val['type'])) {
  6200. $param['options'] = array();
  6201. $type = 'varchar';
  6202. } else {
  6203. $param['options'] = array();
  6204. $type = $this->fields[$key]['type'];
  6205. }
  6206. // Special case that force options and type ($type can be integer, varchar, ...)
  6207. if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
  6208. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  6209. $type = 'select';
  6210. }
  6211. $label = $this->fields[$key]['label'];
  6212. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  6213. $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
  6214. $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
  6215. $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
  6216. $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
  6217. $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
  6218. $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
  6219. $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
  6220. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  6221. $objectid = $this->id;
  6222. if ($computed) {
  6223. if (!preg_match('/^search_/', $keyprefix)) {
  6224. return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  6225. } else {
  6226. return '';
  6227. }
  6228. }
  6229. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  6230. if (empty($morecss) && !empty($val['css'])) {
  6231. $morecss = $val['css'];
  6232. } elseif (empty($morecss)) {
  6233. if ($type == 'date') {
  6234. $morecss = 'minwidth100imp';
  6235. } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
  6236. $morecss = 'minwidth200imp';
  6237. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  6238. $morecss = 'maxwidth75';
  6239. } elseif ($type == 'url') {
  6240. $morecss = 'minwidth400';
  6241. } elseif ($type == 'boolean') {
  6242. $morecss = '';
  6243. } else {
  6244. if (round($size) < 12) {
  6245. $morecss = 'minwidth100';
  6246. } elseif (round($size) <= 48) {
  6247. $morecss = 'minwidth200';
  6248. } else {
  6249. $morecss = 'minwidth400';
  6250. }
  6251. }
  6252. }
  6253. // Add validation state class
  6254. if (!empty($validationClass)) {
  6255. $morecss.= $validationClass;
  6256. }
  6257. if (in_array($type, array('date'))) {
  6258. $tmp = explode(',', $size);
  6259. $newsize = $tmp[0];
  6260. $showtime = 0;
  6261. // Do not show current date when field not required (see selectDate() method)
  6262. if (!$required && $value == '') {
  6263. $value = '-1';
  6264. }
  6265. // TODO Must also support $moreparam
  6266. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  6267. } elseif (in_array($type, array('datetime'))) {
  6268. $tmp = explode(',', $size);
  6269. $newsize = $tmp[0];
  6270. $showtime = 1;
  6271. // Do not show current date when field not required (see selectDate() method)
  6272. if (!$required && $value == '') $value = '-1';
  6273. // TODO Must also support $moreparam
  6274. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
  6275. } elseif (in_array($type, array('duration'))) {
  6276. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  6277. } elseif (in_array($type, array('int', 'integer'))) {
  6278. $tmp = explode(',', $size);
  6279. $newsize = $tmp[0];
  6280. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"'.($newsize > 0 ? ' maxlength="'.$newsize.'"' : '').' value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6281. } elseif (in_array($type, array('real'))) {
  6282. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6283. } elseif (preg_match('/varchar/', $type)) {
  6284. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"'.($size > 0 ? ' maxlength="'.$size.'"' : '').' value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6285. } elseif (in_array($type, array('email', 'mail', 'phone', 'url', 'ip'))) {
  6286. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6287. } elseif (preg_match('/^text/', $type)) {
  6288. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6289. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  6290. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  6291. $out = $doleditor->Create(1);
  6292. } else {
  6293. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  6294. }
  6295. } elseif (preg_match('/^html/', $type)) {
  6296. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6297. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  6298. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor') && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
  6299. $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
  6300. } else {
  6301. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  6302. }
  6303. } elseif ($type == 'boolean') {
  6304. $checked = '';
  6305. if (!empty($value)) {
  6306. $checked = ' checked value="1" ';
  6307. } else {
  6308. $checked = ' value="1" ';
  6309. }
  6310. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  6311. } elseif ($type == 'price') {
  6312. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6313. $value = price($value);
  6314. }
  6315. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  6316. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  6317. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6318. $value = price($value);
  6319. }
  6320. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  6321. } elseif ($type == 'select') {
  6322. $out = '';
  6323. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6324. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6325. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6326. }
  6327. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6328. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
  6329. $out .= '<option value="0">&nbsp;</option>';
  6330. }
  6331. foreach ($param['options'] as $keyb => $valb) {
  6332. if ((string) $keyb == '') {
  6333. continue;
  6334. }
  6335. if (strpos($valb, "|") !== false) {
  6336. list($valb, $parent) = explode('|', $valb);
  6337. }
  6338. $out .= '<option value="'.$keyb.'"';
  6339. $out .= (((string) $value == (string) $keyb) ? ' selected' : '');
  6340. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6341. $out .= '>'.$valb.'</option>';
  6342. }
  6343. $out .= '</select>';
  6344. } elseif ($type == 'sellist') {
  6345. $out = '';
  6346. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6347. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6348. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6349. }
  6350. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6351. if (is_array($param['options'])) {
  6352. $param_list = array_keys($param['options']);
  6353. $InfoFieldList = explode(":", $param_list[0]);
  6354. $parentName = '';
  6355. $parentField = '';
  6356. // 0 : tableName
  6357. // 1 : label field name
  6358. // 2 : key fields name (if differ of rowid)
  6359. // 3 : key field parent (for dependent lists)
  6360. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6361. // 5 : id category type
  6362. // 6 : ids categories list separated by comma for category root
  6363. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6364. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6365. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6366. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6367. } else {
  6368. $keyList = $InfoFieldList[2].' as rowid';
  6369. }
  6370. }
  6371. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6372. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6373. $keyList .= ', '.$parentField;
  6374. }
  6375. $filter_categorie = false;
  6376. if (count($InfoFieldList) > 5) {
  6377. if ($InfoFieldList[0] == 'categorie') {
  6378. $filter_categorie = true;
  6379. }
  6380. }
  6381. if ($filter_categorie === false) {
  6382. $fields_label = explode('|', $InfoFieldList[1]);
  6383. if (is_array($fields_label)) {
  6384. $keyList .= ', ';
  6385. $keyList .= implode(', ', $fields_label);
  6386. }
  6387. $sqlwhere = '';
  6388. $sql = "SELECT " . $keyList;
  6389. $sql .= " FROM " . $this->db->prefix() . $InfoFieldList[0];
  6390. if (!empty($InfoFieldList[4])) {
  6391. // can use SELECT request
  6392. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6393. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6394. }
  6395. // current object id can be use into filter
  6396. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6397. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6398. } else {
  6399. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6400. }
  6401. //We have to join on extrafield table
  6402. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6403. $sql .= " as main, " . $this->db->prefix() . $InfoFieldList[0] . "_extrafields as extra";
  6404. $sqlwhere .= " WHERE extra.fk_object=main." . $InfoFieldList[2] . " AND " . $InfoFieldList[4];
  6405. } else {
  6406. $sqlwhere .= " WHERE " . $InfoFieldList[4];
  6407. }
  6408. } else {
  6409. $sqlwhere .= ' WHERE 1=1';
  6410. }
  6411. // Some tables may have field, some other not. For the moment we disable it.
  6412. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6413. $sqlwhere .= " AND entity = " . ((int) $conf->entity);
  6414. }
  6415. $sql .= $sqlwhere;
  6416. //print $sql;
  6417. $sql .= ' ORDER BY ' . implode(', ', $fields_label);
  6418. dol_syslog(get_class($this) . '::showInputField type=sellist', LOG_DEBUG);
  6419. $resql = $this->db->query($sql);
  6420. if ($resql) {
  6421. $out .= '<option value="0">&nbsp;</option>';
  6422. $num = $this->db->num_rows($resql);
  6423. $i = 0;
  6424. while ($i < $num) {
  6425. $labeltoshow = '';
  6426. $obj = $this->db->fetch_object($resql);
  6427. // Several field into label (eq table:code|libelle:rowid)
  6428. $notrans = false;
  6429. $fields_label = explode('|', $InfoFieldList[1]);
  6430. if (count($fields_label) > 1) {
  6431. $notrans = true;
  6432. foreach ($fields_label as $field_toshow) {
  6433. $labeltoshow .= $obj->$field_toshow . ' ';
  6434. }
  6435. } else {
  6436. $labeltoshow = $obj->{$InfoFieldList[1]};
  6437. }
  6438. $labeltoshow = dol_trunc($labeltoshow, 45);
  6439. if ($value == $obj->rowid) {
  6440. foreach ($fields_label as $field_toshow) {
  6441. $translabel = $langs->trans($obj->$field_toshow);
  6442. if ($translabel != $obj->$field_toshow) {
  6443. $labeltoshow = dol_trunc($translabel) . ' ';
  6444. } else {
  6445. $labeltoshow = dol_trunc($obj->$field_toshow) . ' ';
  6446. }
  6447. }
  6448. $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
  6449. } else {
  6450. if (!$notrans) {
  6451. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6452. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6453. $labeltoshow = dol_trunc($translabel, 18);
  6454. } else {
  6455. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
  6456. }
  6457. }
  6458. if (empty($labeltoshow)) {
  6459. $labeltoshow = '(not defined)';
  6460. }
  6461. if ($value == $obj->rowid) {
  6462. $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
  6463. }
  6464. if (!empty($InfoFieldList[3]) && $parentField) {
  6465. $parent = $parentName . ':' . $obj->{$parentField};
  6466. $isDependList = 1;
  6467. }
  6468. $out .= '<option value="' . $obj->rowid . '"';
  6469. $out .= ($value == $obj->rowid ? ' selected' : '');
  6470. $out .= (!empty($parent) ? ' parent="' . $parent . '"' : '');
  6471. $out .= '>' . $labeltoshow . '</option>';
  6472. }
  6473. $i++;
  6474. }
  6475. $this->db->free($resql);
  6476. } else {
  6477. print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
  6478. }
  6479. } else {
  6480. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  6481. $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
  6482. $out .= '<option value="0">&nbsp;</option>';
  6483. foreach ($data as $data_key => $data_value) {
  6484. $out .= '<option value="' . $data_key . '"';
  6485. $out .= ($value == $data_key ? ' selected' : '');
  6486. $out .= '>' . $data_value . '</option>';
  6487. }
  6488. }
  6489. }
  6490. $out .= '</select>';
  6491. } elseif ($type == 'checkbox') {
  6492. $value_arr = explode(',', $value);
  6493. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, $morecss, 0, '100%');
  6494. } elseif ($type == 'radio') {
  6495. $out = '';
  6496. foreach ($param['options'] as $keyopt => $valopt) {
  6497. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  6498. $out .= ' value="'.$keyopt.'"';
  6499. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  6500. $out .= ($value == $keyopt ? 'checked' : '');
  6501. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$valopt.'</label><br>';
  6502. }
  6503. } elseif ($type == 'chkbxlst') {
  6504. if (is_array($value)) {
  6505. $value_arr = $value;
  6506. } else {
  6507. $value_arr = explode(',', $value);
  6508. }
  6509. if (is_array($param['options'])) {
  6510. $param_list = array_keys($param['options']);
  6511. $InfoFieldList = explode(":", $param_list[0]);
  6512. $parentName = '';
  6513. $parentField = '';
  6514. // 0 : tableName
  6515. // 1 : label field name
  6516. // 2 : key fields name (if differ of rowid)
  6517. // 3 : key field parent (for dependent lists)
  6518. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6519. // 5 : id category type
  6520. // 6 : ids categories list separated by comma for category root
  6521. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6522. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6523. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6524. $keyList .= ', '.$parentField;
  6525. }
  6526. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6527. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6528. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6529. } else {
  6530. $keyList = $InfoFieldList[2].' as rowid';
  6531. }
  6532. }
  6533. $filter_categorie = false;
  6534. if (count($InfoFieldList) > 5) {
  6535. if ($InfoFieldList[0] == 'categorie') {
  6536. $filter_categorie = true;
  6537. }
  6538. }
  6539. if ($filter_categorie === false) {
  6540. $fields_label = explode('|', $InfoFieldList[1]);
  6541. if (is_array($fields_label)) {
  6542. $keyList .= ', ';
  6543. $keyList .= implode(', ', $fields_label);
  6544. }
  6545. $sqlwhere = '';
  6546. $sql = "SELECT " . $keyList;
  6547. $sql .= ' FROM ' . $this->db->prefix() . $InfoFieldList[0];
  6548. if (!empty($InfoFieldList[4])) {
  6549. // can use SELECT request
  6550. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6551. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6552. }
  6553. // current object id can be use into filter
  6554. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6555. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6556. } else {
  6557. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6558. }
  6559. // We have to join on extrafield table
  6560. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6561. $sql .= ' as main, ' . $this->db->prefix() . $InfoFieldList[0] . '_extrafields as extra';
  6562. $sqlwhere .= " WHERE extra.fk_object=main." . $InfoFieldList[2] . " AND " . $InfoFieldList[4];
  6563. } else {
  6564. $sqlwhere .= " WHERE " . $InfoFieldList[4];
  6565. }
  6566. } else {
  6567. $sqlwhere .= ' WHERE 1=1';
  6568. }
  6569. // Some tables may have field, some other not. For the moment we disable it.
  6570. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6571. $sqlwhere .= " AND entity = " . ((int) $conf->entity);
  6572. }
  6573. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  6574. // print $sql;
  6575. $sql .= $sqlwhere;
  6576. dol_syslog(get_class($this) . '::showInputField type=chkbxlst', LOG_DEBUG);
  6577. $resql = $this->db->query($sql);
  6578. if ($resql) {
  6579. $num = $this->db->num_rows($resql);
  6580. $i = 0;
  6581. $data = array();
  6582. while ($i < $num) {
  6583. $labeltoshow = '';
  6584. $obj = $this->db->fetch_object($resql);
  6585. $notrans = false;
  6586. // Several field into label (eq table:code|libelle:rowid)
  6587. $fields_label = explode('|', $InfoFieldList[1]);
  6588. if (count($fields_label) > 1) {
  6589. $notrans = true;
  6590. foreach ($fields_label as $field_toshow) {
  6591. $labeltoshow .= $obj->$field_toshow . ' ';
  6592. }
  6593. } else {
  6594. $labeltoshow = $obj->{$InfoFieldList[1]};
  6595. }
  6596. $labeltoshow = dol_trunc($labeltoshow, 45);
  6597. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6598. foreach ($fields_label as $field_toshow) {
  6599. $translabel = $langs->trans($obj->$field_toshow);
  6600. if ($translabel != $obj->$field_toshow) {
  6601. $labeltoshow = dol_trunc($translabel, 18) . ' ';
  6602. } else {
  6603. $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
  6604. }
  6605. }
  6606. $data[$obj->rowid] = $labeltoshow;
  6607. } else {
  6608. if (!$notrans) {
  6609. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6610. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6611. $labeltoshow = dol_trunc($translabel, 18);
  6612. } else {
  6613. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  6614. }
  6615. }
  6616. if (empty($labeltoshow)) {
  6617. $labeltoshow = '(not defined)';
  6618. }
  6619. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6620. $data[$obj->rowid] = $labeltoshow;
  6621. }
  6622. if (!empty($InfoFieldList[3]) && $parentField) {
  6623. $parent = $parentName . ':' . $obj->{$parentField};
  6624. $isDependList = 1;
  6625. }
  6626. $data[$obj->rowid] = $labeltoshow;
  6627. }
  6628. $i++;
  6629. }
  6630. $this->db->free($resql);
  6631. $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, '', 0, $morecss, 0, '100%');
  6632. } else {
  6633. print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
  6634. }
  6635. } else {
  6636. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  6637. $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
  6638. $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, '', 0, $morecss, 0, '100%');
  6639. }
  6640. }
  6641. } elseif ($type == 'link') {
  6642. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
  6643. $param_list_array = explode(':', $param_list[0]);
  6644. $showempty = (($required && $default != '') ? 0 : 1);
  6645. if (!preg_match('/search_/', $keyprefix)) {
  6646. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6647. if (!empty($this->fields[$key]['picto'])) {
  6648. $morecss .= ' widthcentpercentminusxx';
  6649. } else {
  6650. $morecss .= ' widthcentpercentminusx';
  6651. }
  6652. } else {
  6653. if (!empty($this->fields[$key]['picto'])) {
  6654. $morecss .= ' widthcentpercentminusx';
  6655. }
  6656. }
  6657. }
  6658. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  6659. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6660. if (!GETPOSTISSET('backtopage') && empty($val['disabled']) && empty($nonewbutton)) { // To avoid to open several times the 'Create Object' button and to avoid to have button if field is protected by a "disabled".
  6661. list($class, $classfile) = explode(':', $param_list[0]);
  6662. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
  6663. $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  6664. } else {
  6665. $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  6666. }
  6667. $paramforthenewlink = '';
  6668. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  6669. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  6670. $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin='.GETPOST('origin', 'aZ09') : '');
  6671. $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid='.GETPOST('originid', 'int') : '');
  6672. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  6673. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  6674. $out .= '<a class="butActionNew" title="'.$langs->trans("New").'" href="'.$url_path.'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF'].($paramforthenewlink ? '?'.$paramforthenewlink : '')).'"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6675. }
  6676. }
  6677. } elseif ($type == 'password') {
  6678. // If prefix is 'search_', field is used as a filter, we use a common text field.
  6679. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  6680. } elseif ($type == 'array') {
  6681. $newval = $val;
  6682. $newval['type'] = 'varchar(256)';
  6683. $out = '';
  6684. if (!empty($value)) {
  6685. foreach ($value as $option) {
  6686. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6687. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  6688. }
  6689. }
  6690. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6691. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6692. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  6693. if (!empty($conf->use_javascript_ajax)) {
  6694. $out .= '
  6695. <script nonce="'.getNonce().'">
  6696. $(document).ready(function() {
  6697. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  6698. $("'.dol_escape_js($newInput).'").insertBefore(this);
  6699. });
  6700. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  6701. $(this).parent().remove();
  6702. });
  6703. });
  6704. </script>';
  6705. }
  6706. }
  6707. if (!empty($hidden)) {
  6708. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  6709. }
  6710. if ($isDependList==1) {
  6711. $out .= $this->getJSListDependancies('_common');
  6712. }
  6713. /* Add comments
  6714. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  6715. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  6716. */
  6717. // Display error message for field
  6718. if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
  6719. $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
  6720. }
  6721. return $out;
  6722. }
  6723. /**
  6724. * Return HTML string to show a field into a page
  6725. * Code very similar with showOutputField of extra fields
  6726. *
  6727. * @param array $val Array of properties of field to show
  6728. * @param string $key Key of attribute
  6729. * @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)
  6730. * @param string $moreparam To add more parametes on html input tag
  6731. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6732. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6733. * @param mixed $morecss Value for css to define size. May also be a numeric.
  6734. * @return string
  6735. */
  6736. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  6737. {
  6738. global $conf, $langs, $form;
  6739. if (!is_object($form)) {
  6740. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6741. $form = new Form($this->db);
  6742. }
  6743. $objectid = $this->id; // Not used ???
  6744. $label = empty($val['label']) ? '' : $val['label'];
  6745. $type = empty($val['type']) ? '' : $val['type'];
  6746. $size = empty($val['css']) ? '' : $val['css'];
  6747. $reg = array();
  6748. // Convert var to be able to share same code than showOutputField of extrafields
  6749. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6750. $type = 'varchar'; // convert varchar(xx) int varchar
  6751. $size = $reg[1];
  6752. } elseif (preg_match('/varchar/', $type)) {
  6753. $type = 'varchar'; // convert varchar(xx) int varchar
  6754. }
  6755. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6756. $type = 'select';
  6757. }
  6758. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6759. $type = 'link';
  6760. }
  6761. $default = empty($val['default']) ? '' : $val['default'];
  6762. $computed = empty($val['computed']) ? '' : $val['computed'];
  6763. $unique = empty($val['unique']) ? '' : $val['unique'];
  6764. $required = empty($val['required']) ? '' : $val['required'];
  6765. $param = array();
  6766. $param['options'] = array();
  6767. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6768. $param['options'] = $val['arrayofkeyval'];
  6769. }
  6770. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6771. $type = 'link';
  6772. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6773. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6774. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6775. $type = 'sellist';
  6776. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6777. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6778. $type = 'sellist';
  6779. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6780. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6781. $type = 'sellist';
  6782. } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
  6783. $param['options'] = array($reg[1] => 'N');
  6784. $type = 'chkbxlst';
  6785. }
  6786. $langfile = empty($val['langfile']) ? '' : $val['langfile'];
  6787. $list = (empty($val['list']) ? '' : $val['list']);
  6788. $help = (empty($val['help']) ? '' : $val['help']);
  6789. $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)
  6790. if ($hidden) {
  6791. return '';
  6792. }
  6793. // If field is a computed field, value must become result of compute
  6794. if ($computed) {
  6795. // Make the eval of compute string
  6796. //var_dump($computed);
  6797. $value = dol_eval($computed, 1, 0, '');
  6798. }
  6799. if (empty($morecss)) {
  6800. if ($type == 'date') {
  6801. $morecss = 'minwidth100imp';
  6802. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6803. $morecss = 'minwidth200imp';
  6804. } elseif (in_array($type, array('int', 'double', 'price'))) {
  6805. $morecss = 'maxwidth75';
  6806. } elseif ($type == 'url') {
  6807. $morecss = 'minwidth400';
  6808. } elseif ($type == 'boolean') {
  6809. $morecss = '';
  6810. } else {
  6811. if (is_numeric($size) && round($size) < 12) {
  6812. $morecss = 'minwidth100';
  6813. } elseif (is_numeric($size) && round($size) <= 48) {
  6814. $morecss = 'minwidth200';
  6815. } else {
  6816. $morecss = 'minwidth400';
  6817. }
  6818. }
  6819. }
  6820. // Format output value differently according to properties of field
  6821. if (in_array($key, array('rowid', 'ref')) && method_exists($this, 'getNomUrl')) {
  6822. if ($key != 'rowid' || empty($this->fields['ref'])) { // If we want ref field or if we want ID and there is no ref field, we show the link.
  6823. $value = $this->getNomUrl(1, '', 0, '', 1);
  6824. }
  6825. } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
  6826. $value = $this->getLibStatut(3);
  6827. } elseif ($type == 'date') {
  6828. if (!empty($value)) {
  6829. $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
  6830. } else {
  6831. $value = '';
  6832. }
  6833. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6834. if (!empty($value)) {
  6835. $value = dol_print_date($value, 'dayhour', 'tzuserrel');
  6836. } else {
  6837. $value = '';
  6838. }
  6839. } elseif ($type == 'duration') {
  6840. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6841. if (!is_null($value) && $value !== '') {
  6842. $value = convertSecondToTime($value, 'allhourmin');
  6843. }
  6844. } elseif ($type == 'double' || $type == 'real') {
  6845. if (!is_null($value) && $value !== '') {
  6846. $value = price($value);
  6847. }
  6848. } elseif ($type == 'boolean') {
  6849. $checked = '';
  6850. if (!empty($value)) {
  6851. $checked = ' checked ';
  6852. }
  6853. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  6854. } elseif ($type == 'mail' || $type == 'email') {
  6855. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  6856. } elseif ($type == 'url') {
  6857. $value = dol_print_url($value, '_blank', 32, 1);
  6858. } elseif ($type == 'phone') {
  6859. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 'phone');
  6860. } elseif ($type == 'ip') {
  6861. $value = dol_print_ip($value, 0);
  6862. } elseif ($type == 'price') {
  6863. if (!is_null($value) && $value !== '') {
  6864. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  6865. }
  6866. } elseif ($type == 'select') {
  6867. $value = isset($param['options'][$value])?$param['options'][$value]:'';
  6868. } elseif ($type == 'sellist') {
  6869. $param_list = array_keys($param['options']);
  6870. $InfoFieldList = explode(":", $param_list[0]);
  6871. $selectkey = "rowid";
  6872. $keyList = 'rowid';
  6873. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6874. $selectkey = $InfoFieldList[2];
  6875. $keyList = $InfoFieldList[2].' as rowid';
  6876. }
  6877. $fields_label = explode('|', $InfoFieldList[1]);
  6878. if (is_array($fields_label)) {
  6879. $keyList .= ', ';
  6880. $keyList .= implode(', ', $fields_label);
  6881. }
  6882. $filter_categorie = false;
  6883. if (count($InfoFieldList) > 5) {
  6884. if ($InfoFieldList[0] == 'categorie') {
  6885. $filter_categorie = true;
  6886. }
  6887. }
  6888. $sql = "SELECT ".$keyList;
  6889. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6890. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6891. $sql .= ' as main';
  6892. }
  6893. if ($selectkey == 'rowid' && empty($value)) {
  6894. $sql .= " WHERE ".$selectkey." = 0";
  6895. } elseif ($selectkey == 'rowid') {
  6896. $sql .= " WHERE ".$selectkey." = ".((int) $value);
  6897. } else {
  6898. $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
  6899. }
  6900. //$sql.= ' AND entity = '.$conf->entity;
  6901. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  6902. $resql = $this->db->query($sql);
  6903. if ($resql) {
  6904. if ($filter_categorie === false) {
  6905. $value = ''; // value was used, so now we reste it to use it to build final output
  6906. $numrows = $this->db->num_rows($resql);
  6907. if ($numrows) {
  6908. $obj = $this->db->fetch_object($resql);
  6909. // Several field into label (eq table:code|libelle:rowid)
  6910. $fields_label = explode('|', $InfoFieldList[1]);
  6911. if (is_array($fields_label) && count($fields_label) > 1) {
  6912. foreach ($fields_label as $field_toshow) {
  6913. $translabel = '';
  6914. if (!empty($obj->$field_toshow)) {
  6915. $translabel = $langs->trans($obj->$field_toshow);
  6916. }
  6917. if ($translabel != $field_toshow) {
  6918. $value .= dol_trunc($translabel, 18) . ' ';
  6919. } else {
  6920. $value .= $obj->$field_toshow . ' ';
  6921. }
  6922. }
  6923. } else {
  6924. $translabel = '';
  6925. if (!empty($obj->{$InfoFieldList[1]})) {
  6926. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6927. }
  6928. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6929. $value = dol_trunc($translabel, 18);
  6930. } else {
  6931. $value = $obj->{$InfoFieldList[1]};
  6932. }
  6933. }
  6934. }
  6935. } else {
  6936. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  6937. $toprint = array();
  6938. $obj = $this->db->fetch_object($resql);
  6939. $c = new Categorie($this->db);
  6940. $c->fetch($obj->rowid);
  6941. $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
  6942. foreach ($ways as $way) {
  6943. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
  6944. }
  6945. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6946. }
  6947. } else {
  6948. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6949. }
  6950. } elseif ($type == 'radio') {
  6951. $value = $param['options'][$value];
  6952. } elseif ($type == 'checkbox') {
  6953. $value_arr = explode(',', $value);
  6954. $value = '';
  6955. if (is_array($value_arr) && count($value_arr) > 0) {
  6956. $toprint = array();
  6957. foreach ($value_arr as $keyval => $valueval) {
  6958. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  6959. }
  6960. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6961. }
  6962. } elseif ($type == 'chkbxlst') {
  6963. $value_arr = explode(',', $value);
  6964. $param_list = array_keys($param['options']);
  6965. $InfoFieldList = explode(":", $param_list[0]);
  6966. $selectkey = "rowid";
  6967. $keyList = 'rowid';
  6968. if (count($InfoFieldList) >= 3) {
  6969. $selectkey = $InfoFieldList[2];
  6970. $keyList = $InfoFieldList[2].' as rowid';
  6971. }
  6972. $fields_label = explode('|', $InfoFieldList[1]);
  6973. if (is_array($fields_label)) {
  6974. $keyList .= ', ';
  6975. $keyList .= implode(', ', $fields_label);
  6976. }
  6977. $filter_categorie = false;
  6978. if (count($InfoFieldList) > 5) {
  6979. if ($InfoFieldList[0] == 'categorie') {
  6980. $filter_categorie = true;
  6981. }
  6982. }
  6983. $sql = "SELECT ".$keyList;
  6984. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6985. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6986. $sql .= ' as main';
  6987. }
  6988. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  6989. // $sql.= ' AND entity = '.$conf->entity;
  6990. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  6991. $resql = $this->db->query($sql);
  6992. if ($resql) {
  6993. if ($filter_categorie === false) {
  6994. $value = ''; // value was used, so now we reste it to use it to build final output
  6995. $toprint = array();
  6996. while ($obj = $this->db->fetch_object($resql)) {
  6997. // Several field into label (eq table:code|libelle:rowid)
  6998. $fields_label = explode('|', $InfoFieldList[1]);
  6999. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  7000. if (is_array($fields_label) && count($fields_label) > 1) {
  7001. foreach ($fields_label as $field_toshow) {
  7002. $translabel = '';
  7003. if (!empty($obj->$field_toshow)) {
  7004. $translabel = $langs->trans($obj->$field_toshow);
  7005. }
  7006. if ($translabel != $field_toshow) {
  7007. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
  7008. } else {
  7009. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow . '</li>';
  7010. }
  7011. }
  7012. } else {
  7013. $translabel = '';
  7014. if (!empty($obj->{$InfoFieldList[1]})) {
  7015. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  7016. }
  7017. if ($translabel != $obj->{$InfoFieldList[1]}) {
  7018. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
  7019. } else {
  7020. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} . '</li>';
  7021. }
  7022. }
  7023. }
  7024. }
  7025. } else {
  7026. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  7027. $toprint = array();
  7028. while ($obj = $this->db->fetch_object($resql)) {
  7029. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  7030. $c = new Categorie($this->db);
  7031. $c->fetch($obj->rowid);
  7032. $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
  7033. foreach ($ways as $way) {
  7034. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
  7035. }
  7036. }
  7037. }
  7038. }
  7039. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  7040. } else {
  7041. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  7042. }
  7043. } elseif ($type == 'link') {
  7044. $out = '';
  7045. // only if something to display (perf)
  7046. if ($value) {
  7047. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  7048. $InfoFieldList = explode(":", $param_list[0]);
  7049. $classname = $InfoFieldList[0];
  7050. $classpath = $InfoFieldList[1];
  7051. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  7052. $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
  7053. if (!empty($classpath)) {
  7054. dol_include_once($InfoFieldList[1]);
  7055. if ($classname && class_exists($classname)) {
  7056. $object = new $classname($this->db);
  7057. if ($object->element === 'product') { // Special cas for product because default valut of fetch are wrong
  7058. $result = $object->fetch($value, '', '', '', 0, 1, 1);
  7059. } else {
  7060. $result = $object->fetch($value);
  7061. }
  7062. if ($result > 0) {
  7063. if ($object->element === 'product') {
  7064. $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0, '', 0);
  7065. if (isset($val['get_name_url_params'])) {
  7066. $get_name_url_params = explode(':', $val['get_name_url_params']);
  7067. if (!empty($get_name_url_params)) {
  7068. $param_num_max = count($get_name_url_param_arr) - 1;
  7069. foreach ($get_name_url_params as $param_num => $param_value) {
  7070. if ($param_num > $param_num_max) {
  7071. break;
  7072. }
  7073. $get_name_url_param_arr[$param_num] = $param_value;
  7074. }
  7075. }
  7076. }
  7077. /**
  7078. * @var Product $object
  7079. */
  7080. $value = $object->getNomUrl($get_name_url_param_arr[0], $get_name_url_param_arr[1], $get_name_url_param_arr[2], $get_name_url_param_arr[3], $get_name_url_param_arr[4], $get_name_url_param_arr[5], $get_name_url_param_arr[6]);
  7081. } else {
  7082. $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
  7083. }
  7084. } else {
  7085. $value = '';
  7086. }
  7087. }
  7088. } else {
  7089. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  7090. return 'Error bad setup of extrafield';
  7091. }
  7092. } else {
  7093. $value = '';
  7094. }
  7095. } elseif ($type == 'password') {
  7096. $value = preg_replace('/./i', '*', $value);
  7097. } elseif ($type == 'array') {
  7098. $value = implode('<br>', $value);
  7099. } else { // text|html|varchar
  7100. $value = dol_htmlentitiesbr($value);
  7101. }
  7102. //print $type.'-'.$size.'-'.$value;
  7103. $out = $value;
  7104. return $out;
  7105. }
  7106. /**
  7107. * clear validation message result for a field
  7108. *
  7109. * @param string $fieldKey Key of attribute to clear
  7110. * @return void
  7111. */
  7112. public function clearFieldError($fieldKey)
  7113. {
  7114. $this->error = '';
  7115. unset($this->validateFieldsErrors[$fieldKey]);
  7116. }
  7117. /**
  7118. * set validation error message a field
  7119. *
  7120. * @param string $fieldKey Key of attribute
  7121. * @param string $msg the field error message
  7122. * @return void
  7123. */
  7124. public function setFieldError($fieldKey, $msg = '')
  7125. {
  7126. global $langs;
  7127. if (empty($msg)) {
  7128. $msg = $langs->trans("UnknowError");
  7129. }
  7130. $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
  7131. }
  7132. /**
  7133. * get field error message
  7134. *
  7135. * @param string $fieldKey Key of attribute
  7136. * @return string Error message of validation ('' if no error)
  7137. */
  7138. public function getFieldError($fieldKey)
  7139. {
  7140. if (!empty($this->validateFieldsErrors[$fieldKey])) {
  7141. return $this->validateFieldsErrors[$fieldKey];
  7142. }
  7143. return '';
  7144. }
  7145. /**
  7146. * Return validation test result for a field
  7147. *
  7148. * @param array $fields Array of properties of field to show
  7149. * @param string $fieldKey Key of attribute
  7150. * @param string $fieldValue value of attribute
  7151. * @return bool return false if fail true on success, see $this->error for error message
  7152. */
  7153. public function validateField($fields, $fieldKey, $fieldValue)
  7154. {
  7155. global $langs;
  7156. if (!class_exists('Validate')) {
  7157. require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php';
  7158. }
  7159. $this->clearFieldError($fieldKey);
  7160. if (!isset($fields[$fieldKey])) {
  7161. $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
  7162. return false;
  7163. }
  7164. $val = $fields[$fieldKey];
  7165. $param = array();
  7166. $param['options'] = array();
  7167. $type = $val['type'];
  7168. $required = false;
  7169. if (isset($val['notnull']) && $val['notnull'] === 1) {
  7170. // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  7171. $required = true;
  7172. }
  7173. $maxSize = 0;
  7174. $minSize = 0;
  7175. //
  7176. // PREPARE Elements
  7177. //
  7178. $reg = array();
  7179. // Convert var to be able to share same code than showOutputField of extrafields
  7180. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  7181. $type = 'varchar'; // convert varchar(xx) int varchar
  7182. $maxSize = $reg[1];
  7183. } elseif (preg_match('/varchar/', $type)) {
  7184. $type = 'varchar'; // convert varchar(xx) int varchar
  7185. }
  7186. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  7187. $type = 'select';
  7188. }
  7189. if (!empty($val['type']) && preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  7190. $type = 'link';
  7191. }
  7192. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  7193. $param['options'] = $val['arrayofkeyval'];
  7194. }
  7195. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  7196. $type = 'link';
  7197. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  7198. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  7199. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  7200. $type = 'sellist';
  7201. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  7202. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  7203. $type = 'sellist';
  7204. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  7205. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  7206. $type = 'sellist';
  7207. }
  7208. //
  7209. // TEST Value
  7210. //
  7211. // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
  7212. $validate = new Validate($this->db, $langs);
  7213. // little trick : to perform tests with good performances sort tests by quick to low
  7214. //
  7215. // COMMON TESTS
  7216. //
  7217. // Required test and empty value
  7218. if ($required && !$validate->isNotEmptyString($fieldValue)) {
  7219. $this->setFieldError($fieldKey, $validate->error);
  7220. return false;
  7221. } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
  7222. // if no value sent and the field is not mandatory, no need to perform tests
  7223. return true;
  7224. }
  7225. // MAX Size test
  7226. if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
  7227. $this->setFieldError($fieldKey, $validate->error);
  7228. return false;
  7229. }
  7230. // MIN Size test
  7231. if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
  7232. $this->setFieldError($fieldKey, $validate->error);
  7233. return false;
  7234. }
  7235. //
  7236. // TESTS for TYPE
  7237. //
  7238. if (in_array($type, array('date', 'datetime', 'timestamp'))) {
  7239. if (!$validate->isTimestamp($fieldValue)) {
  7240. $this->setFieldError($fieldKey, $validate->error);
  7241. return false;
  7242. } else { return true; }
  7243. } elseif ($type == 'duration') {
  7244. if (!$validate->isDuration($fieldValue)) {
  7245. $this->setFieldError($fieldKey, $validate->error);
  7246. return false;
  7247. } else { return true; }
  7248. } elseif (in_array($type, array('double', 'real', 'price'))) {
  7249. // is numeric
  7250. if (!$validate->isNumeric($fieldValue)) {
  7251. $this->setFieldError($fieldKey, $validate->error);
  7252. return false;
  7253. } else { return true; }
  7254. } elseif ($type == 'boolean') {
  7255. if (!$validate->isBool($fieldValue)) {
  7256. $this->setFieldError($fieldKey, $validate->error);
  7257. return false;
  7258. } else { return true; }
  7259. } elseif ($type == 'mail') {
  7260. if (!$validate->isEmail($fieldValue)) {
  7261. $this->setFieldError($fieldKey, $validate->error);
  7262. return false;
  7263. }
  7264. } elseif ($type == 'url') {
  7265. if (!$validate->isUrl($fieldValue)) {
  7266. $this->setFieldError($fieldKey, $validate->error);
  7267. return false;
  7268. } else { return true; }
  7269. } elseif ($type == 'phone') {
  7270. if (!$validate->isPhone($fieldValue)) {
  7271. $this->setFieldError($fieldKey, $validate->error);
  7272. return false;
  7273. } else { return true; }
  7274. } elseif ($type == 'select' || $type == 'radio') {
  7275. if (!isset($param['options'][$fieldValue])) {
  7276. $this->error = $langs->trans('RequireValidValue');
  7277. return false;
  7278. } else { return true; }
  7279. } elseif ($type == 'sellist' || $type == 'chkbxlst') {
  7280. $param_list = array_keys($param['options']);
  7281. $InfoFieldList = explode(":", $param_list[0]);
  7282. $value_arr = explode(',', $fieldValue);
  7283. $value_arr = array_map(array($this->db, 'escape'), $value_arr);
  7284. $selectkey = "rowid";
  7285. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  7286. $selectkey = $InfoFieldList[2];
  7287. }
  7288. if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
  7289. $this->setFieldError($fieldKey, $validate->error);
  7290. return false;
  7291. } else { return true; }
  7292. } elseif ($type == 'link') {
  7293. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  7294. $InfoFieldList = explode(":", $param_list[0]);
  7295. $classname = $InfoFieldList[0];
  7296. $classpath = $InfoFieldList[1];
  7297. if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
  7298. $this->setFieldError($fieldKey, $validate->error);
  7299. return false;
  7300. } else { return true; }
  7301. }
  7302. // if no test failled all is ok
  7303. return true;
  7304. }
  7305. /**
  7306. * Function to show lines of extrafields with output datas.
  7307. * This function is responsible to output the <tr> and <td> according to correct number of columns received into $params['colspan'] or <div> according to $display_type
  7308. *
  7309. * @param Extrafields $extrafields Extrafield Object
  7310. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  7311. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  7312. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  7313. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  7314. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  7315. * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...)
  7316. * @return string String with html content to show
  7317. */
  7318. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
  7319. {
  7320. global $db, $conf, $langs, $action, $form, $hookmanager;
  7321. if (!is_object($form)) {
  7322. $form = new Form($db);
  7323. }
  7324. if (!is_object($extrafields)) {
  7325. dol_syslog('Bad parameter extrafields for showOptionals', LOG_ERR);
  7326. return 'Bad parameter extrafields for showOptionals';
  7327. }
  7328. if (!is_array($extrafields->attributes[$this->table_element])) {
  7329. dol_syslog("extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
  7330. }
  7331. $out = '';
  7332. $parameters = array('mode'=>$mode, 'params'=>$params, 'keysuffix'=>$keysuffix, 'keyprefix'=>$keyprefix, 'display_type'=>$display_type);
  7333. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  7334. if (empty($reshook)) {
  7335. if (is_array($extrafields->attributes[$this->table_element]) && key_exists('label', $extrafields->attributes[$this->table_element]) && is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0) {
  7336. $out .= "\n";
  7337. $out .= '<!-- commonobject:showOptionals --> ';
  7338. $out .= "\n";
  7339. $nbofextrafieldsshown = 0;
  7340. $e = 0; // var to manage the modulo (odd/even)
  7341. $lastseparatorkeyfound = '';
  7342. $extrafields_collapse_num = '';
  7343. $extrafields_collapse_num_old = '';
  7344. $i = 0;
  7345. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
  7346. $i++;
  7347. // Show only the key field in params
  7348. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
  7349. continue;
  7350. }
  7351. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  7352. $enabled = 1;
  7353. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  7354. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '2');
  7355. }
  7356. if (empty($enabled)) {
  7357. continue;
  7358. }
  7359. $visibility = 1;
  7360. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  7361. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '2');
  7362. }
  7363. $perms = 1;
  7364. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  7365. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '2');
  7366. }
  7367. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
  7368. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  7369. } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
  7370. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  7371. } elseif ($mode == 'view' && empty($visibility)) {
  7372. continue;
  7373. }
  7374. if (empty($perms)) {
  7375. continue;
  7376. }
  7377. // Load language if required
  7378. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  7379. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  7380. }
  7381. $colspan = 0;
  7382. if (is_array($params) && count($params) > 0 && $display_type=='card') {
  7383. if (array_key_exists('cols', $params)) {
  7384. $colspan = $params['cols'];
  7385. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  7386. $reg = array();
  7387. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  7388. $colspan = $reg[1];
  7389. } else {
  7390. $colspan = $params['colspan'];
  7391. }
  7392. }
  7393. }
  7394. $colspan = intval($colspan);
  7395. switch ($mode) {
  7396. case "view":
  7397. $value = ((!empty($this->array_options) && array_key_exists("options_".$key.$keysuffix, $this->array_options)) ? $this->array_options["options_".$key.$keysuffix] : null); // Value may be cleaned or formated later
  7398. break;
  7399. case "create":
  7400. case "edit":
  7401. // We get the value of property found with GETPOST so it takes into account:
  7402. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  7403. $check = 'alphanohtml';
  7404. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  7405. $check = 'restricthtml';
  7406. }
  7407. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  7408. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  7409. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
  7410. if (is_array($getposttemp)) {
  7411. // $getposttemp is an array but following code expects a comma separated string
  7412. $value = implode(",", $getposttemp);
  7413. } else {
  7414. $value = $getposttemp;
  7415. }
  7416. } else {
  7417. $value = (!empty($this->array_options["options_".$key]) ? $this->array_options["options_".$key] : ''); // No GET, no POST, no default value, so we take value of object.
  7418. }
  7419. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  7420. break;
  7421. }
  7422. $nbofextrafieldsshown++;
  7423. // Output value of the current field
  7424. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  7425. $extrafields_collapse_num = $key;
  7426. /*
  7427. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  7428. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  7429. $extrafield_param_list = array_keys($extrafield_param['options']);
  7430. if (count($extrafield_param_list) > 0) {
  7431. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  7432. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  7433. //$extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  7434. $extrafields_collapse_num = $key;
  7435. }
  7436. }
  7437. }
  7438. */
  7439. // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
  7440. $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
  7441. $lastseparatorkeyfound = $key;
  7442. } else {
  7443. $collapse_group = $extrafields_collapse_num.(!empty($this->id) ? '_'.$this->id : '');
  7444. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  7445. $csstyle = '';
  7446. if (is_array($params) && count($params) > 0) {
  7447. if (array_key_exists('class', $params)) {
  7448. $class .= $params['class'].' ';
  7449. }
  7450. if (array_key_exists('style', $params)) {
  7451. $csstyle = $params['style'];
  7452. }
  7453. }
  7454. // add html5 elements
  7455. $domData = ' data-element="extrafield"';
  7456. $domData .= ' data-targetelement="'.$this->element.'"';
  7457. $domData .= ' data-targetid="'.$this->id.'"';
  7458. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  7459. if ($display_type=='card') {
  7460. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
  7461. $colspan = 0;
  7462. }
  7463. if ($action == 'selectlines') {
  7464. $colspan++;
  7465. }
  7466. }
  7467. // Convert date into timestamp format (value in memory must be a timestamp)
  7468. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
  7469. $datenotinstring = null;
  7470. if (array_key_exists('options_'.$key, $this->array_options)) {
  7471. $datenotinstring = $this->array_options['options_'.$key];
  7472. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7473. $datenotinstring = $this->db->jdate($datenotinstring);
  7474. }
  7475. }
  7476. $datekey = $keyprefix.'options_'.$key.$keysuffix;
  7477. $value = (GETPOSTISSET($datekey)) ? dol_mktime(12, 0, 0, GETPOST($datekey.'month', 'int', 3), GETPOST($datekey.'day', 'int', 3), GETPOST($datekey.'year', 'int', 3)) : $datenotinstring;
  7478. }
  7479. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
  7480. $datenotinstring = null;
  7481. if (array_key_exists('options_'.$key, $this->array_options)) {
  7482. $datenotinstring = $this->array_options['options_'.$key];
  7483. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7484. $datenotinstring = $this->db->jdate($datenotinstring);
  7485. }
  7486. }
  7487. $timekey = $keyprefix.'options_'.$key.$keysuffix;
  7488. $value = (GETPOSTISSET($timekey)) ? dol_mktime(GETPOST($timekey.'hour', 'int', 3), GETPOST($timekey.'min', 'int', 3), GETPOST($timekey.'sec', 'int', 3), GETPOST($timekey.'month', 'int', 3), GETPOST($timekey.'day', 'int', 3), GETPOST($timekey.'year', 'int', 3), 'tzuserrel') : $datenotinstring;
  7489. }
  7490. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  7491. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
  7492. if (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) {
  7493. $value = price2num($value);
  7494. } elseif (isset($this->array_options['options_'.$key])) {
  7495. $value = $this->array_options['options_'.$key];
  7496. }
  7497. }
  7498. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  7499. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int', 'boolean'))) {
  7500. if ($action == 'create') {
  7501. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  7502. }
  7503. }
  7504. $labeltoshow = $langs->trans($label);
  7505. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  7506. if ($display_type == 'card') {
  7507. $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="field_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$collapse_group.'" '.$domData.' >';
  7508. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action == 'view' || $action == 'valid' || $action == 'editline' || $action == 'confirm_valid' || $action == 'confirm_cancel')) {
  7509. $out .= '<td></td>';
  7510. }
  7511. $out .= '<td class="'.(empty($params['tdclass']) ? 'titlefieldcreate' : $params['tdclass']).' wordbreak';
  7512. } elseif ($display_type == 'line') {
  7513. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="fieldline_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$collapse_group.'" '.$domData.' >';
  7514. $out .= '<div style="display: inline-block; padding-right:4px" class="wordbreak';
  7515. }
  7516. //$out .= "titlefield";
  7517. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  7518. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  7519. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  7520. if ($tpl_context != "public") { // Public page : red dot instead of fieldrequired characters
  7521. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7522. $out .= ' fieldrequired';
  7523. }
  7524. }
  7525. $out .= '">';
  7526. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  7527. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7528. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7529. } else {
  7530. $out .= $labeltoshow;
  7531. }
  7532. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7533. $out .= '&nbsp;<span style="color: red">*</span>';
  7534. }
  7535. } else {
  7536. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7537. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7538. } else {
  7539. $out .= $labeltoshow;
  7540. }
  7541. }
  7542. $out .= ($display_type == 'card' ? '</td>' : '</div>');
  7543. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  7544. if ($display_type == 'card') {
  7545. // a first td column was already output (and may be another on before if MAIN_VIEW_LINE_NUMBER set), so this td is the next one
  7546. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="valuefieldcreate '.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  7547. } elseif ($display_type == 'line') {
  7548. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').' style="display: inline-block" class="valuefieldcreate '.$this->element.'_extras_'.$key.' extra_inline_'.$extrafields->attributes[$this->table_element]['type'][$key].'">';
  7549. }
  7550. switch ($mode) {
  7551. case "view":
  7552. $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
  7553. break;
  7554. case "create":
  7555. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7556. break;
  7557. case "edit":
  7558. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7559. break;
  7560. }
  7561. $out .= ($display_type=='card' ? '</td>' : '</div>');
  7562. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
  7563. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7564. } else {
  7565. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7566. }
  7567. $e++;
  7568. }
  7569. }
  7570. $out .= "\n";
  7571. // Add code to manage list depending on others
  7572. if (!empty($conf->use_javascript_ajax)) {
  7573. $out .= $this->getJSListDependancies();
  7574. }
  7575. $out .= '<!-- commonobject:showOptionals end --> '."\n";
  7576. if (empty($nbofextrafieldsshown)) {
  7577. $out = '';
  7578. }
  7579. }
  7580. }
  7581. $out .= $hookmanager->resPrint;
  7582. return $out;
  7583. }
  7584. /**
  7585. * @param string $type Type for prefix
  7586. * @return string Javacript code to manage dependency
  7587. */
  7588. public function getJSListDependancies($type = '_extra')
  7589. {
  7590. $out = '
  7591. <script nonce="'.getNonce().'">
  7592. jQuery(document).ready(function() {
  7593. function showOptions'.$type.'(child_list, parent_list, orig_select)
  7594. {
  7595. var val = $("select[name=\""+parent_list+"\"]").val();
  7596. var parentVal = parent_list + ":" + val;
  7597. if(typeof val == "string"){
  7598. if(val != "") {
  7599. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7600. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7601. $("select[name=\""+child_list+"\"]").append(options);
  7602. } else {
  7603. var options = orig_select.find("option[parent]").clone();
  7604. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7605. $("select[name=\""+child_list+"\"]").append(options);
  7606. }
  7607. } else if(val > 0) {
  7608. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7609. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7610. $("select[name=\""+child_list+"\"]").append(options);
  7611. } else {
  7612. var options = orig_select.find("option[parent]").clone();
  7613. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7614. $("select[name=\""+child_list+"\"]").append(options);
  7615. }
  7616. }
  7617. function setListDependencies'.$type.'() {
  7618. jQuery("select option[parent]").parent().each(function() {
  7619. var orig_select = {};
  7620. var child_list = $(this).attr("name");
  7621. orig_select[child_list] = $(this).clone();
  7622. var parent = $(this).find("option[parent]:first").attr("parent");
  7623. var infos = parent.split(":");
  7624. var parent_list = infos[0];
  7625. //Hide daughters lists
  7626. if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
  7627. $("#"+child_list).hide();
  7628. //Show mother lists
  7629. } else if ($("#"+parent_list).val() != 0){
  7630. $("#"+parent_list).show();
  7631. }
  7632. //Show the child list if the parent list value is selected
  7633. $("select[name=\""+parent_list+"\"]").click(function() {
  7634. if ($(this).val() != 0){
  7635. $("#"+child_list).show()
  7636. }
  7637. });
  7638. //When we change parent list
  7639. $("select[name=\""+parent_list+"\"]").change(function() {
  7640. showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
  7641. //Select the value 0 on child list after a change on the parent list
  7642. $("#"+child_list).val(0).trigger("change");
  7643. //Hide child lists if the parent value is set to 0
  7644. if ($(this).val() == 0){
  7645. $("#"+child_list).hide();
  7646. }
  7647. });
  7648. });
  7649. }
  7650. setListDependencies'.$type.'();
  7651. });
  7652. </script>'."\n";
  7653. return $out;
  7654. }
  7655. /**
  7656. * Returns the rights used for this class
  7657. * @return stdClass
  7658. */
  7659. public function getRights()
  7660. {
  7661. global $user;
  7662. $element = $this->element;
  7663. if ($element == 'facturerec') {
  7664. $element = 'facture';
  7665. } elseif ($element == 'invoice_supplier_rec') {
  7666. return $user->rights->fournisseur->facture;
  7667. } elseif ($element == 'evaluation') {
  7668. return $user->rights->hrm->evaluation;
  7669. }
  7670. return $user->rights->{$element};
  7671. }
  7672. /**
  7673. * Function used to replace a thirdparty id with another one.
  7674. * This function is meant to be called from replaceThirdparty with the appropriate tables
  7675. * Column name fk_soc MUST be used to identify thirdparties
  7676. *
  7677. * @param DoliDB $dbs Database handler
  7678. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  7679. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  7680. * @param string[] $tables Tables that need to be changed
  7681. * @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)
  7682. * @return bool True if success, False if error
  7683. */
  7684. public static function commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7685. {
  7686. foreach ($tables as $table) {
  7687. $sql = 'UPDATE '.$dbs->prefix().$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
  7688. if (!$dbs->query($sql)) {
  7689. if ($ignoreerrors) {
  7690. return true; // TODO Not enough. If there is A-B on kept thirdparty and B-C on old one, we must get A-B-C after merge. Not A-B.
  7691. }
  7692. //$this->errors = $db->lasterror();
  7693. return false;
  7694. }
  7695. }
  7696. return true;
  7697. }
  7698. /**
  7699. * Function used to replace a product id with another one.
  7700. * This function is meant to be called from replaceProduct with the appropriate tables
  7701. * Column name fk_product MUST be used to identify products
  7702. *
  7703. * @param DoliDB $dbs Database handler
  7704. * @param int $origin_id Old product id (the product to delete)
  7705. * @param int $dest_id New product id (the product that will received element of the other)
  7706. * @param string[] $tables Tables that need to be changed
  7707. * @param int $ignoreerrors Ignore errors. Return true even if errors. We need this when replacement can fails like for categories (categorie of old product may already exists on new one)
  7708. * @return bool True if success, False if error
  7709. */
  7710. public static function commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7711. {
  7712. foreach ($tables as $table) {
  7713. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_product = '.((int) $dest_id).' WHERE fk_product = '.((int) $origin_id);
  7714. if (!$dbs->query($sql)) {
  7715. if ($ignoreerrors) {
  7716. return true; // TODO Not enough. If there is A-B on kept product and B-C on old one, we must get A-B-C after merge. Not A-B.
  7717. }
  7718. //$this->errors = $db->lasterror();
  7719. return false;
  7720. }
  7721. }
  7722. return true;
  7723. }
  7724. /**
  7725. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  7726. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  7727. * elseif calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  7728. * elseif calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  7729. * else set min buy price as buy price
  7730. *
  7731. * @param float $unitPrice Product unit price
  7732. * @param float $discountPercent Line discount percent
  7733. * @param int $fk_product Product id
  7734. * @return float <0 if KO, buyprice if OK
  7735. */
  7736. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  7737. {
  7738. global $conf;
  7739. $buyPrice = 0;
  7740. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
  7741. // When ForceBuyingPriceIfNull is set
  7742. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  7743. } else {
  7744. // Get cost price for margin calculation
  7745. if (!empty($fk_product) && $fk_product > 0) {
  7746. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
  7747. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7748. $product = new Product($this->db);
  7749. $result = $product->fetch($fk_product);
  7750. if ($result <= 0) {
  7751. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7752. return -1;
  7753. }
  7754. if ($product->cost_price > 0) {
  7755. $buyPrice = $product->cost_price;
  7756. } elseif ($product->pmp > 0) {
  7757. $buyPrice = $product->pmp;
  7758. }
  7759. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
  7760. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7761. $product = new Product($this->db);
  7762. $result = $product->fetch($fk_product);
  7763. if ($result <= 0) {
  7764. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7765. return -1;
  7766. }
  7767. if ($product->pmp > 0) {
  7768. $buyPrice = $product->pmp;
  7769. }
  7770. }
  7771. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
  7772. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  7773. $productFournisseur = new ProductFournisseur($this->db);
  7774. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
  7775. $buyPrice = $productFournisseur->fourn_unitprice;
  7776. } elseif ($result < 0) {
  7777. $this->errors[] = $productFournisseur->error;
  7778. return -2;
  7779. }
  7780. }
  7781. }
  7782. }
  7783. return $buyPrice;
  7784. }
  7785. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7786. /**
  7787. * Show photos of an object (nbmax maximum), into several columns
  7788. *
  7789. * @param string $modulepart 'product', 'ticket', ...
  7790. * @param string $sdir Directory to scan (full absolute path)
  7791. * @param int $size 0=original size, 1='small' use thumbnail if possible
  7792. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  7793. * @param int $nbbyrow Number of image per line or -1 to use div separator or 0 to use no separator. Used only if size=1 or 'small'.
  7794. * @param int $showfilename 1=Show filename
  7795. * @param int $showaction 1=Show icon with action links (resize, delete)
  7796. * @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.
  7797. * @param int $maxWidth Max width of original image when size='small'
  7798. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  7799. * @param int|string $overwritetitle Do not add title tag on image
  7800. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  7801. * @param string $cache A string if we want to use a cached version of image
  7802. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  7803. */
  7804. public function show_photos($modulepart, $sdir, $size = 0, $nbmax = 0, $nbbyrow = 5, $showfilename = 0, $showaction = 0, $maxHeight = 120, $maxWidth = 160, $nolink = 0, $overwritetitle = 0, $usesharelink = 0, $cache = '')
  7805. {
  7806. // phpcs:enable
  7807. global $conf, $user, $langs;
  7808. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7809. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  7810. $sortfield = 'position_name';
  7811. $sortorder = 'asc';
  7812. $dir = $sdir.'/';
  7813. $pdir = '/';
  7814. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7815. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7816. // For backward compatibility
  7817. if ($modulepart == 'product') {
  7818. if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
  7819. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7820. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7821. }
  7822. }
  7823. // Defined relative dir to DOL_DATA_ROOT
  7824. $relativedir = '';
  7825. if ($dir) {
  7826. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  7827. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  7828. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  7829. }
  7830. $dirthumb = $dir.'thumbs/';
  7831. $pdirthumb = $pdir.'thumbs/';
  7832. $return = '<!-- Photo -->'."\n";
  7833. $nbphoto = 0;
  7834. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  7835. /*if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) // For backward compatiblity, we scan also old dirs
  7836. {
  7837. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  7838. $filearray=array_merge($filearray, $filearrayold);
  7839. }*/
  7840. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  7841. if (count($filearray)) {
  7842. if ($sortfield && $sortorder) {
  7843. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  7844. }
  7845. foreach ($filearray as $key => $val) {
  7846. $photo = '';
  7847. $file = $val['name'];
  7848. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  7849. if (image_format_supported($file) >= 0) {
  7850. $nbphoto++;
  7851. $photo = $file;
  7852. $viewfilename = $file;
  7853. if ($size == 1 || $size == 'small') { // Format vignette
  7854. // Find name of thumb file
  7855. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  7856. if (!dol_is_file($dirthumb.$photo_vignette)) {
  7857. // The thumb does not exists, so we will use the original file
  7858. $dirthumb = $dir;
  7859. $pdirthumb = $pdir;
  7860. $photo_vignette = basename($file);
  7861. }
  7862. // Get filesize of original file
  7863. $imgarray = dol_getImageSize($dir.$photo);
  7864. if ($nbbyrow > 0) {
  7865. if ($nbphoto == 1) {
  7866. $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  7867. }
  7868. if ($nbphoto % $nbbyrow == 1) {
  7869. $return .= '<tr class="center valignmiddle" style="border: 1px">';
  7870. }
  7871. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">'."\n";
  7872. } elseif ($nbbyrow < 0) {
  7873. $return .= '<div class="inline-block">'."\n";
  7874. }
  7875. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  7876. if (empty($nolink)) {
  7877. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  7878. if ($urladvanced) {
  7879. $return .= '<a href="'.$urladvanced.'">';
  7880. } else {
  7881. $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
  7882. }
  7883. }
  7884. // Show image (width height=$maxHeight)
  7885. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  7886. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  7887. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  7888. if ($overwritetitle) {
  7889. if (is_numeric($overwritetitle)) {
  7890. $alt = '';
  7891. } else {
  7892. $alt = $overwritetitle;
  7893. }
  7894. }
  7895. $addphotorefcss = 1;
  7896. if ($usesharelink) {
  7897. if ($val['share']) {
  7898. if (empty($maxHeight) || ($photo_vignette && $imgarray['height'] > $maxHeight)) {
  7899. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  7900. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'"'.($maxHeight ?' height="'.$maxHeight.'"': '').' src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).($cache ? '&cache='.urlencode($cache) : '').'" title="'.dol_escape_htmltag($alt).'">';
  7901. } else {
  7902. $return .= '<!-- Show original file -->';
  7903. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).($cache ? '&cache='.urlencode($cache) : '').'" title="'.dol_escape_htmltag($alt).'">';
  7904. }
  7905. } else {
  7906. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  7907. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  7908. }
  7909. } else {
  7910. if (empty($maxHeight) || ($photo_vignette && $imgarray['height'] > $maxHeight)) {
  7911. $return .= '<!-- Show thumb -->';
  7912. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').' maxwidth150onsmartphone maxwidth200"'.($maxHeight ?' height="'.$maxHeight.'"': '').' src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.($cache ? '&cache='.urlencode($cache) : '').'&file='.urlencode($pdirthumb.$photo_vignette).'" title="'.dol_escape_htmltag($alt).'">';
  7913. } else {
  7914. $return .= '<!-- Show original file -->';
  7915. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.($cache ? '&cache='.urlencode($cache) : '').'&file='.urlencode($pdir.$photo).'" title="'.dol_escape_htmltag($alt).'">';
  7916. }
  7917. }
  7918. if (empty($nolink)) {
  7919. $return .= '</a>';
  7920. }
  7921. if ($showfilename) {
  7922. $return .= '<br>'.$viewfilename;
  7923. }
  7924. if ($showaction) {
  7925. $return .= '<br>';
  7926. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  7927. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
  7928. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=addthumb&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'), 'refresh').'&nbsp;&nbsp;</a>';
  7929. }
  7930. // Special cas for product
  7931. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7932. // Link to resize
  7933. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  7934. // Link to delete
  7935. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7936. $return .= img_delete().'</a>';
  7937. }
  7938. }
  7939. $return .= "\n";
  7940. if ($nbbyrow > 0) {
  7941. $return .= '</td>';
  7942. if (($nbphoto % $nbbyrow) == 0) {
  7943. $return .= '</tr>';
  7944. }
  7945. } elseif ($nbbyrow < 0) {
  7946. $return .= '</div>'."\n";
  7947. }
  7948. }
  7949. if (empty($size)) { // Format origine
  7950. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  7951. if ($showfilename) {
  7952. $return .= '<br>'.$viewfilename;
  7953. }
  7954. if ($showaction) {
  7955. // Special case for product
  7956. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7957. // Link to resize
  7958. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  7959. // Link to delete
  7960. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7961. $return .= img_delete().'</a>';
  7962. }
  7963. }
  7964. }
  7965. // On continue ou on arrete de boucler ?
  7966. if ($nbmax && $nbphoto >= $nbmax) {
  7967. break;
  7968. }
  7969. }
  7970. }
  7971. if ($size == 1 || $size == 'small') {
  7972. if ($nbbyrow > 0) {
  7973. // Ferme tableau
  7974. while ($nbphoto % $nbbyrow) {
  7975. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  7976. $nbphoto++;
  7977. }
  7978. if ($nbphoto) {
  7979. $return .= '</table>';
  7980. }
  7981. }
  7982. }
  7983. }
  7984. $this->nbphoto = $nbphoto;
  7985. return $return;
  7986. }
  7987. /**
  7988. * Function test if type is array
  7989. *
  7990. * @param array $info content informations of field
  7991. * @return bool true if array
  7992. */
  7993. protected function isArray($info)
  7994. {
  7995. if (is_array($info)) {
  7996. if (isset($info['type']) && $info['type'] == 'array') {
  7997. return true;
  7998. } else {
  7999. return false;
  8000. }
  8001. }
  8002. return false;
  8003. }
  8004. /**
  8005. * Function test if type is date
  8006. *
  8007. * @param array $info content informations of field
  8008. * @return bool true if date
  8009. */
  8010. public function isDate($info)
  8011. {
  8012. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
  8013. return true;
  8014. }
  8015. return false;
  8016. }
  8017. /**
  8018. * Function test if type is duration
  8019. *
  8020. * @param array $info content informations of field
  8021. * @return bool true if field of type duration
  8022. */
  8023. public function isDuration($info)
  8024. {
  8025. if (is_array($info)) {
  8026. if (isset($info['type']) && ($info['type'] == 'duration')) {
  8027. return true;
  8028. } else {
  8029. return false;
  8030. }
  8031. } else {
  8032. return false;
  8033. }
  8034. }
  8035. /**
  8036. * Function test if type is integer
  8037. *
  8038. * @param array $info content informations of field
  8039. * @return bool true if integer
  8040. */
  8041. public function isInt($info)
  8042. {
  8043. if (is_array($info)) {
  8044. if (isset($info['type']) && (preg_match('/(^int|int$)/i', $info['type']))) {
  8045. return true;
  8046. } else {
  8047. return false;
  8048. }
  8049. } else {
  8050. return false;
  8051. }
  8052. }
  8053. /**
  8054. * Function test if type is float
  8055. *
  8056. * @param array $info content informations of field
  8057. * @return bool true if float
  8058. */
  8059. public function isFloat($info)
  8060. {
  8061. if (is_array($info)) {
  8062. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
  8063. return true;
  8064. } else {
  8065. return false;
  8066. }
  8067. }
  8068. return false;
  8069. }
  8070. /**
  8071. * Function test if type is text
  8072. *
  8073. * @param array $info content informations of field
  8074. * @return bool true if type text
  8075. */
  8076. public function isText($info)
  8077. {
  8078. if (is_array($info)) {
  8079. if (isset($info['type']) && $info['type'] == 'text') {
  8080. return true;
  8081. } else {
  8082. return false;
  8083. }
  8084. }
  8085. return false;
  8086. }
  8087. /**
  8088. * Function test if field can be null
  8089. *
  8090. * @param array $info content informations of field
  8091. * @return bool true if it can be null
  8092. */
  8093. protected function canBeNull($info)
  8094. {
  8095. if (is_array($info)) {
  8096. if (isset($info['notnull']) && $info['notnull'] != '1') {
  8097. return true;
  8098. } else {
  8099. return false;
  8100. }
  8101. }
  8102. return true;
  8103. }
  8104. /**
  8105. * Function test if field is forced to null if zero or empty
  8106. *
  8107. * @param array $info content informations of field
  8108. * @return bool true if forced to null
  8109. */
  8110. protected function isForcedToNullIfZero($info)
  8111. {
  8112. if (is_array($info)) {
  8113. if (isset($info['notnull']) && $info['notnull'] == '-1') {
  8114. return true;
  8115. } else {
  8116. return false;
  8117. }
  8118. }
  8119. return false;
  8120. }
  8121. /**
  8122. * Function test if is indexed
  8123. *
  8124. * @param array $info content informations of field
  8125. * @return bool
  8126. */
  8127. protected function isIndex($info)
  8128. {
  8129. if (is_array($info)) {
  8130. if (isset($info['index']) && $info['index'] == true) {
  8131. return true;
  8132. } else {
  8133. return false;
  8134. }
  8135. }
  8136. return false;
  8137. }
  8138. /**
  8139. * Function to prepare a part of the query for insert by returning an array with all properties of object.
  8140. *
  8141. * Note $this->${field} are set by the page that make the createCommon() or the updateCommon().
  8142. * $this->${field} should be a clean and string value (so date are formated for SQL insert).
  8143. *
  8144. * @return array Array with all values of each properties to update
  8145. */
  8146. protected function setSaveQuery()
  8147. {
  8148. global $conf;
  8149. $queryarray = array();
  8150. foreach ($this->fields as $field => $info) { // Loop on definition of fields
  8151. // Depending on field type ('datetime', ...)
  8152. if ($this->isDate($info)) {
  8153. if (empty($this->{$field})) {
  8154. $queryarray[$field] = null;
  8155. } else {
  8156. $queryarray[$field] = $this->db->idate($this->{$field});
  8157. }
  8158. } elseif ($this->isDuration($info)) {
  8159. // $this->{$field} may be null, '', 0, '0', 123, '123'
  8160. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  8161. if (!isset($this->{$field})) {
  8162. if (!empty($info['default'])) {
  8163. $queryarray[$field] = $info['default'];
  8164. } else {
  8165. $queryarray[$field] = 0;
  8166. }
  8167. } else {
  8168. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  8169. }
  8170. } else {
  8171. $queryarray[$field] = null;
  8172. }
  8173. } elseif ($this->isInt($info) || $this->isFloat($info)) {
  8174. if ($field == 'entity' && is_null($this->{$field})) {
  8175. $queryarray[$field] = ((int) $conf->entity);
  8176. } else {
  8177. // $this->{$field} may be null, '', 0, '0', 123, '123'
  8178. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  8179. if (!isset($this->{$field})) {
  8180. $queryarray[$field] = 0;
  8181. } elseif ($this->isInt($info)) {
  8182. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  8183. } elseif ($this->isFloat($info)) {
  8184. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  8185. }
  8186. } else {
  8187. $queryarray[$field] = null;
  8188. }
  8189. }
  8190. } else {
  8191. // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
  8192. // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
  8193. $queryarray[$field] = $this->{$field};
  8194. }
  8195. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
  8196. unset($queryarray[$field]);
  8197. }
  8198. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
  8199. $queryarray[$field] = null; // May force 0 to null
  8200. }
  8201. }
  8202. return $queryarray;
  8203. }
  8204. /**
  8205. * Function to load data from a SQL pointer into properties of current object $this
  8206. *
  8207. * @param stdClass $obj Contain data of object from database
  8208. * @return void
  8209. */
  8210. public function setVarsFromFetchObj(&$obj)
  8211. {
  8212. global $db;
  8213. foreach ($this->fields as $field => $info) {
  8214. if ($this->isDate($info)) {
  8215. if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
  8216. $this->{$field} = '';
  8217. } else {
  8218. $this->{$field} = $db->jdate($obj->{$field});
  8219. }
  8220. } elseif ($this->isInt($info)) {
  8221. if ($field == 'rowid') {
  8222. $this->id = (int) $obj->{$field};
  8223. } else {
  8224. if ($this->isForcedToNullIfZero($info)) {
  8225. if (empty($obj->{$field})) {
  8226. $this->{$field} = null;
  8227. } else {
  8228. $this->{$field} = (double) $obj->{$field};
  8229. }
  8230. } else {
  8231. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  8232. $this->{$field} = (int) $obj->{$field};
  8233. } else {
  8234. $this->{$field} = null;
  8235. }
  8236. }
  8237. }
  8238. } elseif ($this->isFloat($info)) {
  8239. if ($this->isForcedToNullIfZero($info)) {
  8240. if (empty($obj->{$field})) {
  8241. $this->{$field} = null;
  8242. } else {
  8243. $this->{$field} = (double) $obj->{$field};
  8244. }
  8245. } else {
  8246. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  8247. $this->{$field} = (double) $obj->{$field};
  8248. } else {
  8249. $this->{$field} = null;
  8250. }
  8251. }
  8252. } else {
  8253. $this->{$field} = isset($obj->{$field}) ? $obj->{$field} : null;
  8254. }
  8255. }
  8256. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  8257. if (!isset($this->fields['ref']) && isset($this->id)) {
  8258. $this->ref = $this->id;
  8259. }
  8260. }
  8261. /**
  8262. * Function to concat keys of fields
  8263. *
  8264. * @param string $alias String of alias of table for fields. For example 't'. It is recommended to use '' and set alias into fields defintion.
  8265. * @return string list of alias fields
  8266. */
  8267. public function getFieldList($alias = '')
  8268. {
  8269. $keys = array_keys($this->fields);
  8270. if (!empty($alias)) {
  8271. $keys_with_alias = array();
  8272. foreach ($keys as $fieldname) {
  8273. $keys_with_alias[] = $alias . '.' . $fieldname;
  8274. }
  8275. return implode(',', $keys_with_alias);
  8276. } else {
  8277. return implode(',', $keys);
  8278. }
  8279. }
  8280. /**
  8281. * Add quote to field value if necessary
  8282. *
  8283. * @param string|int $value Value to protect
  8284. * @param array $fieldsentry Properties of field
  8285. * @return string
  8286. */
  8287. protected function quote($value, $fieldsentry)
  8288. {
  8289. if (is_null($value)) {
  8290. return 'NULL';
  8291. } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
  8292. return price2num("$value");
  8293. } elseif (preg_match('/int$/i', $fieldsentry['type'])) {
  8294. return (int) $value;
  8295. } elseif ($fieldsentry['type'] == 'boolean') {
  8296. if ($value) {
  8297. return 'true';
  8298. } else {
  8299. return 'false';
  8300. }
  8301. } else {
  8302. return "'".$this->db->escape($value)."'";
  8303. }
  8304. }
  8305. /**
  8306. * Create object into database
  8307. *
  8308. * @param User $user User that creates
  8309. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8310. * @return int <0 if KO, Id of created object if OK
  8311. */
  8312. public function createCommon(User $user, $notrigger = false)
  8313. {
  8314. global $langs;
  8315. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  8316. $error = 0;
  8317. $now = dol_now();
  8318. $fieldvalues = $this->setSaveQuery();
  8319. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
  8320. $fieldvalues['date_creation'] = $this->db->idate($now);
  8321. }
  8322. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
  8323. $fieldvalues['fk_user_creat'] = $user->id;
  8324. }
  8325. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  8326. if (array_key_exists('ref', $fieldvalues)) {
  8327. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8328. }
  8329. $keys = array();
  8330. $values = array(); // Array to store string forged for SQL syntax
  8331. foreach ($fieldvalues as $k => $v) {
  8332. $keys[$k] = $k;
  8333. $value = $this->fields[$k];
  8334. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  8335. }
  8336. // Clean and check mandatory
  8337. foreach ($keys as $key) {
  8338. // If field is an implicit foreign key field (so type = 'integer:...')
  8339. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8340. $values[$key] = '';
  8341. }
  8342. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8343. $values[$key] = '';
  8344. }
  8345. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
  8346. $error++;
  8347. $langs->load("errors");
  8348. dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
  8349. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8350. }
  8351. // If value is null and there is a default value for field
  8352. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
  8353. $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
  8354. }
  8355. // If field is an implicit foreign key field (so type = 'integer:...')
  8356. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  8357. if (isset($this->fields[$key]['default'])) {
  8358. $values[$key] = ((int) $this->fields[$key]['default']);
  8359. } else {
  8360. $values[$key] = 'null';
  8361. }
  8362. }
  8363. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
  8364. $values[$key] = 'null';
  8365. }
  8366. }
  8367. if ($error) {
  8368. return -1;
  8369. }
  8370. $this->db->begin();
  8371. if (!$error) {
  8372. $sql = "INSERT INTO ".$this->db->prefix().$this->table_element;
  8373. $sql .= " (".implode(", ", $keys).')';
  8374. $sql .= " VALUES (".implode(", ", $values).")"; // $values can contains 'abc' or 123
  8375. $res = $this->db->query($sql);
  8376. if (!$res) {
  8377. $error++;
  8378. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  8379. $this->errors[] = "ErrorRefAlreadyExists";
  8380. } else {
  8381. $this->errors[] = $this->db->lasterror();
  8382. }
  8383. }
  8384. }
  8385. if (!$error) {
  8386. $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
  8387. }
  8388. // If we have a field ref with a default value of (PROV)
  8389. if (!$error) {
  8390. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
  8391. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
  8392. $resqlupdate = $this->db->query($sql);
  8393. if ($resqlupdate === false) {
  8394. $error++;
  8395. $this->errors[] = $this->db->lasterror();
  8396. } else {
  8397. $this->ref = '(PROV'.$this->id.')';
  8398. }
  8399. }
  8400. }
  8401. // Create extrafields
  8402. if (!$error) {
  8403. $result = $this->insertExtraFields();
  8404. if ($result < 0) {
  8405. $error++;
  8406. }
  8407. }
  8408. // Create lines
  8409. if (!empty($this->table_element_line) && !empty($this->fk_element)) {
  8410. $num = (is_array($this->lines) ? count($this->lines) : 0);
  8411. for ($i = 0; $i < $num; $i++) {
  8412. $line = $this->lines[$i];
  8413. $keyforparent = $this->fk_element;
  8414. $line->$keyforparent = $this->id;
  8415. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  8416. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  8417. if (!is_object($line)) {
  8418. $line = (object) $line;
  8419. }
  8420. $result = $line->create($user, 1);
  8421. if ($result < 0) {
  8422. $this->error = $line->error;
  8423. $this->db->rollback();
  8424. return -1;
  8425. }
  8426. }
  8427. }
  8428. // Triggers
  8429. if (!$error && !$notrigger) {
  8430. // Call triggers
  8431. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  8432. if ($result < 0) {
  8433. $error++;
  8434. }
  8435. // End call triggers
  8436. }
  8437. // Commit or rollback
  8438. if ($error) {
  8439. $this->db->rollback();
  8440. return -1;
  8441. } else {
  8442. $this->db->commit();
  8443. return $this->id;
  8444. }
  8445. }
  8446. /**
  8447. * Load object in memory from the database
  8448. *
  8449. * @param int $id Id object
  8450. * @param string $ref Ref
  8451. * @param string $morewhere More SQL filters (' AND ...')
  8452. * @return int <0 if KO, 0 if not found, >0 if OK
  8453. */
  8454. public function fetchCommon($id, $ref = null, $morewhere = '')
  8455. {
  8456. if (empty($id) && empty($ref) && empty($morewhere)) {
  8457. return -1;
  8458. }
  8459. $fieldlist = $this->getFieldList('t');
  8460. if (empty($fieldlist)) {
  8461. return 0;
  8462. }
  8463. $sql = "SELECT ".$fieldlist;
  8464. $sql .= " FROM ".$this->db->prefix().$this->table_element.' as t';
  8465. if (!empty($id)) {
  8466. $sql .= ' WHERE t.rowid = '.((int) $id);
  8467. } elseif (!empty($ref)) {
  8468. $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
  8469. } else {
  8470. $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  8471. }
  8472. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  8473. $sql .= ' AND t.entity IN ('.getEntity($this->element).')';
  8474. }
  8475. if ($morewhere) {
  8476. $sql .= $morewhere;
  8477. }
  8478. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  8479. $res = $this->db->query($sql);
  8480. if ($res) {
  8481. $obj = $this->db->fetch_object($res);
  8482. if ($obj) {
  8483. $this->setVarsFromFetchObj($obj);
  8484. // Retrieve all extrafield
  8485. // fetch optionals attributes and labels
  8486. $this->fetch_optionals();
  8487. return $this->id;
  8488. } else {
  8489. return 0;
  8490. }
  8491. } else {
  8492. $this->error = $this->db->lasterror();
  8493. $this->errors[] = $this->error;
  8494. return -1;
  8495. }
  8496. }
  8497. /**
  8498. * Load object in memory from the database
  8499. *
  8500. * @param string $morewhere More SQL filters (' AND ...')
  8501. * @return int <0 if KO, 0 if not found, >0 if OK
  8502. */
  8503. public function fetchLinesCommon($morewhere = '')
  8504. {
  8505. $objectlineclassname = get_class($this).'Line';
  8506. if (!class_exists($objectlineclassname)) {
  8507. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  8508. return -1;
  8509. }
  8510. $objectline = new $objectlineclassname($this->db);
  8511. $sql = "SELECT ".$objectline->getFieldList('l');
  8512. $sql .= " FROM ".$this->db->prefix().$objectline->table_element." as l";
  8513. $sql .= " WHERE l.fk_".$this->db->escape($this->element)." = ".((int) $this->id);
  8514. if ($morewhere) {
  8515. $sql .= $morewhere;
  8516. }
  8517. if (isset($objectline->fields['position'])) {
  8518. $sql .= $this->db->order('position', 'ASC');
  8519. }
  8520. $resql = $this->db->query($sql);
  8521. if ($resql) {
  8522. $num_rows = $this->db->num_rows($resql);
  8523. $i = 0;
  8524. while ($i < $num_rows) {
  8525. $obj = $this->db->fetch_object($resql);
  8526. if ($obj) {
  8527. $newline = new $objectlineclassname($this->db);
  8528. $newline->setVarsFromFetchObj($obj);
  8529. $this->lines[] = $newline;
  8530. }
  8531. $i++;
  8532. }
  8533. return 1;
  8534. } else {
  8535. $this->error = $this->db->lasterror();
  8536. $this->errors[] = $this->error;
  8537. return -1;
  8538. }
  8539. }
  8540. /**
  8541. * Update object into database
  8542. *
  8543. * @param User $user User that modifies
  8544. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8545. * @return int <0 if KO, >0 if OK
  8546. */
  8547. public function updateCommon(User $user, $notrigger = false)
  8548. {
  8549. global $conf, $langs;
  8550. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  8551. $error = 0;
  8552. $now = dol_now();
  8553. // $this->oldcopy should have been set by the caller of update
  8554. //if (empty($this->oldcopy)) {
  8555. // $this->oldcopy = dol_clone($this);
  8556. //}
  8557. $fieldvalues = $this->setSaveQuery();
  8558. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
  8559. $fieldvalues['date_modification'] = $this->db->idate($now);
  8560. }
  8561. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
  8562. $fieldvalues['fk_user_modif'] = $user->id;
  8563. }
  8564. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  8565. if (array_key_exists('ref', $fieldvalues)) {
  8566. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8567. }
  8568. // Add quotes and escape on fields with type string
  8569. $keys = array();
  8570. $values = array();
  8571. $tmp = array();
  8572. foreach ($fieldvalues as $k => $v) {
  8573. $keys[$k] = $k;
  8574. $value = $this->fields[$k];
  8575. $values[$k] = $this->quote($v, $value);
  8576. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  8577. }
  8578. // Clean and check mandatory fields
  8579. foreach ($keys as $key) {
  8580. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8581. $values[$key] = ''; // This is an implicit foreign key field
  8582. }
  8583. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8584. $values[$key] = ''; // This is an explicit foreign key field
  8585. }
  8586. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  8587. /*
  8588. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  8589. {
  8590. $error++;
  8591. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8592. }*/
  8593. }
  8594. $sql = 'UPDATE '.$this->db->prefix().$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
  8595. $this->db->begin();
  8596. if (!$error) {
  8597. $res = $this->db->query($sql);
  8598. if (!$res) {
  8599. $error++;
  8600. $this->errors[] = $this->db->lasterror();
  8601. }
  8602. }
  8603. // Update extrafield
  8604. if (!$error) {
  8605. $result = $this->insertExtraFields();
  8606. if ($result < 0) {
  8607. $error++;
  8608. }
  8609. }
  8610. // Triggers
  8611. if (!$error && !$notrigger) {
  8612. // Call triggers
  8613. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  8614. if ($result < 0) {
  8615. $error++;
  8616. } //Do also here what you must do to rollback action if trigger fail
  8617. // End call triggers
  8618. }
  8619. // Commit or rollback
  8620. if ($error) {
  8621. $this->db->rollback();
  8622. return -1;
  8623. } else {
  8624. $this->db->commit();
  8625. return $this->id;
  8626. }
  8627. }
  8628. /**
  8629. * Delete object in database
  8630. *
  8631. * @param User $user User that deletes
  8632. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8633. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  8634. * @return int <0 if KO, 0=Nothing done because object has child, >0 if OK
  8635. */
  8636. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  8637. {
  8638. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  8639. $error = 0;
  8640. $this->db->begin();
  8641. if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
  8642. foreach ($this->childtables as $table) {
  8643. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8644. $resql = $this->db->query($sql);
  8645. if (!$resql) {
  8646. $this->error = $this->db->lasterror();
  8647. $this->errors[] = $this->error;
  8648. $this->db->rollback();
  8649. return -1;
  8650. }
  8651. }
  8652. } elseif (!empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
  8653. $objectisused = $this->isObjectUsed($this->id);
  8654. if (!empty($objectisused)) {
  8655. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  8656. $this->error = 'ErrorRecordHasChildren';
  8657. $this->errors[] = $this->error;
  8658. $this->db->rollback();
  8659. return 0;
  8660. }
  8661. }
  8662. // Delete cascade first
  8663. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  8664. foreach ($this->childtablesoncascade as $table) {
  8665. $deleteFromObject = explode(':', $table);
  8666. if (count($deleteFromObject) >= 2) {
  8667. $className = str_replace('@', '', $deleteFromObject[0]);
  8668. $filePath = $deleteFromObject[1];
  8669. $columnName = $deleteFromObject[2];
  8670. $TMoreSQL = array();
  8671. $more_sql = $deleteFromObject[3];
  8672. if (!empty($more_sql)) {
  8673. $TMoreSQL['customsql'] = $more_sql;
  8674. }
  8675. if (dol_include_once($filePath)) {
  8676. $childObject = new $className($this->db);
  8677. if (method_exists($childObject, 'deleteByParentField')) {
  8678. $result = $childObject->deleteByParentField($this->id, $columnName, $TMoreSQL);
  8679. if ($result < 0) {
  8680. $error++;
  8681. $this->errors[] = $childObject->error;
  8682. break;
  8683. }
  8684. } else {
  8685. $error++;
  8686. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  8687. break;
  8688. }
  8689. } else {
  8690. $error++;
  8691. $this->errors[] = 'Cannot include child class file '.$filePath;
  8692. break;
  8693. }
  8694. } else {
  8695. // Delete record in child table
  8696. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8697. $resql = $this->db->query($sql);
  8698. if (!$resql) {
  8699. $error++;
  8700. $this->error = $this->db->lasterror();
  8701. $this->errors[] = $this->error;
  8702. break;
  8703. }
  8704. }
  8705. }
  8706. }
  8707. if (!$error) {
  8708. if (!$notrigger) {
  8709. // Call triggers
  8710. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  8711. if ($result < 0) {
  8712. $error++;
  8713. } // Do also here what you must do to rollback action if trigger fail
  8714. // End call triggers
  8715. }
  8716. }
  8717. // Delete llx_ecm_files
  8718. if (!$error) {
  8719. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  8720. if (!$res) {
  8721. $error++;
  8722. }
  8723. }
  8724. // Delete linked object
  8725. $res = $this->deleteObjectLinked();
  8726. if ($res < 0) {
  8727. $error++;
  8728. }
  8729. if (!$error && !empty($this->isextrafieldmanaged)) {
  8730. $result = $this->deleteExtraFields();
  8731. if ($result < 0) {
  8732. $error++;
  8733. }
  8734. }
  8735. if (!$error) {
  8736. $sql = 'DELETE FROM '.$this->db->prefix().$this->table_element.' WHERE rowid='.((int) $this->id);
  8737. $resql = $this->db->query($sql);
  8738. if (!$resql) {
  8739. $error++;
  8740. $this->errors[] = $this->db->lasterror();
  8741. }
  8742. }
  8743. // Commit or rollback
  8744. if ($error) {
  8745. $this->db->rollback();
  8746. return -1;
  8747. } else {
  8748. $this->db->commit();
  8749. return 1;
  8750. }
  8751. }
  8752. /**
  8753. * Delete all child object from a parent ID
  8754. *
  8755. * @param int $parentId Parent Id
  8756. * @param string $parentField Name of Foreign key parent column
  8757. * @param array $filter an array filter
  8758. * @param string $filtermode AND or OR
  8759. * @return int <0 if KO, >0 if OK
  8760. * @throws Exception
  8761. */
  8762. public function deleteByParentField($parentId = 0, $parentField = '', $filter = array(), $filtermode = "AND")
  8763. {
  8764. global $user;
  8765. $error = 0;
  8766. $deleted = 0;
  8767. if (!empty($parentId) && !empty($parentField)) {
  8768. $this->db->begin();
  8769. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
  8770. $sql .= " WHERE ".$parentField." = ".(int) $parentId;
  8771. // Manage filters
  8772. $sqlwhere = array();
  8773. if (count($filter) > 0) {
  8774. foreach ($filter as $key => $value) {
  8775. if ($key == 'customsql') {
  8776. $sqlwhere[] = $value;
  8777. } elseif (strpos($value, '%') === false) {
  8778. $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
  8779. } else {
  8780. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  8781. }
  8782. }
  8783. }
  8784. if (count($sqlwhere) > 0) {
  8785. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  8786. }
  8787. $resql = $this->db->query($sql);
  8788. if (!$resql) {
  8789. $this->errors[] = $this->db->lasterror();
  8790. $error++;
  8791. } else {
  8792. while ($obj = $this->db->fetch_object($resql)) {
  8793. $result = $this->fetch($obj->rowid);
  8794. if ($result < 0) {
  8795. $error++;
  8796. $this->errors[] = $this->error;
  8797. } else {
  8798. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  8799. $result = $this->delete();
  8800. } else {
  8801. $result = $this->delete($user);
  8802. }
  8803. if ($result < 0) {
  8804. $error++;
  8805. $this->errors[] = $this->error;
  8806. } else {
  8807. $deleted++;
  8808. }
  8809. }
  8810. }
  8811. }
  8812. if (empty($error)) {
  8813. $this->db->commit();
  8814. return $deleted;
  8815. } else {
  8816. $this->error = implode(', ', $this->errors);
  8817. $this->db->rollback();
  8818. return $error * -1;
  8819. }
  8820. }
  8821. return $deleted;
  8822. }
  8823. /**
  8824. * Delete a line of object in database
  8825. *
  8826. * @param User $user User that delete
  8827. * @param int $idline Id of line to delete
  8828. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8829. * @return int >0 if OK, <0 if KO
  8830. */
  8831. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  8832. {
  8833. global $conf;
  8834. $error = 0;
  8835. $tmpforobjectclass = get_class($this);
  8836. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  8837. $this->db->begin();
  8838. // Call trigger
  8839. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  8840. if ($result < 0) {
  8841. $error++;
  8842. }
  8843. // End call triggers
  8844. if (empty($error)) {
  8845. $sql = "DELETE FROM ".$this->db->prefix().$this->table_element_line;
  8846. $sql .= " WHERE rowid = ".((int) $idline);
  8847. $resql = $this->db->query($sql);
  8848. if (!$resql) {
  8849. $this->error = "Error ".$this->db->lasterror();
  8850. $error++;
  8851. }
  8852. }
  8853. if (empty($error)) {
  8854. // Remove extrafields
  8855. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  8856. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  8857. $tmpobjectline->id = $idline;
  8858. $result = $tmpobjectline->deleteExtraFields();
  8859. if ($result < 0) {
  8860. $error++;
  8861. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  8862. }
  8863. }
  8864. }
  8865. if (empty($error)) {
  8866. $this->db->commit();
  8867. return 1;
  8868. } else {
  8869. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  8870. $this->db->rollback();
  8871. return -1;
  8872. }
  8873. }
  8874. /**
  8875. * Set to a status
  8876. *
  8877. * @param User $user Object user that modify
  8878. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  8879. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  8880. * @param string $triggercode Trigger code to use
  8881. * @return int <0 if KO, >0 if OK
  8882. */
  8883. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  8884. {
  8885. $error = 0;
  8886. $this->db->begin();
  8887. $statusfield = 'status';
  8888. if (in_array($this->element, array('don', 'donation', 'shipping'))) {
  8889. $statusfield = 'fk_statut';
  8890. }
  8891. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  8892. $sql .= " SET ".$statusfield." = ".((int) $status);
  8893. $sql .= " WHERE rowid = ".((int) $this->id);
  8894. if ($this->db->query($sql)) {
  8895. if (!$error) {
  8896. $this->oldcopy = clone $this;
  8897. }
  8898. if (!$error && !$notrigger) {
  8899. // Call trigger
  8900. $result = $this->call_trigger($triggercode, $user);
  8901. if ($result < 0) {
  8902. $error++;
  8903. }
  8904. }
  8905. if (!$error) {
  8906. $this->status = $status;
  8907. $this->db->commit();
  8908. return 1;
  8909. } else {
  8910. $this->db->rollback();
  8911. return -1;
  8912. }
  8913. } else {
  8914. $this->error = $this->db->error();
  8915. $this->db->rollback();
  8916. return -1;
  8917. }
  8918. }
  8919. /**
  8920. * Initialise object with example values
  8921. * Id must be 0 if object instance is a specimen
  8922. *
  8923. * @return int
  8924. */
  8925. public function initAsSpecimenCommon()
  8926. {
  8927. global $user;
  8928. $this->id = 0;
  8929. $this->specimen = 1;
  8930. $fields = array(
  8931. 'label' => 'This is label',
  8932. 'ref' => 'ABCD1234',
  8933. 'description' => 'This is a description',
  8934. 'qty' => 123.12,
  8935. 'note_public' => 'Public note',
  8936. 'note_private' => 'Private note',
  8937. 'date_creation' => (dol_now() - 3600 * 48),
  8938. 'date_modification' => (dol_now() - 3600 * 24),
  8939. 'fk_user_creat' => $user->id,
  8940. 'fk_user_modif' => $user->id,
  8941. 'date' => dol_now(),
  8942. );
  8943. foreach ($fields as $key => $value) {
  8944. if (array_key_exists($key, $this->fields)) {
  8945. $this->{$key} = $value;
  8946. }
  8947. }
  8948. return 1;
  8949. }
  8950. /* Part for comments */
  8951. /**
  8952. * Load comments linked with current task
  8953. * @return boolean 1 if ok
  8954. */
  8955. public function fetchComments()
  8956. {
  8957. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  8958. $comment = new Comment($this->db);
  8959. $result = $comment->fetchAllFor($this->element, $this->id);
  8960. if ($result < 0) {
  8961. $this->errors = array_merge($this->errors, $comment->errors);
  8962. return -1;
  8963. } else {
  8964. $this->comments = $comment->comments;
  8965. }
  8966. return count($this->comments);
  8967. }
  8968. /**
  8969. * Return nb comments already posted
  8970. *
  8971. * @return int
  8972. */
  8973. public function getNbComments()
  8974. {
  8975. return count($this->comments);
  8976. }
  8977. /**
  8978. * Trim object parameters
  8979. *
  8980. * @param string[] $parameters array of parameters to trim
  8981. * @return void
  8982. */
  8983. public function trimParameters($parameters)
  8984. {
  8985. if (!is_array($parameters)) {
  8986. return;
  8987. }
  8988. foreach ($parameters as $parameter) {
  8989. if (isset($this->$parameter)) {
  8990. $this->$parameter = trim($this->$parameter);
  8991. }
  8992. }
  8993. }
  8994. /* Part for categories/tags */
  8995. /**
  8996. * Sets object to given categories.
  8997. *
  8998. * Deletes object from existing categories not supplied.
  8999. * Adds it to non existing supplied categories.
  9000. * Existing categories are left untouch.
  9001. *
  9002. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  9003. * @return int Array of category objects or < 0 if KO
  9004. */
  9005. public function getCategoriesCommon($type_categ)
  9006. {
  9007. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  9008. // Get current categories
  9009. $c = new Categorie($this->db);
  9010. $existing = $c->containing($this->id, $type_categ, 'id');
  9011. return $existing;
  9012. }
  9013. /**
  9014. * Sets object to given categories.
  9015. *
  9016. * Adds it to non existing supplied categories.
  9017. * Deletes object from existing categories not supplied (if remove_existing==true).
  9018. * Existing categories are left untouch.
  9019. *
  9020. * @param int[]|int $categories Category ID or array of Categories IDs
  9021. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) definied into const class Categorie type
  9022. * @param boolean $remove_existing True: Remove existings categories from Object if not supplies by $categories, False: let them
  9023. * @return int <0 if KO, >0 if OK
  9024. */
  9025. public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
  9026. {
  9027. // Handle single category
  9028. if (!is_array($categories)) {
  9029. $categories = array($categories);
  9030. }
  9031. dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
  9032. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  9033. if (empty($type_categ)) {
  9034. dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
  9035. return -1;
  9036. }
  9037. // Get current categories
  9038. $c = new Categorie($this->db);
  9039. $existing = $c->containing($this->id, $type_categ, 'id');
  9040. if ($remove_existing) {
  9041. // Diff
  9042. if (is_array($existing)) {
  9043. $to_del = array_diff($existing, $categories);
  9044. $to_add = array_diff($categories, $existing);
  9045. } else {
  9046. $to_del = array(); // Nothing to delete
  9047. $to_add = $categories;
  9048. }
  9049. } else {
  9050. $to_del = array(); // Nothing to delete
  9051. $to_add = array_diff($categories, $existing);
  9052. }
  9053. $error = 0;
  9054. $ok = 0;
  9055. // Process
  9056. foreach ($to_del as $del) {
  9057. if ($c->fetch($del) > 0) {
  9058. $result=$c->del_type($this, $type_categ);
  9059. if ($result < 0) {
  9060. $error++;
  9061. $this->error = $c->error;
  9062. $this->errors = $c->errors;
  9063. break;
  9064. } else {
  9065. $ok += $result;
  9066. }
  9067. }
  9068. }
  9069. foreach ($to_add as $add) {
  9070. if ($c->fetch($add) > 0) {
  9071. $result = $c->add_type($this, $type_categ);
  9072. if ($result < 0) {
  9073. $error++;
  9074. $this->error = $c->error;
  9075. $this->errors = $c->errors;
  9076. break;
  9077. } else {
  9078. $ok += $result;
  9079. }
  9080. }
  9081. }
  9082. return $error ? (-1 * $error) : $ok;
  9083. }
  9084. /**
  9085. * Copy related categories to another object
  9086. *
  9087. * @param int $fromId Id object source
  9088. * @param int $toId Id object cible
  9089. * @param string $type Type of category ('product', ...)
  9090. * @return int < 0 if error, > 0 if ok
  9091. */
  9092. public function cloneCategories($fromId, $toId, $type = '')
  9093. {
  9094. $this->db->begin();
  9095. if (empty($type)) {
  9096. $type = $this->table_element;
  9097. }
  9098. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  9099. $categorystatic = new Categorie($this->db);
  9100. $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  9101. $sql .= " SELECT fk_categorie, $toId FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  9102. $sql .= " WHERE fk_product = ".((int) $fromId);
  9103. if (!$this->db->query($sql)) {
  9104. $this->error = $this->db->lasterror();
  9105. $this->db->rollback();
  9106. return -1;
  9107. }
  9108. $this->db->commit();
  9109. return 1;
  9110. }
  9111. /**
  9112. * Delete related files of object in database
  9113. *
  9114. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  9115. * @return bool True if OK, False if KO
  9116. */
  9117. public function deleteEcmFiles($mode = 0)
  9118. {
  9119. global $conf;
  9120. $this->db->begin();
  9121. // Delete in database with mode 0
  9122. if ($mode == 0) {
  9123. switch ($this->element) {
  9124. case 'propal':
  9125. $element = 'propale';
  9126. break;
  9127. case 'product':
  9128. $element = 'produit';
  9129. break;
  9130. case 'order_supplier':
  9131. $element = 'fournisseur/commande';
  9132. break;
  9133. case 'invoice_supplier':
  9134. $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  9135. break;
  9136. case 'shipping':
  9137. $element = 'expedition/sending';
  9138. break;
  9139. default:
  9140. $element = $this->element;
  9141. }
  9142. // Delete ecm_files extrafields
  9143. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files_extrafields WHERE fk_object IN (";
  9144. $sql .= " SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  9145. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  9146. $sql .= ")";
  9147. if (!$this->db->query($sql)) {
  9148. $this->error = $this->db->lasterror();
  9149. $this->db->rollback();
  9150. return false;
  9151. }
  9152. // Delete ecm_files
  9153. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files";
  9154. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  9155. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  9156. if (!$this->db->query($sql)) {
  9157. $this->error = $this->db->lasterror();
  9158. $this->db->rollback();
  9159. return false;
  9160. }
  9161. }
  9162. // Delete in database with mode 1
  9163. if ($mode == 1) {
  9164. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files_extrafields";
  9165. $sql .= " WHERE fk_object IN (SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id).")";
  9166. $resql = $this->db->query($sql);
  9167. if (!$resql) {
  9168. $this->error = $this->db->lasterror();
  9169. $this->db->rollback();
  9170. return false;
  9171. }
  9172. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files";
  9173. $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
  9174. $resql = $this->db->query($sql);
  9175. if (!$resql) {
  9176. $this->error = $this->db->lasterror();
  9177. $this->db->rollback();
  9178. return false;
  9179. }
  9180. }
  9181. $this->db->commit();
  9182. return true;
  9183. }
  9184. }