commonobject.class.php 333 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719
  1. <?php
  2. /* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
  5. * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
  6. * Copyright (C) 2011-2019 Philippe Grand <philippe.grand@atoo-net.com>
  7. * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
  8. * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  9. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  10. * Copyright (C) 2015-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
  11. * Copyright (C) 2016 Bahfir abbes <dolipar@dolipar.org>
  12. * Copyright (C) 2017 ATM Consulting <support@atm-consulting.fr>
  13. * Copyright (C) 2017-2019 Nicolas ZABOURI <info@inovea-conseil.com>
  14. * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
  15. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  16. * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
  17. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  18. *
  19. * This program is free software; you can redistribute it and/or modify
  20. * it under the terms of the GNU General Public License as published by
  21. * the Free Software Foundation; either version 3 of the License, or
  22. * (at your option) any later version.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU General Public License
  30. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  31. */
  32. /**
  33. * \file htdocs/core/class/commonobject.class.php
  34. * \ingroup core
  35. * \brief File of parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  36. */
  37. /**
  38. * Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  39. */
  40. abstract class CommonObject
  41. {
  42. /**
  43. * @var DoliDb Database handler (result of a new DoliDB)
  44. */
  45. public $db;
  46. /**
  47. * @var int The object identifier
  48. */
  49. public $id;
  50. /**
  51. * @var int The environment ID when using a multicompany module
  52. */
  53. public $entity;
  54. /**
  55. * @var string Error string
  56. * @see $errors
  57. */
  58. public $error;
  59. /**
  60. * @var string Error string that is hidden but can be used to store complementatry technical code.
  61. */
  62. public $errorhidden;
  63. /**
  64. * @var string[] Array of error strings
  65. */
  66. public $errors = array();
  67. /**
  68. * @var array To store error results of ->validateField()
  69. */
  70. public $validateFieldsErrors = array();
  71. /**
  72. * @var string ID to identify managed object
  73. */
  74. public $element;
  75. /**
  76. * @var string Name of table without prefix where object is stored
  77. */
  78. public $table_element;
  79. /**
  80. * @var string Name of subtable line
  81. */
  82. public $table_element_line = '';
  83. /**
  84. * @var string Key value used to track if data is coming from import wizard
  85. */
  86. public $import_key;
  87. /**
  88. * @var mixed Contains data to manage extrafields
  89. */
  90. public $array_options = array();
  91. /**
  92. * @var mixed Array to store alternative languages values of object
  93. */
  94. public $array_languages = null; // Value is array() when load already tried
  95. /**
  96. * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked
  97. */
  98. public $linkedObjectsIds;
  99. /**
  100. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  101. */
  102. public $linkedObjects;
  103. /**
  104. * @var Object To store a cloned copy of object before to edit it and keep track of old properties
  105. */
  106. public $oldcopy;
  107. /**
  108. * @var string Column name of the ref field.
  109. */
  110. protected $table_ref_field = '';
  111. /**
  112. * @var integer 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user
  113. */
  114. public $restrictiononfksoc = 0;
  115. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  116. /**
  117. * @var array<string,mixed> Can be used to pass information when only object is provided to method
  118. */
  119. public $context = array();
  120. /**
  121. * @var string Contains canvas name if record is an alternative canvas record
  122. */
  123. public $canvas;
  124. /**
  125. * @var Project The related project
  126. * @see fetch_projet()
  127. */
  128. public $project;
  129. /**
  130. * @var int The related project ID
  131. * @see setProject(), project
  132. */
  133. public $fk_project;
  134. /**
  135. * @deprecated
  136. * @see project
  137. */
  138. public $projet;
  139. /**
  140. * @var Contact a related contact
  141. * @see fetch_contact()
  142. */
  143. public $contact;
  144. /**
  145. * @var int The related contact ID
  146. * @see fetch_contact()
  147. */
  148. public $contact_id;
  149. /**
  150. * @var Societe A related thirdparty
  151. * @see fetch_thirdparty()
  152. */
  153. public $thirdparty;
  154. /**
  155. * @var User A related user
  156. * @see fetch_user()
  157. */
  158. public $user;
  159. /**
  160. * @var string The type of originating object ('commande', 'facture', ...)
  161. * @see fetch_origin()
  162. */
  163. public $origin;
  164. /**
  165. * @var int The id of originating object
  166. * @see fetch_origin()
  167. */
  168. public $origin_id;
  169. /**
  170. * @var string The object's reference
  171. */
  172. public $ref;
  173. /**
  174. * @var string An external reference for the object
  175. */
  176. public $ref_ext;
  177. /**
  178. * @var string The object's previous reference
  179. */
  180. public $ref_previous;
  181. /**
  182. * @var string The object's next reference
  183. */
  184. public $ref_next;
  185. /**
  186. * @var string Ref to store on object to save the new ref to use for example when making a validate() of an object
  187. */
  188. public $newref;
  189. /**
  190. * @var int The object's status
  191. * @see setStatut()
  192. */
  193. public $statut;
  194. /**
  195. * @var int The object's status
  196. * @see setStatut()
  197. */
  198. public $status;
  199. /**
  200. * @var string
  201. * @see getFullAddress()
  202. */
  203. public $country;
  204. /**
  205. * @var int
  206. * @see getFullAddress(), country
  207. */
  208. public $country_id;
  209. /**
  210. * @var string
  211. * @see getFullAddress(), isInEEC(), country
  212. */
  213. public $country_code;
  214. /**
  215. * @var string
  216. * @see getFullAddress()
  217. */
  218. public $state;
  219. /**
  220. * @var int
  221. * @see getFullAddress(), state
  222. */
  223. public $state_id;
  224. /**
  225. * @var string
  226. * @see getFullAddress(), $state
  227. */
  228. public $state_code;
  229. /**
  230. * @var int
  231. * @see getFullAddress(), $region_code, $region
  232. */
  233. public $region_id;
  234. /**
  235. * @var string
  236. * @see getFullAddress(), $region_id, $region
  237. */
  238. public $region_code;
  239. /**
  240. * @var string
  241. * @see getFullAddress(), $region_id, $region_code
  242. */
  243. public $region;
  244. /**
  245. * @var int
  246. * @see fetch_barcode()
  247. */
  248. public $barcode_type;
  249. /**
  250. * @var string
  251. * @see fetch_barcode(), barcode_type
  252. */
  253. public $barcode_type_code;
  254. /**
  255. * @var string
  256. * @see fetch_barcode(), barcode_type
  257. */
  258. public $barcode_type_label;
  259. /**
  260. * @var string
  261. * @see fetch_barcode(), barcode_type
  262. */
  263. public $barcode_type_coder;
  264. /**
  265. * @var int Payment method ID (cheque, cash, ...)
  266. * @see setPaymentMethods()
  267. */
  268. public $mode_reglement_id;
  269. /**
  270. * @var int Payment terms ID
  271. * @see setPaymentTerms()
  272. */
  273. public $cond_reglement_id;
  274. /**
  275. * @var int Demand reason ID
  276. */
  277. public $demand_reason_id;
  278. /**
  279. * @var int Transport mode ID (For module intracomm report)
  280. * @see setTransportMode()
  281. */
  282. public $transport_mode_id;
  283. /**
  284. * @var int Payment terms ID
  285. * @deprecated Kept for compatibility
  286. * @see cond_reglement_id;
  287. */
  288. public $cond_reglement;
  289. /**
  290. * @var int Delivery address ID
  291. * @see setDeliveryAddress()
  292. * @deprecated
  293. */
  294. public $fk_delivery_address;
  295. /**
  296. * @var int Shipping method ID
  297. * @see setShippingMethod()
  298. */
  299. public $shipping_method_id;
  300. /**
  301. * @var string
  302. * @see SetDocModel()
  303. */
  304. public $model_pdf;
  305. /**
  306. * @var string
  307. * @deprecated
  308. * @see $model_pdf
  309. */
  310. public $modelpdf;
  311. /**
  312. * @var string
  313. * Contains relative path of last generated main file
  314. */
  315. public $last_main_doc;
  316. /**
  317. * @var int Bank account ID sometimes, ID of record into llx_bank sometimes
  318. * @deprecated
  319. * @see $fk_account
  320. */
  321. public $fk_bank;
  322. /**
  323. * @var int Bank account ID
  324. * @see SetBankAccount()
  325. */
  326. public $fk_account;
  327. /**
  328. * @var string Open ID
  329. */
  330. public $openid;
  331. /**
  332. * @var string Public note
  333. * @see update_note()
  334. */
  335. public $note_public;
  336. /**
  337. * @var string Private note
  338. * @see update_note()
  339. */
  340. public $note_private;
  341. /**
  342. * @deprecated
  343. * @see $note_private
  344. */
  345. public $note;
  346. /**
  347. * @var float Total amount before taxes
  348. * @see update_price()
  349. */
  350. public $total_ht;
  351. /**
  352. * @var float Total VAT amount
  353. * @see update_price()
  354. */
  355. public $total_tva;
  356. /**
  357. * @var float Total local tax 1 amount
  358. * @see update_price()
  359. */
  360. public $total_localtax1;
  361. /**
  362. * @var float Total local tax 2 amount
  363. * @see update_price()
  364. */
  365. public $total_localtax2;
  366. /**
  367. * @var float Total amount with taxes
  368. * @see update_price()
  369. */
  370. public $total_ttc;
  371. /**
  372. * @var CommonObjectLine[]
  373. */
  374. public $lines;
  375. /**
  376. * @var mixed Contains comments
  377. * @see fetchComments()
  378. */
  379. public $comments = array();
  380. /**
  381. * @var string The name
  382. */
  383. public $name;
  384. /**
  385. * @var string The lastname
  386. */
  387. public $lastname;
  388. /**
  389. * @var string The firstname
  390. */
  391. public $firstname;
  392. /**
  393. * @var string The civility code, not an integer
  394. */
  395. public $civility_id;
  396. // Dates
  397. /**
  398. * @var integer|string date_creation
  399. */
  400. public $date_creation;
  401. /**
  402. * @var integer|string $date_validation;
  403. */
  404. public $date_validation; // Date validation
  405. /**
  406. * @var integer|string $date_modification;
  407. */
  408. public $date_modification; // Date last change (tms field)
  409. public $next_prev_filter;
  410. /**
  411. * @var int 1 if object is specimen
  412. */
  413. public $specimen = 0;
  414. /**
  415. * @var int Id of contact to send object (used by the trigger of module Agenda)
  416. */
  417. public $sendtoid;
  418. /**
  419. * @var float Amount already paid (used to show correct status)
  420. */
  421. public $alreadypaid;
  422. /**
  423. * @var array List of child tables. To test if we can delete object.
  424. */
  425. protected $childtables = array();
  426. /**
  427. * @var array List of child tables. To know object to delete on cascade.
  428. * If name is like '@ClassName:FilePathClass:ParentFkFieldName', it will
  429. * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object.
  430. */
  431. protected $childtablesoncascade = array();
  432. // No constructor as it is an abstract class
  433. /**
  434. * Check an object id/ref exists
  435. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  436. *
  437. * @param string $element String of element ('product', 'facture', ...)
  438. * @param int $id Id of object
  439. * @param string $ref Ref of object to check
  440. * @param string $ref_ext Ref ext of object to check
  441. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  442. */
  443. public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
  444. {
  445. global $db, $conf;
  446. $sql = "SELECT rowid, ref, ref_ext";
  447. $sql .= " FROM ".MAIN_DB_PREFIX.$element;
  448. $sql .= " WHERE entity IN (".getEntity($element).")";
  449. if ($id > 0) {
  450. $sql .= " AND rowid = ".((int) $id);
  451. } elseif ($ref) {
  452. $sql .= " AND ref = '".$db->escape($ref)."'";
  453. } elseif ($ref_ext) {
  454. $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
  455. } else {
  456. $error = 'ErrorWrongParameters';
  457. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  458. return -1;
  459. }
  460. if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
  461. $sql .= " AND entity = ".((int) $conf->entity);
  462. }
  463. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  464. $resql = $db->query($sql);
  465. if ($resql) {
  466. $num = $db->num_rows($resql);
  467. if ($num > 0) {
  468. return 1;
  469. } else {
  470. return 0;
  471. }
  472. }
  473. return -1;
  474. }
  475. /**
  476. * Method to output saved errors
  477. *
  478. * @return string String with errors
  479. */
  480. public function errorsToString()
  481. {
  482. return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
  483. }
  484. /**
  485. * Return customer ref for screen output.
  486. *
  487. * @param string $objref Customer ref
  488. * @return string Customer ref formated
  489. */
  490. public function getFormatedCustomerRef($objref)
  491. {
  492. global $hookmanager;
  493. $parameters = array('objref'=>$objref);
  494. $action = '';
  495. $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  496. if ($reshook > 0) {
  497. return $hookmanager->resArray['objref'];
  498. }
  499. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  500. }
  501. /**
  502. * Return supplier ref for screen output.
  503. *
  504. * @param string $objref Supplier ref
  505. * @return string Supplier ref formated
  506. */
  507. public function getFormatedSupplierRef($objref)
  508. {
  509. global $hookmanager;
  510. $parameters = array('objref'=>$objref);
  511. $action = '';
  512. $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  513. if ($reshook > 0) {
  514. return $hookmanager->resArray['objref'];
  515. }
  516. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  517. }
  518. /**
  519. * Return full name (civility+' '+name+' '+lastname)
  520. *
  521. * @param Translate $langs Language object for translation of civility (used only if option is 1)
  522. * @param int $option 0=No option, 1=Add civility
  523. * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname, 3=Firstname if defined else lastname, 4=Lastname, 5=Lastname if defined else firstname
  524. * @param int $maxlen Maximum length
  525. * @return string String with full name
  526. */
  527. public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
  528. {
  529. //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
  530. $lastname = $this->lastname;
  531. $firstname = $this->firstname;
  532. if (empty($lastname)) {
  533. $lastname = (isset($this->lastname) ? $this->lastname : (isset($this->name) ? $this->name : (isset($this->nom) ? $this->nom : (isset($this->societe) ? $this->societe : (isset($this->company) ? $this->company : '')))));
  534. }
  535. $ret = '';
  536. if (!empty($option) && !empty($this->civility_code)) {
  537. if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) {
  538. $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
  539. } else {
  540. $ret .= $this->civility_code.' ';
  541. }
  542. }
  543. $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
  544. return dol_trunc($ret, $maxlen);
  545. }
  546. /**
  547. * Set to upper or ucwords/lower if needed
  548. *
  549. * @return void;
  550. */
  551. public function setUpperOrLowerCase()
  552. {
  553. global $conf;
  554. if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
  555. $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
  556. $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
  557. $this->name = dol_ucwords(dol_strtolower($this->name));
  558. $this->name_alias = dol_ucwords(dol_strtolower($this->name_alias));
  559. }
  560. if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
  561. $this->lastname = dol_strtoupper($this->lastname);
  562. $this->name = dol_strtoupper($this->name);
  563. $this->name_alias = dol_strtoupper($this->name_alias);
  564. }
  565. if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
  566. $this->address = dol_strtoupper($this->address);
  567. $this->town = dol_strtoupper($this->town);
  568. }
  569. }
  570. /**
  571. * Return clicable link of object (with eventually picto)
  572. *
  573. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  574. * @return string HTML Code for Kanban thumb.
  575. */
  576. public function getKanbanView($option = '')
  577. {
  578. $return = '<div class="box-flex-item">';
  579. $return .= '<div class="info-box info-box-sm">';
  580. $return .= '<span class="info-box-icon bg-infobox-action">';
  581. $return .= '<i class="fa fa-dol-action"></i>'; // Can be image
  582. $return .= '</span>';
  583. $return .= '<div class="info-box-content">';
  584. $return .= '<span class="info-box-title">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  585. $return .= '</div>';
  586. $return .= '</div>';
  587. $return .= '</div>';
  588. return $return;
  589. }
  590. /**
  591. * Return full address of contact
  592. *
  593. * @param int $withcountry 1=Add country into address string
  594. * @param string $sep Separator to use to build string
  595. * @param int $withregion 1=Add region into address string
  596. * @param string $extralangcode User extralanguages as value
  597. * @return string Full address string
  598. */
  599. public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
  600. {
  601. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
  602. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  603. $tmparray = getCountry($this->country_id, 'all');
  604. $this->country_code = $tmparray['code'];
  605. $this->country = $tmparray['label'];
  606. }
  607. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
  608. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  609. $tmparray = getState($this->state_id, 'all', 0, 1);
  610. $this->state_code = $tmparray['code'];
  611. $this->state = $tmparray['label'];
  612. $this->region_code = $tmparray['region_code'];
  613. $this->region = $tmparray['region'];
  614. }
  615. return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
  616. }
  617. /**
  618. * Return full address for banner
  619. *
  620. * @param string $htmlkey HTML id to make banner content unique
  621. * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member)
  622. * @return string Full address string
  623. */
  624. public function getBannerAddress($htmlkey, $object)
  625. {
  626. global $conf, $langs, $form, $extralanguages;
  627. $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
  628. $contactid = 0;
  629. $thirdpartyid = 0;
  630. $elementforaltlanguage = $this->element;
  631. if ($this->element == 'societe') {
  632. $thirdpartyid = $this->id;
  633. }
  634. if ($this->element == 'contact') {
  635. $contactid = $this->id;
  636. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  637. }
  638. if ($this->element == 'user') {
  639. $contactid = $this->contact_id;
  640. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  641. }
  642. $out = '';
  643. $outdone = 0;
  644. $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
  645. if ($coords) {
  646. if (!empty($conf->use_javascript_ajax)) {
  647. // Add picto with tooltip on map
  648. $namecoords = '';
  649. if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
  650. $namecoords .= $object->name.'<br>';
  651. }
  652. $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
  653. // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
  654. $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
  655. $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
  656. $out .= '</a> ';
  657. }
  658. $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  659. $outdone++;
  660. $outdone++;
  661. // List of extra languages
  662. $arrayoflangcode = array();
  663. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  664. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  665. }
  666. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  667. if (!is_object($extralanguages)) {
  668. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  669. $extralanguages = new ExtraLanguages($this->db);
  670. }
  671. $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
  672. if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
  673. $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
  674. $this->fetchValuesForExtraLanguages();
  675. if (!is_object($form)) {
  676. $form = new Form($this->db);
  677. }
  678. $htmltext = '';
  679. // If there is extra languages
  680. foreach ($arrayoflangcode as $extralangcode) {
  681. $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  682. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
  683. $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  684. }
  685. $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  686. }
  687. }
  688. }
  689. if (!in_array($this->country_code, $countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS) // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
  690. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
  691. if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
  692. $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
  693. } else {
  694. $out .= ($outdone ? ' - ' : '').$this->state;
  695. }
  696. $outdone++;
  697. }
  698. if (!empty($this->phone) || !empty($this->phone_pro) || !empty($this->phone_mobile) || !empty($this->phone_perso) || !empty($this->fax) || !empty($this->office_phone) || !empty($this->user_mobile) || !empty($this->office_fax)) {
  699. $out .= ($outdone ? '<br>' : '');
  700. }
  701. if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  702. $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  703. $outdone++;
  704. }
  705. if (!empty($this->phone_pro)) {
  706. $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  707. $outdone++;
  708. }
  709. if (!empty($this->phone_mobile)) {
  710. $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  711. $outdone++;
  712. }
  713. if (!empty($this->phone_perso)) {
  714. $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
  715. $outdone++;
  716. }
  717. if (!empty($this->office_phone)) {
  718. $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  719. $outdone++;
  720. }
  721. if (!empty($this->user_mobile)) {
  722. $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  723. $outdone++;
  724. }
  725. if (!empty($this->fax)) {
  726. $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  727. $outdone++;
  728. }
  729. if (!empty($this->office_fax)) {
  730. $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  731. $outdone++;
  732. }
  733. if ($out) {
  734. $out .= '<div style="clear: both;"></div>';
  735. }
  736. $outdone = 0;
  737. if (!empty($this->email)) {
  738. $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
  739. $outdone++;
  740. }
  741. if (!empty($this->url)) {
  742. //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
  743. $out .= dol_print_url($this->url, '_blank', 0, 1);
  744. $outdone++;
  745. }
  746. if (!empty($conf->socialnetworks->enabled)) {
  747. $outsocialnetwork = '';
  748. if (!empty($this->socialnetworks) && is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
  749. $socialnetworksdict = getArrayOfSocialNetworks();
  750. foreach ($this->socialnetworks as $key => $value) {
  751. if ($value) {
  752. $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
  753. }
  754. $outdone++;
  755. }
  756. } else { // Old code to remove
  757. if (!empty($this->skype)) {
  758. $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
  759. }
  760. $outdone++;
  761. if (!empty($this->jabberid)) {
  762. $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
  763. }
  764. $outdone++;
  765. if (!empty($this->twitter)) {
  766. $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
  767. }
  768. $outdone++;
  769. if (!empty($this->facebook)) {
  770. $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
  771. }
  772. $outdone++;
  773. if (!empty($this->linkedin)) {
  774. $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
  775. }
  776. $outdone++;
  777. }
  778. if ($outsocialnetwork) {
  779. $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
  780. }
  781. }
  782. if ($out) {
  783. return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
  784. } else {
  785. return '';
  786. }
  787. }
  788. /**
  789. * Return the link of last main doc file for direct public download.
  790. *
  791. * @param string $modulepart Module related to document
  792. * @param int $initsharekey Init the share key if it was not yet defined
  793. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  794. * @return string Link or empty string if there is no download link
  795. */
  796. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  797. {
  798. global $user, $dolibarr_main_url_root;
  799. if (empty($this->last_main_doc)) {
  800. return ''; // No way to known which document name to use
  801. }
  802. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  803. $ecmfile = new EcmFiles($this->db);
  804. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  805. if ($result < 0) {
  806. $this->error = $ecmfile->error;
  807. $this->errors = $ecmfile->errors;
  808. return -1;
  809. }
  810. if (empty($ecmfile->id)) {
  811. // Add entry into index
  812. if ($initsharekey) {
  813. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  814. // TODO We can't, we dont' have full path of file, only last_main_doc and ->element, so we must first rebuild full path $destfull
  815. /*
  816. $ecmfile->filepath = $rel_dir;
  817. $ecmfile->filename = $filename;
  818. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  819. $ecmfile->fullpath_orig = '';
  820. $ecmfile->gen_or_uploaded = 'generated';
  821. $ecmfile->description = ''; // indexed content
  822. $ecmfile->keywords = ''; // keyword content
  823. $ecmfile->share = getRandomPassword(true);
  824. $result = $ecmfile->create($user);
  825. if ($result < 0)
  826. {
  827. $this->error = $ecmfile->error;
  828. $this->errors = $ecmfile->errors;
  829. }
  830. */
  831. } else {
  832. return '';
  833. }
  834. } elseif (empty($ecmfile->share)) {
  835. // Add entry into index
  836. if ($initsharekey) {
  837. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  838. $ecmfile->share = getRandomPassword(true);
  839. $ecmfile->update($user);
  840. } else {
  841. return '';
  842. }
  843. }
  844. // Define $urlwithroot
  845. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  846. // This is to use external domain name found into config file
  847. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  848. //else
  849. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  850. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  851. $forcedownload = 0;
  852. $paramlink = '';
  853. //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  854. //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  855. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  856. if (!empty($ecmfile->share)) {
  857. $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
  858. }
  859. if ($forcedownload) {
  860. $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  861. }
  862. if ($relativelink) {
  863. $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
  864. } else {
  865. $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  866. }
  867. // Here $ecmfile->share is defined
  868. return $linktoreturn;
  869. }
  870. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  871. /**
  872. * Add a link between element $this->element and a contact
  873. *
  874. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  875. * @param int|string $type_contact Type of contact (code or id). Must be id or code found into table llx_c_type_contact. For example: SALESREPFOLL
  876. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  877. * @param int $notrigger Disable all triggers
  878. * @return int <0 if KO, 0 if already added, >0 if OK
  879. */
  880. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  881. {
  882. // phpcs:enable
  883. global $user, $langs;
  884. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  885. // Check parameters
  886. if ($fk_socpeople <= 0) {
  887. $langs->load("errors");
  888. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  889. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  890. return -1;
  891. }
  892. if (!$type_contact) {
  893. $langs->load("errors");
  894. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  895. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  896. return -2;
  897. }
  898. $id_type_contact = 0;
  899. if (is_numeric($type_contact)) {
  900. $id_type_contact = $type_contact;
  901. } else {
  902. // We look for id type_contact
  903. $sql = "SELECT tc.rowid";
  904. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  905. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  906. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  907. $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  908. //print $sql;
  909. $resql = $this->db->query($sql);
  910. if ($resql) {
  911. $obj = $this->db->fetch_object($resql);
  912. if ($obj) {
  913. $id_type_contact = $obj->rowid;
  914. }
  915. }
  916. }
  917. if ($id_type_contact == 0) {
  918. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  919. dol_syslog("CODE_NOT_VALID_FOR_THIS_ELEMENT: Code type of contact '".$type_contact."' does not exists or is not active for element ".$this->element.", we can ignore it");
  920. return -3;
  921. }
  922. $datecreate = dol_now();
  923. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  924. $TListeContacts = $this->liste_contact(-1, $source);
  925. $already_added = false;
  926. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  927. foreach ($TListeContacts as $array_contact) {
  928. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  929. $already_added = true;
  930. break;
  931. }
  932. }
  933. }
  934. if (!$already_added) {
  935. $this->db->begin();
  936. // Insert into database
  937. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact";
  938. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  939. $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
  940. $sql .= "'".$this->db->idate($datecreate)."'";
  941. $sql .= ", 4, ".((int) $id_type_contact);
  942. $sql .= ")";
  943. $resql = $this->db->query($sql);
  944. if ($resql) {
  945. if (!$notrigger) {
  946. $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  947. if ($result < 0) {
  948. $this->db->rollback();
  949. return -1;
  950. }
  951. }
  952. $this->db->commit();
  953. return 1;
  954. } else {
  955. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  956. $this->error = $this->db->errno();
  957. $this->db->rollback();
  958. return -2;
  959. } else {
  960. $this->error = $this->db->lasterror();
  961. $this->db->rollback();
  962. return -1;
  963. }
  964. }
  965. } else {
  966. return 0;
  967. }
  968. }
  969. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  970. /**
  971. * Copy contact from one element to current
  972. *
  973. * @param CommonObject $objFrom Source element
  974. * @param string $source Nature of contact ('internal' or 'external')
  975. * @return int >0 if OK, <0 if KO
  976. */
  977. public function copy_linked_contact($objFrom, $source = 'internal')
  978. {
  979. // phpcs:enable
  980. $contacts = $objFrom->liste_contact(-1, $source);
  981. foreach ($contacts as $contact) {
  982. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
  983. return -1;
  984. }
  985. }
  986. return 1;
  987. }
  988. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  989. /**
  990. * Update a link to contact line
  991. *
  992. * @param int $rowid Id of line contact-element
  993. * @param int $statut New status of link
  994. * @param int $type_contact_id Id of contact type (not modified if 0)
  995. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  996. * @return int <0 if KO, >= 0 if OK
  997. */
  998. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  999. {
  1000. // phpcs:enable
  1001. // Insert into database
  1002. $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set";
  1003. $sql .= " statut = ".$statut;
  1004. if ($type_contact_id) {
  1005. $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
  1006. }
  1007. if ($fk_socpeople) {
  1008. $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
  1009. }
  1010. $sql .= " where rowid = ".((int) $rowid);
  1011. $resql = $this->db->query($sql);
  1012. if ($resql) {
  1013. return 0;
  1014. } else {
  1015. $this->error = $this->db->lasterror();
  1016. return -1;
  1017. }
  1018. }
  1019. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1020. /**
  1021. * Delete a link to contact line
  1022. *
  1023. * @param int $rowid Id of contact link line to delete
  1024. * @param int $notrigger Disable all triggers
  1025. * @return int >0 if OK, <0 if KO
  1026. */
  1027. public function delete_contact($rowid, $notrigger = 0)
  1028. {
  1029. // phpcs:enable
  1030. global $user;
  1031. $this->db->begin();
  1032. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  1033. $sql .= " WHERE rowid = ".((int) $rowid);
  1034. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  1035. if ($this->db->query($sql)) {
  1036. if (!$notrigger) {
  1037. $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  1038. if ($result < 0) {
  1039. $this->db->rollback();
  1040. return -1;
  1041. }
  1042. }
  1043. $this->db->commit();
  1044. return 1;
  1045. } else {
  1046. $this->error = $this->db->lasterror();
  1047. $this->db->rollback();
  1048. return -1;
  1049. }
  1050. }
  1051. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1052. /**
  1053. * Delete all links between an object $this and all its contacts
  1054. *
  1055. * @param string $source '' or 'internal' or 'external'
  1056. * @param string $code Type of contact (code or id)
  1057. * @return int >0 if OK, <0 if KO
  1058. */
  1059. public function delete_linked_contact($source = '', $code = '')
  1060. {
  1061. // phpcs:enable
  1062. $temp = array();
  1063. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  1064. foreach ($typeContact as $key => $value) {
  1065. array_push($temp, $key);
  1066. }
  1067. $listId = implode(",", $temp);
  1068. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  1069. $sql .= " WHERE element_id = ".((int) $this->id);
  1070. if ($listId) {
  1071. $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
  1072. }
  1073. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  1074. if ($this->db->query($sql)) {
  1075. return 1;
  1076. } else {
  1077. $this->error = $this->db->lasterror();
  1078. return -1;
  1079. }
  1080. }
  1081. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1082. /**
  1083. * Get array of all contacts for an object
  1084. *
  1085. * @param int $status Status of links to get (-1=all)
  1086. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  1087. * @param int $list 0:Return array contains all properties, 1:Return array contains just id
  1088. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1089. * @return array|int Array of contacts, -1 if error
  1090. */
  1091. public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
  1092. {
  1093. // phpcs:enable
  1094. global $langs;
  1095. $tab = array();
  1096. $sql = "SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact"; // This field contains id of llx_socpeople or id of llx_user
  1097. if ($source == 'internal') {
  1098. $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  1099. }
  1100. if ($source == 'external' || $source == 'thirdparty') {
  1101. $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1102. }
  1103. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  1104. $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
  1105. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
  1106. $sql .= ", ".MAIN_DB_PREFIX."element_contact ec";
  1107. if ($source == 'internal') {
  1108. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
  1109. }
  1110. if ($source == 'external' || $source == 'thirdparty') {
  1111. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
  1112. }
  1113. $sql .= " WHERE ec.element_id = ".((int) $this->id);
  1114. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1115. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1116. if ($code) {
  1117. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1118. }
  1119. if ($source == 'internal') {
  1120. $sql .= " AND tc.source = 'internal'";
  1121. }
  1122. if ($source == 'external' || $source == 'thirdparty') {
  1123. $sql .= " AND tc.source = 'external'";
  1124. }
  1125. $sql .= " AND tc.active=1";
  1126. if ($status >= 0) {
  1127. $sql .= " AND ec.statut = ".((int) $status);
  1128. }
  1129. $sql .= " ORDER BY t.lastname ASC";
  1130. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  1131. $resql = $this->db->query($sql);
  1132. if ($resql) {
  1133. $num = $this->db->num_rows($resql);
  1134. $i = 0;
  1135. while ($i < $num) {
  1136. $obj = $this->db->fetch_object($resql);
  1137. if (!$list) {
  1138. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1139. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1140. $tab[$i] = array(
  1141. 'source' => $obj->source,
  1142. 'socid' => $obj->socid,
  1143. 'id' => $obj->id,
  1144. 'nom' => $obj->lastname, // For backward compatibility
  1145. 'civility' => $obj->civility,
  1146. 'lastname' => $obj->lastname,
  1147. 'firstname' => $obj->firstname,
  1148. 'email'=>$obj->email,
  1149. 'login'=> (empty($obj->login) ? '' : $obj->login),
  1150. 'photo' => (empty($obj->photo) ? '' : $obj->photo),
  1151. 'statuscontact' => $obj->statuscontact,
  1152. 'rowid' => $obj->rowid,
  1153. 'code' => $obj->code,
  1154. 'libelle' => $libelle_type,
  1155. 'status' => $obj->statuslink,
  1156. 'fk_c_type_contact' => $obj->fk_c_type_contact
  1157. );
  1158. } else {
  1159. $tab[$i] = $obj->id;
  1160. }
  1161. $i++;
  1162. }
  1163. return $tab;
  1164. } else {
  1165. $this->error = $this->db->lasterror();
  1166. dol_print_error($this->db);
  1167. return -1;
  1168. }
  1169. }
  1170. /**
  1171. * Update status of a contact linked to object
  1172. *
  1173. * @param int $rowid Id of link between object and contact
  1174. * @return int <0 if KO, >=0 if OK
  1175. */
  1176. public function swapContactStatus($rowid)
  1177. {
  1178. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1179. $sql .= " tc.code, tc.libelle";
  1180. $sql .= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)";
  1181. $sql .= " WHERE ec.rowid =".((int) $rowid);
  1182. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1183. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1184. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  1185. $resql = $this->db->query($sql);
  1186. if ($resql) {
  1187. $obj = $this->db->fetch_object($resql);
  1188. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1189. $result = $this->update_contact($rowid, $newstatut);
  1190. $this->db->free($resql);
  1191. return $result;
  1192. } else {
  1193. $this->error = $this->db->error();
  1194. dol_print_error($this->db);
  1195. return -1;
  1196. }
  1197. }
  1198. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1199. /**
  1200. * Return array with list of possible values for type of contacts
  1201. *
  1202. * @param string $source 'internal', 'external' or 'all'
  1203. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  1204. * @param int $option 0=Return array id->label, 1=Return array code->label
  1205. * @param int $activeonly 0=all status of contact, 1=only the active
  1206. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1207. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1208. */
  1209. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1210. {
  1211. // phpcs:enable
  1212. global $langs;
  1213. if (empty($order)) {
  1214. $order = 'position';
  1215. }
  1216. if ($order == 'position') {
  1217. $order .= ',code';
  1218. }
  1219. $tab = array();
  1220. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  1221. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  1222. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1223. if ($activeonly == 1) {
  1224. $sql .= " AND tc.active=1"; // only the active types
  1225. }
  1226. if (!empty($source) && $source != 'all') {
  1227. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1228. }
  1229. if (!empty($code)) {
  1230. $sql .= " AND tc.code='".$this->db->escape($code)."'";
  1231. }
  1232. $sql .= $this->db->order($order, 'ASC');
  1233. //print "sql=".$sql;
  1234. $resql = $this->db->query($sql);
  1235. if ($resql) {
  1236. $num = $this->db->num_rows($resql);
  1237. $i = 0;
  1238. while ($i < $num) {
  1239. $obj = $this->db->fetch_object($resql);
  1240. $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
  1241. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1242. if (empty($option)) {
  1243. $tab[$obj->rowid] = $libelle_type;
  1244. } else {
  1245. $tab[$obj->code] = $libelle_type;
  1246. }
  1247. $i++;
  1248. }
  1249. return $tab;
  1250. } else {
  1251. $this->error = $this->db->lasterror();
  1252. //dol_print_error($this->db);
  1253. return null;
  1254. }
  1255. }
  1256. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1257. /**
  1258. * Return array with list of possible values for type of contacts
  1259. *
  1260. * @param string $source 'internal', 'external' or 'all'
  1261. * @param int $option 0=Return array id->label, 1=Return array code->label
  1262. * @param int $activeonly 0=all status of contact, 1=only the active
  1263. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1264. * @param string $element Filter on 1 element type
  1265. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1266. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1267. */
  1268. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1269. {
  1270. // phpcs:enable
  1271. global $langs, $conf;
  1272. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1273. $tab = array();
  1274. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
  1275. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  1276. $sqlWhere = array();
  1277. if (!empty($element)) {
  1278. $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
  1279. }
  1280. if (!empty($excludeelement)) {
  1281. $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
  1282. }
  1283. if ($activeonly == 1) {
  1284. $sqlWhere[] = " tc.active=1"; // only the active types
  1285. }
  1286. if (!empty($source) && $source != 'all') {
  1287. $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
  1288. }
  1289. if (!empty($code)) {
  1290. $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
  1291. }
  1292. if (count($sqlWhere) > 0) {
  1293. $sql .= " WHERE ".implode(' AND ', $sqlWhere);
  1294. }
  1295. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1296. dol_syslog(__METHOD__, LOG_DEBUG);
  1297. $resql = $this->db->query($sql);
  1298. if ($resql) {
  1299. $num = $this->db->num_rows($resql);
  1300. if ($num > 0) {
  1301. $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
  1302. while ($obj = $this->db->fetch_object($resql)) {
  1303. $modulename = $obj->element;
  1304. if (strpos($obj->element, 'project') !== false) {
  1305. $modulename = 'projet';
  1306. } elseif ($obj->element == 'contrat') {
  1307. $element = 'contract';
  1308. } elseif ($obj->element == 'action') {
  1309. $modulename = 'agenda';
  1310. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1311. $modulename = 'fournisseur';
  1312. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1313. $modulename = 'fournisseur';
  1314. }
  1315. if (!empty($conf->{$modulename}->enabled)) {
  1316. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1317. $tmpelement = $obj->element;
  1318. $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
  1319. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1320. if (empty($option)) {
  1321. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1322. } else {
  1323. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1324. }
  1325. }
  1326. }
  1327. }
  1328. return $tab;
  1329. } else {
  1330. $this->error = $this->db->lasterror();
  1331. return null;
  1332. }
  1333. }
  1334. /**
  1335. * Return id of contacts for a source and a contact code.
  1336. * Example: contact client de facturation ('external', 'BILLING')
  1337. * Example: contact client de livraison ('external', 'SHIPPING')
  1338. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1339. *
  1340. * @param string $source 'external' or 'internal'
  1341. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1342. * @param int $status limited to a certain status
  1343. * @return array List of id for such contacts
  1344. */
  1345. public function getIdContact($source, $code, $status = 0)
  1346. {
  1347. global $conf;
  1348. $result = array();
  1349. $i = 0;
  1350. //cas particulier pour les expeditions
  1351. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1352. $id = $this->origin_id;
  1353. $element = 'commande';
  1354. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1355. $id = $this->origin_id;
  1356. $element = 'order_supplier';
  1357. } else {
  1358. $id = $this->id;
  1359. $element = $this->element;
  1360. }
  1361. $sql = "SELECT ec.fk_socpeople";
  1362. $sql .= " FROM ".MAIN_DB_PREFIX."element_contact as ec,";
  1363. if ($source == 'internal') {
  1364. $sql .= " ".MAIN_DB_PREFIX."user as c,";
  1365. }
  1366. if ($source == 'external') {
  1367. $sql .= " ".MAIN_DB_PREFIX."socpeople as c,";
  1368. }
  1369. $sql .= " ".MAIN_DB_PREFIX."c_type_contact as tc";
  1370. $sql .= " WHERE ec.element_id = ".((int) $id);
  1371. $sql .= " AND ec.fk_socpeople = c.rowid";
  1372. if ($source == 'internal') {
  1373. $sql .= " AND c.entity IN (".getEntity('user').")";
  1374. }
  1375. if ($source == 'external') {
  1376. $sql .= " AND c.entity IN (".getEntity('societe').")";
  1377. }
  1378. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1379. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1380. $sql .= " AND tc.source = '".$this->db->escape($source)."'";
  1381. if ($code) {
  1382. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1383. }
  1384. $sql .= " AND tc.active = 1";
  1385. if ($status) {
  1386. $sql .= " AND ec.statut = ".((int) $status);
  1387. }
  1388. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1389. $resql = $this->db->query($sql);
  1390. if ($resql) {
  1391. while ($obj = $this->db->fetch_object($resql)) {
  1392. $result[$i] = $obj->fk_socpeople;
  1393. $i++;
  1394. }
  1395. } else {
  1396. $this->error = $this->db->error();
  1397. return null;
  1398. }
  1399. return $result;
  1400. }
  1401. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1402. /**
  1403. * Load object contact with id=$this->contact_id into $this->contact
  1404. *
  1405. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1406. * @return int <0 if KO, >0 if OK
  1407. */
  1408. public function fetch_contact($contactid = null)
  1409. {
  1410. // phpcs:enable
  1411. if (empty($contactid)) {
  1412. $contactid = $this->contact_id;
  1413. }
  1414. if (empty($contactid)) {
  1415. return 0;
  1416. }
  1417. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1418. $contact = new Contact($this->db);
  1419. $result = $contact->fetch($contactid);
  1420. $this->contact = $contact;
  1421. return $result;
  1422. }
  1423. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1424. /**
  1425. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1426. *
  1427. * @param int $force_thirdparty_id Force thirdparty id
  1428. * @return int <0 if KO, >0 if OK
  1429. */
  1430. public function fetch_thirdparty($force_thirdparty_id = 0)
  1431. {
  1432. // phpcs:enable
  1433. global $conf;
  1434. if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) {
  1435. return 0;
  1436. }
  1437. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1438. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
  1439. if ($force_thirdparty_id) {
  1440. $idtofetch = $force_thirdparty_id;
  1441. }
  1442. if ($idtofetch) {
  1443. $thirdparty = new Societe($this->db);
  1444. $result = $thirdparty->fetch($idtofetch);
  1445. if ($result<0) {
  1446. $this->errors=array_merge($this->errors, $thirdparty->errors);
  1447. }
  1448. $this->thirdparty = $thirdparty;
  1449. // Use first price level if level not defined for third party
  1450. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1451. $this->thirdparty->price_level = 1;
  1452. }
  1453. return $result;
  1454. } else {
  1455. return -1;
  1456. }
  1457. }
  1458. /**
  1459. * Looks for an object with ref matching the wildcard provided
  1460. * It does only work when $this->table_ref_field is set
  1461. *
  1462. * @param string $ref Wildcard
  1463. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1464. */
  1465. public function fetchOneLike($ref)
  1466. {
  1467. if (!$this->table_ref_field) {
  1468. return 0;
  1469. }
  1470. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."' LIMIT 1";
  1471. $query = $this->db->query($sql);
  1472. if (!$this->db->num_rows($query)) {
  1473. return 0;
  1474. }
  1475. $result = $this->db->fetch_object($query);
  1476. return $this->fetch($result->rowid);
  1477. }
  1478. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1479. /**
  1480. * Load data for barcode into properties ->barcode_type*
  1481. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1482. * if it is not defined, ->element must be defined to know default barcode type.
  1483. *
  1484. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1485. */
  1486. public function fetch_barcode()
  1487. {
  1488. // phpcs:enable
  1489. global $conf;
  1490. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1491. $idtype = $this->barcode_type;
  1492. if (empty($idtype) && $idtype != '0') { // If type of barcode no set, we try to guess. If set to '0' it means we forced to have type remain not defined
  1493. if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
  1494. $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1495. } elseif ($this->element == 'societe') {
  1496. $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1497. } else {
  1498. dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1499. }
  1500. }
  1501. if ($idtype > 0) {
  1502. if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) { // If data not already loaded
  1503. $sql = "SELECT rowid, code, libelle as label, coder";
  1504. $sql .= " FROM ".MAIN_DB_PREFIX."c_barcode_type";
  1505. $sql .= " WHERE rowid = ".((int) $idtype);
  1506. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1507. $resql = $this->db->query($sql);
  1508. if ($resql) {
  1509. $obj = $this->db->fetch_object($resql);
  1510. $this->barcode_type = $obj->rowid;
  1511. $this->barcode_type_code = $obj->code;
  1512. $this->barcode_type_label = $obj->label;
  1513. $this->barcode_type_coder = $obj->coder;
  1514. return 1;
  1515. } else {
  1516. dol_print_error($this->db);
  1517. return -1;
  1518. }
  1519. }
  1520. }
  1521. return 0;
  1522. }
  1523. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1524. /**
  1525. * Load the project with id $this->fk_project into this->project
  1526. *
  1527. * @return int <0 if KO, >=0 if OK
  1528. */
  1529. public function fetch_project()
  1530. {
  1531. // phpcs:enable
  1532. return $this->fetch_projet();
  1533. }
  1534. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1535. /**
  1536. * Load the project with id $this->fk_project into this->project
  1537. *
  1538. * @return int <0 if KO, >=0 if OK
  1539. */
  1540. public function fetch_projet()
  1541. {
  1542. // phpcs:enable
  1543. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1544. if (empty($this->fk_project) && !empty($this->fk_projet)) {
  1545. $this->fk_project = $this->fk_projet; // For backward compatibility
  1546. }
  1547. if (empty($this->fk_project)) {
  1548. return 0;
  1549. }
  1550. $project = new Project($this->db);
  1551. $result = $project->fetch($this->fk_project);
  1552. $this->projet = $project; // deprecated
  1553. $this->project = $project;
  1554. return $result;
  1555. }
  1556. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1557. /**
  1558. * Load the product with id $this->fk_product into this->product
  1559. *
  1560. * @return int <0 if KO, >=0 if OK
  1561. */
  1562. public function fetch_product()
  1563. {
  1564. // phpcs:enable
  1565. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1566. if (empty($this->fk_product)) {
  1567. return 0;
  1568. }
  1569. $product = new Product($this->db);
  1570. $result = $product->fetch($this->fk_product);
  1571. $this->product = $product;
  1572. return $result;
  1573. }
  1574. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1575. /**
  1576. * Load the user with id $userid into this->user
  1577. *
  1578. * @param int $userid Id du contact
  1579. * @return int <0 if KO, >0 if OK
  1580. */
  1581. public function fetch_user($userid)
  1582. {
  1583. // phpcs:enable
  1584. $user = new User($this->db);
  1585. $result = $user->fetch($userid);
  1586. $this->user = $user;
  1587. return $result;
  1588. }
  1589. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1590. /**
  1591. * Read linked origin object
  1592. *
  1593. * @return void
  1594. */
  1595. public function fetch_origin()
  1596. {
  1597. // phpcs:enable
  1598. if ($this->origin == 'shipping') {
  1599. $this->origin = 'expedition';
  1600. }
  1601. if ($this->origin == 'delivery') {
  1602. $this->origin = 'livraison';
  1603. }
  1604. if ($this->origin == 'order_supplier') {
  1605. $this->origin = 'commandeFournisseur';
  1606. }
  1607. $origin = $this->origin;
  1608. $classname = ucfirst($origin);
  1609. $this->$origin = new $classname($this->db);
  1610. $this->$origin->fetch($this->origin_id);
  1611. }
  1612. /**
  1613. * Load object from specific field
  1614. *
  1615. * @param string $table Table element or element line
  1616. * @param string $field Field selected
  1617. * @param string $key Import key
  1618. * @param string $element Element name
  1619. * @return int <0 if KO, >0 if OK
  1620. */
  1621. public function fetchObjectFrom($table, $field, $key, $element = null)
  1622. {
  1623. global $conf;
  1624. $result = false;
  1625. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$table;
  1626. $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
  1627. if (!empty($element)) {
  1628. $sql .= " AND entity IN (".getEntity($element).")";
  1629. } else {
  1630. $sql .= " AND entity = ".((int) $conf->entity);
  1631. }
  1632. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1633. $resql = $this->db->query($sql);
  1634. if ($resql) {
  1635. $row = $this->db->fetch_row($resql);
  1636. // Test for avoid error -1
  1637. if ($row[0] > 0) {
  1638. $result = $this->fetch($row[0]);
  1639. }
  1640. }
  1641. return $result;
  1642. }
  1643. /**
  1644. * Getter generic. Load value from a specific field
  1645. *
  1646. * @param string $table Table of element or element line
  1647. * @param int $id Element id
  1648. * @param string $field Field selected
  1649. * @return int <0 if KO, >0 if OK
  1650. */
  1651. public function getValueFrom($table, $id, $field)
  1652. {
  1653. $result = false;
  1654. if (!empty($id) && !empty($field) && !empty($table)) {
  1655. $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table;
  1656. $sql .= " WHERE rowid = ".((int) $id);
  1657. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1658. $resql = $this->db->query($sql);
  1659. if ($resql) {
  1660. $row = $this->db->fetch_row($resql);
  1661. $result = $row[0];
  1662. }
  1663. }
  1664. return $result;
  1665. }
  1666. /**
  1667. * Setter generic. Update a specific field into database.
  1668. * Warning: Trigger is run only if param trigkey is provided.
  1669. *
  1670. * @param string $field Field to update
  1671. * @param mixed $value New value
  1672. * @param string $table To force other table element or element line (should not be used)
  1673. * @param int $id To force other object id (should not be used)
  1674. * @param string $format Data format ('text', 'date'). 'text' is used if not defined
  1675. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1676. * @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'
  1677. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1678. * @param string $fk_user_field Name of field to save user id making change
  1679. * @return int <0 if KO, >0 if OK
  1680. * @see updateExtraField()
  1681. */
  1682. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1683. {
  1684. global $user, $langs, $conf;
  1685. if (empty($table)) {
  1686. $table = $this->table_element;
  1687. }
  1688. if (empty($id)) {
  1689. $id = $this->id;
  1690. }
  1691. if (empty($format)) {
  1692. $format = 'text';
  1693. }
  1694. if (empty($id_field)) {
  1695. $id_field = 'rowid';
  1696. }
  1697. $error = 0;
  1698. $this->db->begin();
  1699. // Special case
  1700. if ($table == 'product' && $field == 'note_private') {
  1701. $field = 'note';
  1702. }
  1703. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  1704. $fk_user_field = 'fk_user_mod';
  1705. }
  1706. $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
  1707. if ($format == 'text') {
  1708. $sql .= $field." = '".$this->db->escape($value)."'";
  1709. } elseif ($format == 'int') {
  1710. $sql .= $field." = ".((int) $value);
  1711. } elseif ($format == 'date') {
  1712. $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1713. }
  1714. if ($fk_user_field) {
  1715. if (!empty($fuser) && is_object($fuser)) {
  1716. $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
  1717. } elseif (empty($fuser) || $fuser != 'none') {
  1718. $sql .= ", ".$fk_user_field." = ".((int) $user->id);
  1719. }
  1720. }
  1721. $sql .= " WHERE ".$id_field." = ".((int) $id);
  1722. dol_syslog(__METHOD__."", LOG_DEBUG);
  1723. $resql = $this->db->query($sql);
  1724. if ($resql) {
  1725. if ($trigkey) {
  1726. // call trigger with updated object values
  1727. if (empty($this->fields) && method_exists($this, 'fetch')) {
  1728. $result = $this->fetch($id);
  1729. } else {
  1730. $result = $this->fetchCommon($id);
  1731. }
  1732. if ($result >= 0) {
  1733. $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1734. }
  1735. if ($result < 0) {
  1736. $error++;
  1737. }
  1738. }
  1739. if (!$error) {
  1740. if (property_exists($this, $field)) {
  1741. $this->$field = $value;
  1742. }
  1743. $this->db->commit();
  1744. return 1;
  1745. } else {
  1746. $this->db->rollback();
  1747. return -2;
  1748. }
  1749. } else {
  1750. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1751. $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
  1752. } else {
  1753. $this->error = $this->db->lasterror();
  1754. }
  1755. $this->db->rollback();
  1756. return -1;
  1757. }
  1758. }
  1759. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1760. /**
  1761. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1762. *
  1763. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')". Do not allow user input data here.
  1764. * @param string $fieldid Name of field to use for the select MAX and MIN
  1765. * @param int $nodbprefix Do not include DB prefix to forge table name
  1766. * @return int <0 if KO, >0 if OK
  1767. */
  1768. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1769. {
  1770. // phpcs:enable
  1771. global $conf, $user;
  1772. if (!$this->table_element) {
  1773. dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1774. return -1;
  1775. }
  1776. if ($fieldid == 'none') {
  1777. return 1;
  1778. }
  1779. // For backward compatibility
  1780. if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
  1781. $fieldid = 'titre';
  1782. }
  1783. // Security on socid
  1784. $socid = 0;
  1785. if ($user->socid > 0) {
  1786. $socid = $user->socid;
  1787. }
  1788. // this->ismultientitymanaged contains
  1789. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1790. $aliastablesociete = 's';
  1791. if ($this->element == 'societe') {
  1792. $aliastablesociete = 'te'; // te as table_element
  1793. }
  1794. $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
  1795. $sql = "SELECT MAX(te.".$fieldid.")";
  1796. $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1797. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1798. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  1799. }
  1800. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1801. $tmparray = explode('@', $this->ismultientitymanaged);
  1802. $sql .= ", ".MAIN_DB_PREFIX.$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1803. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1804. $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid
  1805. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1806. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1807. }
  1808. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1809. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1810. }
  1811. $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)
  1812. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1813. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1814. }
  1815. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1816. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1817. }
  1818. if (!empty($filter)) {
  1819. if (!preg_match('/^\s*AND/i', $filter)) {
  1820. $sql .= " AND "; // For backward compatibility
  1821. }
  1822. $sql .= $filter;
  1823. }
  1824. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1825. $tmparray = explode('@', $this->ismultientitymanaged);
  1826. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1827. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1828. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1829. }
  1830. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1831. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1832. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1833. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1834. } else {
  1835. $sql .= " AND ug.fk_user = te.rowid";
  1836. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1837. }
  1838. } else {
  1839. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1840. }
  1841. }
  1842. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1843. $tmparray = explode('@', $this->ismultientitymanaged);
  1844. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1845. }
  1846. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1847. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1848. }
  1849. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1850. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1851. }
  1852. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1853. $sql .= ' AND te.rowid = '.((int) $socid);
  1854. }
  1855. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1856. $result = $this->db->query($sql);
  1857. if (!$result) {
  1858. $this->error = $this->db->lasterror();
  1859. return -1;
  1860. }
  1861. $row = $this->db->fetch_row($result);
  1862. $this->ref_previous = $row[0];
  1863. $sql = "SELECT MIN(te.".$fieldid.")";
  1864. $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1865. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1866. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  1867. }
  1868. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1869. $tmparray = explode('@', $this->ismultientitymanaged);
  1870. $sql .= ", ".MAIN_DB_PREFIX.$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1871. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1872. $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid
  1873. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1874. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1875. }
  1876. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1877. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1878. }
  1879. $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)
  1880. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1881. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1882. }
  1883. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1884. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1885. }
  1886. if (!empty($filter)) {
  1887. if (!preg_match('/^\s*AND/i', $filter)) {
  1888. $sql .= " AND "; // For backward compatibility
  1889. }
  1890. $sql .= $filter;
  1891. }
  1892. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1893. $tmparray = explode('@', $this->ismultientitymanaged);
  1894. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1895. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1896. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1897. }
  1898. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1899. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1900. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1901. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1902. } else {
  1903. $sql .= " AND ug.fk_user = te.rowid";
  1904. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1905. }
  1906. } else {
  1907. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1908. }
  1909. }
  1910. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1911. $tmparray = explode('@', $this->ismultientitymanaged);
  1912. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1913. }
  1914. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1915. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1916. }
  1917. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1918. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1919. }
  1920. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1921. $sql .= ' AND te.rowid = '.((int) $socid);
  1922. }
  1923. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1924. // 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
  1925. $result = $this->db->query($sql);
  1926. if (!$result) {
  1927. $this->error = $this->db->lasterror();
  1928. return -2;
  1929. }
  1930. $row = $this->db->fetch_row($result);
  1931. $this->ref_next = $row[0];
  1932. return 1;
  1933. }
  1934. /**
  1935. * Return list of id of contacts of object
  1936. *
  1937. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  1938. * @return array Array of id of contacts (if source=external or internal)
  1939. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  1940. */
  1941. public function getListContactId($source = 'external')
  1942. {
  1943. $contactAlreadySelected = array();
  1944. $tab = $this->liste_contact(-1, $source);
  1945. $num = count($tab);
  1946. $i = 0;
  1947. while ($i < $num) {
  1948. if ($source == 'thirdparty') {
  1949. $contactAlreadySelected[$i] = $tab[$i]['socid'];
  1950. } else {
  1951. $contactAlreadySelected[$i] = $tab[$i]['id'];
  1952. }
  1953. $i++;
  1954. }
  1955. return $contactAlreadySelected;
  1956. }
  1957. /**
  1958. * Link element with a project
  1959. *
  1960. * @param int $projectid Project id to link element to
  1961. * @return int <0 if KO, >0 if OK
  1962. */
  1963. public function setProject($projectid)
  1964. {
  1965. if (!$this->table_element) {
  1966. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  1967. return -1;
  1968. }
  1969. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  1970. if (!empty($this->fields['fk_project'])) { // Common case
  1971. if ($projectid) {
  1972. $sql .= " SET fk_project = ".((int) $projectid);
  1973. } else {
  1974. $sql .= " SET fk_project = NULL";
  1975. }
  1976. $sql .= ' WHERE rowid = '.((int) $this->id);
  1977. } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
  1978. if ($projectid) {
  1979. $sql .= " SET fk_project = ".((int) $projectid);
  1980. } else {
  1981. $sql .= " SET fk_project = NULL";
  1982. }
  1983. $sql .= ' WHERE id = '.((int) $this->id);
  1984. } else // Special case for old architecture objects
  1985. {
  1986. if ($projectid) {
  1987. $sql .= ' SET fk_projet = '.((int) $projectid);
  1988. } else {
  1989. $sql .= ' SET fk_projet = NULL';
  1990. }
  1991. $sql .= " WHERE rowid = ".((int) $this->id);
  1992. }
  1993. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  1994. if ($this->db->query($sql)) {
  1995. $this->fk_project = ((int) $projectid);
  1996. return 1;
  1997. } else {
  1998. dol_print_error($this->db);
  1999. return -1;
  2000. }
  2001. }
  2002. /**
  2003. * Change the payments methods
  2004. *
  2005. * @param int $id Id of new payment method
  2006. * @return int >0 if OK, <0 if KO
  2007. */
  2008. public function setPaymentMethods($id)
  2009. {
  2010. global $user;
  2011. $error = 0; $notrigger = 0;
  2012. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  2013. if ($this->statut >= 0 || $this->element == 'societe') {
  2014. // TODO uniformize field name
  2015. $fieldname = 'fk_mode_reglement';
  2016. if ($this->element == 'societe') {
  2017. $fieldname = 'mode_reglement';
  2018. }
  2019. if (get_class($this) == 'Fournisseur') {
  2020. $fieldname = 'mode_reglement_supplier';
  2021. }
  2022. if (get_class($this) == 'Tva') {
  2023. $fieldname = 'fk_typepayment';
  2024. }
  2025. if (get_class($this) == 'Salary') {
  2026. $fieldname = 'fk_typepayment';
  2027. }
  2028. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2029. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2030. $sql .= ' WHERE rowid='.((int) $this->id);
  2031. if ($this->db->query($sql)) {
  2032. $this->mode_reglement_id = $id;
  2033. // for supplier
  2034. if (get_class($this) == 'Fournisseur') {
  2035. $this->mode_reglement_supplier_id = $id;
  2036. }
  2037. // Triggers
  2038. if (!$error && !$notrigger) {
  2039. // Call triggers
  2040. if (get_class($this) == 'Commande') {
  2041. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2042. } else {
  2043. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  2044. }
  2045. if ($result < 0) {
  2046. $error++;
  2047. }
  2048. // End call triggers
  2049. }
  2050. return 1;
  2051. } else {
  2052. dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
  2053. $this->error = $this->db->error();
  2054. return -1;
  2055. }
  2056. } else {
  2057. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  2058. $this->error = 'Status of the object is incompatible '.$this->statut;
  2059. return -2;
  2060. }
  2061. }
  2062. /**
  2063. * Change the multicurrency code
  2064. *
  2065. * @param string $code multicurrency code
  2066. * @return int >0 if OK, <0 if KO
  2067. */
  2068. public function setMulticurrencyCode($code)
  2069. {
  2070. dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
  2071. if ($this->statut >= 0 || $this->element == 'societe') {
  2072. $fieldname = 'multicurrency_code';
  2073. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2074. $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
  2075. $sql .= ' WHERE rowid='.((int) $this->id);
  2076. if ($this->db->query($sql)) {
  2077. $this->multicurrency_code = $code;
  2078. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  2079. if ($rate) {
  2080. $this->setMulticurrencyRate($rate, 2);
  2081. }
  2082. return 1;
  2083. } else {
  2084. dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
  2085. $this->error = $this->db->error();
  2086. return -1;
  2087. }
  2088. } else {
  2089. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  2090. $this->error = 'Status of the object is incompatible '.$this->statut;
  2091. return -2;
  2092. }
  2093. }
  2094. /**
  2095. * Change the multicurrency rate
  2096. *
  2097. * @param double $rate multicurrency rate
  2098. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  2099. * @return int >0 if OK, <0 if KO
  2100. */
  2101. public function setMulticurrencyRate($rate, $mode = 1)
  2102. {
  2103. dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
  2104. if ($this->statut >= 0 || $this->element == 'societe') {
  2105. $fieldname = 'multicurrency_tx';
  2106. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2107. $sql .= " SET ".$fieldname." = ".((float) $rate);
  2108. $sql .= ' WHERE rowid='.((int) $this->id);
  2109. if ($this->db->query($sql)) {
  2110. $this->multicurrency_tx = $rate;
  2111. // Update line price
  2112. if (!empty($this->lines)) {
  2113. foreach ($this->lines as &$line) {
  2114. // Amounts in company currency will be recalculated
  2115. if ($mode == 1) {
  2116. $line->subprice = 0;
  2117. }
  2118. // Amounts in foreign currency will be recalculated
  2119. if ($mode == 2) {
  2120. $line->multicurrency_subprice = 0;
  2121. }
  2122. switch ($this->element) {
  2123. case 'propal':
  2124. $this->updateline(
  2125. $line->id,
  2126. $line->subprice,
  2127. $line->qty,
  2128. $line->remise_percent,
  2129. $line->tva_tx,
  2130. $line->localtax1_tx,
  2131. $line->localtax2_tx,
  2132. ($line->description ? $line->description : $line->desc),
  2133. 'HT',
  2134. $line->info_bits,
  2135. $line->special_code,
  2136. $line->fk_parent_line,
  2137. $line->skip_update_total,
  2138. $line->fk_fournprice,
  2139. $line->pa_ht,
  2140. $line->label,
  2141. $line->product_type,
  2142. $line->date_start,
  2143. $line->date_end,
  2144. $line->array_options,
  2145. $line->fk_unit,
  2146. $line->multicurrency_subprice
  2147. );
  2148. break;
  2149. case 'commande':
  2150. $this->updateline(
  2151. $line->id,
  2152. ($line->description ? $line->description : $line->desc),
  2153. $line->subprice,
  2154. $line->qty,
  2155. $line->remise_percent,
  2156. $line->tva_tx,
  2157. $line->localtax1_tx,
  2158. $line->localtax2_tx,
  2159. 'HT',
  2160. $line->info_bits,
  2161. $line->date_start,
  2162. $line->date_end,
  2163. $line->product_type,
  2164. $line->fk_parent_line,
  2165. $line->skip_update_total,
  2166. $line->fk_fournprice,
  2167. $line->pa_ht,
  2168. $line->label,
  2169. $line->special_code,
  2170. $line->array_options,
  2171. $line->fk_unit,
  2172. $line->multicurrency_subprice
  2173. );
  2174. break;
  2175. case 'facture':
  2176. $this->updateline(
  2177. $line->id,
  2178. ($line->description ? $line->description : $line->desc),
  2179. $line->subprice,
  2180. $line->qty,
  2181. $line->remise_percent,
  2182. $line->date_start,
  2183. $line->date_end,
  2184. $line->tva_tx,
  2185. $line->localtax1_tx,
  2186. $line->localtax2_tx,
  2187. 'HT',
  2188. $line->info_bits,
  2189. $line->product_type,
  2190. $line->fk_parent_line,
  2191. $line->skip_update_total,
  2192. $line->fk_fournprice,
  2193. $line->pa_ht,
  2194. $line->label,
  2195. $line->special_code,
  2196. $line->array_options,
  2197. $line->situation_percent,
  2198. $line->fk_unit,
  2199. $line->multicurrency_subprice
  2200. );
  2201. break;
  2202. case 'supplier_proposal':
  2203. $this->updateline(
  2204. $line->id,
  2205. $line->subprice,
  2206. $line->qty,
  2207. $line->remise_percent,
  2208. $line->tva_tx,
  2209. $line->localtax1_tx,
  2210. $line->localtax2_tx,
  2211. ($line->description ? $line->description : $line->desc),
  2212. 'HT',
  2213. $line->info_bits,
  2214. $line->special_code,
  2215. $line->fk_parent_line,
  2216. $line->skip_update_total,
  2217. $line->fk_fournprice,
  2218. $line->pa_ht,
  2219. $line->label,
  2220. $line->product_type,
  2221. $line->array_options,
  2222. $line->ref_fourn,
  2223. $line->multicurrency_subprice
  2224. );
  2225. break;
  2226. case 'order_supplier':
  2227. $this->updateline(
  2228. $line->id,
  2229. ($line->description ? $line->description : $line->desc),
  2230. $line->subprice,
  2231. $line->qty,
  2232. $line->remise_percent,
  2233. $line->tva_tx,
  2234. $line->localtax1_tx,
  2235. $line->localtax2_tx,
  2236. 'HT',
  2237. $line->info_bits,
  2238. $line->product_type,
  2239. false,
  2240. $line->date_start,
  2241. $line->date_end,
  2242. $line->array_options,
  2243. $line->fk_unit,
  2244. $line->multicurrency_subprice,
  2245. $line->ref_supplier
  2246. );
  2247. break;
  2248. case 'invoice_supplier':
  2249. $this->updateline(
  2250. $line->id,
  2251. ($line->description ? $line->description : $line->desc),
  2252. $line->subprice,
  2253. $line->tva_tx,
  2254. $line->localtax1_tx,
  2255. $line->localtax2_tx,
  2256. $line->qty,
  2257. 0,
  2258. 'HT',
  2259. $line->info_bits,
  2260. $line->product_type,
  2261. $line->remise_percent,
  2262. false,
  2263. $line->date_start,
  2264. $line->date_end,
  2265. $line->array_options,
  2266. $line->fk_unit,
  2267. $line->multicurrency_subprice,
  2268. $line->ref_supplier
  2269. );
  2270. break;
  2271. default:
  2272. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  2273. break;
  2274. }
  2275. }
  2276. }
  2277. return 1;
  2278. } else {
  2279. dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
  2280. $this->error = $this->db->error();
  2281. return -1;
  2282. }
  2283. } else {
  2284. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  2285. $this->error = 'Status of the object is incompatible '.$this->statut;
  2286. return -2;
  2287. }
  2288. }
  2289. /**
  2290. * Change the payments terms
  2291. *
  2292. * @param int $id Id of new payment terms
  2293. * @return int >0 if OK, <0 if KO
  2294. */
  2295. public function setPaymentTerms($id)
  2296. {
  2297. dol_syslog(get_class($this).'::setPaymentTerms('.$id.')');
  2298. if ($this->statut >= 0 || $this->element == 'societe') {
  2299. // TODO uniformize field name
  2300. $fieldname = 'fk_cond_reglement';
  2301. if ($this->element == 'societe') {
  2302. $fieldname = 'cond_reglement';
  2303. }
  2304. if (get_class($this) == 'Fournisseur') {
  2305. $fieldname = 'cond_reglement_supplier';
  2306. }
  2307. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2308. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2309. $sql .= ' WHERE rowid='.((int) $this->id);
  2310. if ($this->db->query($sql)) {
  2311. $this->cond_reglement_id = $id;
  2312. // for supplier
  2313. if (get_class($this) == 'Fournisseur') {
  2314. $this->cond_reglement_supplier_id = $id;
  2315. }
  2316. $this->cond_reglement = $id; // for compatibility
  2317. return 1;
  2318. } else {
  2319. dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
  2320. $this->error = $this->db->error();
  2321. return -1;
  2322. }
  2323. } else {
  2324. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  2325. $this->error = 'Status of the object is incompatible '.$this->statut;
  2326. return -2;
  2327. }
  2328. }
  2329. /**
  2330. * Change the transport mode methods
  2331. *
  2332. * @param int $id Id of transport mode
  2333. * @return int >0 if OK, <0 if KO
  2334. */
  2335. public function setTransportMode($id)
  2336. {
  2337. dol_syslog(get_class($this).'::setTransportMode('.$id.')');
  2338. if ($this->statut >= 0 || $this->element == 'societe') {
  2339. $fieldname = 'fk_transport_mode';
  2340. if ($this->element == 'societe') {
  2341. $fieldname = 'transport_mode';
  2342. }
  2343. if (get_class($this) == 'Fournisseur') {
  2344. $fieldname = 'transport_mode_supplier';
  2345. }
  2346. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2347. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2348. $sql .= ' WHERE rowid='.((int) $this->id);
  2349. if ($this->db->query($sql)) {
  2350. $this->transport_mode_id = $id;
  2351. // for supplier
  2352. if (get_class($this) == 'Fournisseur') {
  2353. $this->transport_mode_supplier_id = $id;
  2354. }
  2355. return 1;
  2356. } else {
  2357. dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
  2358. $this->error = $this->db->error();
  2359. return -1;
  2360. }
  2361. } else {
  2362. dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
  2363. $this->error = 'Status of the object is incompatible '.$this->statut;
  2364. return -2;
  2365. }
  2366. }
  2367. /**
  2368. * Change the retained warranty payments terms
  2369. *
  2370. * @param int $id Id of new payment terms
  2371. * @return int >0 if OK, <0 if KO
  2372. */
  2373. public function setRetainedWarrantyPaymentTerms($id)
  2374. {
  2375. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
  2376. if ($this->statut >= 0 || $this->element == 'societe') {
  2377. $fieldname = 'retained_warranty_fk_cond_reglement';
  2378. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2379. $sql .= " SET ".$fieldname." = ".((int) $id);
  2380. $sql .= ' WHERE rowid='.((int) $this->id);
  2381. if ($this->db->query($sql)) {
  2382. $this->retained_warranty_fk_cond_reglement = $id;
  2383. return 1;
  2384. } else {
  2385. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
  2386. $this->error = $this->db->error();
  2387. return -1;
  2388. }
  2389. } else {
  2390. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  2391. $this->error = 'Status of the object is incompatible '.$this->statut;
  2392. return -2;
  2393. }
  2394. }
  2395. /**
  2396. * Define delivery address
  2397. * @deprecated
  2398. *
  2399. * @param int $id Address id
  2400. * @return int <0 si ko, >0 si ok
  2401. */
  2402. public function setDeliveryAddress($id)
  2403. {
  2404. $fieldname = 'fk_delivery_address';
  2405. if ($this->element == 'delivery' || $this->element == 'shipping') {
  2406. $fieldname = 'fk_address';
  2407. }
  2408. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".((int) $id);
  2409. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
  2410. if ($this->db->query($sql)) {
  2411. $this->fk_delivery_address = $id;
  2412. return 1;
  2413. } else {
  2414. $this->error = $this->db->error();
  2415. dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
  2416. return -1;
  2417. }
  2418. }
  2419. /**
  2420. * Change the shipping method
  2421. *
  2422. * @param int $shipping_method_id Id of shipping method
  2423. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2424. * @param User $userused Object user
  2425. *
  2426. * @return int 1 if OK, 0 if KO
  2427. */
  2428. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  2429. {
  2430. global $user;
  2431. if (empty($userused)) {
  2432. $userused = $user;
  2433. }
  2434. $error = 0;
  2435. if (!$this->table_element) {
  2436. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2437. return -1;
  2438. }
  2439. $this->db->begin();
  2440. if ($shipping_method_id < 0) {
  2441. $shipping_method_id = 'NULL';
  2442. }
  2443. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  2444. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2445. $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
  2446. $sql .= " WHERE rowid=".((int) $this->id);
  2447. $resql = $this->db->query($sql);
  2448. if (!$resql) {
  2449. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  2450. $this->error = $this->db->lasterror();
  2451. $error++;
  2452. } else {
  2453. if (!$notrigger) {
  2454. // Call trigger
  2455. $this->context = array('shippingmethodupdate'=>1);
  2456. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2457. if ($result < 0) {
  2458. $error++;
  2459. }
  2460. // End call trigger
  2461. }
  2462. }
  2463. if ($error) {
  2464. $this->db->rollback();
  2465. return -1;
  2466. } else {
  2467. $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
  2468. $this->db->commit();
  2469. return 1;
  2470. }
  2471. }
  2472. /**
  2473. * Change the warehouse
  2474. *
  2475. * @param int $warehouse_id Id of warehouse
  2476. * @return int 1 if OK, 0 if KO
  2477. */
  2478. public function setWarehouse($warehouse_id)
  2479. {
  2480. if (!$this->table_element) {
  2481. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2482. return -1;
  2483. }
  2484. if ($warehouse_id < 0) {
  2485. $warehouse_id = 'NULL';
  2486. }
  2487. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  2488. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2489. $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
  2490. $sql .= " WHERE rowid=".((int) $this->id);
  2491. if ($this->db->query($sql)) {
  2492. $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
  2493. return 1;
  2494. } else {
  2495. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  2496. $this->error = $this->db->error();
  2497. return 0;
  2498. }
  2499. }
  2500. /**
  2501. * Set last model used by doc generator
  2502. *
  2503. * @param User $user User object that make change
  2504. * @param string $modelpdf Modele name
  2505. * @return int <0 if KO, >0 if OK
  2506. */
  2507. public function setDocModel($user, $modelpdf)
  2508. {
  2509. if (!$this->table_element) {
  2510. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2511. return -1;
  2512. }
  2513. $newmodelpdf = dol_trunc($modelpdf, 255);
  2514. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2515. $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  2516. $sql .= " WHERE rowid = ".((int) $this->id);
  2517. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  2518. $resql = $this->db->query($sql);
  2519. if ($resql) {
  2520. $this->model_pdf = $modelpdf;
  2521. $this->modelpdf = $modelpdf; // For bakward compatibility
  2522. return 1;
  2523. } else {
  2524. dol_print_error($this->db);
  2525. return 0;
  2526. }
  2527. }
  2528. /**
  2529. * Change the bank account
  2530. *
  2531. * @param int $fk_account Id of bank account
  2532. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2533. * @param User $userused Object user
  2534. * @return int 1 if OK, 0 if KO
  2535. */
  2536. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2537. {
  2538. global $user;
  2539. if (empty($userused)) {
  2540. $userused = $user;
  2541. }
  2542. $error = 0;
  2543. if (!$this->table_element) {
  2544. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2545. return -1;
  2546. }
  2547. $this->db->begin();
  2548. if ($fk_account < 0) {
  2549. $fk_account = 'NULL';
  2550. }
  2551. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  2552. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2553. $sql .= " SET fk_account = ".((int) $fk_account);
  2554. $sql .= " WHERE rowid=".((int) $this->id);
  2555. $resql = $this->db->query($sql);
  2556. if (!$resql) {
  2557. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  2558. $this->error = $this->db->lasterror();
  2559. $error++;
  2560. } else {
  2561. if (!$notrigger) {
  2562. // Call trigger
  2563. $this->context = array('bankaccountupdate'=>1);
  2564. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2565. if ($result < 0) {
  2566. $error++;
  2567. }
  2568. // End call trigger
  2569. }
  2570. }
  2571. if ($error) {
  2572. $this->db->rollback();
  2573. return -1;
  2574. } else {
  2575. $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
  2576. $this->db->commit();
  2577. return 1;
  2578. }
  2579. }
  2580. // TODO: Move line related operations to CommonObjectLine?
  2581. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2582. /**
  2583. * Save a new position (field rang) for details lines.
  2584. * You can choose to set position for lines with already a position or lines without any position defined.
  2585. *
  2586. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2587. * @param string $rowidorder ASC or DESC
  2588. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2589. * @return int <0 if KO, >0 if OK
  2590. */
  2591. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2592. {
  2593. // phpcs:enable
  2594. if (!$this->table_element_line) {
  2595. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2596. return -1;
  2597. }
  2598. if (!$this->fk_element) {
  2599. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2600. return -1;
  2601. }
  2602. // Count number of lines to reorder (according to choice $renum)
  2603. $nl = 0;
  2604. $sql = "SELECT count(rowid) FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  2605. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2606. if (!$renum) {
  2607. $sql .= ' AND rang = 0';
  2608. }
  2609. if ($renum) {
  2610. $sql .= ' AND rang <> 0';
  2611. }
  2612. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  2613. $resql = $this->db->query($sql);
  2614. if ($resql) {
  2615. $row = $this->db->fetch_row($resql);
  2616. $nl = $row[0];
  2617. } else {
  2618. dol_print_error($this->db);
  2619. }
  2620. if ($nl > 0) {
  2621. // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
  2622. $rows = array();
  2623. // We first search all lines that are parent lines (for multilevel details lines)
  2624. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  2625. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2626. if ($fk_parent_line) {
  2627. $sql .= ' AND fk_parent_line IS NULL';
  2628. }
  2629. $sql .= " ORDER BY rang ASC, rowid ".$rowidorder;
  2630. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  2631. $resql = $this->db->query($sql);
  2632. if ($resql) {
  2633. $i = 0;
  2634. $num = $this->db->num_rows($resql);
  2635. while ($i < $num) {
  2636. $row = $this->db->fetch_row($resql);
  2637. $rows[] = $row[0]; // Add parent line into array rows
  2638. $childrens = $this->getChildrenOfLine($row[0]);
  2639. if (!empty($childrens)) {
  2640. foreach ($childrens as $child) {
  2641. array_push($rows, $child);
  2642. }
  2643. }
  2644. $i++;
  2645. }
  2646. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2647. if (!empty($rows)) {
  2648. foreach ($rows as $key => $row) {
  2649. $this->updateRangOfLine($row, ($key + 1));
  2650. }
  2651. }
  2652. } else {
  2653. dol_print_error($this->db);
  2654. }
  2655. }
  2656. return 1;
  2657. }
  2658. /**
  2659. * Get children of line
  2660. *
  2661. * @param int $id Id of parent line
  2662. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2663. * @return array Array with list of children lines id
  2664. */
  2665. public function getChildrenOfLine($id, $includealltree = 0)
  2666. {
  2667. $rows = array();
  2668. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  2669. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2670. $sql .= ' AND fk_parent_line = '.((int) $id);
  2671. $sql .= ' ORDER BY rang ASC';
  2672. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
  2673. $resql = $this->db->query($sql);
  2674. if ($resql) {
  2675. if ($this->db->num_rows($resql) > 0) {
  2676. while ($row = $this->db->fetch_row($resql)) {
  2677. $rows[] = $row[0];
  2678. if (!empty($includealltree)) {
  2679. $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2680. }
  2681. }
  2682. }
  2683. }
  2684. return $rows;
  2685. }
  2686. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2687. /**
  2688. * Update a line to have a lower rank
  2689. *
  2690. * @param int $rowid Id of line
  2691. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2692. * @return void
  2693. */
  2694. public function line_up($rowid, $fk_parent_line = true)
  2695. {
  2696. // phpcs:enable
  2697. $this->line_order(false, 'ASC', $fk_parent_line);
  2698. // Get rang of line
  2699. $rang = $this->getRangOfLine($rowid);
  2700. // Update position of line
  2701. $this->updateLineUp($rowid, $rang);
  2702. }
  2703. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2704. /**
  2705. * Update a line to have a higher rank
  2706. *
  2707. * @param int $rowid Id of line
  2708. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2709. * @return void
  2710. */
  2711. public function line_down($rowid, $fk_parent_line = true)
  2712. {
  2713. // phpcs:enable
  2714. $this->line_order(false, 'ASC', $fk_parent_line);
  2715. // Get rang of line
  2716. $rang = $this->getRangOfLine($rowid);
  2717. // Get max value for rang
  2718. $max = $this->line_max();
  2719. // Update position of line
  2720. $this->updateLineDown($rowid, $rang, $max);
  2721. }
  2722. /**
  2723. * Update position of line (rang)
  2724. *
  2725. * @param int $rowid Id of line
  2726. * @param int $rang Position
  2727. * @return int <0 if KO, >0 if OK
  2728. */
  2729. public function updateRangOfLine($rowid, $rang)
  2730. {
  2731. global $hookmanager;
  2732. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2733. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction'))) {
  2734. $fieldposition = 'position';
  2735. }
  2736. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2737. $sql .= ' WHERE rowid = '.((int) $rowid);
  2738. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2739. if (!$this->db->query($sql)) {
  2740. dol_print_error($this->db);
  2741. return -1;
  2742. } else {
  2743. $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
  2744. $action='';
  2745. $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
  2746. return 1;
  2747. }
  2748. }
  2749. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2750. /**
  2751. * Update position of line with ajax (rang)
  2752. *
  2753. * @param array $rows Array of rows
  2754. * @return void
  2755. */
  2756. public function line_ajaxorder($rows)
  2757. {
  2758. // phpcs:enable
  2759. $num = count($rows);
  2760. for ($i = 0; $i < $num; $i++) {
  2761. $this->updateRangOfLine($rows[$i], ($i + 1));
  2762. }
  2763. }
  2764. /**
  2765. * Update position of line up (rang)
  2766. *
  2767. * @param int $rowid Id of line
  2768. * @param int $rang Position
  2769. * @return void
  2770. */
  2771. public function updateLineUp($rowid, $rang)
  2772. {
  2773. if ($rang > 1) {
  2774. $fieldposition = 'rang';
  2775. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
  2776. $fieldposition = 'position';
  2777. }
  2778. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2779. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2780. $sql .= ' AND rang = '.((int) ($rang - 1));
  2781. if ($this->db->query($sql)) {
  2782. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
  2783. $sql .= ' WHERE rowid = '.((int) $rowid);
  2784. if (!$this->db->query($sql)) {
  2785. dol_print_error($this->db);
  2786. }
  2787. } else {
  2788. dol_print_error($this->db);
  2789. }
  2790. }
  2791. }
  2792. /**
  2793. * Update position of line down (rang)
  2794. *
  2795. * @param int $rowid Id of line
  2796. * @param int $rang Position
  2797. * @param int $max Max
  2798. * @return void
  2799. */
  2800. public function updateLineDown($rowid, $rang, $max)
  2801. {
  2802. if ($rang < $max) {
  2803. $fieldposition = 'rang';
  2804. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
  2805. $fieldposition = 'position';
  2806. }
  2807. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2808. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2809. $sql .= ' AND rang = '.((int) ($rang + 1));
  2810. if ($this->db->query($sql)) {
  2811. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
  2812. $sql .= ' WHERE rowid = '.((int) $rowid);
  2813. if (!$this->db->query($sql)) {
  2814. dol_print_error($this->db);
  2815. }
  2816. } else {
  2817. dol_print_error($this->db);
  2818. }
  2819. }
  2820. }
  2821. /**
  2822. * Get position of line (rang)
  2823. *
  2824. * @param int $rowid Id of line
  2825. * @return int Value of rang in table of lines
  2826. */
  2827. public function getRangOfLine($rowid)
  2828. {
  2829. $sql = "SELECT rang FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  2830. $sql .= " WHERE rowid = ".((int) $rowid);
  2831. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  2832. $resql = $this->db->query($sql);
  2833. if ($resql) {
  2834. $row = $this->db->fetch_row($resql);
  2835. return $row[0];
  2836. }
  2837. }
  2838. /**
  2839. * Get rowid of the line relative to its position
  2840. *
  2841. * @param int $rang Rang value
  2842. * @return int Rowid of the line
  2843. */
  2844. public function getIdOfLine($rang)
  2845. {
  2846. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  2847. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2848. $sql .= " AND rang = ".((int) $rang);
  2849. $resql = $this->db->query($sql);
  2850. if ($resql) {
  2851. $row = $this->db->fetch_row($resql);
  2852. return $row[0];
  2853. }
  2854. }
  2855. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2856. /**
  2857. * Get max value used for position of line (rang)
  2858. *
  2859. * @param int $fk_parent_line Parent line id
  2860. * @return int Max value of rang in table of lines
  2861. */
  2862. public function line_max($fk_parent_line = 0)
  2863. {
  2864. // phpcs:enable
  2865. $positionfield = 'rang';
  2866. if ($this->table_element == 'bom_bom') {
  2867. $positionfield = 'position';
  2868. }
  2869. // Search the last rang with fk_parent_line
  2870. if ($fk_parent_line) {
  2871. $sql = "SELECT max(".$positionfield.") FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  2872. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2873. $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
  2874. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2875. $resql = $this->db->query($sql);
  2876. if ($resql) {
  2877. $row = $this->db->fetch_row($resql);
  2878. if (!empty($row[0])) {
  2879. return $row[0];
  2880. } else {
  2881. return $this->getRangOfLine($fk_parent_line);
  2882. }
  2883. }
  2884. } else {
  2885. // If not, search the last rang of element
  2886. $sql = "SELECT max(".$positionfield.") FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  2887. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2888. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2889. $resql = $this->db->query($sql);
  2890. if ($resql) {
  2891. $row = $this->db->fetch_row($resql);
  2892. return $row[0];
  2893. }
  2894. }
  2895. }
  2896. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2897. /**
  2898. * Update external ref of element
  2899. *
  2900. * @param string $ref_ext Update field ref_ext
  2901. * @return int <0 if KO, >0 if OK
  2902. */
  2903. public function update_ref_ext($ref_ext)
  2904. {
  2905. // phpcs:enable
  2906. if (!$this->table_element) {
  2907. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  2908. return -1;
  2909. }
  2910. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2911. $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  2912. $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
  2913. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  2914. if ($this->db->query($sql)) {
  2915. $this->ref_ext = $ref_ext;
  2916. return 1;
  2917. } else {
  2918. $this->error = $this->db->error();
  2919. return -1;
  2920. }
  2921. }
  2922. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2923. /**
  2924. * Update note of element
  2925. *
  2926. * @param string $note New value for note
  2927. * @param string $suffix '', '_public' or '_private'
  2928. * @return int <0 if KO, >0 if OK
  2929. */
  2930. public function update_note($note, $suffix = '')
  2931. {
  2932. // phpcs:enable
  2933. global $user;
  2934. if (!$this->table_element) {
  2935. $this->error = 'update_note was called on objet with property table_element not defined';
  2936. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  2937. return -1;
  2938. }
  2939. if (!in_array($suffix, array('', '_public', '_private'))) {
  2940. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  2941. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  2942. return -2;
  2943. }
  2944. $newsuffix = $suffix;
  2945. // Special cas
  2946. if ($this->table_element == 'product' && $newsuffix == '_private') {
  2947. $newsuffix = '';
  2948. }
  2949. if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  2950. $fieldusermod = "fk_user_mod";
  2951. } elseif ($this->table_element == 'ecm_files') {
  2952. $fieldusermod = "fk_user_m";
  2953. } else {
  2954. $fieldusermod = "fk_user_modif";
  2955. }
  2956. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2957. $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
  2958. $sql .= ", ".$fieldusermod." = ".((int) $user->id);
  2959. $sql .= " WHERE rowid = ".((int) $this->id);
  2960. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  2961. if ($this->db->query($sql)) {
  2962. if ($suffix == '_public') {
  2963. $this->note_public = $note;
  2964. } elseif ($suffix == '_private') {
  2965. $this->note_private = $note;
  2966. } else {
  2967. $this->note = $note; // deprecated
  2968. $this->note_private = $note;
  2969. }
  2970. return 1;
  2971. } else {
  2972. $this->error = $this->db->lasterror();
  2973. return -1;
  2974. }
  2975. }
  2976. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2977. /**
  2978. * Update public note (kept for backward compatibility)
  2979. *
  2980. * @param string $note New value for note
  2981. * @return int <0 if KO, >0 if OK
  2982. * @deprecated
  2983. * @see update_note()
  2984. */
  2985. public function update_note_public($note)
  2986. {
  2987. // phpcs:enable
  2988. return $this->update_note($note, '_public');
  2989. }
  2990. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2991. /**
  2992. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  2993. * Must be called at end of methods addline or updateline.
  2994. *
  2995. * @param int $exclspec >0 = Exclude special product (product_type=9)
  2996. * @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
  2997. * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object.
  2998. * @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.
  2999. * @return int <0 if KO, >0 if OK
  3000. */
  3001. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  3002. {
  3003. // phpcs:enable
  3004. global $conf, $hookmanager, $action;
  3005. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  3006. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3007. if ($reshook > 0) {
  3008. return 1; // replacement code
  3009. } elseif ($reshook < 0) {
  3010. return -1; // failure
  3011. } // reshook = 0 => execute normal code
  3012. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  3013. $MODULE = "";
  3014. if ($this->element == 'propal') {
  3015. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  3016. } elseif ($this->element == 'commande' || $this->element == 'order') {
  3017. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  3018. } elseif ($this->element == 'facture' || $this->element == 'invoice') {
  3019. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  3020. } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier') {
  3021. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  3022. } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
  3023. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  3024. } elseif ($this->element == 'supplier_proposal') {
  3025. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  3026. }
  3027. if (!empty($MODULE)) {
  3028. if (!empty($conf->global->$MODULE)) {
  3029. $modsactivated = explode(',', $conf->global->$MODULE);
  3030. foreach ($modsactivated as $mod) {
  3031. if ($conf->$mod->enabled) {
  3032. return 1; // update was disabled by specific setup
  3033. }
  3034. }
  3035. }
  3036. }
  3037. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  3038. if ($roundingadjust == '-1') {
  3039. $roundingadjust = 'auto'; // For backward compatibility
  3040. }
  3041. $forcedroundingmode = $roundingadjust;
  3042. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
  3043. $forcedroundingmode = $conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
  3044. } elseif ($forcedroundingmode == 'auto') {
  3045. $forcedroundingmode = '0';
  3046. }
  3047. $error = 0;
  3048. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  3049. // Define constants to find lines to sum
  3050. $fieldtva = 'total_tva';
  3051. $fieldlocaltax1 = 'total_localtax1';
  3052. $fieldlocaltax2 = 'total_localtax2';
  3053. $fieldup = 'subprice';
  3054. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3055. $fieldtva = 'tva';
  3056. $fieldup = 'pu_ht';
  3057. }
  3058. if ($this->element == 'expensereport') {
  3059. $fieldup = 'value_unit';
  3060. }
  3061. $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,";
  3062. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  3063. if ($this->table_element_line == 'facturedet') {
  3064. $sql .= ', situation_percent';
  3065. }
  3066. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3067. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  3068. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3069. if ($exclspec) {
  3070. $product_field = 'product_type';
  3071. if ($this->table_element_line == 'contratdet') {
  3072. $product_field = ''; // contratdet table has no product_type field
  3073. }
  3074. if ($product_field) {
  3075. $sql .= " AND ".$product_field." <> 9";
  3076. }
  3077. }
  3078. $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
  3079. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3080. $resql = $this->db->query($sql);
  3081. if ($resql) {
  3082. $this->total_ht = 0;
  3083. $this->total_tva = 0;
  3084. $this->total_localtax1 = 0;
  3085. $this->total_localtax2 = 0;
  3086. $this->total_ttc = 0;
  3087. $total_ht_by_vats = array();
  3088. $total_tva_by_vats = array();
  3089. $total_ttc_by_vats = array();
  3090. $this->multicurrency_total_ht = 0;
  3091. $this->multicurrency_total_tva = 0;
  3092. $this->multicurrency_total_ttc = 0;
  3093. $num = $this->db->num_rows($resql);
  3094. $i = 0;
  3095. while ($i < $num) {
  3096. $obj = $this->db->fetch_object($resql);
  3097. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  3098. $parameters = array('fk_element' => $obj->rowid);
  3099. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3100. 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'
  3101. // This part of code is to fix data. We should not call it too often.
  3102. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  3103. $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);
  3104. $diff_when_using_price_ht = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); // If price was set with tax price adn unit price HT has a low number of digits, then we may have a diff on recalculation from unit price HT.
  3105. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  3106. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
  3107. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  3108. if ($diff_when_using_price_ht && $diff_on_current_total) {
  3109. $sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2])." WHERE rowid = ".((int) $obj->rowid);
  3110. dol_syslog('We found unconsistent data into detailed line (diff_when_using_price_ht = '.$diff_when_using_price_ht.' and diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (total vat of line calculated=".$tmpcal[1].", database=".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix, LOG_WARNING);
  3111. $resqlfix = $this->db->query($sqlfix);
  3112. if (!$resqlfix) {
  3113. dol_print_error($this->db, 'Failed to update line');
  3114. }
  3115. $obj->total_tva = $tmpcal[1];
  3116. $obj->total_ttc = $tmpcal[2];
  3117. }
  3118. }
  3119. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  3120. $this->total_tva += $obj->total_tva;
  3121. $this->total_localtax1 += $obj->total_localtax1;
  3122. $this->total_localtax2 += $obj->total_localtax2;
  3123. $this->total_ttc += $obj->total_ttc;
  3124. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  3125. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  3126. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  3127. if (!isset($total_ht_by_vats[$obj->vatrate])) {
  3128. $total_ht_by_vats[$obj->vatrate] = 0;
  3129. }
  3130. if (!isset($total_tva_by_vats[$obj->vatrate])) {
  3131. $total_tva_by_vats[$obj->vatrate] = 0;
  3132. }
  3133. if (!isset($total_ttc_by_vats[$obj->vatrate])) {
  3134. $total_ttc_by_vats[$obj->vatrate] = 0;
  3135. }
  3136. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  3137. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  3138. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  3139. if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  3140. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  3141. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  3142. //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";
  3143. if ($diff) {
  3144. if (abs($diff) > 0.1) {
  3145. $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.';
  3146. dol_syslog($errmsg, LOG_WARNING);
  3147. dol_print_error('', $errmsg);
  3148. exit;
  3149. }
  3150. $sqlfix = "UPDATE ".MAIN_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);
  3151. 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);
  3152. $resqlfix = $this->db->query($sqlfix);
  3153. if (!$resqlfix) {
  3154. dol_print_error($this->db, 'Failed to update line');
  3155. }
  3156. $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1);
  3157. $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1);
  3158. $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1);
  3159. $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1);
  3160. }
  3161. }
  3162. $i++;
  3163. }
  3164. // Add revenue stamp to total
  3165. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  3166. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  3167. // Situations totals
  3168. if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
  3169. $prev_sits = $this->get_prev_sits();
  3170. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  3171. $this->total_ht -= $sit->total_ht;
  3172. $this->total_tva -= $sit->total_tva;
  3173. $this->total_localtax1 -= $sit->total_localtax1;
  3174. $this->total_localtax2 -= $sit->total_localtax2;
  3175. $this->total_ttc -= $sit->total_ttc;
  3176. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  3177. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  3178. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  3179. }
  3180. }
  3181. // Clean total
  3182. $this->total_ht = (float) price2num($this->total_ht);
  3183. $this->total_tva = (float) price2num($this->total_tva);
  3184. $this->total_localtax1 = (float) price2num($this->total_localtax1);
  3185. $this->total_localtax2 = (float) price2num($this->total_localtax2);
  3186. $this->total_ttc = (float) price2num($this->total_ttc);
  3187. $this->db->free($resql);
  3188. // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_*
  3189. $fieldht = 'total_ht';
  3190. $fieldtva = 'tva';
  3191. $fieldlocaltax1 = 'localtax1';
  3192. $fieldlocaltax2 = 'localtax2';
  3193. $fieldttc = 'total_ttc';
  3194. // Specific code for backward compatibility with old field names
  3195. if ($this->element == 'facture' || $this->element == 'facturerec') {
  3196. $fieldtva = 'total_tva';
  3197. }
  3198. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3199. $fieldtva = 'total_tva';
  3200. }
  3201. if ($this->element == 'propal') {
  3202. $fieldtva = 'total_tva';
  3203. }
  3204. if ($this->element == 'expensereport') {
  3205. $fieldtva = 'total_tva';
  3206. }
  3207. if ($this->element == 'supplier_proposal') {
  3208. $fieldtva = 'total_tva';
  3209. }
  3210. if ($this->element == 'commande') {
  3211. $fieldtva = 'total_tva';
  3212. }
  3213. if ($this->element == 'order_supplier') {
  3214. $fieldtva = 'total_tva';
  3215. }
  3216. if (empty($nodatabaseupdate)) {
  3217. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element.' SET';
  3218. $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht, 'MT', 1)).",";
  3219. $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva, 'MT', 1)).",";
  3220. $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1, 'MT', 1)).",";
  3221. $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2, 'MT', 1)).",";
  3222. $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc, 'MT', 1));
  3223. $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
  3224. $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
  3225. $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
  3226. $sql .= " WHERE rowid = ".((int) $this->id);
  3227. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3228. $resql = $this->db->query($sql);
  3229. if (!$resql) {
  3230. $error++;
  3231. $this->error = $this->db->lasterror();
  3232. $this->errors[] = $this->db->lasterror();
  3233. }
  3234. }
  3235. if (!$error) {
  3236. return 1;
  3237. } else {
  3238. return -1;
  3239. }
  3240. } else {
  3241. dol_print_error($this->db, 'Bad request in update_price');
  3242. return -1;
  3243. }
  3244. }
  3245. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3246. /**
  3247. * Add objects linked in llx_element_element.
  3248. *
  3249. * @param string $origin Linked element type
  3250. * @param int $origin_id Linked element id
  3251. * @param User $f_user User that create
  3252. * @param int $notrigger 1=Does not execute triggers, 0=execute triggers
  3253. * @return int <=0 if KO, >0 if OK
  3254. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  3255. */
  3256. public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
  3257. {
  3258. // phpcs:enable
  3259. global $user, $hookmanager, $action;
  3260. $origin = (!empty($origin) ? $origin : $this->origin);
  3261. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  3262. $f_user = isset($f_user) ? $f_user : $user;
  3263. // Special case
  3264. if ($origin == 'order') {
  3265. $origin = 'commande';
  3266. }
  3267. if ($origin == 'invoice') {
  3268. $origin = 'facture';
  3269. }
  3270. if ($origin == 'invoice_template') {
  3271. $origin = 'facturerec';
  3272. }
  3273. if ($origin == 'supplierorder') {
  3274. $origin = 'order_supplier';
  3275. }
  3276. // 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.
  3277. // 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.
  3278. $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization');
  3279. // Add module part to target type if object has $module property and isn't in core modules.
  3280. $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
  3281. $parameters = array('targettype'=>$targettype);
  3282. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3283. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3284. if ($reshook > 0) {
  3285. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3286. }
  3287. $this->db->begin();
  3288. $error = 0;
  3289. $sql = "INSERT INTO " . MAIN_DB_PREFIX . "element_element (";
  3290. $sql .= "fk_source";
  3291. $sql .= ", sourcetype";
  3292. $sql .= ", fk_target";
  3293. $sql .= ", targettype";
  3294. $sql .= ") VALUES (";
  3295. $sql .= ((int) $origin_id);
  3296. $sql .= ", '" . $this->db->escape($origin) . "'";
  3297. $sql .= ", " . ((int) $this->id);
  3298. $sql .= ", '" . $this->db->escape($targettype) . "'";
  3299. $sql .= ")";
  3300. dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
  3301. if ($this->db->query($sql)) {
  3302. if (!$notrigger) {
  3303. // Call trigger
  3304. $this->context['link_origin'] = $origin;
  3305. $this->context['link_origin_id'] = $origin_id;
  3306. $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
  3307. if ($result < 0) {
  3308. $error++;
  3309. }
  3310. // End call triggers
  3311. }
  3312. } else {
  3313. $this->error = $this->db->lasterror();
  3314. $error++;
  3315. }
  3316. if (!$error) {
  3317. $this->db->commit();
  3318. return 1;
  3319. } else {
  3320. $this->db->rollback();
  3321. return 0;
  3322. }
  3323. }
  3324. /**
  3325. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  3326. * this->linkedObjectsIds array +
  3327. * this->linkedObjects array if $loadalsoobjects = 1 or $loadalsoobjects = type
  3328. * Possible usage for parameters:
  3329. * - all parameters empty -> we look all link to current object (current object can be source or target)
  3330. * - source id+type -> will get list of targets linked to source
  3331. * - target id+type -> will get list of sources linked to target
  3332. * - source id+type + target type -> will get list of targets of the type linked to source
  3333. * - target id+type + source type -> will get list of sources of the type linked to target
  3334. *
  3335. * @param int $sourceid Object source id (if not defined, id of object)
  3336. * @param string $sourcetype Object source type (if not defined, element name of object)
  3337. * @param int $targetid Object target id (if not defined, id of object)
  3338. * @param string $targettype Object target type (if not defined, element name of object)
  3339. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  3340. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  3341. * @param string $orderby SQL 'ORDER BY' clause
  3342. * @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.
  3343. * @return int <0 if KO, >0 if OK
  3344. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  3345. */
  3346. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  3347. {
  3348. global $conf, $hookmanager, $action;
  3349. $this->linkedObjectsIds = array();
  3350. $this->linkedObjects = array();
  3351. $justsource = false;
  3352. $justtarget = false;
  3353. $withtargettype = false;
  3354. $withsourcetype = false;
  3355. $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
  3356. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3357. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3358. if ($reshook > 0) {
  3359. if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
  3360. if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
  3361. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3362. if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
  3363. }
  3364. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
  3365. $justsource = true; // the source (id and type) is a search criteria
  3366. if (!empty($targettype)) {
  3367. $withtargettype = true;
  3368. }
  3369. }
  3370. if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
  3371. $justtarget = true; // the target (id and type) is a search criteria
  3372. if (!empty($sourcetype)) {
  3373. $withsourcetype = true;
  3374. }
  3375. }
  3376. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3377. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3378. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3379. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3380. /*if (empty($sourceid) && empty($targetid))
  3381. {
  3382. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  3383. return -1;
  3384. }*/
  3385. // Links between objects are stored in table element_element
  3386. $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype';
  3387. $sql .= ' FROM '.MAIN_DB_PREFIX.'element_element';
  3388. $sql .= " WHERE ";
  3389. if ($justsource || $justtarget) {
  3390. if ($justsource) {
  3391. $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3392. if ($withtargettype) {
  3393. $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
  3394. }
  3395. } elseif ($justtarget) {
  3396. $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
  3397. if ($withsourcetype) {
  3398. $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3399. }
  3400. }
  3401. } else {
  3402. $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
  3403. $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
  3404. }
  3405. $sql .= ' ORDER BY '.$orderby;
  3406. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  3407. $resql = $this->db->query($sql);
  3408. if ($resql) {
  3409. $num = $this->db->num_rows($resql);
  3410. $i = 0;
  3411. while ($i < $num) {
  3412. $obj = $this->db->fetch_object($resql);
  3413. if ($justsource || $justtarget) {
  3414. if ($justsource) {
  3415. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3416. } elseif ($justtarget) {
  3417. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3418. }
  3419. } else {
  3420. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
  3421. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3422. }
  3423. if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
  3424. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3425. }
  3426. }
  3427. $i++;
  3428. }
  3429. if (!empty($this->linkedObjectsIds)) {
  3430. $tmparray = $this->linkedObjectsIds;
  3431. foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  3432. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  3433. $module = $element = $subelement = $objecttype;
  3434. $regs = array();
  3435. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  3436. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  3437. $module = $element = $regs[1];
  3438. $subelement = $regs[2];
  3439. }
  3440. $classpath = $element.'/class';
  3441. // To work with non standard classpath or module name
  3442. if ($objecttype == 'facture') {
  3443. $classpath = 'compta/facture/class';
  3444. } elseif ($objecttype == 'facturerec') {
  3445. $classpath = 'compta/facture/class';
  3446. $module = 'facture';
  3447. } elseif ($objecttype == 'propal') {
  3448. $classpath = 'comm/propal/class';
  3449. } elseif ($objecttype == 'supplier_proposal') {
  3450. $classpath = 'supplier_proposal/class';
  3451. } elseif ($objecttype == 'shipping') {
  3452. $classpath = 'expedition/class';
  3453. $subelement = 'expedition';
  3454. $module = 'expedition_bon';
  3455. } elseif ($objecttype == 'delivery') {
  3456. $classpath = 'delivery/class';
  3457. $subelement = 'delivery';
  3458. $module = 'delivery_note';
  3459. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  3460. $classpath = 'fourn/class';
  3461. $module = 'fournisseur';
  3462. } elseif ($objecttype == 'fichinter') {
  3463. $classpath = 'fichinter/class';
  3464. $subelement = 'fichinter';
  3465. $module = 'ficheinter';
  3466. } elseif ($objecttype == 'subscription') {
  3467. $classpath = 'adherents/class';
  3468. $module = 'adherent';
  3469. } elseif ($objecttype == 'contact') {
  3470. $module = 'societe';
  3471. }
  3472. // Set classfile
  3473. $classfile = strtolower($subelement);
  3474. $classname = ucfirst($subelement);
  3475. if ($objecttype == 'order') {
  3476. $classfile = 'commande';
  3477. $classname = 'Commande';
  3478. } elseif ($objecttype == 'invoice_supplier') {
  3479. $classfile = 'fournisseur.facture';
  3480. $classname = 'FactureFournisseur';
  3481. } elseif ($objecttype == 'order_supplier') {
  3482. $classfile = 'fournisseur.commande';
  3483. $classname = 'CommandeFournisseur';
  3484. } elseif ($objecttype == 'supplier_proposal') {
  3485. $classfile = 'supplier_proposal';
  3486. $classname = 'SupplierProposal';
  3487. } elseif ($objecttype == 'facturerec') {
  3488. $classfile = 'facture-rec';
  3489. $classname = 'FactureRec';
  3490. } elseif ($objecttype == 'subscription') {
  3491. $classfile = 'subscription';
  3492. $classname = 'Subscription';
  3493. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  3494. $classpath = 'projet/class';
  3495. $classfile = 'project';
  3496. $classname = 'Project';
  3497. } elseif ($objecttype == 'conferenceorboothattendee') {
  3498. $classpath = 'eventorganization/class';
  3499. $classfile = 'conferenceorboothattendee';
  3500. $classname = 'ConferenceOrBoothAttendee';
  3501. $module = 'eventorganization';
  3502. } elseif ($objecttype == 'conferenceorbooth') {
  3503. $classpath = 'eventorganization/class';
  3504. $classfile = 'conferenceorbooth';
  3505. $classname = 'ConferenceOrBooth';
  3506. $module = 'eventorganization';
  3507. } elseif ($objecttype == 'mo') {
  3508. $classpath = 'mrp/class';
  3509. $classfile = 'mo';
  3510. $classname = 'Mo';
  3511. $module = 'mrp';
  3512. }
  3513. // Here $module, $classfile and $classname are set, we can use them.
  3514. if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
  3515. if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
  3516. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  3517. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  3518. if (class_exists($classname)) {
  3519. foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
  3520. $object = new $classname($this->db);
  3521. $ret = $object->fetch($objectid);
  3522. if ($ret >= 0) {
  3523. $this->linkedObjects[$objecttype][$i] = $object;
  3524. }
  3525. }
  3526. }
  3527. }
  3528. } else {
  3529. unset($this->linkedObjectsIds[$objecttype]);
  3530. }
  3531. }
  3532. }
  3533. return 1;
  3534. } else {
  3535. dol_print_error($this->db);
  3536. return -1;
  3537. }
  3538. }
  3539. /**
  3540. * Update object linked of a current object
  3541. *
  3542. * @param int $sourceid Object source id
  3543. * @param string $sourcetype Object source type
  3544. * @param int $targetid Object target id
  3545. * @param string $targettype Object target type
  3546. * @param User $f_user User that create
  3547. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3548. * @return int >0 if OK, <0 if KO
  3549. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3550. */
  3551. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
  3552. {
  3553. global $user;
  3554. $updatesource = false;
  3555. $updatetarget = false;
  3556. $f_user = isset($f_user) ? $f_user : $user;
  3557. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3558. $updatesource = true;
  3559. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3560. $updatetarget = true;
  3561. }
  3562. $this->db->begin();
  3563. $error = 0;
  3564. $sql = "UPDATE " . MAIN_DB_PREFIX . "element_element SET ";
  3565. if ($updatesource) {
  3566. $sql .= "fk_source = " . ((int) $sourceid);
  3567. $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3568. $sql .= " WHERE fk_target = " . ((int) $this->id);
  3569. $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
  3570. } elseif ($updatetarget) {
  3571. $sql .= "fk_target = " . ((int) $targetid);
  3572. $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
  3573. $sql .= " WHERE fk_source = " . ((int) $this->id);
  3574. $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3575. }
  3576. dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
  3577. if ($this->db->query($sql)) {
  3578. if (!$notrigger) {
  3579. // Call trigger
  3580. $this->context['link_source_id'] = $sourceid;
  3581. $this->context['link_source_type'] = $sourcetype;
  3582. $this->context['link_target_id'] = $targetid;
  3583. $this->context['link_target_type'] = $targettype;
  3584. $result = $this->call_trigger('OBJECT_LINK_UPDATE', $f_user);
  3585. if ($result < 0) {
  3586. $error++;
  3587. }
  3588. // End call triggers
  3589. }
  3590. } else {
  3591. $this->error = $this->db->lasterror();
  3592. $error++;
  3593. }
  3594. if (!$error) {
  3595. $this->db->commit();
  3596. return 1;
  3597. } else {
  3598. $this->db->rollback();
  3599. return -1;
  3600. }
  3601. }
  3602. /**
  3603. * Delete all links between an object $this
  3604. *
  3605. * @param int $sourceid Object source id
  3606. * @param string $sourcetype Object source type
  3607. * @param int $targetid Object target id
  3608. * @param string $targettype Object target type
  3609. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3610. * @param User $f_user User that create
  3611. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3612. * @return int >0 if OK, <0 if KO
  3613. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3614. */
  3615. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
  3616. {
  3617. global $user;
  3618. $deletesource = false;
  3619. $deletetarget = false;
  3620. $f_user = isset($f_user) ? $f_user : $user;
  3621. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3622. $deletesource = true;
  3623. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3624. $deletetarget = true;
  3625. }
  3626. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3627. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3628. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3629. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3630. $this->db->begin();
  3631. $error = 0;
  3632. if (!$notrigger) {
  3633. // Call trigger
  3634. $this->context['link_id'] = $rowid;
  3635. $this->context['link_source_id'] = $sourceid;
  3636. $this->context['link_source_type'] = $sourcetype;
  3637. $this->context['link_target_id'] = $targetid;
  3638. $this->context['link_target_type'] = $targettype;
  3639. $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
  3640. if ($result < 0) {
  3641. $error++;
  3642. }
  3643. // End call triggers
  3644. }
  3645. if (!$error) {
  3646. $sql = "DELETE FROM " . MAIN_DB_PREFIX . "element_element";
  3647. $sql .= " WHERE";
  3648. if ($rowid > 0) {
  3649. $sql .= " rowid = " . ((int) $rowid);
  3650. } else {
  3651. if ($deletesource) {
  3652. $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3653. $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
  3654. } elseif ($deletetarget) {
  3655. $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
  3656. $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3657. } else {
  3658. $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
  3659. $sql .= " OR";
  3660. $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
  3661. }
  3662. }
  3663. dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
  3664. if (!$this->db->query($sql)) {
  3665. $this->error = $this->db->lasterror();
  3666. $this->errors[] = $this->error;
  3667. $error++;
  3668. }
  3669. }
  3670. if (!$error) {
  3671. $this->db->commit();
  3672. return 1;
  3673. } else {
  3674. $this->db->rollback();
  3675. return 0;
  3676. }
  3677. }
  3678. /**
  3679. * Function used to get an array with all items linked to an object id in association table
  3680. *
  3681. * @param int $fk_object_where id of object we need to get linked items
  3682. * @param string $field_select name of field we need to get a list
  3683. * @param string $field_where name of field of object we need to get linked items
  3684. * @param string $table_element name of association table
  3685. * @return array Array of record
  3686. */
  3687. public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
  3688. {
  3689. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3690. return -1;
  3691. }
  3692. global $db;
  3693. $sql = "SELECT ".$field_select." FROM ".MAIN_DB_PREFIX.$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3694. $resql = $db->query($sql);
  3695. $TRes = array();
  3696. if (!empty($resql)) {
  3697. while ($res = $db->fetch_object($resql)) {
  3698. $TRes[] = $res->{$field_select};
  3699. }
  3700. }
  3701. return $TRes;
  3702. }
  3703. /**
  3704. * Function used to remove all items linked to an object id in association table
  3705. *
  3706. * @param int $fk_object_where id of object we need to remove linked items
  3707. * @param string $field_where name of field of object we need to delete linked items
  3708. * @param string $table_element name of association table
  3709. * @return int <0 if KO, 0 if nothing done, >0 if OK and something done
  3710. */
  3711. public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
  3712. {
  3713. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3714. return -1;
  3715. }
  3716. global $db;
  3717. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3718. $resql = $db->query($sql);
  3719. if (empty($resql)) {
  3720. return 0;
  3721. }
  3722. return 1;
  3723. }
  3724. /**
  3725. * Set status of an object
  3726. *
  3727. * @param int $status Status to set
  3728. * @param int $elementId Id of element to force (use this->id by default if null)
  3729. * @param string $elementType Type of element to force (use this->table_element by default)
  3730. * @param string $trigkey Trigger key to use for trigger. Use '' means automatic but it is not recommended and is deprecated.
  3731. * @param string $fieldstatus Name of status field in this->table_element
  3732. * @return int <0 if KO, >0 if OK
  3733. */
  3734. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
  3735. {
  3736. global $user, $langs, $conf;
  3737. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3738. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3739. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3740. $this->db->begin();
  3741. if ($elementTable == 'facture_rec') {
  3742. $fieldstatus = "suspended";
  3743. }
  3744. if ($elementTable == 'mailing') {
  3745. $fieldstatus = "statut";
  3746. }
  3747. if ($elementTable == 'cronjob') {
  3748. $fieldstatus = "status";
  3749. }
  3750. if ($elementTable == 'user') {
  3751. $fieldstatus = "statut";
  3752. }
  3753. if ($elementTable == 'expensereport') {
  3754. $fieldstatus = "fk_statut";
  3755. }
  3756. if ($elementTable == 'commande_fournisseur_dispatch') {
  3757. $fieldstatus = "status";
  3758. }
  3759. if (is_array($this->fields) && array_key_exists('status', $this->fields)) {
  3760. $fieldstatus = 'status';
  3761. }
  3762. $sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable;
  3763. $sql .= " SET ".$fieldstatus." = ".((int) $status);
  3764. // If status = 1 = validated, update also fk_user_valid
  3765. // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
  3766. if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
  3767. $sql .= ", fk_user_valid = ".((int) $user->id);
  3768. }
  3769. if ($status == 1 && in_array($elementTable, array('expensereport'))) {
  3770. $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
  3771. }
  3772. if ($status == 1 && in_array($elementTable, array('inventory'))) {
  3773. $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
  3774. }
  3775. $sql .= " WHERE rowid = ".((int) $elementId);
  3776. $sql .= " AND ".$fieldstatus." <> ".((int) $status); // We avoid update if status already correct
  3777. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  3778. $resql = $this->db->query($sql);
  3779. if ($resql) {
  3780. $error = 0;
  3781. $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
  3782. if ($nb_rows_affected >= 0) {
  3783. if (empty($trigkey)) {
  3784. // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
  3785. if ($this->element == 'supplier_proposal' && $status == 2) {
  3786. $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3787. }
  3788. if ($this->element == 'supplier_proposal' && $status == 3) {
  3789. $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3790. }
  3791. if ($this->element == 'supplier_proposal' && $status == 4) {
  3792. $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3793. }
  3794. if ($this->element == 'fichinter' && $status == 3) {
  3795. $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3796. }
  3797. if ($this->element == 'fichinter' && $status == 2) {
  3798. $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3799. }
  3800. if ($this->element == 'fichinter' && $status == 1) {
  3801. $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3802. }
  3803. }
  3804. if ($trigkey) {
  3805. // Call trigger
  3806. $result = $this->call_trigger($trigkey, $user);
  3807. if ($result < 0) {
  3808. $error++;
  3809. }
  3810. // End call triggers
  3811. }
  3812. } else {
  3813. // The status was probably already good. We do nothing more, no triggers.
  3814. }
  3815. if (!$error) {
  3816. $this->db->commit();
  3817. if (empty($savElementId)) {
  3818. // If the element we update is $this (so $elementId was provided as null)
  3819. if ($fieldstatus == 'tosell') {
  3820. $this->status = $status;
  3821. } elseif ($fieldstatus == 'tobuy') {
  3822. $this->status_buy = $status;
  3823. } else {
  3824. $this->statut = $status;
  3825. $this->status = $status;
  3826. }
  3827. }
  3828. return 1;
  3829. } else {
  3830. $this->db->rollback();
  3831. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  3832. return -1;
  3833. }
  3834. } else {
  3835. $this->error = $this->db->lasterror();
  3836. $this->db->rollback();
  3837. return -1;
  3838. }
  3839. }
  3840. /**
  3841. * Load type of canvas of an object if it exists
  3842. *
  3843. * @param int $id Record id
  3844. * @param string $ref Record ref
  3845. * @return int <0 if KO, 0 if nothing done, >0 if OK
  3846. */
  3847. public function getCanvas($id = 0, $ref = '')
  3848. {
  3849. global $conf;
  3850. if (empty($id) && empty($ref)) {
  3851. return 0;
  3852. }
  3853. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
  3854. return 0; // To increase speed. Not enabled by default.
  3855. }
  3856. // Clean parameters
  3857. $ref = trim($ref);
  3858. $sql = "SELECT rowid, canvas";
  3859. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
  3860. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  3861. if (!empty($id)) {
  3862. $sql .= " AND rowid = ".((int) $id);
  3863. }
  3864. if (!empty($ref)) {
  3865. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  3866. }
  3867. $resql = $this->db->query($sql);
  3868. if ($resql) {
  3869. $obj = $this->db->fetch_object($resql);
  3870. if ($obj) {
  3871. $this->canvas = $obj->canvas;
  3872. return 1;
  3873. } else {
  3874. return 0;
  3875. }
  3876. } else {
  3877. dol_print_error($this->db);
  3878. return -1;
  3879. }
  3880. }
  3881. /**
  3882. * Get special code of a line
  3883. *
  3884. * @param int $lineid Id of line
  3885. * @return int Special code
  3886. */
  3887. public function getSpecialCode($lineid)
  3888. {
  3889. $sql = "SELECT special_code FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  3890. $sql .= " WHERE rowid = ".((int) $lineid);
  3891. $resql = $this->db->query($sql);
  3892. if ($resql) {
  3893. $row = $this->db->fetch_row($resql);
  3894. return $row[0];
  3895. }
  3896. }
  3897. /**
  3898. * Function to check if an object is used by others.
  3899. * Check is done into this->childtables. There is no check into llx_element_element.
  3900. *
  3901. * @param int $id Force id of object
  3902. * @return int <0 if KO, 0 if not used, >0 if already used
  3903. */
  3904. public function isObjectUsed($id = 0)
  3905. {
  3906. global $langs;
  3907. if (empty($id)) {
  3908. $id = $this->id;
  3909. }
  3910. // Check parameters
  3911. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
  3912. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  3913. return -1;
  3914. }
  3915. $arraytoscan = $this->childtables;
  3916. // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
  3917. $tmparray = array_keys($this->childtables);
  3918. if (is_numeric($tmparray[0])) {
  3919. $arraytoscan = array_flip($this->childtables);
  3920. }
  3921. // Test if child exists
  3922. $haschild = 0;
  3923. foreach ($arraytoscan as $table => $elementname) {
  3924. //print $id.'-'.$table.'-'.$elementname.'<br>';
  3925. // Check if third party can be deleted
  3926. $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table;
  3927. $sql .= " WHERE ".$this->fk_element." = ".((int) $id);
  3928. $resql = $this->db->query($sql);
  3929. if ($resql) {
  3930. $obj = $this->db->fetch_object($resql);
  3931. if ($obj->nb > 0) {
  3932. $langs->load("errors");
  3933. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  3934. $haschild += $obj->nb;
  3935. if (is_numeric($elementname)) { // old usage
  3936. $this->errors[] = $langs->transnoentities("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
  3937. } else // new usage: $elementname=Translation key
  3938. {
  3939. $this->errors[] = $langs->transnoentities("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($elementname));
  3940. }
  3941. break; // We found at least one, we stop here
  3942. }
  3943. } else {
  3944. $this->errors[] = $this->db->lasterror();
  3945. return -1;
  3946. }
  3947. }
  3948. if ($haschild > 0) {
  3949. $this->errors[] = "ErrorRecordHasChildren";
  3950. return $haschild;
  3951. } else {
  3952. return 0;
  3953. }
  3954. }
  3955. /**
  3956. * Function to say how many lines object contains
  3957. *
  3958. * @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
  3959. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  3960. */
  3961. public function hasProductsOrServices($predefined = -1)
  3962. {
  3963. $nb = 0;
  3964. foreach ($this->lines as $key => $val) {
  3965. $qualified = 0;
  3966. if ($predefined == -1) {
  3967. $qualified = 1;
  3968. }
  3969. if ($predefined == 1 && $val->fk_product > 0) {
  3970. $qualified = 1;
  3971. }
  3972. if ($predefined == 0 && $val->fk_product <= 0) {
  3973. $qualified = 1;
  3974. }
  3975. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
  3976. $qualified = 1;
  3977. }
  3978. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
  3979. $qualified = 1;
  3980. }
  3981. if ($qualified) {
  3982. $nb++;
  3983. }
  3984. }
  3985. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  3986. return $nb;
  3987. }
  3988. /**
  3989. * Function that returns the total amount HT of discounts applied for all lines.
  3990. *
  3991. * @return float|string Total amout of discount
  3992. */
  3993. public function getTotalDiscount()
  3994. {
  3995. if (!empty($this->table_element_line) ) {
  3996. $total_discount = 0.00;
  3997. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  3998. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  3999. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  4000. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  4001. $resql = $this->db->query($sql);
  4002. if ($resql) {
  4003. $num = $this->db->num_rows($resql);
  4004. $i = 0;
  4005. while ($i < $num) {
  4006. $obj = $this->db->fetch_object($resql);
  4007. $pu_ht = $obj->pu_ht;
  4008. $qty = $obj->qty;
  4009. $total_ht = $obj->total_ht;
  4010. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  4011. $total_discount += $total_discount_line;
  4012. $i++;
  4013. }
  4014. }
  4015. //print $total_discount; exit;
  4016. return price2num($total_discount);
  4017. }
  4018. return null;
  4019. }
  4020. /**
  4021. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  4022. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  4023. *
  4024. * @return array array('weight'=>...,'volume'=>...)
  4025. */
  4026. public function getTotalWeightVolume()
  4027. {
  4028. $totalWeight = 0;
  4029. $totalVolume = 0;
  4030. // defined for shipment only
  4031. $totalOrdered = '';
  4032. // defined for shipment only
  4033. $totalToShip = '';
  4034. foreach ($this->lines as $line) {
  4035. if (isset($line->qty_asked)) {
  4036. if (empty($totalOrdered)) {
  4037. $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  4038. }
  4039. $totalOrdered += $line->qty_asked; // defined for shipment only
  4040. }
  4041. if (isset($line->qty_shipped)) {
  4042. if (empty($totalToShip)) {
  4043. $totalToShip = 0; // Avoid warning because $totalToShip is ''
  4044. }
  4045. $totalToShip += $line->qty_shipped; // defined for shipment only
  4046. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
  4047. if (empty($totalToShip)) {
  4048. $totalToShip = 0;
  4049. }
  4050. $totalToShip += $line->qty; // defined for reception only
  4051. }
  4052. // Define qty, weight, volume, weight_units, volume_units
  4053. if ($this->element == 'shipping') {
  4054. // for shipments
  4055. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  4056. } else {
  4057. $qty = $line->qty ? $line->qty : 0;
  4058. }
  4059. $weight = !empty($line->weight) ? $line->weight : 0;
  4060. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  4061. $volume = !empty($line->volume) ? $line->volume : 0;
  4062. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  4063. $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
  4064. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  4065. $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
  4066. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  4067. $weightUnit = 0;
  4068. $volumeUnit = 0;
  4069. if (!empty($weight_units)) {
  4070. $weightUnit = $weight_units;
  4071. }
  4072. if (!empty($volume_units)) {
  4073. $volumeUnit = $volume_units;
  4074. }
  4075. if (empty($totalWeight)) {
  4076. $totalWeight = 0; // Avoid warning because $totalWeight is ''
  4077. }
  4078. if (empty($totalVolume)) {
  4079. $totalVolume = 0; // Avoid warning because $totalVolume is ''
  4080. }
  4081. //var_dump($line->volume_units);
  4082. if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4083. $trueWeightUnit = pow(10, $weightUnit);
  4084. $totalWeight += $weight * $qty * $trueWeightUnit;
  4085. } else {
  4086. if ($weight_units == 99) {
  4087. // conversion 1 Pound = 0.45359237 KG
  4088. $trueWeightUnit = 0.45359237;
  4089. $totalWeight += $weight * $qty * $trueWeightUnit;
  4090. } elseif ($weight_units == 98) {
  4091. // conversion 1 Ounce = 0.0283495 KG
  4092. $trueWeightUnit = 0.0283495;
  4093. $totalWeight += $weight * $qty * $trueWeightUnit;
  4094. } else {
  4095. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  4096. }
  4097. }
  4098. if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4099. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  4100. $trueVolumeUnit = pow(10, $volumeUnit);
  4101. //print $line->volume;
  4102. $totalVolume += $volume * $qty * $trueVolumeUnit;
  4103. } else {
  4104. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  4105. }
  4106. }
  4107. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  4108. }
  4109. /**
  4110. * Set extra parameters
  4111. *
  4112. * @return int <0 if KO, >0 if OK
  4113. */
  4114. public function setExtraParameters()
  4115. {
  4116. $this->db->begin();
  4117. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  4118. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  4119. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  4120. $sql .= " WHERE rowid = ".((int) $this->id);
  4121. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  4122. $resql = $this->db->query($sql);
  4123. if (!$resql) {
  4124. $this->error = $this->db->lasterror();
  4125. $this->db->rollback();
  4126. return -1;
  4127. } else {
  4128. $this->db->commit();
  4129. return 1;
  4130. }
  4131. }
  4132. // --------------------
  4133. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  4134. // --------------------
  4135. /* This is to show add lines */
  4136. /**
  4137. * Show add free and predefined products/services form
  4138. *
  4139. * @param int $dateSelector 1=Show also date range input fields
  4140. * @param Societe $seller Object thirdparty who sell
  4141. * @param Societe $buyer Object thirdparty who buy
  4142. * @param string $defaulttpldir Directory where to find the template
  4143. * @return void
  4144. */
  4145. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  4146. {
  4147. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  4148. global $form;
  4149. // Line extrafield
  4150. if (!is_object($extrafields)) {
  4151. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4152. $extrafields = new ExtraFields($this->db);
  4153. }
  4154. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4155. // Output template part (modules that overwrite templates must declare this into descriptor)
  4156. // Use global variables + $dateSelector + $seller and $buyer
  4157. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  4158. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4159. foreach ($dirtpls as $module => $reldir) {
  4160. if (!empty($module)) {
  4161. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  4162. } else {
  4163. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  4164. }
  4165. if (empty($conf->file->strict_mode)) {
  4166. $res = @include $tpl;
  4167. } else {
  4168. $res = include $tpl; // for debug
  4169. }
  4170. if ($res) {
  4171. break;
  4172. }
  4173. }
  4174. }
  4175. /* This is to show array of line of details */
  4176. /**
  4177. * Return HTML table for object lines
  4178. * TODO Move this into an output class file (htmlline.class.php)
  4179. * If lines are into a template, title must also be into a template
  4180. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4181. *
  4182. * @param string $action Action code
  4183. * @param string $seller Object of seller third party
  4184. * @param string $buyer Object of buyer third party
  4185. * @param int $selected Object line selected
  4186. * @param int $dateSelector 1=Show also date range input fields
  4187. * @param string $defaulttpldir Directory where to find the template
  4188. * @return void
  4189. */
  4190. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  4191. {
  4192. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  4193. // TODO We should not use global var for this
  4194. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  4195. // Define usemargins
  4196. $usemargins = 0;
  4197. if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
  4198. $usemargins = 1;
  4199. }
  4200. $num = count($this->lines);
  4201. // Line extrafield
  4202. if (!is_object($extrafields)) {
  4203. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4204. $extrafields = new ExtraFields($this->db);
  4205. }
  4206. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4207. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  4208. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4209. if (empty($reshook)) {
  4210. // Output template part (modules that overwrite templates must declare this into descriptor)
  4211. // Use global variables + $dateSelector + $seller and $buyer
  4212. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  4213. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4214. foreach ($dirtpls as $module => $reldir) {
  4215. if (!empty($module)) {
  4216. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  4217. } else {
  4218. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  4219. }
  4220. if (empty($conf->file->strict_mode)) {
  4221. $res = @include $tpl;
  4222. } else {
  4223. $res = include $tpl; // for debug
  4224. }
  4225. if ($res) {
  4226. break;
  4227. }
  4228. }
  4229. }
  4230. $i = 0;
  4231. print "<!-- begin printObjectLines() --><tbody>\n";
  4232. foreach ($this->lines as $line) {
  4233. //Line extrafield
  4234. $line->fetch_optionals();
  4235. //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  4236. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4237. if (empty($line->fk_parent_line)) {
  4238. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  4239. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4240. } else {
  4241. $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);
  4242. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4243. }
  4244. }
  4245. if (empty($reshook)) {
  4246. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  4247. }
  4248. $i++;
  4249. }
  4250. print "</tbody><!-- end printObjectLines() -->\n";
  4251. }
  4252. /**
  4253. * Return HTML content of a detail line
  4254. * TODO Move this into an output class file (htmlline.class.php)
  4255. *
  4256. * @param string $action GET/POST action
  4257. * @param CommonObjectLine $line Selected object line to output
  4258. * @param string $var Is it a an odd line (true)
  4259. * @param int $num Number of line (0)
  4260. * @param int $i I
  4261. * @param int $dateSelector 1=Show also date range input fields
  4262. * @param string $seller Object of seller third party
  4263. * @param string $buyer Object of buyer third party
  4264. * @param int $selected Object line selected
  4265. * @param Extrafields $extrafields Object of extrafields
  4266. * @param string $defaulttpldir Directory where to find the template (deprecated)
  4267. * @return void
  4268. */
  4269. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  4270. {
  4271. global $conf, $langs, $user, $object, $hookmanager;
  4272. global $form;
  4273. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  4274. $object_rights = $this->getRights();
  4275. $element = $this->element;
  4276. $text = '';
  4277. $description = '';
  4278. // Line in view mode
  4279. if ($action != 'editline' || $selected != $line->id) {
  4280. // Product
  4281. if ($line->fk_product > 0) {
  4282. $product_static = new Product($this->db);
  4283. $product_static->fetch($line->fk_product);
  4284. $product_static->ref = $line->ref; //can change ref in hook
  4285. $product_static->label = $line->label; //can change label in hook
  4286. $text = $product_static->getNomUrl(1);
  4287. // Define output language and label
  4288. if (!empty($conf->global->MAIN_MULTILANGS)) {
  4289. if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
  4290. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  4291. return;
  4292. }
  4293. $prod = new Product($this->db);
  4294. $prod->fetch($line->fk_product);
  4295. $outputlangs = $langs;
  4296. $newlang = '';
  4297. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  4298. $newlang = GETPOST('lang_id', 'aZ09');
  4299. }
  4300. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
  4301. $newlang = $this->thirdparty->default_lang; // To use language of customer
  4302. }
  4303. if (!empty($newlang)) {
  4304. $outputlangs = new Translate("", $conf);
  4305. $outputlangs->setDefaultLang($newlang);
  4306. }
  4307. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  4308. } else {
  4309. $label = $line->product_label;
  4310. }
  4311. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  4312. $description .= (!empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : dol_htmlentitiesbr($line->description)); // Description is what to show on popup. We shown nothing if already into desc.
  4313. }
  4314. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4315. // Output template part (modules that overwrite templates must declare this into descriptor)
  4316. // Use global variables + $dateSelector + $seller and $buyer
  4317. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4318. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4319. foreach ($dirtpls as $module => $reldir) {
  4320. if (!empty($module)) {
  4321. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  4322. } else {
  4323. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  4324. }
  4325. if (empty($conf->file->strict_mode)) {
  4326. $res = @include $tpl;
  4327. } else {
  4328. $res = include $tpl; // for debug
  4329. }
  4330. if ($res) {
  4331. break;
  4332. }
  4333. }
  4334. }
  4335. // Line in update mode
  4336. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
  4337. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  4338. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4339. // Output template part (modules that overwrite templates must declare this into descriptor)
  4340. // Use global variables + $dateSelector + $seller and $buyer
  4341. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4342. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4343. foreach ($dirtpls as $module => $reldir) {
  4344. if (!empty($module)) {
  4345. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  4346. } else {
  4347. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  4348. }
  4349. if (empty($conf->file->strict_mode)) {
  4350. $res = @include $tpl;
  4351. } else {
  4352. $res = include $tpl; // for debug
  4353. }
  4354. if ($res) {
  4355. break;
  4356. }
  4357. }
  4358. }
  4359. }
  4360. /* This is to show array of line of details of source object */
  4361. /**
  4362. * Return HTML table table of source object lines
  4363. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4364. * If lines are into a template, title must also be into a template
  4365. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  4366. *
  4367. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  4368. * @param array $selectedLines Array of lines id for selected lines
  4369. * @return void
  4370. */
  4371. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  4372. {
  4373. global $langs, $hookmanager, $conf, $form, $action;
  4374. print '<tr class="liste_titre">';
  4375. print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
  4376. print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
  4377. print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
  4378. print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
  4379. if (!empty($conf->multicurrency->enabled)) {
  4380. print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
  4381. }
  4382. print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
  4383. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4384. print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
  4385. }
  4386. print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
  4387. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  4388. print '</tr>';
  4389. $i = 0;
  4390. if (!empty($this->lines)) {
  4391. foreach ($this->lines as $line) {
  4392. $reshook = 0;
  4393. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
  4394. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4395. $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
  4396. if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
  4397. $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4398. }
  4399. if (empty($reshook)) {
  4400. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  4401. }
  4402. $i++;
  4403. }
  4404. }
  4405. }
  4406. /**
  4407. * Return HTML with a line of table array of source object lines
  4408. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4409. * If lines are into a template, title must also be into a template
  4410. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4411. *
  4412. * @param CommonObjectLine $line Line
  4413. * @param string $var Var
  4414. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  4415. * @param string $defaulttpldir Directory where to find the template
  4416. * @param array $selectedLines Array of lines id for selected lines
  4417. * @return void
  4418. */
  4419. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  4420. {
  4421. global $langs, $conf;
  4422. //var_dump($line);
  4423. if (!empty($line->date_start)) {
  4424. $date_start = $line->date_start;
  4425. } else {
  4426. $date_start = $line->date_debut_prevue;
  4427. if ($line->date_debut_reel) {
  4428. $date_start = $line->date_debut_reel;
  4429. }
  4430. }
  4431. if (!empty($line->date_end)) {
  4432. $date_end = $line->date_end;
  4433. } else {
  4434. $date_end = $line->date_fin_prevue;
  4435. if ($line->date_fin_reel) {
  4436. $date_end = $line->date_fin_reel;
  4437. }
  4438. }
  4439. $this->tpl['id'] = $line->id;
  4440. $this->tpl['label'] = '';
  4441. if (!empty($line->fk_parent_line)) {
  4442. $this->tpl['label'] .= img_picto('', 'rightarrow');
  4443. }
  4444. if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
  4445. $discount = new DiscountAbsolute($this->db);
  4446. $discount->fk_soc = $this->socid;
  4447. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  4448. } elseif (!empty($line->fk_product)) {
  4449. $productstatic = new Product($this->db);
  4450. $productstatic->id = $line->fk_product;
  4451. $productstatic->ref = $line->ref;
  4452. $productstatic->type = $line->fk_product_type;
  4453. if (empty($productstatic->ref)) {
  4454. $line->fetch_product();
  4455. $productstatic = $line->product;
  4456. }
  4457. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  4458. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  4459. // Dates
  4460. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4461. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4462. }
  4463. } else {
  4464. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  4465. if (!empty($line->desc)) {
  4466. $this->tpl['label'] .= $line->desc;
  4467. } else {
  4468. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  4469. }
  4470. // Dates
  4471. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4472. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4473. }
  4474. }
  4475. if (!empty($line->desc)) {
  4476. if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
  4477. $discount = new DiscountAbsolute($this->db);
  4478. $discount->fetch($line->fk_remise_except);
  4479. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  4480. } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
  4481. $discount = new DiscountAbsolute($this->db);
  4482. $discount->fetch($line->fk_remise_except);
  4483. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  4484. } elseif ($line->desc == '(EXCESS RECEIVED)') {
  4485. $discount = new DiscountAbsolute($this->db);
  4486. $discount->fetch($line->fk_remise_except);
  4487. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  4488. } elseif ($line->desc == '(EXCESS PAID)') {
  4489. $discount = new DiscountAbsolute($this->db);
  4490. $discount->fetch($line->fk_remise_except);
  4491. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  4492. } else {
  4493. $this->tpl['description'] = dol_trunc($line->desc, 60);
  4494. }
  4495. } else {
  4496. $this->tpl['description'] = '&nbsp;';
  4497. }
  4498. // VAT Rate
  4499. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  4500. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  4501. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
  4502. $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  4503. }
  4504. $this->tpl['price'] = price($line->subprice);
  4505. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  4506. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  4507. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4508. $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  4509. }
  4510. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  4511. // Is the line strike or not
  4512. $this->tpl['strike'] = 0;
  4513. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
  4514. $this->tpl['strike'] = 1;
  4515. }
  4516. // Output template part (modules that overwrite templates must declare this into descriptor)
  4517. // Use global variables + $dateSelector + $seller and $buyer
  4518. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4519. foreach ($dirtpls as $module => $reldir) {
  4520. if (!empty($module)) {
  4521. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  4522. } else {
  4523. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  4524. }
  4525. if (empty($conf->file->strict_mode)) {
  4526. $res = @include $tpl;
  4527. } else {
  4528. $res = include $tpl; // for debug
  4529. }
  4530. if ($res) {
  4531. break;
  4532. }
  4533. }
  4534. }
  4535. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4536. /**
  4537. * Add resources to the current object : add entry into llx_element_resources
  4538. * Need $this->element & $this->id
  4539. *
  4540. * @param int $resource_id Resource id
  4541. * @param string $resource_type 'resource'
  4542. * @param int $busy Busy or not
  4543. * @param int $mandatory Mandatory or not
  4544. * @return int <=0 if KO, >0 if OK
  4545. */
  4546. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  4547. {
  4548. // phpcs:enable
  4549. $this->db->begin();
  4550. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources (";
  4551. $sql .= "resource_id";
  4552. $sql .= ", resource_type";
  4553. $sql .= ", element_id";
  4554. $sql .= ", element_type";
  4555. $sql .= ", busy";
  4556. $sql .= ", mandatory";
  4557. $sql .= ") VALUES (";
  4558. $sql .= $resource_id;
  4559. $sql .= ", '".$this->db->escape($resource_type)."'";
  4560. $sql .= ", '".$this->db->escape($this->id)."'";
  4561. $sql .= ", '".$this->db->escape($this->element)."'";
  4562. $sql .= ", '".$this->db->escape($busy)."'";
  4563. $sql .= ", '".$this->db->escape($mandatory)."'";
  4564. $sql .= ")";
  4565. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  4566. if ($this->db->query($sql)) {
  4567. $this->db->commit();
  4568. return 1;
  4569. } else {
  4570. $this->error = $this->db->lasterror();
  4571. $this->db->rollback();
  4572. return 0;
  4573. }
  4574. }
  4575. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4576. /**
  4577. * Delete a link to resource line
  4578. *
  4579. * @param int $rowid Id of resource line to delete
  4580. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  4581. * @param int $notrigger Disable all triggers
  4582. * @return int >0 if OK, <0 if KO
  4583. */
  4584. public function delete_resource($rowid, $element, $notrigger = 0)
  4585. {
  4586. // phpcs:enable
  4587. global $user;
  4588. $this->db->begin();
  4589. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
  4590. $sql .= " WHERE rowid = ".((int) $rowid);
  4591. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  4592. $resql = $this->db->query($sql);
  4593. if (!$resql) {
  4594. $this->error = $this->db->lasterror();
  4595. $this->db->rollback();
  4596. return -1;
  4597. } else {
  4598. if (!$notrigger) {
  4599. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  4600. if ($result < 0) {
  4601. $this->db->rollback();
  4602. return -1;
  4603. }
  4604. }
  4605. $this->db->commit();
  4606. return 1;
  4607. }
  4608. }
  4609. /**
  4610. * Overwrite magic function to solve problem of cloning object that are kept as references
  4611. *
  4612. * @return void
  4613. */
  4614. public function __clone()
  4615. {
  4616. // Force a copy of this->lines, otherwise it will point to same object.
  4617. if (isset($this->lines) && is_array($this->lines)) {
  4618. $nboflines = count($this->lines);
  4619. for ($i = 0; $i < $nboflines; $i++) {
  4620. $this->lines[$i] = clone $this->lines[$i];
  4621. }
  4622. }
  4623. }
  4624. /**
  4625. * Common function for all objects extending CommonObject for generating documents
  4626. *
  4627. * @param string $modelspath Relative folder where generators are placed
  4628. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4629. * @param Translate $outputlangs Output language to use
  4630. * @param int $hidedetails 1 to hide details. 0 by default
  4631. * @param int $hidedesc 1 to hide product description. 0 by default
  4632. * @param int $hideref 1 to hide product reference. 0 by default
  4633. * @param null|array $moreparams Array to provide more information
  4634. * @return int >0 if OK, <0 if KO
  4635. * @see addFileIntoDatabaseIndex()
  4636. */
  4637. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4638. {
  4639. global $conf, $langs, $user, $hookmanager, $action;
  4640. $srctemplatepath = '';
  4641. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  4642. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4643. if (empty($reshook)) {
  4644. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4645. if (empty($modele)) {
  4646. $this->error = 'BadValueForParameterModele';
  4647. return -1;
  4648. }
  4649. // Increase limit for PDF build
  4650. $err = error_reporting();
  4651. error_reporting(0);
  4652. @set_time_limit(120);
  4653. error_reporting($err);
  4654. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4655. $tmp = explode(':', $modele, 2);
  4656. if (!empty($tmp[1])) {
  4657. $modele = $tmp[0];
  4658. $srctemplatepath = $tmp[1];
  4659. }
  4660. // Search template files
  4661. $file = '';
  4662. $classname = '';
  4663. $filefound = '';
  4664. $dirmodels = array('/');
  4665. if (is_array($conf->modules_parts['models'])) {
  4666. $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4667. }
  4668. foreach ($dirmodels as $reldir) {
  4669. foreach (array('doc', 'pdf') as $prefix) {
  4670. if (in_array(get_class($this), array('Adherent'))) {
  4671. // Member module use prefix_modele.class.php
  4672. $file = $prefix."_".$modele.".class.php";
  4673. } else {
  4674. // Other module use prefix_modele.modules.php
  4675. $file = $prefix."_".$modele.".modules.php";
  4676. }
  4677. // On verifie l'emplacement du modele
  4678. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  4679. if (file_exists($file)) {
  4680. $filefound = $file;
  4681. $classname = $prefix.'_'.$modele;
  4682. break;
  4683. }
  4684. }
  4685. if ($filefound) {
  4686. break;
  4687. }
  4688. }
  4689. // If generator was found
  4690. if ($filefound) {
  4691. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4692. require_once $file;
  4693. $obj = new $classname($this->db);
  4694. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4695. if ($obj->type == 'odt' && empty($srctemplatepath)) {
  4696. $varfortemplatedir = $obj->scandir;
  4697. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
  4698. $dirtoscan = $conf->global->$varfortemplatedir;
  4699. $listoffiles = array();
  4700. // Now we add first model found in directories scanned
  4701. $listofdir = explode(',', $dirtoscan);
  4702. foreach ($listofdir as $key => $tmpdir) {
  4703. $tmpdir = trim($tmpdir);
  4704. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4705. if (!$tmpdir) {
  4706. unset($listofdir[$key]);
  4707. continue;
  4708. }
  4709. if (is_dir($tmpdir)) {
  4710. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4711. if (count($tmpfiles)) {
  4712. $listoffiles = array_merge($listoffiles, $tmpfiles);
  4713. }
  4714. }
  4715. }
  4716. if (count($listoffiles)) {
  4717. foreach ($listoffiles as $record) {
  4718. $srctemplatepath = $record['fullname'];
  4719. break;
  4720. }
  4721. }
  4722. }
  4723. if (empty($srctemplatepath)) {
  4724. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4725. return -1;
  4726. }
  4727. }
  4728. if ($obj->type == 'odt' && !empty($srctemplatepath)) {
  4729. if (!dol_is_file($srctemplatepath)) {
  4730. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  4731. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4732. return -1;
  4733. }
  4734. }
  4735. // We save charset_output to restore it because write_file can change it if needed for
  4736. // output format that does not support UTF8.
  4737. $sav_charset_output = $outputlangs->charset_output;
  4738. if (in_array(get_class($this), array('Adherent'))) {
  4739. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
  4740. } else {
  4741. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4742. }
  4743. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4744. if ($resultwritefile > 0) {
  4745. $outputlangs->charset_output = $sav_charset_output;
  4746. // We delete old preview
  4747. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4748. dol_delete_preview($this);
  4749. // Index file in database
  4750. if (!empty($obj->result['fullpath'])) {
  4751. $destfull = $obj->result['fullpath'];
  4752. // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
  4753. $update_main_doc_field = 0;
  4754. if (!empty($obj->update_main_doc_field)) {
  4755. $update_main_doc_field = 1;
  4756. }
  4757. $this->indexFile($destfull, $update_main_doc_field);
  4758. } else {
  4759. 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);
  4760. }
  4761. // Success in building document. We build meta file.
  4762. dol_meta_create($this);
  4763. return 1;
  4764. } else {
  4765. $outputlangs->charset_output = $sav_charset_output;
  4766. dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
  4767. return -1;
  4768. }
  4769. } else {
  4770. if (!$filefound) {
  4771. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4772. dol_print_error('', $this->error);
  4773. } else {
  4774. $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
  4775. dol_print_error('', $this->error);
  4776. }
  4777. return -1;
  4778. }
  4779. } else {
  4780. return $reshook;
  4781. }
  4782. }
  4783. /**
  4784. * Index a file into the ECM database
  4785. *
  4786. * @param string $destfull Full path of file to index
  4787. * @param int $update_main_doc_field Update field main_doc file into table of object
  4788. * @return int <0 if KO, >0 if OK
  4789. */
  4790. public function indexFile($destfull, $update_main_doc_field)
  4791. {
  4792. global $conf, $user;
  4793. $upload_dir = dirname($destfull);
  4794. $destfile = basename($destfull);
  4795. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  4796. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  4797. $filename = basename($destfile);
  4798. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4799. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4800. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4801. $ecmfile = new EcmFiles($this->db);
  4802. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  4803. // Set the public "share" key
  4804. $setsharekey = false;
  4805. if ($this->element == 'propal' || $this->element == 'proposal') {
  4806. if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
  4807. $setsharekey = true; // feature to make online signature is not set or set to on (default)
  4808. }
  4809. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4810. $setsharekey = true;
  4811. }
  4812. }
  4813. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  4814. $setsharekey = true;
  4815. }
  4816. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  4817. $setsharekey = true;
  4818. }
  4819. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4820. $setsharekey = true;
  4821. }
  4822. if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4823. $setsharekey = true;
  4824. }
  4825. if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4826. $setsharekey = true;
  4827. }
  4828. if ($setsharekey) {
  4829. if (empty($ecmfile->share)) { // Because object not found or share not set yet
  4830. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  4831. $ecmfile->share = getRandomPassword(true);
  4832. }
  4833. }
  4834. if ($result > 0) {
  4835. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4836. $ecmfile->fullpath_orig = '';
  4837. $ecmfile->gen_or_uploaded = 'generated';
  4838. $ecmfile->description = ''; // indexed content
  4839. $ecmfile->keywords = ''; // keyword content
  4840. $result = $ecmfile->update($user);
  4841. if ($result < 0) {
  4842. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4843. return -1;
  4844. }
  4845. } else {
  4846. $ecmfile->entity = $conf->entity;
  4847. $ecmfile->filepath = $rel_dir;
  4848. $ecmfile->filename = $filename;
  4849. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4850. $ecmfile->fullpath_orig = '';
  4851. $ecmfile->gen_or_uploaded = 'generated';
  4852. $ecmfile->description = ''; // indexed content
  4853. $ecmfile->keywords = ''; // keyword content
  4854. $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
  4855. $ecmfile->src_object_id = $this->id;
  4856. $result = $ecmfile->create($user);
  4857. if ($result < 0) {
  4858. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4859. return -1;
  4860. }
  4861. }
  4862. /*$this->result['fullname']=$destfull;
  4863. $this->result['filepath']=$ecmfile->filepath;
  4864. $this->result['filename']=$ecmfile->filename;*/
  4865. //var_dump($obj->update_main_doc_field);exit;
  4866. if ($update_main_doc_field && !empty($this->table_element)) {
  4867. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
  4868. $sql .= " WHERE rowid = ".((int) $this->id);
  4869. $resql = $this->db->query($sql);
  4870. if (!$resql) {
  4871. dol_print_error($this->db);
  4872. return -1;
  4873. } else {
  4874. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  4875. }
  4876. }
  4877. }
  4878. return 1;
  4879. }
  4880. /**
  4881. * Build thumb
  4882. * @todo Move this into files.lib.php
  4883. *
  4884. * @param string $file Path file in UTF8 to original file to create thumbs from.
  4885. * @return void
  4886. */
  4887. public function addThumbs($file)
  4888. {
  4889. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  4890. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  4891. $file_osencoded = dol_osencode($file);
  4892. if (file_exists($file_osencoded)) {
  4893. // Create small thumbs for company (Ratio is near 16/9)
  4894. // Used on logon for example
  4895. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  4896. // Create mini thumbs for company (Ratio is near 16/9)
  4897. // Used on menu or for setup page for example
  4898. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  4899. }
  4900. }
  4901. /* Functions common to commonobject and commonobjectline */
  4902. /* For default values */
  4903. /**
  4904. * Return the default value to use for a field when showing the create form of object.
  4905. * Return values in this order:
  4906. * 1) If parameter is available into POST, we return it first.
  4907. * 2) If not but an alternate value was provided as parameter of function, we return it.
  4908. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  4909. * 4) Return value found into database (TODO No yet implemented)
  4910. *
  4911. * @param string $fieldname Name of field
  4912. * @param string $alternatevalue Alternate value to use
  4913. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  4914. **/
  4915. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
  4916. {
  4917. global $conf, $_POST;
  4918. // If param here has been posted, we use this value first.
  4919. if (GETPOSTISSET($fieldname)) {
  4920. return GETPOST($fieldname, 'alphanohtml', 3);
  4921. }
  4922. if (isset($alternatevalue)) {
  4923. return $alternatevalue;
  4924. }
  4925. $newelement = $this->element;
  4926. if ($newelement == 'facture') {
  4927. $newelement = 'invoice';
  4928. }
  4929. if ($newelement == 'commande') {
  4930. $newelement = 'order';
  4931. }
  4932. if (empty($newelement)) {
  4933. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  4934. return '';
  4935. }
  4936. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  4937. //var_dump($keyforfieldname);
  4938. if (isset($conf->global->$keyforfieldname)) {
  4939. return $conf->global->$keyforfieldname;
  4940. }
  4941. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  4942. }
  4943. /* For triggers */
  4944. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4945. /**
  4946. * Call trigger based on this instance.
  4947. * Some context information may also be provided into array property this->context.
  4948. * NB: Error from trigger are stacked in interface->errors
  4949. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  4950. *
  4951. * @param string $triggerName trigger's name to execute
  4952. * @param User $user Object user
  4953. * @return int Result of run_triggers
  4954. */
  4955. public function call_trigger($triggerName, $user)
  4956. {
  4957. // phpcs:enable
  4958. global $langs, $conf;
  4959. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  4960. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4961. $langs = new Translate('', $conf);
  4962. }
  4963. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  4964. $interface = new Interfaces($this->db);
  4965. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  4966. if ($result < 0) {
  4967. if (!empty($this->errors)) {
  4968. $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.
  4969. } else {
  4970. $this->errors = $interface->errors;
  4971. }
  4972. }
  4973. return $result;
  4974. }
  4975. /* Functions for data in other language */
  4976. /**
  4977. * Function to get alternative languages of a data into $this->array_languages
  4978. * This method is NOT called by method fetch of objects but must be called separately.
  4979. *
  4980. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  4981. * @see fetch_optionnals()
  4982. */
  4983. public function fetchValuesForExtraLanguages()
  4984. {
  4985. // To avoid SQL errors. Probably not the better solution though
  4986. if (!$this->element) {
  4987. return 0;
  4988. }
  4989. if (!($this->id > 0)) {
  4990. return 0;
  4991. }
  4992. if (is_array($this->array_languages)) {
  4993. return 1;
  4994. }
  4995. $this->array_languages = array();
  4996. $element = $this->element;
  4997. if ($element == 'categorie') {
  4998. $element = 'categories'; // For compatibility
  4999. }
  5000. // Request to get translation values for object
  5001. $sql = "SELECT rowid, property, lang , value";
  5002. $sql .= " FROM ".MAIN_DB_PREFIX."object_lang";
  5003. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  5004. $sql .= " AND fk_object = ".((int) $this->id);
  5005. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5006. $resql = $this->db->query($sql);
  5007. if ($resql) {
  5008. $numrows = $this->db->num_rows($resql);
  5009. if ($numrows) {
  5010. $i = 0;
  5011. while ($i < $numrows) {
  5012. $obj = $this->db->fetch_object($resql);
  5013. $key = $obj->property;
  5014. $value = $obj->value;
  5015. $codelang = $obj->lang;
  5016. $type = $this->fields[$key]['type'];
  5017. // we can add this attribute to object
  5018. if (preg_match('/date/', $type)) {
  5019. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  5020. } else {
  5021. $this->array_languages[$key][$codelang] = $value;
  5022. }
  5023. $i++;
  5024. }
  5025. }
  5026. $this->db->free($resql);
  5027. if ($numrows) {
  5028. return $numrows;
  5029. } else {
  5030. return 0;
  5031. }
  5032. } else {
  5033. dol_print_error($this->db);
  5034. return -1;
  5035. }
  5036. }
  5037. /**
  5038. * Fill array_options property of object by extrafields value (using for data sent by forms)
  5039. *
  5040. * @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.
  5041. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  5042. */
  5043. public function setValuesForExtraLanguages($onlykey = '')
  5044. {
  5045. global $_POST, $langs;
  5046. // Get extra fields
  5047. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  5048. $tmparray = explode('-', $postfieldkey);
  5049. if ($tmparray[0] != 'field') {
  5050. continue;
  5051. }
  5052. $element = $tmparray[1];
  5053. $key = $tmparray[2];
  5054. $codelang = $tmparray[3];
  5055. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  5056. if (!empty($onlykey) && $key != $onlykey) {
  5057. continue;
  5058. }
  5059. if ($element != $this->element) {
  5060. continue;
  5061. }
  5062. $key_type = $this->fields[$key]['type'];
  5063. $enabled = 1;
  5064. if (isset($this->fields[$key]['enabled'])) {
  5065. $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
  5066. }
  5067. /*$perms = 1;
  5068. if (isset($this->fields[$key]['perms']))
  5069. {
  5070. $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
  5071. }*/
  5072. if (empty($enabled)) {
  5073. continue;
  5074. }
  5075. //if (empty($perms)) continue;
  5076. if (in_array($key_type, array('date'))) {
  5077. // Clean parameters
  5078. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5079. $value_key = dol_mktime(0, 0, 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]);
  5080. } elseif (in_array($key_type, array('datetime'))) {
  5081. // Clean parameters
  5082. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5083. $value_key = dol_mktime($_POST[$postfieldkey."hour"], $_POST[$postfieldkey."min"], 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]);
  5084. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  5085. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  5086. if (!empty($value_arr)) {
  5087. $value_key = implode(',', $value_arr);
  5088. } else {
  5089. $value_key = '';
  5090. }
  5091. } elseif (in_array($key_type, array('price', 'double'))) {
  5092. $value_arr = GETPOST($postfieldkey, 'alpha');
  5093. $value_key = price2num($value_arr);
  5094. } else {
  5095. $value_key = GETPOST($postfieldkey);
  5096. if (in_array($key_type, array('link')) && $value_key == '-1') {
  5097. $value_key = '';
  5098. }
  5099. }
  5100. $this->array_languages[$key][$codelang] = $value_key;
  5101. /*if ($nofillrequired) {
  5102. $langs->load('errors');
  5103. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  5104. return -1;
  5105. }*/
  5106. }
  5107. return 1;
  5108. }
  5109. /* Functions for extrafields */
  5110. /**
  5111. * Function to make a fetch but set environment to avoid to load computed values before.
  5112. *
  5113. * @param int $id ID of object
  5114. * @return int >0 if OK, 0 if not found, <0 if KO
  5115. */
  5116. public function fetchNoCompute($id)
  5117. {
  5118. global $conf;
  5119. $savDisableCompute = $conf->disable_compute;
  5120. $conf->disable_compute = 1;
  5121. $ret = $this->fetch($id);
  5122. $conf->disable_compute = $savDisableCompute;
  5123. return $ret;
  5124. }
  5125. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5126. /**
  5127. * Function to get extra fields of an object into $this->array_options
  5128. * This method is in most cases called by method fetch of objects but you can call it separately.
  5129. *
  5130. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  5131. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  5132. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  5133. * @see fetchValuesForExtraLanguages()
  5134. */
  5135. public function fetch_optionals($rowid = null, $optionsArray = null)
  5136. {
  5137. // phpcs:enable
  5138. global $conf, $extrafields;
  5139. if (empty($rowid)) {
  5140. $rowid = $this->id;
  5141. }
  5142. if (empty($rowid) && isset($this->rowid)) {
  5143. $rowid = $this->rowid; // deprecated
  5144. }
  5145. // To avoid SQL errors. Probably not the better solution though
  5146. if (!$this->table_element) {
  5147. return 0;
  5148. }
  5149. $this->array_options = array();
  5150. if (!is_array($optionsArray)) {
  5151. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  5152. if (!isset($extrafields) || !is_object($extrafields)) {
  5153. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5154. $extrafields = new ExtraFields($this->db);
  5155. }
  5156. // Load array of extrafields for elementype = $this->table_element
  5157. if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
  5158. $extrafields->fetch_name_optionals_label($this->table_element);
  5159. }
  5160. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  5161. } else {
  5162. global $extrafields;
  5163. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  5164. }
  5165. $table_element = $this->table_element;
  5166. if ($table_element == 'categorie') {
  5167. $table_element = 'categories'; // For compatibility
  5168. }
  5169. // Request to get complementary values
  5170. if (is_array($optionsArray) && count($optionsArray) > 0) {
  5171. $sql = "SELECT rowid";
  5172. foreach ($optionsArray as $name => $label) {
  5173. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
  5174. $sql .= ", ".$name;
  5175. }
  5176. }
  5177. $sql .= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
  5178. $sql .= " WHERE fk_object = ".((int) $rowid);
  5179. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5180. $resql = $this->db->query($sql);
  5181. if ($resql) {
  5182. $numrows = $this->db->num_rows($resql);
  5183. if ($numrows) {
  5184. $tab = $this->db->fetch_array($resql);
  5185. foreach ($tab as $key => $value) {
  5186. // 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)
  5187. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
  5188. // we can add this attribute to object
  5189. if (!empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
  5190. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  5191. $this->array_options["options_".$key] = $this->db->jdate($value);
  5192. } else {
  5193. $this->array_options["options_".$key] = $value;
  5194. }
  5195. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  5196. }
  5197. }
  5198. // If field is a computed field, value must become result of compute
  5199. foreach ($tab as $key => $value) {
  5200. if (!empty($extrafields) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
  5201. //var_dump($conf->disable_compute);
  5202. if (empty($conf->disable_compute)) {
  5203. $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
  5204. }
  5205. }
  5206. }
  5207. }
  5208. $this->db->free($resql);
  5209. if ($numrows) {
  5210. return $numrows;
  5211. } else {
  5212. return 0;
  5213. }
  5214. } else {
  5215. $this->errors[]=$this->db->lasterror;
  5216. return -1;
  5217. }
  5218. }
  5219. return 0;
  5220. }
  5221. /**
  5222. * Delete all extra fields values for the current object.
  5223. *
  5224. * @return int <0 if KO, >0 if OK
  5225. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  5226. */
  5227. public function deleteExtraFields()
  5228. {
  5229. global $conf;
  5230. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5231. return 0;
  5232. }
  5233. $this->db->begin();
  5234. $table_element = $this->table_element;
  5235. if ($table_element == 'categorie') {
  5236. $table_element = 'categories'; // For compatibility
  5237. }
  5238. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  5239. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5240. $resql = $this->db->query($sql_del);
  5241. if (!$resql) {
  5242. $this->error = $this->db->lasterror();
  5243. $this->db->rollback();
  5244. return -1;
  5245. } else {
  5246. $this->db->commit();
  5247. return 1;
  5248. }
  5249. }
  5250. /**
  5251. * Add/Update all extra fields values for the current object.
  5252. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5253. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5254. *
  5255. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5256. * @param User $userused Object user
  5257. * @return int -1=error, O=did nothing, 1=OK
  5258. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  5259. */
  5260. public function insertExtraFields($trigger = '', $userused = null)
  5261. {
  5262. global $conf, $langs, $user;
  5263. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5264. return 0;
  5265. }
  5266. if (empty($userused)) {
  5267. $userused = $user;
  5268. }
  5269. $error = 0;
  5270. if (!empty($this->array_options)) {
  5271. // Check parameters
  5272. $langs->load('admin');
  5273. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5274. $extrafields = new ExtraFields($this->db);
  5275. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  5276. // Eliminate copied source object extra fields that do not exist in target object
  5277. $new_array_options = array();
  5278. foreach ($this->array_options as $key => $value) {
  5279. if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
  5280. $new_array_options[$key] = $value;
  5281. } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
  5282. $new_array_options['options_'.$key] = $value;
  5283. }
  5284. }
  5285. foreach ($new_array_options as $key => $value) {
  5286. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5287. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  5288. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  5289. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  5290. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  5291. $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
  5292. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  5293. // If we clone, we have to clean unique extrafields to prevent duplicates.
  5294. // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
  5295. if (! empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && ! empty($attributeUnique)) {
  5296. $new_array_options[$key] = null;
  5297. }
  5298. // Similar code than into insertExtraFields
  5299. if ($attributeRequired) {
  5300. $mandatorypb = false;
  5301. if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
  5302. $mandatorypb = true;
  5303. }
  5304. if ($this->array_options[$key] === '') {
  5305. $mandatorypb = true;
  5306. }
  5307. if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
  5308. $mandatorypb = true;
  5309. }
  5310. if ($mandatorypb) {
  5311. $langs->load("errors");
  5312. dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
  5313. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5314. return -1;
  5315. }
  5316. }
  5317. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5318. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5319. if (!empty($attrfieldcomputed)) {
  5320. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5321. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5322. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5323. $new_array_options[$key] = $value;
  5324. } else {
  5325. $new_array_options[$key] = null;
  5326. }
  5327. }
  5328. switch ($attributeType) {
  5329. case 'int':
  5330. if (!is_numeric($value) && $value != '') {
  5331. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5332. return -1;
  5333. } elseif ($value == '') {
  5334. $new_array_options[$key] = null;
  5335. }
  5336. break;
  5337. case 'price':
  5338. case 'double':
  5339. $value = price2num($value);
  5340. if (!is_numeric($value) && $value != '') {
  5341. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5342. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5343. return -1;
  5344. } elseif ($value == '') {
  5345. $value = null;
  5346. }
  5347. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5348. $new_array_options[$key] = $value;
  5349. break;
  5350. /*case 'select': // Not required, we chosed value='0' for undefined values
  5351. if ($value=='-1')
  5352. {
  5353. $this->array_options[$key] = null;
  5354. }
  5355. break;*/
  5356. case 'password':
  5357. $algo = '';
  5358. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
  5359. // If there is an encryption choice, we use it to crypt data before insert
  5360. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  5361. $algo = reset($tmparrays);
  5362. if ($algo != '') {
  5363. //global $action; // $action may be 'create', 'update', 'update_extras'...
  5364. //var_dump($action);
  5365. //var_dump($this->oldcopy);exit;
  5366. 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
  5367. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  5368. if ($this->array_options[$key] == $this->oldcopy->array_options[$key]) { // If old value crypted in database is same than submited new value, it means we don't change it, so we don't update.
  5369. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5370. } else {
  5371. // var_dump($algo);
  5372. $newvalue = dol_hash($this->array_options[$key], $algo);
  5373. $new_array_options[$key] = $newvalue;
  5374. }
  5375. } else {
  5376. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5377. }
  5378. }
  5379. } else // Common usage
  5380. {
  5381. $new_array_options[$key] = $this->array_options[$key];
  5382. }
  5383. break;
  5384. case 'date':
  5385. case 'datetime':
  5386. // If data is a string instead of a timestamp, we convert it
  5387. if (!is_int($this->array_options[$key])) {
  5388. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5389. }
  5390. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  5391. break;
  5392. case 'link':
  5393. $param_list = array_keys($attributeParam['options']);
  5394. // 0 : ObjectName
  5395. // 1 : classPath
  5396. $InfoFieldList = explode(":", $param_list[0]);
  5397. dol_include_once($InfoFieldList[1]);
  5398. if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
  5399. if ($value == '-1') { // -1 is key for no defined in combo list of objects
  5400. $new_array_options[$key] = '';
  5401. } elseif ($value) {
  5402. $object = new $InfoFieldList[0]($this->db);
  5403. if (is_numeric($value)) {
  5404. $res = $object->fetch($value); // Common case
  5405. } else {
  5406. $res = $object->fetch('', $value); // For compatibility
  5407. }
  5408. if ($res > 0) {
  5409. $new_array_options[$key] = $object->id;
  5410. } else {
  5411. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5412. $this->db->rollback();
  5413. return -1;
  5414. }
  5415. }
  5416. } else {
  5417. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5418. }
  5419. break;
  5420. }
  5421. }
  5422. $this->db->begin();
  5423. $table_element = $this->table_element;
  5424. if ($table_element == 'categorie') {
  5425. $table_element = 'categories'; // For compatibility
  5426. }
  5427. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  5428. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5429. $this->db->query($sql_del);
  5430. $sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object";
  5431. foreach ($new_array_options as $key => $value) {
  5432. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5433. // Add field of attribut
  5434. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
  5435. $sql .= ",".$attributeKey;
  5436. }
  5437. }
  5438. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5439. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5440. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5441. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5442. $sql .= ",".$tmpkey;
  5443. }
  5444. }
  5445. }
  5446. $sql .= ") VALUES (".$this->id;
  5447. foreach ($new_array_options as $key => $value) {
  5448. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5449. // Add field of attribute
  5450. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
  5451. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
  5452. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  5453. } else {
  5454. $sql .= ",null";
  5455. }
  5456. }
  5457. }
  5458. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5459. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5460. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5461. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5462. if (in_array($tmpval, array('int', 'double', 'price'))) {
  5463. $sql .= ", 0";
  5464. } else {
  5465. $sql .= ", ''";
  5466. }
  5467. }
  5468. }
  5469. }
  5470. $sql .= ")";
  5471. $resql = $this->db->query($sql);
  5472. if (!$resql) {
  5473. $this->error = $this->db->lasterror();
  5474. $error++;
  5475. }
  5476. if (!$error && $trigger) {
  5477. // Call trigger
  5478. $this->context = array('extrafieldaddupdate'=>1);
  5479. $result = $this->call_trigger($trigger, $userused);
  5480. if ($result < 0) {
  5481. $error++;
  5482. }
  5483. // End call trigger
  5484. }
  5485. if ($error) {
  5486. $this->db->rollback();
  5487. return -1;
  5488. } else {
  5489. $this->db->commit();
  5490. return 1;
  5491. }
  5492. } else {
  5493. return 0;
  5494. }
  5495. }
  5496. /**
  5497. * Add/Update all extra fields values for the current object.
  5498. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5499. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5500. *
  5501. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5502. * @param User $userused Object user
  5503. * @return int -1=error, O=did nothing, 1=OK
  5504. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  5505. */
  5506. public function insertExtraLanguages($trigger = '', $userused = null)
  5507. {
  5508. global $conf, $langs, $user;
  5509. if (empty($userused)) {
  5510. $userused = $user;
  5511. }
  5512. $error = 0;
  5513. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5514. return 0; // For avoid conflicts if trigger used
  5515. }
  5516. if (is_array($this->array_languages)) {
  5517. $new_array_languages = $this->array_languages;
  5518. foreach ($new_array_languages as $key => $value) {
  5519. $attributeKey = $key;
  5520. $attributeType = $this->fields[$attributeKey]['type'];
  5521. $attributeLabel = $this->fields[$attributeKey]['label'];
  5522. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5523. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5524. switch ($attributeType) {
  5525. case 'int':
  5526. if (!is_numeric($value) && $value != '') {
  5527. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5528. return -1;
  5529. } elseif ($value == '') {
  5530. $new_array_languages[$key] = null;
  5531. }
  5532. break;
  5533. case 'double':
  5534. $value = price2num($value);
  5535. if (!is_numeric($value) && $value != '') {
  5536. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5537. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5538. return -1;
  5539. } elseif ($value == '') {
  5540. $new_array_languages[$key] = null;
  5541. }
  5542. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5543. $new_array_languages[$key] = $value;
  5544. break;
  5545. /*case 'select': // Not required, we chosed value='0' for undefined values
  5546. if ($value=='-1')
  5547. {
  5548. $this->array_options[$key] = null;
  5549. }
  5550. break;*/
  5551. }
  5552. }
  5553. $this->db->begin();
  5554. $table_element = $this->table_element;
  5555. if ($table_element == 'categorie') {
  5556. $table_element = 'categories'; // For compatibility
  5557. }
  5558. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  5559. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  5560. foreach ($langcodearray as $langcode => $value) {
  5561. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX."object_lang";
  5562. $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  5563. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  5564. $this->db->query($sql_del);
  5565. if ($value !== '') {
  5566. $sql = "INSERT INTO ".MAIN_DB_PREFIX."object_lang (fk_object, property, type_object, lang, value";
  5567. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  5568. $sql .= ")";
  5569. $resql = $this->db->query($sql);
  5570. if (!$resql) {
  5571. $this->error = $this->db->lasterror();
  5572. $error++;
  5573. break;
  5574. }
  5575. }
  5576. }
  5577. }
  5578. if (!$error && $trigger) {
  5579. // Call trigger
  5580. $this->context = array('extralanguagesaddupdate'=>1);
  5581. $result = $this->call_trigger($trigger, $userused);
  5582. if ($result < 0) {
  5583. $error++;
  5584. }
  5585. // End call trigger
  5586. }
  5587. if ($error) {
  5588. $this->db->rollback();
  5589. return -1;
  5590. } else {
  5591. $this->db->commit();
  5592. return 1;
  5593. }
  5594. } else {
  5595. return 0;
  5596. }
  5597. }
  5598. /**
  5599. * Update 1 extra field value for the current object. Keep other fields unchanged.
  5600. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5601. *
  5602. * @param string $key Key of the extrafield to update (without starting 'options_')
  5603. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5604. * @param User $userused Object user
  5605. * @return int -1=error, O=did nothing, 1=OK
  5606. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  5607. */
  5608. public function updateExtraField($key, $trigger = null, $userused = null)
  5609. {
  5610. global $conf, $langs, $user;
  5611. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5612. return 0;
  5613. }
  5614. if (empty($userused)) {
  5615. $userused = $user;
  5616. }
  5617. $error = 0;
  5618. if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
  5619. // Check parameters
  5620. $langs->load('admin');
  5621. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5622. $extrafields = new ExtraFields($this->db);
  5623. $extrafields->fetch_name_optionals_label($this->table_element);
  5624. $value = $this->array_options["options_".$key];
  5625. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  5626. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  5627. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  5628. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  5629. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  5630. // Similar code than into insertExtraFields
  5631. if ($attributeRequired) {
  5632. $mandatorypb = false;
  5633. if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
  5634. $mandatorypb = true;
  5635. }
  5636. if ($this->array_options["options_".$key] === '') {
  5637. $mandatorypb = true;
  5638. }
  5639. if ($mandatorypb) {
  5640. $langs->load("errors");
  5641. dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
  5642. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5643. return -1;
  5644. }
  5645. }
  5646. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5647. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5648. if (!empty($attrfieldcomputed)) {
  5649. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5650. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5651. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5652. $this->array_options["options_".$key] = $value;
  5653. } else {
  5654. $this->array_options["options_".$key] = null;
  5655. }
  5656. }
  5657. switch ($attributeType) {
  5658. case 'int':
  5659. if (!is_numeric($value) && $value != '') {
  5660. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5661. return -1;
  5662. } elseif ($value === '') {
  5663. $this->array_options["options_".$key] = null;
  5664. }
  5665. break;
  5666. case 'double':
  5667. $value = price2num($value);
  5668. if (!is_numeric($value) && $value != '') {
  5669. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5670. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5671. return -1;
  5672. } elseif ($value === '') {
  5673. $value = null;
  5674. }
  5675. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5676. $this->array_options["options_".$key] = $value;
  5677. break;
  5678. /*case 'select': // Not required, we chosed value='0' for undefined values
  5679. if ($value=='-1')
  5680. {
  5681. $this->array_options[$key] = null;
  5682. }
  5683. break;*/
  5684. case 'price':
  5685. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  5686. break;
  5687. case 'date':
  5688. case 'datetime':
  5689. if (empty($this->array_options["options_".$key])) {
  5690. $this->array_options["options_".$key] = null;
  5691. } else {
  5692. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5693. }
  5694. break;
  5695. case 'boolean':
  5696. if (empty($this->array_options["options_".$key])) {
  5697. $this->array_options["options_".$key] = null;
  5698. }
  5699. break;
  5700. /*
  5701. case 'link':
  5702. $param_list = array_keys($attributeParam['options']);
  5703. // 0 : ObjectName
  5704. // 1 : classPath
  5705. $InfoFieldList = explode(":", $param_list[0]);
  5706. dol_include_once($InfoFieldList[1]);
  5707. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  5708. {
  5709. if ($value == '-1') // -1 is key for no defined in combo list of objects
  5710. {
  5711. $new_array_options[$key] = '';
  5712. } elseif ($value) {
  5713. $object = new $InfoFieldList[0]($this->db);
  5714. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  5715. else $res = $object->fetch('', $value); // For compatibility
  5716. if ($res > 0) $new_array_options[$key] = $object->id;
  5717. else {
  5718. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5719. $this->db->rollback();
  5720. return -1;
  5721. }
  5722. }
  5723. } else {
  5724. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5725. }
  5726. break;
  5727. */
  5728. }
  5729. $this->db->begin();
  5730. $linealreadyfound = 0;
  5731. // 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)
  5732. $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5733. $resql = $this->db->query($sql);
  5734. if ($resql) {
  5735. $tmpobj = $this->db->fetch_object($resql);
  5736. if ($tmpobj) {
  5737. $linealreadyfound = $tmpobj->nb;
  5738. }
  5739. }
  5740. if ($linealreadyfound) {
  5741. if ($this->array_options["options_".$key] === null) {
  5742. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key." = null";
  5743. } else {
  5744. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
  5745. }
  5746. $sql .= " WHERE fk_object = ".((int) $this->id);
  5747. } else {
  5748. $result = $this->insertExtraFields('', $user);
  5749. if ($result < 0) {
  5750. $error++;
  5751. }
  5752. }
  5753. $resql = $this->db->query($sql);
  5754. if (!$resql) {
  5755. $error++;
  5756. $this->error = $this->db->lasterror();
  5757. }
  5758. if (!$error && $trigger) {
  5759. // Call trigger
  5760. $this->context = array('extrafieldupdate'=>1);
  5761. $result = $this->call_trigger($trigger, $userused);
  5762. if ($result < 0) {
  5763. $error++;
  5764. }
  5765. // End call trigger
  5766. }
  5767. if ($error) {
  5768. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  5769. $this->db->rollback();
  5770. return -1;
  5771. } else {
  5772. $this->db->commit();
  5773. return 1;
  5774. }
  5775. } else {
  5776. return 0;
  5777. }
  5778. }
  5779. /**
  5780. * Update an extra language value for the current object.
  5781. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5782. *
  5783. * @param string $key Key of the extrafield (without starting 'options_')
  5784. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5785. * @param User $userused Object user
  5786. * @return int -1=error, O=did nothing, 1=OK
  5787. * @see updateExtraFields(), insertExtraLanguages()
  5788. */
  5789. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  5790. {
  5791. global $conf, $langs, $user;
  5792. if (empty($userused)) {
  5793. $userused = $user;
  5794. }
  5795. $error = 0;
  5796. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5797. return 0; // For avoid conflicts if trigger used
  5798. }
  5799. return 0;
  5800. }
  5801. /**
  5802. * Return HTML string to put an input field into a page
  5803. * Code very similar with showInputField of extra fields
  5804. *
  5805. * @param array $val Array of properties for field to show (used only if ->fields not defined)
  5806. * @param string $key Key of attribute
  5807. * @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)
  5808. * @param string $moreparam To add more parameters on html input tag
  5809. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5810. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5811. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  5812. * @param int $nonewbutton Force to not show the new button on field that are links to object
  5813. * @return string
  5814. */
  5815. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  5816. {
  5817. global $conf, $langs, $form;
  5818. if (!is_object($form)) {
  5819. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  5820. $form = new Form($this->db);
  5821. }
  5822. if (!empty($this->fields)) {
  5823. $val = $this->fields[$key];
  5824. }
  5825. // Validation tests and output
  5826. $fieldValidationErrorMsg = '';
  5827. $validationClass = '';
  5828. $fieldValidationErrorMsg = $this->getFieldError($key);
  5829. if (!empty($fieldValidationErrorMsg)) {
  5830. $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
  5831. } else {
  5832. $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
  5833. }
  5834. $out = '';
  5835. $type = '';
  5836. $isDependList = 0;
  5837. $param = array();
  5838. $param['options'] = array();
  5839. $reg = array();
  5840. $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
  5841. // Because we work on extrafields
  5842. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5843. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5844. $type = 'link';
  5845. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5846. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5847. $type = 'link';
  5848. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  5849. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5850. $type = 'link';
  5851. } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5852. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5853. $type = 'sellist';
  5854. } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5855. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5856. $type = 'sellist';
  5857. } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
  5858. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5859. $type = 'sellist';
  5860. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  5861. $param['options'] = array();
  5862. $type = 'varchar';
  5863. $size = $reg[1];
  5864. } elseif (preg_match('/varchar/', $val['type'])) {
  5865. $param['options'] = array();
  5866. $type = 'varchar';
  5867. } else {
  5868. $param['options'] = array();
  5869. $type = $this->fields[$key]['type'];
  5870. }
  5871. // Special case that force options and type ($type can be integer, varchar, ...)
  5872. if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
  5873. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  5874. $type = 'select';
  5875. }
  5876. $label = $this->fields[$key]['label'];
  5877. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  5878. $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
  5879. $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
  5880. $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
  5881. $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
  5882. $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
  5883. $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
  5884. $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
  5885. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  5886. $objectid = $this->id;
  5887. if ($computed) {
  5888. if (!preg_match('/^search_/', $keyprefix)) {
  5889. return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  5890. } else {
  5891. return '';
  5892. }
  5893. }
  5894. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  5895. if (empty($morecss) && !empty($val['css'])) {
  5896. $morecss = $val['css'];
  5897. } elseif (empty($morecss)) {
  5898. if ($type == 'date') {
  5899. $morecss = 'minwidth100imp';
  5900. } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
  5901. $morecss = 'minwidth200imp';
  5902. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  5903. $morecss = 'maxwidth75';
  5904. } elseif ($type == 'url') {
  5905. $morecss = 'minwidth400';
  5906. } elseif ($type == 'boolean') {
  5907. $morecss = '';
  5908. } else {
  5909. if (round($size) < 12) {
  5910. $morecss = 'minwidth100';
  5911. } elseif (round($size) <= 48) {
  5912. $morecss = 'minwidth200';
  5913. } else {
  5914. $morecss = 'minwidth400';
  5915. }
  5916. }
  5917. }
  5918. // Add validation state class
  5919. if (!empty($validationClass)) {
  5920. $morecss.= ' '.$validationClass;
  5921. }
  5922. if (in_array($type, array('date'))) {
  5923. $tmp = explode(',', $size);
  5924. $newsize = $tmp[0];
  5925. $showtime = 0;
  5926. // Do not show current date when field not required (see selectDate() method)
  5927. if (!$required && $value == '') {
  5928. $value = '-1';
  5929. }
  5930. // TODO Must also support $moreparam
  5931. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  5932. } elseif (in_array($type, array('datetime'))) {
  5933. $tmp = explode(',', $size);
  5934. $newsize = $tmp[0];
  5935. $showtime = 1;
  5936. // Do not show current date when field not required (see selectDate() method)
  5937. if (!$required && $value == '') $value = '-1';
  5938. // TODO Must also support $moreparam
  5939. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
  5940. } elseif (in_array($type, array('duration'))) {
  5941. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  5942. } elseif (in_array($type, array('int', 'integer'))) {
  5943. $tmp = explode(',', $size);
  5944. $newsize = $tmp[0];
  5945. $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' : '').'>';
  5946. } elseif (in_array($type, array('real'))) {
  5947. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5948. } elseif (preg_match('/varchar/', $type)) {
  5949. $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' : '').'>';
  5950. } elseif (in_array($type, array('mail', 'phone', 'url'))) {
  5951. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5952. } elseif (preg_match('/^text/', $type)) {
  5953. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  5954. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5955. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  5956. $out = $doleditor->Create(1);
  5957. } else {
  5958. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5959. }
  5960. } elseif (preg_match('/^html/', $type)) {
  5961. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  5962. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5963. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, !empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
  5964. $out = $doleditor->Create(1);
  5965. } else {
  5966. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5967. }
  5968. } elseif ($type == 'boolean') {
  5969. $checked = '';
  5970. if (!empty($value)) {
  5971. $checked = ' checked value="1" ';
  5972. } else {
  5973. $checked = ' value="1" ';
  5974. }
  5975. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  5976. } elseif ($type == 'price') {
  5977. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5978. $value = price($value);
  5979. }
  5980. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  5981. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  5982. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5983. $value = price($value);
  5984. }
  5985. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  5986. } elseif ($type == 'select') {
  5987. $out = '';
  5988. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  5989. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5990. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  5991. }
  5992. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  5993. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
  5994. $out .= '<option value="0">&nbsp;</option>';
  5995. }
  5996. foreach ($param['options'] as $key => $val) {
  5997. if ((string) $key == '') {
  5998. continue;
  5999. }
  6000. list($val, $parent) = explode('|', $val);
  6001. $out .= '<option value="'.$key.'"';
  6002. $out .= (((string) $value == (string) $key) ? ' selected' : '');
  6003. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6004. $out .= '>'.$val.'</option>';
  6005. }
  6006. $out .= '</select>';
  6007. } elseif ($type == 'sellist') {
  6008. $out = '';
  6009. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6010. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6011. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6012. }
  6013. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6014. if (is_array($param['options'])) {
  6015. $param_list = array_keys($param['options']);
  6016. $InfoFieldList = explode(":", $param_list[0]);
  6017. $parentName = '';
  6018. $parentField = '';
  6019. // 0 : tableName
  6020. // 1 : label field name
  6021. // 2 : key fields name (if differ of rowid)
  6022. // 3 : key field parent (for dependent lists)
  6023. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6024. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6025. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6026. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6027. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6028. } else {
  6029. $keyList = $InfoFieldList[2].' as rowid';
  6030. }
  6031. }
  6032. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6033. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6034. $keyList .= ', '.$parentField;
  6035. }
  6036. $fields_label = explode('|', $InfoFieldList[1]);
  6037. if (is_array($fields_label)) {
  6038. $keyList .= ', ';
  6039. $keyList .= implode(', ', $fields_label);
  6040. }
  6041. $sqlwhere = '';
  6042. $sql = "SELECT ".$keyList;
  6043. $sql .= " FROM ".MAIN_DB_PREFIX.$InfoFieldList[0];
  6044. if (!empty($InfoFieldList[4])) {
  6045. // can use SELECT request
  6046. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6047. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6048. }
  6049. // current object id can be use into filter
  6050. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6051. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6052. } else {
  6053. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6054. }
  6055. //We have to join on extrafield table
  6056. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6057. $sql .= " as main, ".MAIN_DB_PREFIX.$InfoFieldList[0]."_extrafields as extra";
  6058. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  6059. } else {
  6060. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  6061. }
  6062. } else {
  6063. $sqlwhere .= ' WHERE 1=1';
  6064. }
  6065. // Some tables may have field, some other not. For the moment we disable it.
  6066. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6067. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  6068. }
  6069. $sql .= $sqlwhere;
  6070. //print $sql;
  6071. $sql .= ' ORDER BY '.implode(', ', $fields_label);
  6072. dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
  6073. $resql = $this->db->query($sql);
  6074. if ($resql) {
  6075. $out .= '<option value="0">&nbsp;</option>';
  6076. $num = $this->db->num_rows($resql);
  6077. $i = 0;
  6078. while ($i < $num) {
  6079. $labeltoshow = '';
  6080. $obj = $this->db->fetch_object($resql);
  6081. // Several field into label (eq table:code|libelle:rowid)
  6082. $notrans = false;
  6083. $fields_label = explode('|', $InfoFieldList[1]);
  6084. if (count($fields_label) > 1) {
  6085. $notrans = true;
  6086. foreach ($fields_label as $field_toshow) {
  6087. $labeltoshow .= $obj->$field_toshow.' ';
  6088. }
  6089. } else {
  6090. $labeltoshow = $obj->{$InfoFieldList[1]};
  6091. }
  6092. $labeltoshow = dol_trunc($labeltoshow, 45);
  6093. if ($value == $obj->rowid) {
  6094. foreach ($fields_label as $field_toshow) {
  6095. $translabel = $langs->trans($obj->$field_toshow);
  6096. if ($translabel != $obj->$field_toshow) {
  6097. $labeltoshow = dol_trunc($translabel).' ';
  6098. } else {
  6099. $labeltoshow = dol_trunc($obj->$field_toshow).' ';
  6100. }
  6101. }
  6102. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6103. } else {
  6104. if (!$notrans) {
  6105. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6106. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6107. $labeltoshow = dol_trunc($translabel, 18);
  6108. } else {
  6109. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
  6110. }
  6111. }
  6112. if (empty($labeltoshow)) {
  6113. $labeltoshow = '(not defined)';
  6114. }
  6115. if ($value == $obj->rowid) {
  6116. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6117. }
  6118. if (!empty($InfoFieldList[3]) && $parentField) {
  6119. $parent = $parentName.':'.$obj->{$parentField};
  6120. $isDependList = 1;
  6121. }
  6122. $out .= '<option value="'.$obj->rowid.'"';
  6123. $out .= ($value == $obj->rowid ? ' selected' : '');
  6124. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6125. $out .= '>'.$labeltoshow.'</option>';
  6126. }
  6127. $i++;
  6128. }
  6129. $this->db->free($resql);
  6130. } else {
  6131. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6132. }
  6133. }
  6134. $out .= '</select>';
  6135. } elseif ($type == 'checkbox') {
  6136. $value_arr = explode(',', $value);
  6137. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, $morecss, 0, '100%');
  6138. } elseif ($type == 'radio') {
  6139. $out = '';
  6140. foreach ($param['options'] as $keyopt => $val) {
  6141. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  6142. $out .= ' value="'.$keyopt.'"';
  6143. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  6144. $out .= ($value == $keyopt ? 'checked' : '');
  6145. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
  6146. }
  6147. } elseif ($type == 'chkbxlst') {
  6148. if (is_array($value)) {
  6149. $value_arr = $value;
  6150. } else {
  6151. $value_arr = explode(',', $value);
  6152. }
  6153. if (is_array($param['options'])) {
  6154. $param_list = array_keys($param['options']);
  6155. $InfoFieldList = explode(":", $param_list[0]);
  6156. $parentName = '';
  6157. $parentField = '';
  6158. // 0 : tableName
  6159. // 1 : label field name
  6160. // 2 : key fields name (if differ of rowid)
  6161. // 3 : key field parent (for dependent lists)
  6162. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6163. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6164. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6165. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6166. $keyList .= ', '.$parentField;
  6167. }
  6168. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6169. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6170. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6171. } else {
  6172. $keyList = $InfoFieldList[2].' as rowid';
  6173. }
  6174. }
  6175. $fields_label = explode('|', $InfoFieldList[1]);
  6176. if (is_array($fields_label)) {
  6177. $keyList .= ', ';
  6178. $keyList .= implode(', ', $fields_label);
  6179. }
  6180. $sqlwhere = '';
  6181. $sql = "SELECT ".$keyList;
  6182. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6183. if (!empty($InfoFieldList[4])) {
  6184. // can use SELECT request
  6185. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6186. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6187. }
  6188. // current object id can be use into filter
  6189. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6190. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6191. } else {
  6192. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6193. }
  6194. // We have to join on extrafield table
  6195. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6196. $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
  6197. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  6198. } else {
  6199. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  6200. }
  6201. } else {
  6202. $sqlwhere .= ' WHERE 1=1';
  6203. }
  6204. // Some tables may have field, some other not. For the moment we disable it.
  6205. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6206. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  6207. }
  6208. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  6209. // print $sql;
  6210. $sql .= $sqlwhere;
  6211. dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
  6212. $resql = $this->db->query($sql);
  6213. if ($resql) {
  6214. $num = $this->db->num_rows($resql);
  6215. $i = 0;
  6216. $data = array();
  6217. while ($i < $num) {
  6218. $labeltoshow = '';
  6219. $obj = $this->db->fetch_object($resql);
  6220. $notrans = false;
  6221. // Several field into label (eq table:code|libelle:rowid)
  6222. $fields_label = explode('|', $InfoFieldList[1]);
  6223. if (count($fields_label) > 1) {
  6224. $notrans = true;
  6225. foreach ($fields_label as $field_toshow) {
  6226. $labeltoshow .= $obj->$field_toshow.' ';
  6227. }
  6228. } else {
  6229. $labeltoshow = $obj->{$InfoFieldList[1]};
  6230. }
  6231. $labeltoshow = dol_trunc($labeltoshow, 45);
  6232. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6233. foreach ($fields_label as $field_toshow) {
  6234. $translabel = $langs->trans($obj->$field_toshow);
  6235. if ($translabel != $obj->$field_toshow) {
  6236. $labeltoshow = dol_trunc($translabel, 18).' ';
  6237. } else {
  6238. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  6239. }
  6240. }
  6241. $data[$obj->rowid] = $labeltoshow;
  6242. } else {
  6243. if (!$notrans) {
  6244. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6245. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6246. $labeltoshow = dol_trunc($translabel, 18);
  6247. } else {
  6248. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  6249. }
  6250. }
  6251. if (empty($labeltoshow)) {
  6252. $labeltoshow = '(not defined)';
  6253. }
  6254. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6255. $data[$obj->rowid] = $labeltoshow;
  6256. }
  6257. if (!empty($InfoFieldList[3]) && $parentField) {
  6258. $parent = $parentName.':'.$obj->{$parentField};
  6259. $isDependList = 1;
  6260. }
  6261. $data[$obj->rowid] = $labeltoshow;
  6262. }
  6263. $i++;
  6264. }
  6265. $this->db->free($resql);
  6266. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
  6267. } else {
  6268. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6269. }
  6270. }
  6271. } elseif ($type == 'link') {
  6272. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
  6273. $param_list_array = explode(':', $param_list[0]);
  6274. $showempty = (($required && $default != '') ? 0 : 1);
  6275. if (!preg_match('/search_/', $keyprefix)) {
  6276. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6277. if (!empty($this->fields[$key]['picto'])) {
  6278. $morecss .= ' widthcentpercentminusxx';
  6279. } else {
  6280. $morecss .= ' widthcentpercentminusx';
  6281. }
  6282. } else {
  6283. if (!empty($this->fields[$key]['picto'])) {
  6284. $morecss .= ' widthcentpercentminusx';
  6285. }
  6286. }
  6287. }
  6288. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  6289. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6290. 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".
  6291. list($class, $classfile) = explode(':', $param_list[0]);
  6292. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
  6293. $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  6294. } else {
  6295. $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  6296. }
  6297. $paramforthenewlink = '';
  6298. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  6299. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  6300. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  6301. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  6302. $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>';
  6303. }
  6304. }
  6305. } elseif ($type == 'password') {
  6306. // If prefix is 'search_', field is used as a filter, we use a common text field.
  6307. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  6308. } elseif ($type == 'array') {
  6309. $newval = $val;
  6310. $newval['type'] = 'varchar(256)';
  6311. $out = '';
  6312. if (!empty($value)) {
  6313. foreach ($value as $option) {
  6314. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6315. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  6316. }
  6317. }
  6318. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6319. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6320. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  6321. if (!empty($conf->use_javascript_ajax)) {
  6322. $out .= '
  6323. <script>
  6324. $(document).ready(function() {
  6325. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  6326. $("'.dol_escape_js($newInput).'").insertBefore(this);
  6327. });
  6328. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  6329. $(this).parent().remove();
  6330. });
  6331. });
  6332. </script>';
  6333. }
  6334. }
  6335. if (!empty($hidden)) {
  6336. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  6337. }
  6338. if ($isDependList==1) {
  6339. $out .= $this->getJSListDependancies('_common');
  6340. }
  6341. /* Add comments
  6342. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  6343. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  6344. */
  6345. // Display error message for field
  6346. if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
  6347. $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
  6348. }
  6349. return $out;
  6350. }
  6351. /**
  6352. * Return HTML string to show a field into a page
  6353. * Code very similar with showOutputField of extra fields
  6354. *
  6355. * @param array $val Array of properties of field to show
  6356. * @param string $key Key of attribute
  6357. * @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)
  6358. * @param string $moreparam To add more parametes on html input tag
  6359. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6360. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6361. * @param mixed $morecss Value for css to define size. May also be a numeric.
  6362. * @return string
  6363. */
  6364. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  6365. {
  6366. global $conf, $langs, $form;
  6367. if (!is_object($form)) {
  6368. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6369. $form = new Form($this->db);
  6370. }
  6371. $objectid = $this->id; // Not used ???
  6372. $label = empty($val['label']) ? '' : $val['label'];
  6373. $type = empty($val['type']) ? '' : $val['type'];
  6374. $size = empty($val['css']) ? '' : $val['css'];
  6375. $reg = array();
  6376. // Convert var to be able to share same code than showOutputField of extrafields
  6377. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6378. $type = 'varchar'; // convert varchar(xx) int varchar
  6379. $size = $reg[1];
  6380. } elseif (preg_match('/varchar/', $type)) {
  6381. $type = 'varchar'; // convert varchar(xx) int varchar
  6382. }
  6383. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6384. $type = 'select';
  6385. }
  6386. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6387. $type = 'link';
  6388. }
  6389. $default = empty($val['default']) ? '' : $val['default'];
  6390. $computed = empty($val['computed']) ? '' : $val['computed'];
  6391. $unique = empty($val['unique']) ? '' : $val['unique'];
  6392. $required = empty($val['required']) ? '' : $val['required'];
  6393. $param = array();
  6394. $param['options'] = array();
  6395. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6396. $param['options'] = $val['arrayofkeyval'];
  6397. }
  6398. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6399. $type = 'link';
  6400. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6401. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6402. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6403. $type = 'sellist';
  6404. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6405. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6406. $type = 'sellist';
  6407. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6408. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6409. $type = 'sellist';
  6410. }
  6411. $langfile = empty($val['langfile']) ? '' : $val['langfile'];
  6412. $list = (empty($val['list']) ? '' : $val['list']);
  6413. $help = (empty($val['help']) ? '' : $val['help']);
  6414. $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)
  6415. if ($hidden) {
  6416. return '';
  6417. }
  6418. // If field is a computed field, value must become result of compute
  6419. if ($computed) {
  6420. // Make the eval of compute string
  6421. //var_dump($computed);
  6422. $value = dol_eval($computed, 1, 0, '');
  6423. }
  6424. if (empty($morecss)) {
  6425. if ($type == 'date') {
  6426. $morecss = 'minwidth100imp';
  6427. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6428. $morecss = 'minwidth200imp';
  6429. } elseif (in_array($type, array('int', 'double', 'price'))) {
  6430. $morecss = 'maxwidth75';
  6431. } elseif ($type == 'url') {
  6432. $morecss = 'minwidth400';
  6433. } elseif ($type == 'boolean') {
  6434. $morecss = '';
  6435. } else {
  6436. if (is_numeric($size) && round($size) < 12) {
  6437. $morecss = 'minwidth100';
  6438. } elseif (is_numeric($size) && round($size) <= 48) {
  6439. $morecss = 'minwidth200';
  6440. } else {
  6441. $morecss = 'minwidth400';
  6442. }
  6443. }
  6444. }
  6445. // Format output value differently according to properties of field
  6446. if ($key == 'ref' && method_exists($this, 'getNomUrl')) {
  6447. $value = $this->getNomUrl(1, '', 0, '', 1);
  6448. } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
  6449. $value = $this->getLibStatut(3);
  6450. } elseif ($type == 'date') {
  6451. if (!empty($value)) {
  6452. $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
  6453. } else {
  6454. $value = '';
  6455. }
  6456. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6457. if (!empty($value)) {
  6458. $value = dol_print_date($value, 'dayhour', 'tzuserrel');
  6459. } else {
  6460. $value = '';
  6461. }
  6462. } elseif ($type == 'duration') {
  6463. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6464. if (!is_null($value) && $value !== '') {
  6465. $value = convertSecondToTime($value, 'allhourmin');
  6466. }
  6467. } elseif ($type == 'double' || $type == 'real') {
  6468. if (!is_null($value) && $value !== '') {
  6469. $value = price($value);
  6470. }
  6471. } elseif ($type == 'boolean') {
  6472. $checked = '';
  6473. if (!empty($value)) {
  6474. $checked = ' checked ';
  6475. }
  6476. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  6477. } elseif ($type == 'mail') {
  6478. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  6479. } elseif ($type == 'url') {
  6480. $value = dol_print_url($value, '_blank', 32, 1);
  6481. } elseif ($type == 'phone') {
  6482. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
  6483. } elseif ($type == 'price') {
  6484. if (!is_null($value) && $value !== '') {
  6485. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  6486. }
  6487. } elseif ($type == 'select') {
  6488. $value = $param['options'][$value];
  6489. } elseif ($type == 'sellist') {
  6490. $param_list = array_keys($param['options']);
  6491. $InfoFieldList = explode(":", $param_list[0]);
  6492. $selectkey = "rowid";
  6493. $keyList = 'rowid';
  6494. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6495. $selectkey = $InfoFieldList[2];
  6496. $keyList = $InfoFieldList[2].' as rowid';
  6497. }
  6498. $fields_label = explode('|', $InfoFieldList[1]);
  6499. if (is_array($fields_label)) {
  6500. $keyList .= ', ';
  6501. $keyList .= implode(', ', $fields_label);
  6502. }
  6503. $sql = "SELECT ".$keyList;
  6504. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6505. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6506. $sql .= ' as main';
  6507. }
  6508. if ($selectkey == 'rowid' && empty($value)) {
  6509. $sql .= " WHERE ".$selectkey." = 0";
  6510. } elseif ($selectkey == 'rowid') {
  6511. $sql .= " WHERE ".$selectkey." = ".((int) $value);
  6512. } else {
  6513. $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
  6514. }
  6515. //$sql.= ' AND entity = '.$conf->entity;
  6516. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  6517. $resql = $this->db->query($sql);
  6518. if ($resql) {
  6519. $value = ''; // value was used, so now we reste it to use it to build final output
  6520. $obj = $this->db->fetch_object($resql);
  6521. // Several field into label (eq table:code|libelle:rowid)
  6522. $fields_label = explode('|', $InfoFieldList[1]);
  6523. if (is_array($fields_label) && count($fields_label) > 1) {
  6524. foreach ($fields_label as $field_toshow) {
  6525. $translabel = '';
  6526. if (!empty($obj->$field_toshow)) {
  6527. $translabel = $langs->trans($obj->$field_toshow);
  6528. }
  6529. if ($translabel != $field_toshow) {
  6530. $value .= dol_trunc($translabel, 18).' ';
  6531. } else {
  6532. $value .= $obj->$field_toshow.' ';
  6533. }
  6534. }
  6535. } else {
  6536. $translabel = '';
  6537. if (!empty($obj->{$InfoFieldList[1]})) {
  6538. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6539. }
  6540. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6541. $value = dol_trunc($translabel, 18);
  6542. } else {
  6543. $value = $obj->{$InfoFieldList[1]};
  6544. }
  6545. }
  6546. } else {
  6547. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6548. }
  6549. } elseif ($type == 'radio') {
  6550. $value = $param['options'][$value];
  6551. } elseif ($type == 'checkbox') {
  6552. $value_arr = explode(',', $value);
  6553. $value = '';
  6554. if (is_array($value_arr) && count($value_arr) > 0) {
  6555. $toprint = array();
  6556. foreach ($value_arr as $keyval => $valueval) {
  6557. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  6558. }
  6559. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6560. }
  6561. } elseif ($type == 'chkbxlst') {
  6562. $value_arr = explode(',', $value);
  6563. $param_list = array_keys($param['options']);
  6564. $InfoFieldList = explode(":", $param_list[0]);
  6565. $selectkey = "rowid";
  6566. $keyList = 'rowid';
  6567. if (count($InfoFieldList) >= 3) {
  6568. $selectkey = $InfoFieldList[2];
  6569. $keyList = $InfoFieldList[2].' as rowid';
  6570. }
  6571. $fields_label = explode('|', $InfoFieldList[1]);
  6572. if (is_array($fields_label)) {
  6573. $keyList .= ', ';
  6574. $keyList .= implode(', ', $fields_label);
  6575. }
  6576. $sql = "SELECT ".$keyList;
  6577. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6578. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6579. $sql .= ' as main';
  6580. }
  6581. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  6582. // $sql.= ' AND entity = '.$conf->entity;
  6583. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  6584. $resql = $this->db->query($sql);
  6585. if ($resql) {
  6586. $value = ''; // value was used, so now we reste it to use it to build final output
  6587. $toprint = array();
  6588. while ($obj = $this->db->fetch_object($resql)) {
  6589. // Several field into label (eq table:code|libelle:rowid)
  6590. $fields_label = explode('|', $InfoFieldList[1]);
  6591. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6592. if (is_array($fields_label) && count($fields_label) > 1) {
  6593. foreach ($fields_label as $field_toshow) {
  6594. $translabel = '';
  6595. if (!empty($obj->$field_toshow)) {
  6596. $translabel = $langs->trans($obj->$field_toshow);
  6597. }
  6598. if ($translabel != $field_toshow) {
  6599. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6600. } else {
  6601. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->$field_toshow.'</li>';
  6602. }
  6603. }
  6604. } else {
  6605. $translabel = '';
  6606. if (!empty($obj->{$InfoFieldList[1]})) {
  6607. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6608. }
  6609. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6610. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6611. } else {
  6612. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->{$InfoFieldList[1]}.'</li>';
  6613. }
  6614. }
  6615. }
  6616. }
  6617. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6618. } else {
  6619. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6620. }
  6621. } elseif ($type == 'link') {
  6622. $out = '';
  6623. // only if something to display (perf)
  6624. if ($value) {
  6625. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6626. $InfoFieldList = explode(":", $param_list[0]);
  6627. $classname = $InfoFieldList[0];
  6628. $classpath = $InfoFieldList[1];
  6629. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  6630. $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
  6631. if (!empty($classpath)) {
  6632. dol_include_once($InfoFieldList[1]);
  6633. if ($classname && class_exists($classname)) {
  6634. $object = new $classname($this->db);
  6635. if ($object->element === 'product') { // Special cas for product because default valut of fetch are wrong
  6636. $object->fetch($value, '', '', '', 0, 1, 1);
  6637. } else {
  6638. $object->fetch($value);
  6639. }
  6640. $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
  6641. }
  6642. } else {
  6643. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  6644. return 'Error bad setup of extrafield';
  6645. }
  6646. } else {
  6647. $value = '';
  6648. }
  6649. } elseif (preg_match('/^(text|html)/', $type)) {
  6650. $value = dol_htmlentitiesbr($value);
  6651. } elseif ($type == 'password') {
  6652. $value = preg_replace('/./i', '*', $value);
  6653. } elseif ($type == 'array') {
  6654. $value = implode('<br>', $value);
  6655. }
  6656. //print $type.'-'.$size.'-'.$value;
  6657. $out = $value;
  6658. return $out;
  6659. }
  6660. /**
  6661. * clear validation message result for a field
  6662. *
  6663. * @param string $fieldKey Key of attribute to clear
  6664. * @return null
  6665. */
  6666. public function clearFieldError($fieldKey)
  6667. {
  6668. $this->error = '';
  6669. unset($this->validateFieldsErrors[$fieldKey]);
  6670. }
  6671. /**
  6672. * set validation error message a field
  6673. *
  6674. * @param string $fieldKey Key of attribute
  6675. * @param string $msg the field error message
  6676. * @return null
  6677. */
  6678. public function setFieldError($fieldKey, $msg = '')
  6679. {
  6680. global $langs;
  6681. if (empty($msg)) { $msg = $langs->trans("UnknowError"); }
  6682. $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
  6683. }
  6684. /**
  6685. * get field error message
  6686. *
  6687. * @param string $fieldKey Key of attribute
  6688. * @return string
  6689. */
  6690. public function getFieldError($fieldKey)
  6691. {
  6692. if (!empty($this->validateFieldsErrors[$fieldKey])) {
  6693. return $this->validateFieldsErrors[$fieldKey];
  6694. }
  6695. return '';
  6696. }
  6697. /**
  6698. * Return validation test result for a field
  6699. *
  6700. * @param array $val Array of properties of field to show
  6701. * @param string $fieldKey Key of attribute
  6702. * @param string $fieldValue value of attribute
  6703. * @return bool return false if fail true on success, see $this->error for error message
  6704. */
  6705. public function validateField($val, $fieldKey, $fieldValue)
  6706. {
  6707. global $langs;
  6708. if (!class_exists('Validate')) { require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php'; }
  6709. $this->clearFieldError($fieldKey);
  6710. if (!isset($val[$fieldKey])) {
  6711. $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
  6712. return false;
  6713. }
  6714. $param = array();
  6715. $param['options'] = array();
  6716. $type = $val[$fieldKey]['type'];
  6717. $required = false;
  6718. if (isset($val[$fieldKey]['notnull']) && $val[$fieldKey]['notnull'] === 1) {
  6719. // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  6720. $required = true;
  6721. }
  6722. $maxSize = 0;
  6723. $minSize = 0;
  6724. //
  6725. // PREPARE Elements
  6726. //
  6727. // Convert var to be able to share same code than showOutputField of extrafields
  6728. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6729. $type = 'varchar'; // convert varchar(xx) int varchar
  6730. $maxSize = $reg[1];
  6731. } elseif (preg_match('/varchar/', $type)) {
  6732. $type = 'varchar'; // convert varchar(xx) int varchar
  6733. }
  6734. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6735. $type = 'select';
  6736. }
  6737. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6738. $type = 'link';
  6739. }
  6740. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6741. $param['options'] = $val['arrayofkeyval'];
  6742. }
  6743. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6744. $type = 'link';
  6745. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6746. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6747. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6748. $type = 'sellist';
  6749. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6750. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6751. $type = 'sellist';
  6752. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6753. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6754. $type = 'sellist';
  6755. }
  6756. //
  6757. // TEST Value
  6758. //
  6759. // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
  6760. $validate = new Validate($this->db, $langs);
  6761. // little trick : to perform tests with good performances sort tests by quick to low
  6762. //
  6763. // COMMON TESTS
  6764. //
  6765. // Required test and empty value
  6766. if ($required && !$validate->isNotEmptyString($fieldValue)) {
  6767. $this->setFieldError($fieldKey, $validate->error);
  6768. return false;
  6769. } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
  6770. // if no value sent and the field is not mandatory, no need to perform tests
  6771. return true;
  6772. }
  6773. // MAX Size test
  6774. if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
  6775. $this->setFieldError($fieldKey, $validate->error);
  6776. return false;
  6777. }
  6778. // MIN Size test
  6779. if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
  6780. $this->setFieldError($fieldKey, $validate->error);
  6781. return false;
  6782. }
  6783. //
  6784. // TESTS for TYPE
  6785. //
  6786. if (in_array($type, array('date', 'datetime', 'timestamp'))) {
  6787. if (!$validate->isTimestamp($fieldValue)) {
  6788. $this->setFieldError($fieldKey, $validate->error);
  6789. return false;
  6790. } else { return true; }
  6791. } elseif ($type == 'duration') {
  6792. if (!$validate->isDuration($fieldValue)) {
  6793. $this->setFieldError($fieldKey, $validate->error);
  6794. return false;
  6795. } else { return true; }
  6796. } elseif (in_array($type, array('double', 'real', 'price'))) {
  6797. // is numeric
  6798. if (!$validate->isNumeric($fieldValue)) {
  6799. $this->setFieldError($fieldKey, $validate->error);
  6800. return false;
  6801. } else { return true; }
  6802. } elseif ($type == 'boolean') {
  6803. if (!$validate->isBool($fieldValue)) {
  6804. $this->setFieldError($fieldKey, $validate->error);
  6805. return false;
  6806. } else { return true; }
  6807. } elseif ($type == 'mail') {
  6808. if (!$validate->isEmail($fieldValue)) {
  6809. $this->setFieldError($fieldKey, $validate->error);
  6810. return false;
  6811. }
  6812. } elseif ($type == 'url') {
  6813. if (!$validate->isUrl($fieldValue)) {
  6814. $this->setFieldError($fieldKey, $validate->error);
  6815. return false;
  6816. } else { return true; }
  6817. } elseif ($type == 'phone') {
  6818. if (!$validate->isPhone($fieldValue)) {
  6819. $this->setFieldError($fieldKey, $validate->error);
  6820. return false;
  6821. } else { return true; }
  6822. } elseif ($type == 'select' || $type == 'radio') {
  6823. if (!isset($param['options'][$fieldValue])) {
  6824. $this->error = $langs->trans('RequireValidValue');
  6825. return false;
  6826. } else { return true; }
  6827. } elseif ($type == 'sellist' || $type == 'chkbxlst') {
  6828. $param_list = array_keys($param['options']);
  6829. $InfoFieldList = explode(":", $param_list[0]);
  6830. $value_arr = explode(',', $fieldValue);
  6831. $value_arr = array_map(array($this->db, 'escape'), $value_arr);
  6832. $selectkey = "rowid";
  6833. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6834. $selectkey = $InfoFieldList[2];
  6835. }
  6836. if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
  6837. $this->setFieldError($fieldKey, $validate->error);
  6838. return false;
  6839. } else { return true; }
  6840. } elseif ($type == 'link') {
  6841. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6842. $InfoFieldList = explode(":", $param_list[0]);
  6843. $classname = $InfoFieldList[0];
  6844. $classpath = $InfoFieldList[1];
  6845. if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
  6846. $this->setFieldError($fieldKey, $validate->error);
  6847. return false;
  6848. } else { return true; }
  6849. }
  6850. // if no test failled all is ok
  6851. return true;
  6852. }
  6853. /**
  6854. * Function to show lines of extrafields with output datas.
  6855. * 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
  6856. *
  6857. * @param Extrafields $extrafields Extrafield Object
  6858. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  6859. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  6860. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  6861. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  6862. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  6863. * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...)
  6864. * @return string
  6865. */
  6866. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
  6867. {
  6868. global $db, $conf, $langs, $action, $form, $hookmanager;
  6869. if (!is_object($form)) {
  6870. $form = new Form($db);
  6871. }
  6872. $out = '';
  6873. $parameters = array();
  6874. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  6875. if (empty($reshook)) {
  6876. if (key_exists('label', $extrafields->attributes[$this->table_element]) && is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0) {
  6877. $out .= "\n";
  6878. $out .= '<!-- commonobject:showOptionals --> ';
  6879. $out .= "\n";
  6880. $extrafields_collapse_num = '';
  6881. $e = 0;
  6882. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
  6883. // Show only the key field in params
  6884. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
  6885. continue;
  6886. }
  6887. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  6888. $enabled = 1;
  6889. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  6890. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '1');
  6891. }
  6892. if (empty($enabled)) {
  6893. continue;
  6894. }
  6895. $visibility = 1;
  6896. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  6897. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '1');
  6898. }
  6899. $perms = 1;
  6900. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  6901. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '1');
  6902. }
  6903. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
  6904. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  6905. } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
  6906. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  6907. } elseif ($mode == 'view' && empty($visibility)) {
  6908. continue;
  6909. }
  6910. if (empty($perms)) {
  6911. continue;
  6912. }
  6913. // Load language if required
  6914. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  6915. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  6916. }
  6917. $colspan = 0;
  6918. if (is_array($params) && count($params) > 0 && $display_type=='card') {
  6919. if (array_key_exists('cols', $params)) {
  6920. $colspan = $params['cols'];
  6921. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  6922. $reg = array();
  6923. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  6924. $colspan = $reg[1];
  6925. } else {
  6926. $colspan = $params['colspan'];
  6927. }
  6928. }
  6929. }
  6930. $colspan = intval($colspan);
  6931. switch ($mode) {
  6932. case "view":
  6933. $value = $this->array_options["options_".$key.$keysuffix]; // Value may be clean or formated later
  6934. break;
  6935. case "create":
  6936. case "edit":
  6937. // We get the value of property found with GETPOST so it takes into account:
  6938. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  6939. $check = 'alphanohtml';
  6940. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  6941. $check = 'restricthtml';
  6942. }
  6943. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  6944. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  6945. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
  6946. if (is_array($getposttemp)) {
  6947. // $getposttemp is an array but following code expects a comma separated string
  6948. $value = implode(",", $getposttemp);
  6949. } else {
  6950. $value = $getposttemp;
  6951. }
  6952. } else {
  6953. $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.
  6954. }
  6955. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  6956. break;
  6957. }
  6958. // Output value of the current field
  6959. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  6960. $extrafields_collapse_num = '';
  6961. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  6962. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  6963. $extrafield_param_list = array_keys($extrafield_param['options']);
  6964. if (count($extrafield_param_list) > 0) {
  6965. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  6966. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  6967. $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  6968. }
  6969. }
  6970. }
  6971. // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
  6972. $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type);
  6973. } else {
  6974. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  6975. $csstyle = '';
  6976. if (is_array($params) && count($params) > 0) {
  6977. if (array_key_exists('class', $params)) {
  6978. $class .= $params['class'].' ';
  6979. }
  6980. if (array_key_exists('style', $params)) {
  6981. $csstyle = $params['style'];
  6982. }
  6983. }
  6984. // add html5 elements
  6985. $domData = ' data-element="extrafield"';
  6986. $domData .= ' data-targetelement="'.$this->element.'"';
  6987. $domData .= ' data-targetid="'.$this->id.'"';
  6988. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  6989. if ($display_type=='card') {
  6990. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
  6991. $colspan = 0;
  6992. }
  6993. if ($action == 'selectlines') {
  6994. $colspan++;
  6995. }
  6996. }
  6997. // Convert date into timestamp format (value in memory must be a timestamp)
  6998. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
  6999. $datenotinstring = $this->array_options['options_'.$key];
  7000. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7001. $datenotinstring = $this->db->jdate($datenotinstring);
  7002. }
  7003. $datekey = $keyprefix.'options_'.$key.$keysuffix;
  7004. $value = (GETPOSTISSET($datekey)) ? dol_mktime(12, 0, 0, GETPOST($datekey.'month', 'int', 3), GETPOST($datekey.'day', 'int', 3), GETPOST($datekey.'year', 'int', 3)) : $datenotinstring;
  7005. }
  7006. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
  7007. $datenotinstring = $this->array_options['options_'.$key];
  7008. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7009. $datenotinstring = $this->db->jdate($datenotinstring);
  7010. }
  7011. $timekey = $keyprefix.'options_'.$key.$keysuffix;
  7012. $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;
  7013. }
  7014. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  7015. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
  7016. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? price2num($value) : $this->array_options['options_'.$key];
  7017. }
  7018. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  7019. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int', 'boolean'))) {
  7020. if ($action == 'create') {
  7021. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  7022. }
  7023. }
  7024. $labeltoshow = $langs->trans($label);
  7025. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  7026. if ($display_type == 'card') {
  7027. $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="valuefieldcreate '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >';
  7028. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action == 'view' || $action == 'valid' || $action == 'editline')) {
  7029. $out .= '<td></td>';
  7030. }
  7031. $out .= '<td class="wordbreak';
  7032. } elseif ($display_type == 'line') {
  7033. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="valuefieldlinecreate '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >';
  7034. $out .= '<div style="display: inline-block; padding-right:4px" class="wordbreak';
  7035. }
  7036. //$out .= "titlefield";
  7037. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  7038. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  7039. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  7040. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  7041. $out .= '">';
  7042. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7043. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7044. } else {
  7045. $out .= $labeltoshow;
  7046. }
  7047. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7048. $out .= '&nbsp;<span style="color: red">*</span>';
  7049. }
  7050. } else {
  7051. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7052. $out .= ' fieldrequired';
  7053. }
  7054. $out .= '">';
  7055. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7056. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7057. } else {
  7058. $out .= $labeltoshow;
  7059. }
  7060. }
  7061. $out .= ($display_type == 'card' ? '</td>' : '</div>');
  7062. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  7063. if ($display_type == 'card') {
  7064. // 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
  7065. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="'.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  7066. } elseif ($display_type == 'line') {
  7067. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').' style="display: inline-block" class="'.$this->element.'_extras_'.$key.' extra_inline_'.$extrafields->attributes[$this->table_element]['type'][$key].'">';
  7068. }
  7069. switch ($mode) {
  7070. case "view":
  7071. $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
  7072. break;
  7073. case "create":
  7074. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7075. break;
  7076. case "edit":
  7077. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7078. break;
  7079. }
  7080. $out .= ($display_type=='card' ? '</td>' : '</div>');
  7081. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
  7082. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7083. } else {
  7084. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7085. }
  7086. $e++;
  7087. }
  7088. }
  7089. $out .= "\n";
  7090. // Add code to manage list depending on others
  7091. if (!empty($conf->use_javascript_ajax)) {
  7092. $out .= $this->getJSListDependancies();
  7093. }
  7094. $out .= '<!-- /showOptionals --> '."\n";
  7095. }
  7096. }
  7097. $out .= $hookmanager->resPrint;
  7098. return $out;
  7099. }
  7100. /**
  7101. * @param string $type Type for prefix
  7102. * @return string Javacript code to manage dependency
  7103. */
  7104. public function getJSListDependancies($type = '_extra')
  7105. {
  7106. $out = '
  7107. <script>
  7108. jQuery(document).ready(function() {
  7109. function showOptions'.$type.'(child_list, parent_list, orig_select)
  7110. {
  7111. var val = $("select[name=\""+parent_list+"\"]").val();
  7112. var parentVal = parent_list + ":" + val;
  7113. if(typeof val == "string"){
  7114. if(val != "") {
  7115. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7116. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7117. $("select[name=\""+child_list+"\"]").append(options);
  7118. } else {
  7119. var options = orig_select.find("option[parent]").clone();
  7120. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7121. $("select[name=\""+child_list+"\"]").append(options);
  7122. }
  7123. } else if(val > 0) {
  7124. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7125. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7126. $("select[name=\""+child_list+"\"]").append(options);
  7127. } else {
  7128. var options = orig_select.find("option[parent]").clone();
  7129. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7130. $("select[name=\""+child_list+"\"]").append(options);
  7131. }
  7132. }
  7133. function setListDependencies'.$type.'() {
  7134. jQuery("select option[parent]").parent().each(function() {
  7135. var orig_select = {};
  7136. var child_list = $(this).attr("name");
  7137. orig_select[child_list] = $(this).clone();
  7138. var parent = $(this).find("option[parent]:first").attr("parent");
  7139. var infos = parent.split(":");
  7140. var parent_list = infos[0];
  7141. //Hide daughters lists
  7142. if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
  7143. $("#"+child_list).hide();
  7144. //Show mother lists
  7145. } else if ($("#"+parent_list).val() != 0){
  7146. $("#"+parent_list).show();
  7147. }
  7148. //Show the child list if the parent list value is selected
  7149. $("select[name=\""+parent_list+"\"]").click(function() {
  7150. if ($(this).val() != 0){
  7151. $("#"+child_list).show()
  7152. }
  7153. });
  7154. //When we change parent list
  7155. $("select[name=\""+parent_list+"\"]").change(function() {
  7156. showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
  7157. //Select the value 0 on child list after a change on the parent list
  7158. $("#"+child_list).val(0).trigger("change");
  7159. //Hide child lists if the parent value is set to 0
  7160. if ($(this).val() == 0){
  7161. $("#"+child_list).hide();
  7162. }
  7163. });
  7164. });
  7165. }
  7166. setListDependencies'.$type.'();
  7167. });
  7168. </script>'."\n";
  7169. return $out;
  7170. }
  7171. /**
  7172. * Returns the rights used for this class
  7173. * @return stdClass
  7174. */
  7175. public function getRights()
  7176. {
  7177. global $user;
  7178. $element = $this->element;
  7179. if ($element == 'facturerec') {
  7180. $element = 'facture';
  7181. }
  7182. return $user->rights->{$element};
  7183. }
  7184. /**
  7185. * Function used to replace a thirdparty id with another one.
  7186. * This function is meant to be called from replaceThirdparty with the appropiate tables
  7187. * Column name fk_soc MUST be used to identify thirdparties
  7188. *
  7189. * @param DoliDB $db Database handler
  7190. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  7191. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  7192. * @param string[] $tables Tables that need to be changed
  7193. * @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)
  7194. * @return bool True if success, False if error
  7195. */
  7196. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7197. {
  7198. foreach ($tables as $table) {
  7199. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
  7200. if (!$db->query($sql)) {
  7201. if ($ignoreerrors) {
  7202. return true; // TODO Not enough. If there is A-B on kept thirdarty and B-C on old one, we must get A-B-C after merge. Not A-B.
  7203. }
  7204. //$this->errors = $db->lasterror();
  7205. return false;
  7206. }
  7207. }
  7208. return true;
  7209. }
  7210. /**
  7211. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  7212. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  7213. * else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  7214. * else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  7215. * else set min buy price as buy price
  7216. *
  7217. * @param float $unitPrice Product unit price
  7218. * @param float $discountPercent Line discount percent
  7219. * @param int $fk_product Product id
  7220. * @return float <0 if KO, buyprice if OK
  7221. */
  7222. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  7223. {
  7224. global $conf;
  7225. $buyPrice = 0;
  7226. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
  7227. // When ForceBuyingPriceIfNull is set
  7228. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  7229. } else {
  7230. // Get cost price for margin calculation
  7231. if (!empty($fk_product) && $fk_product > 0) {
  7232. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
  7233. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7234. $product = new Product($this->db);
  7235. $result = $product->fetch($fk_product);
  7236. if ($result <= 0) {
  7237. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7238. return -1;
  7239. }
  7240. if ($product->cost_price > 0) {
  7241. $buyPrice = $product->cost_price;
  7242. } elseif ($product->pmp > 0) {
  7243. $buyPrice = $product->pmp;
  7244. }
  7245. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
  7246. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7247. $product = new Product($this->db);
  7248. $result = $product->fetch($fk_product);
  7249. if ($result <= 0) {
  7250. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7251. return -1;
  7252. }
  7253. if ($product->pmp > 0) {
  7254. $buyPrice = $product->pmp;
  7255. }
  7256. }
  7257. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
  7258. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  7259. $productFournisseur = new ProductFournisseur($this->db);
  7260. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
  7261. $buyPrice = $productFournisseur->fourn_unitprice;
  7262. } elseif ($result < 0) {
  7263. $this->errors[] = $productFournisseur->error;
  7264. return -2;
  7265. }
  7266. }
  7267. }
  7268. }
  7269. return $buyPrice;
  7270. }
  7271. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7272. /**
  7273. * Show photos of an object (nbmax maximum), into several columns
  7274. *
  7275. * @param string $modulepart 'product', 'ticket', ...
  7276. * @param string $sdir Directory to scan (full absolute path)
  7277. * @param int $size 0=original size, 1='small' use thumbnail if possible
  7278. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  7279. * @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'.
  7280. * @param int $showfilename 1=Show filename
  7281. * @param int $showaction 1=Show icon with action links (resize, delete)
  7282. * @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.
  7283. * @param int $maxWidth Max width of original image when size='small'
  7284. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  7285. * @param int $notitle Do not add title tag on image
  7286. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  7287. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  7288. */
  7289. public function show_photos($modulepart, $sdir, $size = 0, $nbmax = 0, $nbbyrow = 5, $showfilename = 0, $showaction = 0, $maxHeight = 120, $maxWidth = 160, $nolink = 0, $notitle = 0, $usesharelink = 0)
  7290. {
  7291. // phpcs:enable
  7292. global $conf, $user, $langs;
  7293. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7294. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  7295. $sortfield = 'position_name';
  7296. $sortorder = 'asc';
  7297. $dir = $sdir.'/';
  7298. $pdir = '/';
  7299. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7300. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7301. // For backward compatibility
  7302. if ($modulepart == 'product') {
  7303. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  7304. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7305. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7306. }
  7307. }
  7308. // Defined relative dir to DOL_DATA_ROOT
  7309. $relativedir = '';
  7310. if ($dir) {
  7311. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  7312. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  7313. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  7314. }
  7315. $dirthumb = $dir.'thumbs/';
  7316. $pdirthumb = $pdir.'thumbs/';
  7317. $return = '<!-- Photo -->'."\n";
  7318. $nbphoto = 0;
  7319. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  7320. /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
  7321. {
  7322. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  7323. $filearray=array_merge($filearray, $filearrayold);
  7324. }*/
  7325. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  7326. if (count($filearray)) {
  7327. if ($sortfield && $sortorder) {
  7328. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  7329. }
  7330. foreach ($filearray as $key => $val) {
  7331. $photo = '';
  7332. $file = $val['name'];
  7333. //if (! utf8_check($file)) $file=utf8_encode($file); // To be sure file is stored in UTF8 in memory
  7334. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  7335. if (image_format_supported($file) >= 0) {
  7336. $nbphoto++;
  7337. $photo = $file;
  7338. $viewfilename = $file;
  7339. if ($size == 1 || $size == 'small') { // Format vignette
  7340. // Find name of thumb file
  7341. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  7342. if (!dol_is_file($dirthumb.$photo_vignette)) {
  7343. $photo_vignette = '';
  7344. }
  7345. // Get filesize of original file
  7346. $imgarray = dol_getImageSize($dir.$photo);
  7347. if ($nbbyrow > 0) {
  7348. if ($nbphoto == 1) {
  7349. $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  7350. }
  7351. if ($nbphoto % $nbbyrow == 1) {
  7352. $return .= '<tr class="center valignmiddle" style="border: 1px">';
  7353. }
  7354. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
  7355. } elseif ($nbbyrow < 0) {
  7356. $return .= '<div class="inline-block">';
  7357. }
  7358. $return .= "\n";
  7359. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  7360. if (empty($nolink)) {
  7361. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  7362. if ($urladvanced) {
  7363. $return .= '<a href="'.$urladvanced.'">';
  7364. } else {
  7365. $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
  7366. }
  7367. }
  7368. // Show image (width height=$maxHeight)
  7369. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  7370. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  7371. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  7372. if ($notitle) {
  7373. $alt = '';
  7374. }
  7375. $addphotorefcss = 1;
  7376. if ($usesharelink) {
  7377. if ($val['share']) {
  7378. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7379. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  7380. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7381. } else {
  7382. $return .= '<!-- Show original file -->';
  7383. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7384. }
  7385. } else {
  7386. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  7387. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  7388. }
  7389. } else {
  7390. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7391. $return .= '<!-- Show thumb -->';
  7392. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').' maxwidth150onsmartphone maxwidth200" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdirthumb.$photo_vignette).'" title="'.dol_escape_htmltag($alt).'">';
  7393. } else {
  7394. $return .= '<!-- Show original file -->';
  7395. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" title="'.dol_escape_htmltag($alt).'">';
  7396. }
  7397. }
  7398. if (empty($nolink)) {
  7399. $return .= '</a>';
  7400. }
  7401. $return .= "\n";
  7402. if ($showfilename) {
  7403. $return .= '<br>'.$viewfilename;
  7404. }
  7405. if ($showaction) {
  7406. $return .= '<br>';
  7407. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  7408. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
  7409. $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>';
  7410. }
  7411. // Special cas for product
  7412. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7413. // Link to resize
  7414. $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; ';
  7415. // Link to delete
  7416. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7417. $return .= img_delete().'</a>';
  7418. }
  7419. }
  7420. $return .= "\n";
  7421. if ($nbbyrow > 0) {
  7422. $return .= '</td>';
  7423. if (($nbphoto % $nbbyrow) == 0) {
  7424. $return .= '</tr>';
  7425. }
  7426. } elseif ($nbbyrow < 0) {
  7427. $return .= '</div>';
  7428. }
  7429. }
  7430. if (empty($size)) { // Format origine
  7431. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  7432. if ($showfilename) {
  7433. $return .= '<br>'.$viewfilename;
  7434. }
  7435. if ($showaction) {
  7436. // Special case for product
  7437. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7438. // Link to resize
  7439. $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; ';
  7440. // Link to delete
  7441. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7442. $return .= img_delete().'</a>';
  7443. }
  7444. }
  7445. }
  7446. // On continue ou on arrete de boucler ?
  7447. if ($nbmax && $nbphoto >= $nbmax) {
  7448. break;
  7449. }
  7450. }
  7451. }
  7452. if ($size == 1 || $size == 'small') {
  7453. if ($nbbyrow > 0) {
  7454. // Ferme tableau
  7455. while ($nbphoto % $nbbyrow) {
  7456. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  7457. $nbphoto++;
  7458. }
  7459. if ($nbphoto) {
  7460. $return .= '</table>';
  7461. }
  7462. }
  7463. }
  7464. }
  7465. $this->nbphoto = $nbphoto;
  7466. return $return;
  7467. }
  7468. /**
  7469. * Function test if type is array
  7470. *
  7471. * @param array $info content informations of field
  7472. * @return bool true if array
  7473. */
  7474. protected function isArray($info)
  7475. {
  7476. if (is_array($info)) {
  7477. if (isset($info['type']) && $info['type'] == 'array') {
  7478. return true;
  7479. } else {
  7480. return false;
  7481. }
  7482. }
  7483. return false;
  7484. }
  7485. /**
  7486. * Function test if type is date
  7487. *
  7488. * @param array $info content informations of field
  7489. * @return bool true if date
  7490. */
  7491. public function isDate($info)
  7492. {
  7493. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
  7494. return true;
  7495. }
  7496. return false;
  7497. }
  7498. /**
  7499. * Function test if type is duration
  7500. *
  7501. * @param array $info content informations of field
  7502. * @return bool true if field of type duration
  7503. */
  7504. public function isDuration($info)
  7505. {
  7506. if (is_array($info)) {
  7507. if (isset($info['type']) && ($info['type'] == 'duration')) {
  7508. return true;
  7509. } else {
  7510. return false;
  7511. }
  7512. } else {
  7513. return false;
  7514. }
  7515. }
  7516. /**
  7517. * Function test if type is integer
  7518. *
  7519. * @param array $info content informations of field
  7520. * @return bool true if integer
  7521. */
  7522. public function isInt($info)
  7523. {
  7524. if (is_array($info)) {
  7525. if (isset($info['type']) && ($info['type'] == 'int' || preg_match('/^integer/i', $info['type']))) {
  7526. return true;
  7527. } else {
  7528. return false;
  7529. }
  7530. } else {
  7531. return false;
  7532. }
  7533. }
  7534. /**
  7535. * Function test if type is float
  7536. *
  7537. * @param array $info content informations of field
  7538. * @return bool true if float
  7539. */
  7540. public function isFloat($info)
  7541. {
  7542. if (is_array($info)) {
  7543. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
  7544. return true;
  7545. } else {
  7546. return false;
  7547. }
  7548. }
  7549. return false;
  7550. }
  7551. /**
  7552. * Function test if type is text
  7553. *
  7554. * @param array $info content informations of field
  7555. * @return bool true if type text
  7556. */
  7557. public function isText($info)
  7558. {
  7559. if (is_array($info)) {
  7560. if (isset($info['type']) && $info['type'] == 'text') {
  7561. return true;
  7562. } else {
  7563. return false;
  7564. }
  7565. }
  7566. return false;
  7567. }
  7568. /**
  7569. * Function test if field can be null
  7570. *
  7571. * @param array $info content informations of field
  7572. * @return bool true if it can be null
  7573. */
  7574. protected function canBeNull($info)
  7575. {
  7576. if (is_array($info)) {
  7577. if (isset($info['notnull']) && $info['notnull'] != '1') {
  7578. return true;
  7579. } else {
  7580. return false;
  7581. }
  7582. }
  7583. return true;
  7584. }
  7585. /**
  7586. * Function test if field is forced to null if zero or empty
  7587. *
  7588. * @param array $info content informations of field
  7589. * @return bool true if forced to null
  7590. */
  7591. protected function isForcedToNullIfZero($info)
  7592. {
  7593. if (is_array($info)) {
  7594. if (isset($info['notnull']) && $info['notnull'] == '-1') {
  7595. return true;
  7596. } else {
  7597. return false;
  7598. }
  7599. }
  7600. return false;
  7601. }
  7602. /**
  7603. * Function test if is indexed
  7604. *
  7605. * @param array $info content informations of field
  7606. * @return bool
  7607. */
  7608. protected function isIndex($info)
  7609. {
  7610. if (is_array($info)) {
  7611. if (isset($info['index']) && $info['index'] == true) {
  7612. return true;
  7613. } else {
  7614. return false;
  7615. }
  7616. }
  7617. return false;
  7618. }
  7619. /**
  7620. * Function to prepare a part of the query for insert.
  7621. * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
  7622. * $this->${field} should be a clean value. The page can run
  7623. *
  7624. * @return array
  7625. */
  7626. protected function setSaveQuery()
  7627. {
  7628. global $conf;
  7629. $queryarray = array();
  7630. foreach ($this->fields as $field => $info) { // Loop on definition of fields
  7631. // Depending on field type ('datetime', ...)
  7632. if ($this->isDate($info)) {
  7633. if (empty($this->{$field})) {
  7634. $queryarray[$field] = null;
  7635. } else {
  7636. $queryarray[$field] = $this->db->idate($this->{$field});
  7637. }
  7638. } elseif ($this->isDuration($info)) {
  7639. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7640. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7641. if (!isset($this->{$field})) {
  7642. $queryarray[$field] = 0;
  7643. } else {
  7644. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7645. }
  7646. } else {
  7647. $queryarray[$field] = null;
  7648. }
  7649. } elseif ($this->isInt($info) || $this->isFloat($info)) {
  7650. if ($field == 'entity' && is_null($this->{$field})) {
  7651. $queryarray[$field] = $conf->entity;
  7652. } else {
  7653. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7654. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7655. if (!isset($this->{$field})) {
  7656. $queryarray[$field] = 0;
  7657. } elseif ($this->isInt($info)) {
  7658. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7659. } elseif ($this->isFloat($info)) {
  7660. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7661. }
  7662. } else {
  7663. $queryarray[$field] = null;
  7664. }
  7665. }
  7666. } else {
  7667. // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
  7668. // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
  7669. $queryarray[$field] = $this->{$field};
  7670. }
  7671. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
  7672. unset($queryarray[$field]);
  7673. }
  7674. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
  7675. $queryarray[$field] = null; // May force 0 to null
  7676. }
  7677. }
  7678. return $queryarray;
  7679. }
  7680. /**
  7681. * Function to load data from a SQL pointer into properties of current object $this
  7682. *
  7683. * @param stdClass $obj Contain data of object from database
  7684. * @return void
  7685. */
  7686. public function setVarsFromFetchObj(&$obj)
  7687. {
  7688. global $db;
  7689. foreach ($this->fields as $field => $info) {
  7690. if ($this->isDate($info)) {
  7691. if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
  7692. $this->{$field} = '';
  7693. } else {
  7694. $this->{$field} = $db->jdate($obj->{$field});
  7695. }
  7696. } elseif ($this->isInt($info)) {
  7697. if ($field == 'rowid') {
  7698. $this->id = (int) $obj->{$field};
  7699. } else {
  7700. if ($this->isForcedToNullIfZero($info)) {
  7701. if (empty($obj->{$field})) {
  7702. $this->{$field} = null;
  7703. } else {
  7704. $this->{$field} = (double) $obj->{$field};
  7705. }
  7706. } else {
  7707. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7708. $this->{$field} = (int) $obj->{$field};
  7709. } else {
  7710. $this->{$field} = null;
  7711. }
  7712. }
  7713. }
  7714. } elseif ($this->isFloat($info)) {
  7715. if ($this->isForcedToNullIfZero($info)) {
  7716. if (empty($obj->{$field})) {
  7717. $this->{$field} = null;
  7718. } else {
  7719. $this->{$field} = (double) $obj->{$field};
  7720. }
  7721. } else {
  7722. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7723. $this->{$field} = (double) $obj->{$field};
  7724. } else {
  7725. $this->{$field} = null;
  7726. }
  7727. }
  7728. } else {
  7729. $this->{$field} = $obj->{$field};
  7730. }
  7731. }
  7732. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  7733. if (!isset($this->fields['ref']) && isset($this->id)) {
  7734. $this->ref = $this->id;
  7735. }
  7736. }
  7737. /**
  7738. * Function to concat keys of fields
  7739. *
  7740. * @param string $alias String of alias of table for fields. For example 't'.
  7741. * @return string list of alias fields
  7742. */
  7743. public function getFieldList($alias = '')
  7744. {
  7745. $keys = array_keys($this->fields);
  7746. if (!empty($alias)) {
  7747. $keys_with_alias = array();
  7748. foreach ($keys as $fieldname) {
  7749. $keys_with_alias[] = $alias . '.' . $fieldname;
  7750. }
  7751. return implode(',', $keys_with_alias);
  7752. } else {
  7753. return implode(',', $keys);
  7754. }
  7755. }
  7756. /**
  7757. * Add quote to field value if necessary
  7758. *
  7759. * @param string|int $value Value to protect
  7760. * @param array $fieldsentry Properties of field
  7761. * @return string
  7762. */
  7763. protected function quote($value, $fieldsentry)
  7764. {
  7765. if (is_null($value)) {
  7766. return 'NULL';
  7767. } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
  7768. return price2num("$value");
  7769. } elseif ($fieldsentry['type'] == 'boolean') {
  7770. if ($value) {
  7771. return 'true';
  7772. } else {
  7773. return 'false';
  7774. }
  7775. } else {
  7776. return "'".$this->db->escape($value)."'";
  7777. }
  7778. }
  7779. /**
  7780. * Create object into database
  7781. *
  7782. * @param User $user User that creates
  7783. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7784. * @return int <0 if KO, Id of created object if OK
  7785. */
  7786. public function createCommon(User $user, $notrigger = false)
  7787. {
  7788. global $langs;
  7789. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  7790. $error = 0;
  7791. $now = dol_now();
  7792. $fieldvalues = $this->setSaveQuery();
  7793. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
  7794. $fieldvalues['date_creation'] = $this->db->idate($now);
  7795. }
  7796. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
  7797. $fieldvalues['fk_user_creat'] = $user->id;
  7798. }
  7799. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  7800. if (array_key_exists('ref', $fieldvalues)) {
  7801. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  7802. }
  7803. $keys = array();
  7804. $values = array(); // Array to store string forged for SQL syntax
  7805. foreach ($fieldvalues as $k => $v) {
  7806. $keys[$k] = $k;
  7807. $value = $this->fields[$k];
  7808. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  7809. }
  7810. // Clean and check mandatory
  7811. foreach ($keys as $key) {
  7812. // If field is an implicit foreign key field
  7813. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  7814. $values[$key] = '';
  7815. }
  7816. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  7817. $values[$key] = '';
  7818. }
  7819. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
  7820. $error++;
  7821. $langs->load("errors");
  7822. dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
  7823. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  7824. }
  7825. // If value is null and there is a default value for field
  7826. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
  7827. $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
  7828. }
  7829. // If field is an implicit foreign key field
  7830. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  7831. if (isset($this->fields[$key]['default'])) {
  7832. $values[$key] = ((int) $this->fields[$key]['default']);
  7833. } else {
  7834. $values[$key] = 'null';
  7835. }
  7836. }
  7837. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
  7838. $values[$key] = 'null';
  7839. }
  7840. }
  7841. if ($error) {
  7842. return -1;
  7843. }
  7844. $this->db->begin();
  7845. if (!$error) {
  7846. $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element;
  7847. $sql .= " (".implode(", ", $keys).')';
  7848. $sql .= " VALUES (".implode(", ", $values).")"; // $values can contains 'abc' or 123
  7849. $res = $this->db->query($sql);
  7850. if (!$res) {
  7851. $error++;
  7852. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  7853. $this->errors[] = "ErrorRefAlreadyExists";
  7854. } else {
  7855. $this->errors[] = $this->db->lasterror();
  7856. }
  7857. }
  7858. }
  7859. if (!$error) {
  7860. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
  7861. }
  7862. // If we have a field ref with a default value of (PROV)
  7863. if (!$error) {
  7864. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
  7865. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
  7866. $resqlupdate = $this->db->query($sql);
  7867. if ($resqlupdate === false) {
  7868. $error++;
  7869. $this->errors[] = $this->db->lasterror();
  7870. } else {
  7871. $this->ref = '(PROV'.$this->id.')';
  7872. }
  7873. }
  7874. }
  7875. // Create extrafields
  7876. if (!$error) {
  7877. $result = $this->insertExtraFields();
  7878. if ($result < 0) {
  7879. $error++;
  7880. }
  7881. }
  7882. // Create lines
  7883. if (!empty($this->table_element_line) && !empty($this->fk_element)) {
  7884. $num = (is_array($this->lines) ? count($this->lines) : 0);
  7885. for ($i = 0; $i < $num; $i++) {
  7886. $line = $this->lines[$i];
  7887. $keyforparent = $this->fk_element;
  7888. $line->$keyforparent = $this->id;
  7889. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  7890. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  7891. if (!is_object($line)) {
  7892. $line = (object) $line;
  7893. }
  7894. $result = $line->create($user, 1);
  7895. if ($result < 0) {
  7896. $this->error = $line->error;
  7897. $this->db->rollback();
  7898. return -1;
  7899. }
  7900. }
  7901. }
  7902. // Triggers
  7903. if (!$error && !$notrigger) {
  7904. // Call triggers
  7905. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  7906. if ($result < 0) {
  7907. $error++;
  7908. }
  7909. // End call triggers
  7910. }
  7911. // Commit or rollback
  7912. if ($error) {
  7913. $this->db->rollback();
  7914. return -1;
  7915. } else {
  7916. $this->db->commit();
  7917. return $this->id;
  7918. }
  7919. }
  7920. /**
  7921. * Load object in memory from the database
  7922. *
  7923. * @param int $id Id object
  7924. * @param string $ref Ref
  7925. * @param string $morewhere More SQL filters (' AND ...')
  7926. * @return int <0 if KO, 0 if not found, >0 if OK
  7927. */
  7928. public function fetchCommon($id, $ref = null, $morewhere = '')
  7929. {
  7930. if (empty($id) && empty($ref) && empty($morewhere)) {
  7931. return -1;
  7932. }
  7933. $fieldlist = $this->getFieldList('t');
  7934. if (empty($fieldlist)) {
  7935. return 0;
  7936. }
  7937. $sql = "SELECT ".$fieldlist;
  7938. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element.' as t';
  7939. if (!empty($id)) {
  7940. $sql .= ' WHERE t.rowid = '.((int) $id);
  7941. } elseif (!empty($ref)) {
  7942. $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
  7943. } else {
  7944. $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  7945. }
  7946. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  7947. $sql .= ' AND t.entity IN ('.getEntity($this->table_element).')';
  7948. }
  7949. if ($morewhere) {
  7950. $sql .= $morewhere;
  7951. }
  7952. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  7953. $res = $this->db->query($sql);
  7954. if ($res) {
  7955. $obj = $this->db->fetch_object($res);
  7956. if ($obj) {
  7957. $this->setVarsFromFetchObj($obj);
  7958. // Retrieve all extrafield
  7959. // fetch optionals attributes and labels
  7960. $this->fetch_optionals();
  7961. return $this->id;
  7962. } else {
  7963. return 0;
  7964. }
  7965. } else {
  7966. $this->error = $this->db->lasterror();
  7967. $this->errors[] = $this->error;
  7968. return -1;
  7969. }
  7970. }
  7971. /**
  7972. * Load object in memory from the database
  7973. *
  7974. * @param string $morewhere More SQL filters (' AND ...')
  7975. * @return int <0 if KO, 0 if not found, >0 if OK
  7976. */
  7977. public function fetchLinesCommon($morewhere = '')
  7978. {
  7979. $objectlineclassname = get_class($this).'Line';
  7980. if (!class_exists($objectlineclassname)) {
  7981. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  7982. return -1;
  7983. }
  7984. $objectline = new $objectlineclassname($this->db);
  7985. $sql = "SELECT ".$objectline->getFieldList('l');
  7986. $sql .= " FROM ".MAIN_DB_PREFIX.$objectline->table_element." as l";
  7987. $sql .= " WHERE l.fk_".$this->db->escape($this->element)." = ".((int) $this->id);
  7988. if ($morewhere) {
  7989. $sql .= $morewhere;
  7990. }
  7991. if (isset($objectline->fields['position'])) {
  7992. $sql .= $this->db->order('position', 'ASC');
  7993. }
  7994. $resql = $this->db->query($sql);
  7995. if ($resql) {
  7996. $num_rows = $this->db->num_rows($resql);
  7997. $i = 0;
  7998. while ($i < $num_rows) {
  7999. $obj = $this->db->fetch_object($resql);
  8000. if ($obj) {
  8001. $newline = new $objectlineclassname($this->db);
  8002. $newline->setVarsFromFetchObj($obj);
  8003. $this->lines[] = $newline;
  8004. }
  8005. $i++;
  8006. }
  8007. return 1;
  8008. } else {
  8009. $this->error = $this->db->lasterror();
  8010. $this->errors[] = $this->error;
  8011. return -1;
  8012. }
  8013. }
  8014. /**
  8015. * Update object into database
  8016. *
  8017. * @param User $user User that modifies
  8018. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8019. * @return int <0 if KO, >0 if OK
  8020. */
  8021. public function updateCommon(User $user, $notrigger = false)
  8022. {
  8023. global $conf, $langs;
  8024. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  8025. $error = 0;
  8026. $now = dol_now();
  8027. $fieldvalues = $this->setSaveQuery();
  8028. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
  8029. $fieldvalues['date_modification'] = $this->db->idate($now);
  8030. }
  8031. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
  8032. $fieldvalues['fk_user_modif'] = $user->id;
  8033. }
  8034. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  8035. if (array_key_exists('ref', $fieldvalues)) {
  8036. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8037. }
  8038. // Add quotes and escape on fields with type string
  8039. $keys = array();
  8040. $values = array();
  8041. $tmp = array();
  8042. foreach ($fieldvalues as $k => $v) {
  8043. $keys[$k] = $k;
  8044. $value = $this->fields[$k];
  8045. $values[$k] = $this->quote($v, $value);
  8046. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  8047. }
  8048. // Clean and check mandatory fields
  8049. foreach ($keys as $key) {
  8050. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8051. $values[$key] = ''; // This is an implicit foreign key field
  8052. }
  8053. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8054. $values[$key] = ''; // This is an explicit foreign key field
  8055. }
  8056. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  8057. /*
  8058. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  8059. {
  8060. $error++;
  8061. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8062. }*/
  8063. }
  8064. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
  8065. $this->db->begin();
  8066. if (!$error) {
  8067. $res = $this->db->query($sql);
  8068. if (!$res) {
  8069. $error++;
  8070. $this->errors[] = $this->db->lasterror();
  8071. }
  8072. }
  8073. // Update extrafield
  8074. if (!$error) {
  8075. $result = $this->insertExtraFields();
  8076. if ($result < 0) {
  8077. $error++;
  8078. }
  8079. }
  8080. // Triggers
  8081. if (!$error && !$notrigger) {
  8082. // Call triggers
  8083. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  8084. if ($result < 0) {
  8085. $error++;
  8086. } //Do also here what you must do to rollback action if trigger fail
  8087. // End call triggers
  8088. }
  8089. // Commit or rollback
  8090. if ($error) {
  8091. $this->db->rollback();
  8092. return -1;
  8093. } else {
  8094. $this->db->commit();
  8095. return $this->id;
  8096. }
  8097. }
  8098. /**
  8099. * Delete object in database
  8100. *
  8101. * @param User $user User that deletes
  8102. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8103. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  8104. * @return int <=0 if KO, 0=Nothing done because object has child, >0 if OK
  8105. */
  8106. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  8107. {
  8108. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  8109. $error = 0;
  8110. $this->db->begin();
  8111. if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
  8112. foreach ($this->childtables as $table) {
  8113. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8114. $resql = $this->db->query($sql);
  8115. if (!$resql) {
  8116. $this->error = $this->db->lasterror();
  8117. $this->errors[] = $this->error;
  8118. $this->db->rollback();
  8119. return -1;
  8120. }
  8121. }
  8122. } elseif (!empty($this->fk_element) && !empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
  8123. $objectisused = $this->isObjectUsed($this->id);
  8124. if (!empty($objectisused)) {
  8125. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  8126. $this->error = 'ErrorRecordHasChildren';
  8127. $this->errors[] = $this->error;
  8128. $this->db->rollback();
  8129. return 0;
  8130. }
  8131. }
  8132. // Delete cascade first
  8133. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  8134. foreach ($this->childtablesoncascade as $table) {
  8135. $deleteFromObject = explode(':', $table);
  8136. if (count($deleteFromObject) >= 2) {
  8137. $className = str_replace('@', '', $deleteFromObject[0]);
  8138. $filePath = $deleteFromObject[1];
  8139. $columnName = $deleteFromObject[2];
  8140. $TMoreSQL = array();
  8141. $more_sql = $deleteFromObject[3];
  8142. if (!empty($more_sql)) {
  8143. $TMoreSQL['customsql'] = $more_sql;
  8144. }
  8145. if (dol_include_once($filePath)) {
  8146. $childObject = new $className($this->db);
  8147. if (method_exists($childObject, 'deleteByParentField')) {
  8148. $result = $childObject->deleteByParentField($this->id, $columnName, $TMoreSQL);
  8149. if ($result < 0) {
  8150. $error++;
  8151. $this->errors[] = $childObject->error;
  8152. break;
  8153. }
  8154. } else {
  8155. $error++;
  8156. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  8157. break;
  8158. }
  8159. } else {
  8160. $error++;
  8161. $this->errors[] = 'Cannot include child class file '.$filePath;
  8162. break;
  8163. }
  8164. } else {
  8165. // Delete record in child table
  8166. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8167. $resql = $this->db->query($sql);
  8168. if (!$resql) {
  8169. $error++;
  8170. $this->error = $this->db->lasterror();
  8171. $this->errors[] = $this->error;
  8172. break;
  8173. }
  8174. }
  8175. }
  8176. }
  8177. if (!$error) {
  8178. if (!$notrigger) {
  8179. // Call triggers
  8180. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  8181. if ($result < 0) {
  8182. $error++;
  8183. } // Do also here what you must do to rollback action if trigger fail
  8184. // End call triggers
  8185. }
  8186. }
  8187. // Delete llx_ecm_files
  8188. if (!$error) {
  8189. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  8190. if (!$res) {
  8191. $error++;
  8192. }
  8193. }
  8194. if (!$error && !empty($this->isextrafieldmanaged)) {
  8195. $result = $this->deleteExtraFields();
  8196. if ($result < 0) {
  8197. $error++;
  8198. }
  8199. }
  8200. if (!$error) {
  8201. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.((int) $this->id);
  8202. $resql = $this->db->query($sql);
  8203. if (!$resql) {
  8204. $error++;
  8205. $this->errors[] = $this->db->lasterror();
  8206. }
  8207. }
  8208. // Commit or rollback
  8209. if ($error) {
  8210. $this->db->rollback();
  8211. return -1;
  8212. } else {
  8213. $this->db->commit();
  8214. return 1;
  8215. }
  8216. }
  8217. /**
  8218. * Delete all child object from a parent ID
  8219. *
  8220. * @param int $parentId Parent Id
  8221. * @param string $parentField Name of Foreign key parent column
  8222. * @param array $filter an array filter
  8223. * @param string $filtermode AND or OR
  8224. * @return int <0 if KO, >0 if OK
  8225. * @throws Exception
  8226. */
  8227. public function deleteByParentField($parentId = 0, $parentField = '', $filter = array(), $filtermode = "AND")
  8228. {
  8229. global $user;
  8230. $error = 0;
  8231. $deleted = 0;
  8232. if (!empty($parentId) && !empty($parentField)) {
  8233. $this->db->begin();
  8234. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$this->table_element;
  8235. $sql .= " WHERE ".$parentField." = ".(int) $parentId;
  8236. // Manage filters
  8237. $sqlwhere = array();
  8238. if (count($filter) > 0) {
  8239. foreach ($filter as $key => $value) {
  8240. if ($key == 'customsql') {
  8241. $sqlwhere[] = $value;
  8242. } elseif (strpos($value, '%') === false) {
  8243. $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
  8244. } else {
  8245. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  8246. }
  8247. }
  8248. }
  8249. if (count($sqlwhere) > 0) {
  8250. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  8251. }
  8252. $resql = $this->db->query($sql);
  8253. if (!$resql) {
  8254. $this->errors[] = $this->db->lasterror();
  8255. $error++;
  8256. } else {
  8257. while ($obj = $this->db->fetch_object($resql)) {
  8258. $result = $this->fetch($obj->rowid);
  8259. if ($result < 0) {
  8260. $error++;
  8261. $this->errors[] = $this->error;
  8262. } else {
  8263. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  8264. $result = $this->delete();
  8265. } else {
  8266. $result = $this->delete($user);
  8267. }
  8268. if ($result < 0) {
  8269. $error++;
  8270. $this->errors[] = $this->error;
  8271. } else {
  8272. $deleted++;
  8273. }
  8274. }
  8275. }
  8276. }
  8277. if (empty($error)) {
  8278. $this->db->commit();
  8279. return $deleted;
  8280. } else {
  8281. $this->error = implode(', ', $this->errors);
  8282. $this->db->rollback();
  8283. return $error * -1;
  8284. }
  8285. }
  8286. return $deleted;
  8287. }
  8288. /**
  8289. * Delete a line of object in database
  8290. *
  8291. * @param User $user User that delete
  8292. * @param int $idline Id of line to delete
  8293. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8294. * @return int >0 if OK, <0 if KO
  8295. */
  8296. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  8297. {
  8298. global $conf;
  8299. $error = 0;
  8300. $tmpforobjectclass = get_class($this);
  8301. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  8302. // Call trigger
  8303. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  8304. if ($result < 0) {
  8305. return -1;
  8306. }
  8307. // End call triggers
  8308. $this->db->begin();
  8309. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  8310. $sql .= " WHERE rowid = ".((int) $idline);
  8311. dol_syslog(get_class($this)."::deleteLineCommon", LOG_DEBUG);
  8312. $resql = $this->db->query($sql);
  8313. if (!$resql) {
  8314. $this->error = "Error ".$this->db->lasterror();
  8315. $error++;
  8316. }
  8317. if (empty($error)) {
  8318. // Remove extrafields
  8319. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  8320. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  8321. $tmpobjectline->id = $idline;
  8322. $result = $tmpobjectline->deleteExtraFields();
  8323. if ($result < 0) {
  8324. $error++;
  8325. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  8326. }
  8327. }
  8328. }
  8329. if (empty($error)) {
  8330. $this->db->commit();
  8331. return 1;
  8332. } else {
  8333. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  8334. $this->db->rollback();
  8335. return -1;
  8336. }
  8337. }
  8338. /**
  8339. * Set to a status
  8340. *
  8341. * @param User $user Object user that modify
  8342. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  8343. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  8344. * @param string $triggercode Trigger code to use
  8345. * @return int <0 if KO, >0 if OK
  8346. */
  8347. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  8348. {
  8349. $error = 0;
  8350. $this->db->begin();
  8351. $statusfield = 'status';
  8352. if ($this->element == 'don' || $this->element == 'donation') {
  8353. $statusfield = 'fk_statut';
  8354. }
  8355. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  8356. $sql .= " SET ".$statusfield." = ".((int) $status);
  8357. $sql .= " WHERE rowid = ".((int) $this->id);
  8358. if ($this->db->query($sql)) {
  8359. if (!$error) {
  8360. $this->oldcopy = clone $this;
  8361. }
  8362. if (!$error && !$notrigger) {
  8363. // Call trigger
  8364. $result = $this->call_trigger($triggercode, $user);
  8365. if ($result < 0) {
  8366. $error++;
  8367. }
  8368. }
  8369. if (!$error) {
  8370. $this->status = $status;
  8371. $this->db->commit();
  8372. return 1;
  8373. } else {
  8374. $this->db->rollback();
  8375. return -1;
  8376. }
  8377. } else {
  8378. $this->error = $this->db->error();
  8379. $this->db->rollback();
  8380. return -1;
  8381. }
  8382. }
  8383. /**
  8384. * Initialise object with example values
  8385. * Id must be 0 if object instance is a specimen
  8386. *
  8387. * @return int
  8388. */
  8389. public function initAsSpecimenCommon()
  8390. {
  8391. global $user;
  8392. $this->id = 0;
  8393. $this->specimen = 1;
  8394. $fields = array(
  8395. 'label' => 'This is label',
  8396. 'ref' => 'ABCD1234',
  8397. 'description' => 'This is a description',
  8398. 'qty' => 123.12,
  8399. 'note_public' => 'Public note',
  8400. 'note_private' => 'Private note',
  8401. 'date_creation' => (dol_now() - 3600 * 48),
  8402. 'date_modification' => (dol_now() - 3600 * 24),
  8403. 'fk_user_creat' => $user->id,
  8404. 'fk_user_modif' => $user->id,
  8405. 'date' => dol_now(),
  8406. );
  8407. foreach ($fields as $key => $value) {
  8408. if (array_key_exists($key, $this->fields)) {
  8409. $this->{$key} = $value;
  8410. }
  8411. }
  8412. return 1;
  8413. }
  8414. /* Part for comments */
  8415. /**
  8416. * Load comments linked with current task
  8417. * @return boolean 1 if ok
  8418. */
  8419. public function fetchComments()
  8420. {
  8421. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  8422. $comment = new Comment($this->db);
  8423. $result = $comment->fetchAllFor($this->element, $this->id);
  8424. if ($result < 0) {
  8425. $this->errors = array_merge($this->errors, $comment->errors);
  8426. return -1;
  8427. } else {
  8428. $this->comments = $comment->comments;
  8429. }
  8430. return count($this->comments);
  8431. }
  8432. /**
  8433. * Return nb comments already posted
  8434. *
  8435. * @return int
  8436. */
  8437. public function getNbComments()
  8438. {
  8439. return count($this->comments);
  8440. }
  8441. /**
  8442. * Trim object parameters
  8443. *
  8444. * @param string[] $parameters array of parameters to trim
  8445. * @return void
  8446. */
  8447. public function trimParameters($parameters)
  8448. {
  8449. if (!is_array($parameters)) {
  8450. return;
  8451. }
  8452. foreach ($parameters as $parameter) {
  8453. if (isset($this->$parameter)) {
  8454. $this->$parameter = trim($this->$parameter);
  8455. }
  8456. }
  8457. }
  8458. /* Part for categories/tags */
  8459. /**
  8460. * Sets object to given categories.
  8461. *
  8462. * Deletes object from existing categories not supplied.
  8463. * Adds it to non existing supplied categories.
  8464. * Existing categories are left untouch.
  8465. *
  8466. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  8467. * @return int Array of category objects or < 0 if KO
  8468. */
  8469. public function getCategoriesCommon($type_categ)
  8470. {
  8471. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8472. // Get current categories
  8473. $c = new Categorie($this->db);
  8474. $existing = $c->containing($this->id, $type_categ, 'id');
  8475. return $existing;
  8476. }
  8477. /**
  8478. * Sets object to given categories.
  8479. *
  8480. * Adds it to non existing supplied categories.
  8481. * Deletes object from existing categories not supplied (if remove_existing==true).
  8482. * Existing categories are left untouch.
  8483. *
  8484. * @param int[]|int $categories Category ID or array of Categories IDs
  8485. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) definied into const class Categorie type
  8486. * @param boolean $remove_existing True: Remove existings categories from Object if not supplies by $categories, False: let them
  8487. * @return int <0 if KO, >0 if OK
  8488. */
  8489. public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
  8490. {
  8491. // Handle single category
  8492. if (!is_array($categories)) {
  8493. $categories = array($categories);
  8494. }
  8495. dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
  8496. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8497. if (empty($type_categ)) {
  8498. dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
  8499. return -1;
  8500. }
  8501. // Get current categories
  8502. $c = new Categorie($this->db);
  8503. $existing = $c->containing($this->id, $type_categ, 'id');
  8504. if ($remove_existing) {
  8505. // Diff
  8506. if (is_array($existing)) {
  8507. $to_del = array_diff($existing, $categories);
  8508. $to_add = array_diff($categories, $existing);
  8509. } else {
  8510. $to_del = array(); // Nothing to delete
  8511. $to_add = $categories;
  8512. }
  8513. } else {
  8514. $to_del = array(); // Nothing to delete
  8515. $to_add = array_diff($categories, $existing);
  8516. }
  8517. $error = 0;
  8518. $ok = 0;
  8519. // Process
  8520. foreach ($to_del as $del) {
  8521. if ($c->fetch($del) > 0) {
  8522. $result=$c->del_type($this, $type_categ);
  8523. if ($result < 0) {
  8524. $error++;
  8525. $this->error = $c->error;
  8526. $this->errors = $c->errors;
  8527. break;
  8528. } else {
  8529. $ok += $result;
  8530. }
  8531. }
  8532. }
  8533. foreach ($to_add as $add) {
  8534. if ($c->fetch($add) > 0) {
  8535. $result = $c->add_type($this, $type_categ);
  8536. if ($result < 0) {
  8537. $error++;
  8538. $this->error = $c->error;
  8539. $this->errors = $c->errors;
  8540. break;
  8541. } else {
  8542. $ok += $result;
  8543. }
  8544. }
  8545. }
  8546. return $error ? -1 * $error : $ok;
  8547. }
  8548. /**
  8549. * Copy related categories to another object
  8550. *
  8551. * @param int $fromId Id object source
  8552. * @param int $toId Id object cible
  8553. * @param string $type Type of category ('product', ...)
  8554. * @return int < 0 if error, > 0 if ok
  8555. */
  8556. public function cloneCategories($fromId, $toId, $type = '')
  8557. {
  8558. $this->db->begin();
  8559. if (empty($type)) {
  8560. $type = $this->table_element;
  8561. }
  8562. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8563. $categorystatic = new Categorie($this->db);
  8564. $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  8565. $sql .= " SELECT fk_categorie, $toId FROM ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  8566. $sql .= " WHERE fk_product = ".((int) $fromId);
  8567. if (!$this->db->query($sql)) {
  8568. $this->error = $this->db->lasterror();
  8569. $this->db->rollback();
  8570. return -1;
  8571. }
  8572. $this->db->commit();
  8573. return 1;
  8574. }
  8575. /**
  8576. * Delete related files of object in database
  8577. *
  8578. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  8579. * @return bool True if OK, False if KO
  8580. */
  8581. public function deleteEcmFiles($mode = 0)
  8582. {
  8583. global $conf;
  8584. $this->db->begin();
  8585. // Delete in database with mode 0
  8586. if ($mode == 0) {
  8587. switch ($this->element) {
  8588. case 'propal':
  8589. $element = 'propale';
  8590. break;
  8591. case 'product':
  8592. $element = 'produit';
  8593. break;
  8594. case 'order_supplier':
  8595. $element = 'fournisseur/commande';
  8596. break;
  8597. case 'invoice_supplier':
  8598. $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  8599. break;
  8600. case 'shipping':
  8601. $element = 'expedition/sending';
  8602. break;
  8603. default:
  8604. $element = $this->element;
  8605. }
  8606. // Delete ecm_files extrafields
  8607. $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files_extrafields WHERE fk_object IN (";
  8608. $sql .= " SELECT rowid FROM ".MAIN_DB_PREFIX."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8609. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  8610. $sql .= ")";
  8611. if (!$this->db->query($sql)) {
  8612. $this->error = $this->db->lasterror();
  8613. $this->db->rollback();
  8614. return false;
  8615. }
  8616. // Delete ecm_files
  8617. $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files";
  8618. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8619. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  8620. if (!$this->db->query($sql)) {
  8621. $this->error = $this->db->lasterror();
  8622. $this->db->rollback();
  8623. return false;
  8624. }
  8625. }
  8626. // Delete in database with mode 1
  8627. if ($mode == 1) {
  8628. $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files_extrafields";
  8629. $sql .= " WHERE fk_object IN (SELECT rowid FROM ".MAIN_DB_PREFIX."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id).")";
  8630. $resql = $this->db->query($sql);
  8631. if (!$resql) {
  8632. $this->error = $this->db->lasterror();
  8633. $this->db->rollback();
  8634. return false;
  8635. }
  8636. $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files";
  8637. $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
  8638. $resql = $this->db->query($sql);
  8639. if (!$resql) {
  8640. $this->error = $this->db->lasterror();
  8641. $this->db->rollback();
  8642. return false;
  8643. }
  8644. }
  8645. $this->db->commit();
  8646. return true;
  8647. }
  8648. }