commonobject.class.php 315 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284
  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 string ID to identify managed object
  69. */
  70. public $element;
  71. /**
  72. * @var string Name of table without prefix where object is stored
  73. */
  74. public $table_element;
  75. /**
  76. * @var string Name of subtable line
  77. */
  78. public $table_element_line = '';
  79. /**
  80. * @var string Key value used to track if data is coming from import wizard
  81. */
  82. public $import_key;
  83. /**
  84. * @var mixed Contains data to manage extrafields
  85. */
  86. public $array_options = array();
  87. /**
  88. * @var mixed Array to store alternative languages values of object
  89. */
  90. public $array_languages = null; // Value is array() when load already tried
  91. /**
  92. * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked
  93. */
  94. public $linkedObjectsIds;
  95. /**
  96. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  97. */
  98. public $linkedObjects;
  99. /**
  100. * @var Object To store a cloned copy of object before to edit it and keep track of old properties
  101. */
  102. public $oldcopy;
  103. /**
  104. * @var string Column name of the ref field.
  105. */
  106. protected $table_ref_field = '';
  107. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  108. /**
  109. * @var array<string,mixed> Can be used to pass information when only object is provided to method
  110. */
  111. public $context = array();
  112. /**
  113. * @var string Contains canvas name if record is an alternative canvas record
  114. */
  115. public $canvas;
  116. /**
  117. * @var Project The related project
  118. * @see fetch_projet()
  119. */
  120. public $project;
  121. /**
  122. * @var int The related project ID
  123. * @see setProject(), project
  124. */
  125. public $fk_project;
  126. /**
  127. * @deprecated
  128. * @see project
  129. */
  130. public $projet;
  131. /**
  132. * @var Contact a related contact
  133. * @see fetch_contact()
  134. */
  135. public $contact;
  136. /**
  137. * @var int The related contact ID
  138. * @see fetch_contact()
  139. */
  140. public $contact_id;
  141. /**
  142. * @var Societe A related thirdparty
  143. * @see fetch_thirdparty()
  144. */
  145. public $thirdparty;
  146. /**
  147. * @var User A related user
  148. * @see fetch_user()
  149. */
  150. public $user;
  151. /**
  152. * @var string The type of originating object ('commande', 'facture', ...)
  153. * @see fetch_origin()
  154. */
  155. public $origin;
  156. /**
  157. * @var int The id of originating object
  158. * @see fetch_origin()
  159. */
  160. public $origin_id;
  161. /**
  162. * @var string The object's reference
  163. */
  164. public $ref;
  165. /**
  166. * @var string An external reference for the object
  167. */
  168. public $ref_ext;
  169. /**
  170. * @var string The object's previous reference
  171. */
  172. public $ref_previous;
  173. /**
  174. * @var string The object's next reference
  175. */
  176. public $ref_next;
  177. /**
  178. * @var string Ref to store on object to save the new ref to use for example when making a validate() of an object
  179. */
  180. public $newref;
  181. /**
  182. * @var int The object's status
  183. * @see setStatut()
  184. */
  185. public $statut;
  186. /**
  187. * @var int The object's status
  188. * @see setStatut()
  189. */
  190. public $status;
  191. /**
  192. * @var string
  193. * @see getFullAddress()
  194. */
  195. public $country;
  196. /**
  197. * @var int
  198. * @see getFullAddress(), country
  199. */
  200. public $country_id;
  201. /**
  202. * @var string
  203. * @see getFullAddress(), isInEEC(), country
  204. */
  205. public $country_code;
  206. /**
  207. * @var string
  208. * @see getFullAddress()
  209. */
  210. public $state;
  211. /**
  212. * @var int
  213. * @see getFullAddress(), state
  214. */
  215. public $state_id;
  216. /**
  217. * @var string
  218. * @see getFullAddress(), $state
  219. */
  220. public $state_code;
  221. /**
  222. * @var int
  223. * @see getFullAddress(), $region_code, $region
  224. */
  225. public $region_id;
  226. /**
  227. * @var string
  228. * @see getFullAddress(), $region_id, $region
  229. */
  230. public $region_code;
  231. /**
  232. * @var string
  233. * @see getFullAddress(), $region_id, $region_code
  234. */
  235. public $region;
  236. /**
  237. * @var int
  238. * @see fetch_barcode()
  239. */
  240. public $barcode_type;
  241. /**
  242. * @var string
  243. * @see fetch_barcode(), barcode_type
  244. */
  245. public $barcode_type_code;
  246. /**
  247. * @var string
  248. * @see fetch_barcode(), barcode_type
  249. */
  250. public $barcode_type_label;
  251. /**
  252. * @var string
  253. * @see fetch_barcode(), barcode_type
  254. */
  255. public $barcode_type_coder;
  256. /**
  257. * @var int Payment method ID (cheque, cash, ...)
  258. * @see setPaymentMethods()
  259. */
  260. public $mode_reglement_id;
  261. /**
  262. * @var int Payment terms ID
  263. * @see setPaymentTerms()
  264. */
  265. public $cond_reglement_id;
  266. /**
  267. * @var int Demand reason ID
  268. */
  269. public $demand_reason_id;
  270. /**
  271. * @var int Transport mode ID (For module intracomm report)
  272. * @see setTransportMode()
  273. */
  274. public $transport_mode_id;
  275. /**
  276. * @var int Payment terms ID
  277. * @deprecated Kept for compatibility
  278. * @see cond_reglement_id;
  279. */
  280. public $cond_reglement;
  281. /**
  282. * @var int Delivery address ID
  283. * @see setDeliveryAddress()
  284. * @deprecated
  285. */
  286. public $fk_delivery_address;
  287. /**
  288. * @var int Shipping method ID
  289. * @see setShippingMethod()
  290. */
  291. public $shipping_method_id;
  292. /**
  293. * @var string
  294. * @see SetDocModel()
  295. */
  296. public $model_pdf;
  297. /**
  298. * @var string
  299. * @deprecated
  300. * @see $model_pdf
  301. */
  302. public $modelpdf;
  303. /**
  304. * @var string
  305. * Contains relative path of last generated main file
  306. */
  307. public $last_main_doc;
  308. /**
  309. * @var int Bank account ID sometimes, ID of record into llx_bank sometimes
  310. * @deprecated
  311. * @see $fk_account
  312. */
  313. public $fk_bank;
  314. /**
  315. * @var int Bank account ID
  316. * @see SetBankAccount()
  317. */
  318. public $fk_account;
  319. /**
  320. * @var string Open ID
  321. */
  322. public $openid;
  323. /**
  324. * @var string Public note
  325. * @see update_note()
  326. */
  327. public $note_public;
  328. /**
  329. * @var string Private note
  330. * @see update_note()
  331. */
  332. public $note_private;
  333. /**
  334. * @deprecated
  335. * @see $note_private
  336. */
  337. public $note;
  338. /**
  339. * @var float Total amount before taxes
  340. * @see update_price()
  341. */
  342. public $total_ht;
  343. /**
  344. * @var float Total VAT amount
  345. * @see update_price()
  346. */
  347. public $total_tva;
  348. /**
  349. * @var float Total local tax 1 amount
  350. * @see update_price()
  351. */
  352. public $total_localtax1;
  353. /**
  354. * @var float Total local tax 2 amount
  355. * @see update_price()
  356. */
  357. public $total_localtax2;
  358. /**
  359. * @var float Total amount with taxes
  360. * @see update_price()
  361. */
  362. public $total_ttc;
  363. /**
  364. * @var CommonObjectLine[]
  365. */
  366. public $lines;
  367. /**
  368. * @var mixed Contains comments
  369. * @see fetchComments()
  370. */
  371. public $comments = array();
  372. /**
  373. * @var string The name
  374. */
  375. public $name;
  376. /**
  377. * @var string The lastname
  378. */
  379. public $lastname;
  380. /**
  381. * @var string The firstname
  382. */
  383. public $firstname;
  384. /**
  385. * @var string The civility code, not an integer
  386. */
  387. public $civility_id;
  388. // Dates
  389. /**
  390. * @var integer|string date_creation
  391. */
  392. public $date_creation;
  393. /**
  394. * @var integer|string $date_validation;
  395. */
  396. public $date_validation; // Date validation
  397. /**
  398. * @var integer|string $date_modification;
  399. */
  400. public $date_modification; // Date last change (tms field)
  401. public $next_prev_filter;
  402. /**
  403. * @var int 1 if object is specimen
  404. */
  405. public $specimen = 0;
  406. /**
  407. * @var int Id of contact to send object (used by the trigger of module Agenda)
  408. */
  409. public $sendtoid;
  410. /**
  411. * @var float Amount already paid (used to show correct status)
  412. */
  413. public $alreadypaid;
  414. /**
  415. * @var array List of child tables. To test if we can delete object.
  416. */
  417. protected $childtables = array();
  418. /**
  419. * @var array List of child tables. To know object to delete on cascade.
  420. * If name is like '@ClassName:FilePathClass:ParentFkFieldName', it will
  421. * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object.
  422. */
  423. protected $childtablesoncascade = array();
  424. // No constructor as it is an abstract class
  425. /**
  426. * Check an object id/ref exists
  427. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  428. *
  429. * @param string $element String of element ('product', 'facture', ...)
  430. * @param int $id Id of object
  431. * @param string $ref Ref of object to check
  432. * @param string $ref_ext Ref ext of object to check
  433. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  434. */
  435. public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
  436. {
  437. global $db, $conf;
  438. $sql = "SELECT rowid, ref, ref_ext";
  439. $sql .= " FROM ".MAIN_DB_PREFIX.$element;
  440. $sql .= " WHERE entity IN (".getEntity($element).")";
  441. if ($id > 0) {
  442. $sql .= " AND rowid = ".((int) $id);
  443. } elseif ($ref) {
  444. $sql .= " AND ref = '".$db->escape($ref)."'";
  445. } elseif ($ref_ext) {
  446. $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
  447. } else {
  448. $error = 'ErrorWrongParameters';
  449. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  450. return -1;
  451. }
  452. if ($ref || $ref_ext) {
  453. $sql .= " AND entity = ".((int) $conf->entity);
  454. }
  455. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  456. $resql = $db->query($sql);
  457. if ($resql) {
  458. $num = $db->num_rows($resql);
  459. if ($num > 0) {
  460. return 1;
  461. } else {
  462. return 0;
  463. }
  464. }
  465. return -1;
  466. }
  467. /**
  468. * Method to output saved errors
  469. *
  470. * @return string String with errors
  471. */
  472. public function errorsToString()
  473. {
  474. return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
  475. }
  476. /**
  477. * Return customer ref for screen output.
  478. *
  479. * @param string $objref Customer ref
  480. * @return string Customer ref formated
  481. */
  482. public function getFormatedCustomerRef($objref)
  483. {
  484. global $hookmanager;
  485. $parameters = array('objref'=>$objref);
  486. $action = '';
  487. $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  488. if ($reshook > 0) {
  489. return $hookmanager->resArray['objref'];
  490. }
  491. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  492. }
  493. /**
  494. * Return supplier ref for screen output.
  495. *
  496. * @param string $objref Supplier ref
  497. * @return string Supplier ref formated
  498. */
  499. public function getFormatedSupplierRef($objref)
  500. {
  501. global $hookmanager;
  502. $parameters = array('objref'=>$objref);
  503. $action = '';
  504. $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  505. if ($reshook > 0) {
  506. return $hookmanager->resArray['objref'];
  507. }
  508. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  509. }
  510. /**
  511. * Return full name (civility+' '+name+' '+lastname)
  512. *
  513. * @param Translate $langs Language object for translation of civility (used only if option is 1)
  514. * @param int $option 0=No option, 1=Add civility
  515. * @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
  516. * @param int $maxlen Maximum length
  517. * @return string String with full name
  518. */
  519. public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
  520. {
  521. //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
  522. $lastname = $this->lastname;
  523. $firstname = $this->firstname;
  524. if (empty($lastname)) {
  525. $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 : '')))));
  526. }
  527. $ret = '';
  528. if (!empty($option) && !empty($this->civility_code)) {
  529. if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) {
  530. $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
  531. } else {
  532. $ret .= $this->civility_code.' ';
  533. }
  534. }
  535. $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
  536. return dol_trunc($ret, $maxlen);
  537. }
  538. /**
  539. * Set to upper or ucwords/lower if needed
  540. *
  541. * @return void;
  542. */
  543. public function setUpperOrLowerCase()
  544. {
  545. global $conf;
  546. if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
  547. $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
  548. $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
  549. $this->name = dol_ucwords(dol_strtolower($this->name));
  550. $this->name_alias = dol_ucwords(dol_strtolower($this->name_alias));
  551. }
  552. if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
  553. $this->lastname = dol_strtoupper($this->lastname);
  554. $this->name = dol_strtoupper($this->name);
  555. $this->name_alias = dol_strtoupper($this->name_alias);
  556. }
  557. if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
  558. $this->address = dol_strtoupper($this->address);
  559. $this->town = dol_strtoupper($this->town);
  560. }
  561. }
  562. /**
  563. * Return clicable link of object (with eventually picto)
  564. *
  565. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  566. * @return string HTML Code for Kanban thumb.
  567. */
  568. public function getKanbanView($option = '')
  569. {
  570. $return = '<div class="box-flex-item">';
  571. $return .= '<div class="info-box info-box-sm">';
  572. $return .= '<span class="info-box-icon bg-infobox-action">';
  573. $return .= '<i class="fa fa-dol-action"></i>'; // Can be image
  574. $return .= '</span>';
  575. $return .= '<div class="info-box-content">';
  576. $return .= '<span class="info-box-title">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  577. $return .= '</div>';
  578. $return .= '</div>';
  579. $return .= '</div>';
  580. return $return;
  581. }
  582. /**
  583. * Return full address of contact
  584. *
  585. * @param int $withcountry 1=Add country into address string
  586. * @param string $sep Separator to use to build string
  587. * @param int $withregion 1=Add region into address string
  588. * @param string $extralangcode User extralanguages as value
  589. * @return string Full address string
  590. */
  591. public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
  592. {
  593. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
  594. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  595. $tmparray = getCountry($this->country_id, 'all');
  596. $this->country_code = $tmparray['code'];
  597. $this->country = $tmparray['label'];
  598. }
  599. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
  600. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  601. $tmparray = getState($this->state_id, 'all', 0, 1);
  602. $this->state_code = $tmparray['code'];
  603. $this->state = $tmparray['label'];
  604. $this->region_code = $tmparray['region_code'];
  605. $this->region = $tmparray['region'];
  606. }
  607. return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
  608. }
  609. /**
  610. * Return full address for banner
  611. *
  612. * @param string $htmlkey HTML id to make banner content unique
  613. * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member)
  614. * @return string Full address string
  615. */
  616. public function getBannerAddress($htmlkey, $object)
  617. {
  618. global $conf, $langs, $form, $extralanguages;
  619. $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
  620. $contactid = 0;
  621. $thirdpartyid = 0;
  622. $elementforaltlanguage = $this->element;
  623. if ($this->element == 'societe') {
  624. $thirdpartyid = $this->id;
  625. }
  626. if ($this->element == 'contact') {
  627. $contactid = $this->id;
  628. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  629. }
  630. if ($this->element == 'user') {
  631. $contactid = $this->contact_id;
  632. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  633. }
  634. $out = '';
  635. $outdone = 0;
  636. $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
  637. if ($coords) {
  638. if (!empty($conf->use_javascript_ajax)) {
  639. // Add picto with tooltip on map
  640. $namecoords = '';
  641. if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
  642. $namecoords .= $object->name.'<br>';
  643. }
  644. $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
  645. // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
  646. $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
  647. $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
  648. $out .= '</a> ';
  649. }
  650. $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  651. $outdone++;
  652. $outdone++;
  653. // List of extra languages
  654. $arrayoflangcode = array();
  655. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  656. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  657. }
  658. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  659. if (!is_object($extralanguages)) {
  660. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  661. $extralanguages = new ExtraLanguages($this->db);
  662. }
  663. $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
  664. if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
  665. $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
  666. $this->fetchValuesForExtraLanguages();
  667. if (!is_object($form)) {
  668. $form = new Form($this->db);
  669. }
  670. $htmltext = '';
  671. // If there is extra languages
  672. foreach ($arrayoflangcode as $extralangcode) {
  673. $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  674. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
  675. $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  676. }
  677. $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  678. }
  679. }
  680. }
  681. 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
  682. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
  683. if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
  684. $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
  685. } else {
  686. $out .= ($outdone ? ' - ' : '').$this->state;
  687. }
  688. $outdone++;
  689. }
  690. 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)) {
  691. $out .= ($outdone ? '<br>' : '');
  692. }
  693. if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  694. $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  695. $outdone++;
  696. }
  697. if (!empty($this->phone_pro)) {
  698. $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  699. $outdone++;
  700. }
  701. if (!empty($this->phone_mobile)) {
  702. $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  703. $outdone++;
  704. }
  705. if (!empty($this->phone_perso)) {
  706. $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
  707. $outdone++;
  708. }
  709. if (!empty($this->office_phone)) {
  710. $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  711. $outdone++;
  712. }
  713. if (!empty($this->user_mobile)) {
  714. $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  715. $outdone++;
  716. }
  717. if (!empty($this->fax)) {
  718. $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  719. $outdone++;
  720. }
  721. if (!empty($this->office_fax)) {
  722. $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  723. $outdone++;
  724. }
  725. if ($out) {
  726. $out .= '<div style="clear: both;"></div>';
  727. }
  728. $outdone = 0;
  729. if (!empty($this->email)) {
  730. $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
  731. $outdone++;
  732. }
  733. if (!empty($this->url)) {
  734. //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
  735. $out .= dol_print_url($this->url, '_blank', 0, 1);
  736. $outdone++;
  737. }
  738. if (!empty($conf->socialnetworks->enabled)) {
  739. $outsocialnetwork = '';
  740. if (!empty($this->socialnetworks) && is_countable($this->socialnetworks) && count($this->socialnetworks) > 0) {
  741. $socialnetworksdict = getArrayOfSocialNetworks();
  742. foreach ($this->socialnetworks as $key => $value) {
  743. if ($value) {
  744. $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
  745. }
  746. $outdone++;
  747. }
  748. } else { // Old code to remove
  749. if (!empty($this->skype)) {
  750. $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
  751. }
  752. $outdone++;
  753. if (!empty($this->jabberid)) {
  754. $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
  755. }
  756. $outdone++;
  757. if (!empty($this->twitter)) {
  758. $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
  759. }
  760. $outdone++;
  761. if (!empty($this->facebook)) {
  762. $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
  763. }
  764. $outdone++;
  765. if (!empty($this->linkedin)) {
  766. $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
  767. }
  768. $outdone++;
  769. }
  770. if ($outsocialnetwork) {
  771. $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
  772. }
  773. }
  774. if ($out) {
  775. return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
  776. } else {
  777. return '';
  778. }
  779. }
  780. /**
  781. * Return the link of last main doc file for direct public download.
  782. *
  783. * @param string $modulepart Module related to document
  784. * @param int $initsharekey Init the share key if it was not yet defined
  785. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  786. * @return string Link or empty string if there is no download link
  787. */
  788. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  789. {
  790. global $user, $dolibarr_main_url_root;
  791. if (empty($this->last_main_doc)) {
  792. return ''; // No way to known which document name to use
  793. }
  794. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  795. $ecmfile = new EcmFiles($this->db);
  796. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  797. if ($result < 0) {
  798. $this->error = $ecmfile->error;
  799. $this->errors = $ecmfile->errors;
  800. return -1;
  801. }
  802. if (empty($ecmfile->id)) {
  803. // Add entry into index
  804. if ($initsharekey) {
  805. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  806. // TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first
  807. /*
  808. $ecmfile->filepath = $rel_dir;
  809. $ecmfile->filename = $filename;
  810. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  811. $ecmfile->fullpath_orig = '';
  812. $ecmfile->gen_or_uploaded = 'generated';
  813. $ecmfile->description = ''; // indexed content
  814. $ecmfile->keywords = ''; // keyword content
  815. $ecmfile->share = getRandomPassword(true);
  816. $result = $ecmfile->create($user);
  817. if ($result < 0)
  818. {
  819. $this->error = $ecmfile->error;
  820. $this->errors = $ecmfile->errors;
  821. }
  822. */
  823. } else {
  824. return '';
  825. }
  826. } elseif (empty($ecmfile->share)) {
  827. // Add entry into index
  828. if ($initsharekey) {
  829. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  830. $ecmfile->share = getRandomPassword(true);
  831. $ecmfile->update($user);
  832. } else {
  833. return '';
  834. }
  835. }
  836. // Define $urlwithroot
  837. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  838. // This is to use external domain name found into config file
  839. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  840. //else
  841. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  842. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  843. $forcedownload = 0;
  844. $paramlink = '';
  845. //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  846. //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  847. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  848. if (!empty($ecmfile->share)) {
  849. $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
  850. }
  851. if ($forcedownload) {
  852. $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  853. }
  854. if ($relativelink) {
  855. $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
  856. } else {
  857. $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  858. }
  859. // Here $ecmfile->share is defined
  860. return $linktoreturn;
  861. }
  862. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  863. /**
  864. * Add a link between element $this->element and a contact
  865. *
  866. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  867. * @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
  868. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  869. * @param int $notrigger Disable all triggers
  870. * @return int <0 if KO, 0 if already added, >0 if OK
  871. */
  872. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  873. {
  874. // phpcs:enable
  875. global $user, $langs;
  876. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  877. // Check parameters
  878. if ($fk_socpeople <= 0) {
  879. $langs->load("errors");
  880. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  881. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  882. return -1;
  883. }
  884. if (!$type_contact) {
  885. $langs->load("errors");
  886. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  887. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  888. return -2;
  889. }
  890. $id_type_contact = 0;
  891. if (is_numeric($type_contact)) {
  892. $id_type_contact = $type_contact;
  893. } else {
  894. // We look for id type_contact
  895. $sql = "SELECT tc.rowid";
  896. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  897. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  898. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  899. $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  900. //print $sql;
  901. $resql = $this->db->query($sql);
  902. if ($resql) {
  903. $obj = $this->db->fetch_object($resql);
  904. if ($obj) {
  905. $id_type_contact = $obj->rowid;
  906. }
  907. }
  908. }
  909. if ($id_type_contact == 0) {
  910. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  911. 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");
  912. return -3;
  913. }
  914. $datecreate = dol_now();
  915. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  916. $TListeContacts = $this->liste_contact(-1, $source);
  917. $already_added = false;
  918. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  919. foreach ($TListeContacts as $array_contact) {
  920. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  921. $already_added = true;
  922. break;
  923. }
  924. }
  925. }
  926. if (!$already_added) {
  927. $this->db->begin();
  928. // Insert into database
  929. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact";
  930. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  931. $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
  932. $sql .= "'".$this->db->idate($datecreate)."'";
  933. $sql .= ", 4, ".((int) $id_type_contact);
  934. $sql .= ")";
  935. $resql = $this->db->query($sql);
  936. if ($resql) {
  937. if (!$notrigger) {
  938. $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  939. if ($result < 0) {
  940. $this->db->rollback();
  941. return -1;
  942. }
  943. }
  944. $this->db->commit();
  945. return 1;
  946. } else {
  947. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  948. $this->error = $this->db->errno();
  949. $this->db->rollback();
  950. return -2;
  951. } else {
  952. $this->error = $this->db->lasterror();
  953. $this->db->rollback();
  954. return -1;
  955. }
  956. }
  957. } else {
  958. return 0;
  959. }
  960. }
  961. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  962. /**
  963. * Copy contact from one element to current
  964. *
  965. * @param CommonObject $objFrom Source element
  966. * @param string $source Nature of contact ('internal' or 'external')
  967. * @return int >0 if OK, <0 if KO
  968. */
  969. public function copy_linked_contact($objFrom, $source = 'internal')
  970. {
  971. // phpcs:enable
  972. $contacts = $objFrom->liste_contact(-1, $source);
  973. foreach ($contacts as $contact) {
  974. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
  975. return -1;
  976. }
  977. }
  978. return 1;
  979. }
  980. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  981. /**
  982. * Update a link to contact line
  983. *
  984. * @param int $rowid Id of line contact-element
  985. * @param int $statut New status of link
  986. * @param int $type_contact_id Id of contact type (not modified if 0)
  987. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  988. * @return int <0 if KO, >= 0 if OK
  989. */
  990. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  991. {
  992. // phpcs:enable
  993. // Insert into database
  994. $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set";
  995. $sql .= " statut = ".$statut;
  996. if ($type_contact_id) {
  997. $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
  998. }
  999. if ($fk_socpeople) {
  1000. $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
  1001. }
  1002. $sql .= " where rowid = ".((int) $rowid);
  1003. $resql = $this->db->query($sql);
  1004. if ($resql) {
  1005. return 0;
  1006. } else {
  1007. $this->error = $this->db->lasterror();
  1008. return -1;
  1009. }
  1010. }
  1011. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1012. /**
  1013. * Delete a link to contact line
  1014. *
  1015. * @param int $rowid Id of contact link line to delete
  1016. * @param int $notrigger Disable all triggers
  1017. * @return int >0 if OK, <0 if KO
  1018. */
  1019. public function delete_contact($rowid, $notrigger = 0)
  1020. {
  1021. // phpcs:enable
  1022. global $user;
  1023. $this->db->begin();
  1024. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  1025. $sql .= " WHERE rowid = ".((int) $rowid);
  1026. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  1027. if ($this->db->query($sql)) {
  1028. if (!$notrigger) {
  1029. $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  1030. if ($result < 0) {
  1031. $this->db->rollback();
  1032. return -1;
  1033. }
  1034. }
  1035. $this->db->commit();
  1036. return 1;
  1037. } else {
  1038. $this->error = $this->db->lasterror();
  1039. $this->db->rollback();
  1040. return -1;
  1041. }
  1042. }
  1043. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1044. /**
  1045. * Delete all links between an object $this and all its contacts
  1046. *
  1047. * @param string $source '' or 'internal' or 'external'
  1048. * @param string $code Type of contact (code or id)
  1049. * @return int >0 if OK, <0 if KO
  1050. */
  1051. public function delete_linked_contact($source = '', $code = '')
  1052. {
  1053. // phpcs:enable
  1054. $temp = array();
  1055. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  1056. foreach ($typeContact as $key => $value) {
  1057. array_push($temp, $key);
  1058. }
  1059. $listId = implode(",", $temp);
  1060. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  1061. $sql .= " WHERE element_id = ".$this->id;
  1062. if ($listId) {
  1063. $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
  1064. }
  1065. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  1066. if ($this->db->query($sql)) {
  1067. return 1;
  1068. } else {
  1069. $this->error = $this->db->lasterror();
  1070. return -1;
  1071. }
  1072. }
  1073. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1074. /**
  1075. * Get array of all contacts for an object
  1076. *
  1077. * @param int $status Status of links to get (-1=all)
  1078. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  1079. * @param int $list 0:Return array contains all properties, 1:Return array contains just id
  1080. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1081. * @return array|int Array of contacts, -1 if error
  1082. */
  1083. public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
  1084. {
  1085. // phpcs:enable
  1086. global $langs;
  1087. $tab = array();
  1088. $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
  1089. if ($source == 'internal') {
  1090. $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  1091. }
  1092. if ($source == 'external' || $source == 'thirdparty') {
  1093. $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1094. }
  1095. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  1096. $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
  1097. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
  1098. $sql .= ", ".MAIN_DB_PREFIX."element_contact ec";
  1099. if ($source == 'internal') {
  1100. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
  1101. }
  1102. if ($source == 'external' || $source == 'thirdparty') {
  1103. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
  1104. }
  1105. $sql .= " WHERE ec.element_id =".$this->id;
  1106. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1107. $sql .= " AND tc.element='".$this->db->escape($this->element)."'";
  1108. if ($code) {
  1109. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1110. }
  1111. if ($source == 'internal') {
  1112. $sql .= " AND tc.source = 'internal'";
  1113. }
  1114. if ($source == 'external' || $source == 'thirdparty') {
  1115. $sql .= " AND tc.source = 'external'";
  1116. }
  1117. $sql .= " AND tc.active=1";
  1118. if ($status >= 0) {
  1119. $sql .= " AND ec.statut = ".((int) $status);
  1120. }
  1121. $sql .= " ORDER BY t.lastname ASC";
  1122. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  1123. $resql = $this->db->query($sql);
  1124. if ($resql) {
  1125. $num = $this->db->num_rows($resql);
  1126. $i = 0;
  1127. while ($i < $num) {
  1128. $obj = $this->db->fetch_object($resql);
  1129. if (!$list) {
  1130. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1131. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1132. $tab[$i] = array(
  1133. 'source' => $obj->source,
  1134. 'socid' => $obj->socid,
  1135. 'id' => $obj->id,
  1136. 'nom' => $obj->lastname, // For backward compatibility
  1137. 'civility' => $obj->civility,
  1138. 'lastname' => $obj->lastname,
  1139. 'firstname' => $obj->firstname,
  1140. 'email'=>$obj->email,
  1141. 'login'=> (empty($obj->login) ? '' : $obj->login),
  1142. 'photo' => (empty($obj->photo) ? '' : $obj->photo),
  1143. 'statuscontact' => $obj->statuscontact,
  1144. 'rowid' => $obj->rowid,
  1145. 'code' => $obj->code,
  1146. 'libelle' => $libelle_type,
  1147. 'status' => $obj->statuslink,
  1148. 'fk_c_type_contact' => $obj->fk_c_type_contact
  1149. );
  1150. } else {
  1151. $tab[$i] = $obj->id;
  1152. }
  1153. $i++;
  1154. }
  1155. return $tab;
  1156. } else {
  1157. $this->error = $this->db->lasterror();
  1158. dol_print_error($this->db);
  1159. return -1;
  1160. }
  1161. }
  1162. /**
  1163. * Update status of a contact linked to object
  1164. *
  1165. * @param int $rowid Id of link between object and contact
  1166. * @return int <0 if KO, >=0 if OK
  1167. */
  1168. public function swapContactStatus($rowid)
  1169. {
  1170. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1171. $sql .= " tc.code, tc.libelle";
  1172. $sql .= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)";
  1173. $sql .= " WHERE ec.rowid =".((int) $rowid);
  1174. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1175. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1176. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  1177. $resql = $this->db->query($sql);
  1178. if ($resql) {
  1179. $obj = $this->db->fetch_object($resql);
  1180. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1181. $result = $this->update_contact($rowid, $newstatut);
  1182. $this->db->free($resql);
  1183. return $result;
  1184. } else {
  1185. $this->error = $this->db->error();
  1186. dol_print_error($this->db);
  1187. return -1;
  1188. }
  1189. }
  1190. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1191. /**
  1192. * Return array with list of possible values for type of contacts
  1193. *
  1194. * @param string $source 'internal', 'external' or 'all'
  1195. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  1196. * @param int $option 0=Return array id->label, 1=Return array code->label
  1197. * @param int $activeonly 0=all status of contact, 1=only the active
  1198. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1199. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1200. */
  1201. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1202. {
  1203. // phpcs:enable
  1204. global $langs;
  1205. if (empty($order)) {
  1206. $order = 'position';
  1207. }
  1208. if ($order == 'position') {
  1209. $order .= ',code';
  1210. }
  1211. $tab = array();
  1212. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  1213. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  1214. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1215. if ($activeonly == 1) {
  1216. $sql .= " AND tc.active=1"; // only the active types
  1217. }
  1218. if (!empty($source) && $source != 'all') {
  1219. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1220. }
  1221. if (!empty($code)) {
  1222. $sql .= " AND tc.code='".$this->db->escape($code)."'";
  1223. }
  1224. $sql .= $this->db->order($order, 'ASC');
  1225. //print "sql=".$sql;
  1226. $resql = $this->db->query($sql);
  1227. if ($resql) {
  1228. $num = $this->db->num_rows($resql);
  1229. $i = 0;
  1230. while ($i < $num) {
  1231. $obj = $this->db->fetch_object($resql);
  1232. $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
  1233. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1234. if (empty($option)) {
  1235. $tab[$obj->rowid] = $libelle_type;
  1236. } else {
  1237. $tab[$obj->code] = $libelle_type;
  1238. }
  1239. $i++;
  1240. }
  1241. return $tab;
  1242. } else {
  1243. $this->error = $this->db->lasterror();
  1244. //dol_print_error($this->db);
  1245. return null;
  1246. }
  1247. }
  1248. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1249. /**
  1250. * Return array with list of possible values for type of contacts
  1251. *
  1252. * @param string $source 'internal', 'external' or 'all'
  1253. * @param int $option 0=Return array id->label, 1=Return array code->label
  1254. * @param int $activeonly 0=all status of contact, 1=only the active
  1255. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1256. * @param string $element Filter on 1 element type
  1257. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1258. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1259. */
  1260. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1261. {
  1262. // phpcs:enable
  1263. global $langs, $conf;
  1264. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1265. $tab = array();
  1266. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
  1267. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  1268. $sqlWhere = array();
  1269. if (!empty($element)) {
  1270. $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
  1271. }
  1272. if (!empty($excludeelement)) {
  1273. $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
  1274. }
  1275. if ($activeonly == 1) {
  1276. $sqlWhere[] = " tc.active=1"; // only the active types
  1277. }
  1278. if (!empty($source) && $source != 'all') {
  1279. $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
  1280. }
  1281. if (!empty($code)) {
  1282. $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
  1283. }
  1284. if (count($sqlWhere) > 0) {
  1285. $sql .= " WHERE ".implode(' AND ', $sqlWhere);
  1286. }
  1287. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1288. dol_syslog(__METHOD__, LOG_DEBUG);
  1289. $resql = $this->db->query($sql);
  1290. if ($resql) {
  1291. $num = $this->db->num_rows($resql);
  1292. if ($num > 0) {
  1293. $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
  1294. while ($obj = $this->db->fetch_object($resql)) {
  1295. $modulename = $obj->element;
  1296. if (strpos($obj->element, 'project') !== false) {
  1297. $modulename = 'projet';
  1298. } elseif ($obj->element == 'contrat') {
  1299. $element = 'contract';
  1300. } elseif ($obj->element == 'action') {
  1301. $modulename = 'agenda';
  1302. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1303. $modulename = 'fournisseur';
  1304. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1305. $modulename = 'fournisseur';
  1306. }
  1307. if (!empty($conf->{$modulename}->enabled)) {
  1308. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1309. $tmpelement = $obj->element;
  1310. $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
  1311. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1312. if (empty($option)) {
  1313. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1314. } else {
  1315. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1316. }
  1317. }
  1318. }
  1319. }
  1320. return $tab;
  1321. } else {
  1322. $this->error = $this->db->lasterror();
  1323. return null;
  1324. }
  1325. }
  1326. /**
  1327. * Return id of contacts for a source and a contact code.
  1328. * Example: contact client de facturation ('external', 'BILLING')
  1329. * Example: contact client de livraison ('external', 'SHIPPING')
  1330. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1331. *
  1332. * @param string $source 'external' or 'internal'
  1333. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1334. * @param int $status limited to a certain status
  1335. * @return array List of id for such contacts
  1336. */
  1337. public function getIdContact($source, $code, $status = 0)
  1338. {
  1339. global $conf;
  1340. $result = array();
  1341. $i = 0;
  1342. //cas particulier pour les expeditions
  1343. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1344. $id = $this->origin_id;
  1345. $element = 'commande';
  1346. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1347. $id = $this->origin_id;
  1348. $element = 'order_supplier';
  1349. } else {
  1350. $id = $this->id;
  1351. $element = $this->element;
  1352. }
  1353. $sql = "SELECT ec.fk_socpeople";
  1354. $sql .= " FROM ".MAIN_DB_PREFIX."element_contact as ec,";
  1355. if ($source == 'internal') {
  1356. $sql .= " ".MAIN_DB_PREFIX."user as c,";
  1357. }
  1358. if ($source == 'external') {
  1359. $sql .= " ".MAIN_DB_PREFIX."socpeople as c,";
  1360. }
  1361. $sql .= " ".MAIN_DB_PREFIX."c_type_contact as tc";
  1362. $sql .= " WHERE ec.element_id = ".((int) $id);
  1363. $sql .= " AND ec.fk_socpeople = c.rowid";
  1364. if ($source == 'internal') {
  1365. $sql .= " AND c.entity IN (".getEntity('user').")";
  1366. }
  1367. if ($source == 'external') {
  1368. $sql .= " AND c.entity IN (".getEntity('societe').")";
  1369. }
  1370. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1371. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1372. $sql .= " AND tc.source = '".$this->db->escape($source)."'";
  1373. if ($code) {
  1374. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1375. }
  1376. $sql .= " AND tc.active = 1";
  1377. if ($status) {
  1378. $sql .= " AND ec.statut = ".((int) $status);
  1379. }
  1380. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1381. $resql = $this->db->query($sql);
  1382. if ($resql) {
  1383. while ($obj = $this->db->fetch_object($resql)) {
  1384. $result[$i] = $obj->fk_socpeople;
  1385. $i++;
  1386. }
  1387. } else {
  1388. $this->error = $this->db->error();
  1389. return null;
  1390. }
  1391. return $result;
  1392. }
  1393. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1394. /**
  1395. * Load object contact with id=$this->contact_id into $this->contact
  1396. *
  1397. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1398. * @return int <0 if KO, >0 if OK
  1399. */
  1400. public function fetch_contact($contactid = null)
  1401. {
  1402. // phpcs:enable
  1403. if (empty($contactid)) {
  1404. $contactid = $this->contact_id;
  1405. }
  1406. if (empty($contactid)) {
  1407. return 0;
  1408. }
  1409. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1410. $contact = new Contact($this->db);
  1411. $result = $contact->fetch($contactid);
  1412. $this->contact = $contact;
  1413. return $result;
  1414. }
  1415. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1416. /**
  1417. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1418. *
  1419. * @param int $force_thirdparty_id Force thirdparty id
  1420. * @return int <0 if KO, >0 if OK
  1421. */
  1422. public function fetch_thirdparty($force_thirdparty_id = 0)
  1423. {
  1424. // phpcs:enable
  1425. global $conf;
  1426. if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) {
  1427. return 0;
  1428. }
  1429. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1430. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
  1431. if ($force_thirdparty_id) {
  1432. $idtofetch = $force_thirdparty_id;
  1433. }
  1434. if ($idtofetch) {
  1435. $thirdparty = new Societe($this->db);
  1436. $result = $thirdparty->fetch($idtofetch);
  1437. if ($result<0) {
  1438. $this->errors=array_merge($this->errors, $thirdparty->errors);
  1439. }
  1440. $this->thirdparty = $thirdparty;
  1441. // Use first price level if level not defined for third party
  1442. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1443. $this->thirdparty->price_level = 1;
  1444. }
  1445. return $result;
  1446. } else {
  1447. return -1;
  1448. }
  1449. }
  1450. /**
  1451. * Looks for an object with ref matching the wildcard provided
  1452. * It does only work when $this->table_ref_field is set
  1453. *
  1454. * @param string $ref Wildcard
  1455. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1456. */
  1457. public function fetchOneLike($ref)
  1458. {
  1459. if (!$this->table_ref_field) {
  1460. return 0;
  1461. }
  1462. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE '.$this->table_ref_field.' LIKE "'.$this->db->escape($ref).'" LIMIT 1';
  1463. $query = $this->db->query($sql);
  1464. if (!$this->db->num_rows($query)) {
  1465. return 0;
  1466. }
  1467. $result = $this->db->fetch_object($query);
  1468. return $this->fetch($result->rowid);
  1469. }
  1470. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1471. /**
  1472. * Load data for barcode into properties ->barcode_type*
  1473. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1474. * if it is not defined, ->element must be defined to know default barcode type.
  1475. *
  1476. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1477. */
  1478. public function fetch_barcode()
  1479. {
  1480. // phpcs:enable
  1481. global $conf;
  1482. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1483. $idtype = $this->barcode_type;
  1484. 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
  1485. if ($this->element == 'product') {
  1486. $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1487. } elseif ($this->element == 'societe') {
  1488. $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1489. } else {
  1490. dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1491. }
  1492. }
  1493. if ($idtype > 0) {
  1494. 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
  1495. $sql = "SELECT rowid, code, libelle as label, coder";
  1496. $sql .= " FROM ".MAIN_DB_PREFIX."c_barcode_type";
  1497. $sql .= " WHERE rowid = ".((int) $idtype);
  1498. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1499. $resql = $this->db->query($sql);
  1500. if ($resql) {
  1501. $obj = $this->db->fetch_object($resql);
  1502. $this->barcode_type = $obj->rowid;
  1503. $this->barcode_type_code = $obj->code;
  1504. $this->barcode_type_label = $obj->label;
  1505. $this->barcode_type_coder = $obj->coder;
  1506. return 1;
  1507. } else {
  1508. dol_print_error($this->db);
  1509. return -1;
  1510. }
  1511. }
  1512. }
  1513. return 0;
  1514. }
  1515. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1516. /**
  1517. * Load the project with id $this->fk_project into this->project
  1518. *
  1519. * @return int <0 if KO, >=0 if OK
  1520. */
  1521. public function fetch_projet()
  1522. {
  1523. // phpcs:enable
  1524. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1525. if (empty($this->fk_project) && !empty($this->fk_projet)) {
  1526. $this->fk_project = $this->fk_projet; // For backward compatibility
  1527. }
  1528. if (empty($this->fk_project)) {
  1529. return 0;
  1530. }
  1531. $project = new Project($this->db);
  1532. $result = $project->fetch($this->fk_project);
  1533. $this->projet = $project; // deprecated
  1534. $this->project = $project;
  1535. return $result;
  1536. }
  1537. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1538. /**
  1539. * Load the product with id $this->fk_product into this->product
  1540. *
  1541. * @return int <0 if KO, >=0 if OK
  1542. */
  1543. public function fetch_product()
  1544. {
  1545. // phpcs:enable
  1546. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1547. if (empty($this->fk_product)) {
  1548. return 0;
  1549. }
  1550. $product = new Product($this->db);
  1551. $result = $product->fetch($this->fk_product);
  1552. $this->product = $product;
  1553. return $result;
  1554. }
  1555. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1556. /**
  1557. * Load the user with id $userid into this->user
  1558. *
  1559. * @param int $userid Id du contact
  1560. * @return int <0 if KO, >0 if OK
  1561. */
  1562. public function fetch_user($userid)
  1563. {
  1564. // phpcs:enable
  1565. $user = new User($this->db);
  1566. $result = $user->fetch($userid);
  1567. $this->user = $user;
  1568. return $result;
  1569. }
  1570. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1571. /**
  1572. * Read linked origin object
  1573. *
  1574. * @return void
  1575. */
  1576. public function fetch_origin()
  1577. {
  1578. // phpcs:enable
  1579. if ($this->origin == 'shipping') {
  1580. $this->origin = 'expedition';
  1581. }
  1582. if ($this->origin == 'delivery') {
  1583. $this->origin = 'livraison';
  1584. }
  1585. if ($this->origin == 'order_supplier') {
  1586. $this->origin = 'commandeFournisseur';
  1587. }
  1588. $origin = $this->origin;
  1589. $classname = ucfirst($origin);
  1590. $this->$origin = new $classname($this->db);
  1591. $this->$origin->fetch($this->origin_id);
  1592. }
  1593. /**
  1594. * Load object from specific field
  1595. *
  1596. * @param string $table Table element or element line
  1597. * @param string $field Field selected
  1598. * @param string $key Import key
  1599. * @param string $element Element name
  1600. * @return int <0 if KO, >0 if OK
  1601. */
  1602. public function fetchObjectFrom($table, $field, $key, $element = null)
  1603. {
  1604. global $conf;
  1605. $result = false;
  1606. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$table;
  1607. $sql .= " WHERE ".$field." = '".$key."'";
  1608. if (!empty($element)) {
  1609. $sql .= " AND entity IN (".getEntity($element).")";
  1610. } else {
  1611. $sql .= " AND entity = ".$conf->entity;
  1612. }
  1613. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1614. $resql = $this->db->query($sql);
  1615. if ($resql) {
  1616. $row = $this->db->fetch_row($resql);
  1617. // Test for avoid error -1
  1618. if ($row[0] > 0) {
  1619. $result = $this->fetch($row[0]);
  1620. }
  1621. }
  1622. return $result;
  1623. }
  1624. /**
  1625. * Getter generic. Load value from a specific field
  1626. *
  1627. * @param string $table Table of element or element line
  1628. * @param int $id Element id
  1629. * @param string $field Field selected
  1630. * @return int <0 if KO, >0 if OK
  1631. */
  1632. public function getValueFrom($table, $id, $field)
  1633. {
  1634. $result = false;
  1635. if (!empty($id) && !empty($field) && !empty($table)) {
  1636. $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table;
  1637. $sql .= " WHERE rowid = ".((int) $id);
  1638. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1639. $resql = $this->db->query($sql);
  1640. if ($resql) {
  1641. $row = $this->db->fetch_row($resql);
  1642. $result = $row[0];
  1643. }
  1644. }
  1645. return $result;
  1646. }
  1647. /**
  1648. * Setter generic. Update a specific field into database.
  1649. * Warning: Trigger is run only if param trigkey is provided.
  1650. *
  1651. * @param string $field Field to update
  1652. * @param mixed $value New value
  1653. * @param string $table To force other table element or element line (should not be used)
  1654. * @param int $id To force other object id (should not be used)
  1655. * @param string $format Data format ('text', 'date'). 'text' is used if not defined
  1656. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1657. * @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'
  1658. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1659. * @param string $fk_user_field Name of field to save user id making change
  1660. * @return int <0 if KO, >0 if OK
  1661. * @see updateExtraField()
  1662. */
  1663. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1664. {
  1665. global $user, $langs, $conf;
  1666. if (empty($table)) {
  1667. $table = $this->table_element;
  1668. }
  1669. if (empty($id)) {
  1670. $id = $this->id;
  1671. }
  1672. if (empty($format)) {
  1673. $format = 'text';
  1674. }
  1675. if (empty($id_field)) {
  1676. $id_field = 'rowid';
  1677. }
  1678. $error = 0;
  1679. $this->db->begin();
  1680. // Special case
  1681. if ($table == 'product' && $field == 'note_private') {
  1682. $field = 'note';
  1683. }
  1684. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  1685. $fk_user_field = 'fk_user_mod';
  1686. }
  1687. $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
  1688. if ($format == 'text') {
  1689. $sql .= $field." = '".$this->db->escape($value)."'";
  1690. } elseif ($format == 'int') {
  1691. $sql .= $field." = ".((int) $value);
  1692. } elseif ($format == 'date') {
  1693. $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1694. }
  1695. if ($fk_user_field) {
  1696. if (!empty($fuser) && is_object($fuser)) {
  1697. $sql .= ", ".$fk_user_field." = ".$fuser->id;
  1698. } elseif (empty($fuser) || $fuser != 'none') {
  1699. $sql .= ", ".$fk_user_field." = ".$user->id;
  1700. }
  1701. }
  1702. $sql .= " WHERE ".$id_field." = ".((int) $id);
  1703. dol_syslog(__METHOD__."", LOG_DEBUG);
  1704. $resql = $this->db->query($sql);
  1705. if ($resql) {
  1706. if ($trigkey) {
  1707. // call trigger with updated object values
  1708. if (empty($this->fields) && method_exists($this, 'fetch')) {
  1709. $result = $this->fetch($id);
  1710. } else {
  1711. $result = $this->fetchCommon($id);
  1712. }
  1713. if ($result >= 0) {
  1714. $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1715. }
  1716. if ($result < 0) {
  1717. $error++;
  1718. }
  1719. }
  1720. if (!$error) {
  1721. if (property_exists($this, $field)) {
  1722. $this->$field = $value;
  1723. }
  1724. $this->db->commit();
  1725. return 1;
  1726. } else {
  1727. $this->db->rollback();
  1728. return -2;
  1729. }
  1730. } else {
  1731. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1732. $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
  1733. } else {
  1734. $this->error = $this->db->lasterror();
  1735. }
  1736. $this->db->rollback();
  1737. return -1;
  1738. }
  1739. }
  1740. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1741. /**
  1742. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1743. *
  1744. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')"
  1745. * @param string $fieldid Name of field to use for the select MAX and MIN
  1746. * @param int $nodbprefix Do not include DB prefix to forge table name
  1747. * @return int <0 if KO, >0 if OK
  1748. */
  1749. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1750. {
  1751. // phpcs:enable
  1752. global $conf, $user;
  1753. if (!$this->table_element) {
  1754. dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1755. return -1;
  1756. }
  1757. if ($fieldid == 'none') {
  1758. return 1;
  1759. }
  1760. // Security on socid
  1761. $socid = 0;
  1762. if ($user->socid > 0) {
  1763. $socid = $user->socid;
  1764. }
  1765. // this->ismultientitymanaged contains
  1766. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1767. $aliastablesociete = 's';
  1768. if ($this->element == 'societe') {
  1769. $aliastablesociete = 'te'; // te as table_element
  1770. }
  1771. $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
  1772. $sql = "SELECT MAX(te.".$fieldid.")";
  1773. $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1774. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1775. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  1776. }
  1777. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1778. $tmparray = explode('@', $this->ismultientitymanaged);
  1779. $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
  1780. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1781. $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid
  1782. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1783. $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
  1784. }
  1785. if ($restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) {
  1786. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1787. }
  1788. $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)
  1789. if ($restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) {
  1790. $sql .= " AND sc.fk_user = ".$user->id;
  1791. }
  1792. if ($restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) {
  1793. $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)';
  1794. }
  1795. if (!empty($filter)) {
  1796. if (!preg_match('/^\s*AND/i', $filter)) {
  1797. $sql .= " AND "; // For backward compatibility
  1798. }
  1799. $sql .= $filter;
  1800. }
  1801. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1802. $tmparray = explode('@', $this->ismultientitymanaged);
  1803. $sql .= ' AND te.'.$tmparray[0].' = '.($tmparray[1] == 'societe' ? 's' : 'parenttable').'.rowid'; // If we need to link to this table to limit select to entity
  1804. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1805. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1806. }
  1807. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1808. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1809. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1810. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1811. } else {
  1812. $sql .= " AND ug.fk_user = te.rowid";
  1813. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1814. }
  1815. } else {
  1816. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1817. }
  1818. }
  1819. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1820. $tmparray = explode('@', $this->ismultientitymanaged);
  1821. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1822. }
  1823. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1824. $sql .= ' AND te.fk_soc = '.$socid;
  1825. }
  1826. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1827. $sql .= ' AND (te.fk_soc = '.$socid.' OR te.fk_soc IS NULL)';
  1828. }
  1829. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1830. $sql .= ' AND te.rowid = '.$socid;
  1831. }
  1832. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1833. $result = $this->db->query($sql);
  1834. if (!$result) {
  1835. $this->error = $this->db->lasterror();
  1836. return -1;
  1837. }
  1838. $row = $this->db->fetch_row($result);
  1839. $this->ref_previous = $row[0];
  1840. $sql = "SELECT MIN(te.".$fieldid.")";
  1841. $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1842. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1843. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  1844. }
  1845. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1846. $tmparray = explode('@', $this->ismultientitymanaged);
  1847. $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
  1848. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1849. $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid
  1850. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1851. $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
  1852. }
  1853. if ($restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) {
  1854. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1855. }
  1856. $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)
  1857. if ($restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) {
  1858. $sql .= " AND sc.fk_user = ".$user->id;
  1859. }
  1860. if ($restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) {
  1861. $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)';
  1862. }
  1863. if (!empty($filter)) {
  1864. if (!preg_match('/^\s*AND/i', $filter)) {
  1865. $sql .= " AND "; // For backward compatibility
  1866. }
  1867. $sql .= $filter;
  1868. }
  1869. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1870. $tmparray = explode('@', $this->ismultientitymanaged);
  1871. $sql .= ' AND te.'.$tmparray[0].' = '.($tmparray[1] == 'societe' ? 's' : 'parenttable').'.rowid'; // If we need to link to this table to limit select to entity
  1872. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1873. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1874. }
  1875. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1876. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1877. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1878. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1879. } else {
  1880. $sql .= " AND ug.fk_user = te.rowid";
  1881. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1882. }
  1883. } else {
  1884. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1885. }
  1886. }
  1887. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1888. $tmparray = explode('@', $this->ismultientitymanaged);
  1889. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1890. }
  1891. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1892. $sql .= ' AND te.fk_soc = '.$socid;
  1893. }
  1894. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1895. $sql .= ' AND (te.fk_soc = '.$socid.' OR te.fk_soc IS NULL)';
  1896. }
  1897. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1898. $sql .= ' AND te.rowid = '.$socid;
  1899. }
  1900. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1901. // 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
  1902. $result = $this->db->query($sql);
  1903. if (!$result) {
  1904. $this->error = $this->db->lasterror();
  1905. return -2;
  1906. }
  1907. $row = $this->db->fetch_row($result);
  1908. $this->ref_next = $row[0];
  1909. return 1;
  1910. }
  1911. /**
  1912. * Return list of id of contacts of object
  1913. *
  1914. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  1915. * @return array Array of id of contacts (if source=external or internal)
  1916. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  1917. */
  1918. public function getListContactId($source = 'external')
  1919. {
  1920. $contactAlreadySelected = array();
  1921. $tab = $this->liste_contact(-1, $source);
  1922. $num = count($tab);
  1923. $i = 0;
  1924. while ($i < $num) {
  1925. if ($source == 'thirdparty') {
  1926. $contactAlreadySelected[$i] = $tab[$i]['socid'];
  1927. } else {
  1928. $contactAlreadySelected[$i] = $tab[$i]['id'];
  1929. }
  1930. $i++;
  1931. }
  1932. return $contactAlreadySelected;
  1933. }
  1934. /**
  1935. * Link element with a project
  1936. *
  1937. * @param int $projectid Project id to link element to
  1938. * @return int <0 if KO, >0 if OK
  1939. */
  1940. public function setProject($projectid)
  1941. {
  1942. if (!$this->table_element) {
  1943. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  1944. return -1;
  1945. }
  1946. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1947. if (!empty($this->fields['fk_project'])) { // Common case
  1948. if ($projectid) {
  1949. $sql .= ' SET fk_project = '.((int) $projectid);
  1950. } else {
  1951. $sql .= ' SET fk_project = NULL';
  1952. }
  1953. $sql .= ' WHERE rowid = '.((int) $this->id);
  1954. } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
  1955. if ($projectid) {
  1956. $sql .= ' SET fk_project = '.((int) $projectid);
  1957. } else {
  1958. $sql .= ' SET fk_project = NULL';
  1959. }
  1960. $sql .= ' WHERE id = '.((int) $this->id);
  1961. } else // Special case for old architecture objects
  1962. {
  1963. if ($projectid) {
  1964. $sql .= ' SET fk_projet = '.((int) $projectid);
  1965. } else {
  1966. $sql .= ' SET fk_projet = NULL';
  1967. }
  1968. $sql .= ' WHERE rowid = '.$this->id;
  1969. }
  1970. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  1971. if ($this->db->query($sql)) {
  1972. $this->fk_project = ((int) $projectid);
  1973. return 1;
  1974. } else {
  1975. dol_print_error($this->db);
  1976. return -1;
  1977. }
  1978. }
  1979. /**
  1980. * Change the payments methods
  1981. *
  1982. * @param int $id Id of new payment method
  1983. * @return int >0 if OK, <0 if KO
  1984. */
  1985. public function setPaymentMethods($id)
  1986. {
  1987. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  1988. if ($this->statut >= 0 || $this->element == 'societe') {
  1989. // TODO uniformize field name
  1990. $fieldname = 'fk_mode_reglement';
  1991. if ($this->element == 'societe') {
  1992. $fieldname = 'mode_reglement';
  1993. }
  1994. if (get_class($this) == 'Fournisseur') {
  1995. $fieldname = 'mode_reglement_supplier';
  1996. }
  1997. if (get_class($this) == 'Tva') {
  1998. $fieldname = 'fk_typepayment';
  1999. }
  2000. if (get_class($this) == 'Salary') {
  2001. $fieldname = 'fk_typepayment';
  2002. }
  2003. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2004. $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL');
  2005. $sql .= ' WHERE rowid='.((int) $this->id);
  2006. if ($this->db->query($sql)) {
  2007. $this->mode_reglement_id = $id;
  2008. // for supplier
  2009. if (get_class($this) == 'Fournisseur') {
  2010. $this->mode_reglement_supplier_id = $id;
  2011. }
  2012. return 1;
  2013. } else {
  2014. dol_syslog(get_class($this).'::setPaymentMethods Error '.$sql.' - '.$this->db->error());
  2015. $this->error = $this->db->error();
  2016. return -1;
  2017. }
  2018. } else {
  2019. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  2020. $this->error = 'Status of the object is incompatible '.$this->statut;
  2021. return -2;
  2022. }
  2023. }
  2024. /**
  2025. * Change the multicurrency code
  2026. *
  2027. * @param string $code multicurrency code
  2028. * @return int >0 if OK, <0 if KO
  2029. */
  2030. public function setMulticurrencyCode($code)
  2031. {
  2032. dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
  2033. if ($this->statut >= 0 || $this->element == 'societe') {
  2034. $fieldname = 'multicurrency_code';
  2035. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2036. $sql .= ' SET '.$fieldname." = '".$this->db->escape($code)."'";
  2037. $sql .= ' WHERE rowid='.((int) $this->id);
  2038. if ($this->db->query($sql)) {
  2039. $this->multicurrency_code = $code;
  2040. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  2041. if ($rate) {
  2042. $this->setMulticurrencyRate($rate, 2);
  2043. }
  2044. return 1;
  2045. } else {
  2046. dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
  2047. $this->error = $this->db->error();
  2048. return -1;
  2049. }
  2050. } else {
  2051. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  2052. $this->error = 'Status of the object is incompatible '.$this->statut;
  2053. return -2;
  2054. }
  2055. }
  2056. /**
  2057. * Change the multicurrency rate
  2058. *
  2059. * @param double $rate multicurrency rate
  2060. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  2061. * @return int >0 if OK, <0 if KO
  2062. */
  2063. public function setMulticurrencyRate($rate, $mode = 1)
  2064. {
  2065. dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
  2066. if ($this->statut >= 0 || $this->element == 'societe') {
  2067. $fieldname = 'multicurrency_tx';
  2068. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2069. $sql .= ' SET '.$fieldname.' = '.((float) $rate);
  2070. $sql .= ' WHERE rowid='.((int) $this->id);
  2071. if ($this->db->query($sql)) {
  2072. $this->multicurrency_tx = $rate;
  2073. // Update line price
  2074. if (!empty($this->lines)) {
  2075. foreach ($this->lines as &$line) {
  2076. // Amounts in company currency will be recalculated
  2077. if ($mode == 1) {
  2078. $line->subprice = 0;
  2079. }
  2080. // Amounts in foreign currency will be recalculated
  2081. if ($mode == 2) {
  2082. $line->multicurrency_subprice = 0;
  2083. }
  2084. switch ($this->element) {
  2085. case 'propal':
  2086. $this->updateline(
  2087. $line->id,
  2088. $line->subprice,
  2089. $line->qty,
  2090. $line->remise_percent,
  2091. $line->tva_tx,
  2092. $line->localtax1_tx,
  2093. $line->localtax2_tx,
  2094. ($line->description ? $line->description : $line->desc),
  2095. 'HT',
  2096. $line->info_bits,
  2097. $line->special_code,
  2098. $line->fk_parent_line,
  2099. $line->skip_update_total,
  2100. $line->fk_fournprice,
  2101. $line->pa_ht,
  2102. $line->label,
  2103. $line->product_type,
  2104. $line->date_start,
  2105. $line->date_end,
  2106. $line->array_options,
  2107. $line->fk_unit,
  2108. $line->multicurrency_subprice
  2109. );
  2110. break;
  2111. case 'commande':
  2112. $this->updateline(
  2113. $line->id,
  2114. ($line->description ? $line->description : $line->desc),
  2115. $line->subprice,
  2116. $line->qty,
  2117. $line->remise_percent,
  2118. $line->tva_tx,
  2119. $line->localtax1_tx,
  2120. $line->localtax2_tx,
  2121. 'HT',
  2122. $line->info_bits,
  2123. $line->date_start,
  2124. $line->date_end,
  2125. $line->product_type,
  2126. $line->fk_parent_line,
  2127. $line->skip_update_total,
  2128. $line->fk_fournprice,
  2129. $line->pa_ht,
  2130. $line->label,
  2131. $line->special_code,
  2132. $line->array_options,
  2133. $line->fk_unit,
  2134. $line->multicurrency_subprice
  2135. );
  2136. break;
  2137. case 'facture':
  2138. $this->updateline(
  2139. $line->id,
  2140. ($line->description ? $line->description : $line->desc),
  2141. $line->subprice,
  2142. $line->qty,
  2143. $line->remise_percent,
  2144. $line->date_start,
  2145. $line->date_end,
  2146. $line->tva_tx,
  2147. $line->localtax1_tx,
  2148. $line->localtax2_tx,
  2149. 'HT',
  2150. $line->info_bits,
  2151. $line->product_type,
  2152. $line->fk_parent_line,
  2153. $line->skip_update_total,
  2154. $line->fk_fournprice,
  2155. $line->pa_ht,
  2156. $line->label,
  2157. $line->special_code,
  2158. $line->array_options,
  2159. $line->situation_percent,
  2160. $line->fk_unit,
  2161. $line->multicurrency_subprice
  2162. );
  2163. break;
  2164. case 'supplier_proposal':
  2165. $this->updateline(
  2166. $line->id,
  2167. $line->subprice,
  2168. $line->qty,
  2169. $line->remise_percent,
  2170. $line->tva_tx,
  2171. $line->localtax1_tx,
  2172. $line->localtax2_tx,
  2173. ($line->description ? $line->description : $line->desc),
  2174. 'HT',
  2175. $line->info_bits,
  2176. $line->special_code,
  2177. $line->fk_parent_line,
  2178. $line->skip_update_total,
  2179. $line->fk_fournprice,
  2180. $line->pa_ht,
  2181. $line->label,
  2182. $line->product_type,
  2183. $line->array_options,
  2184. $line->ref_fourn,
  2185. $line->multicurrency_subprice
  2186. );
  2187. break;
  2188. case 'order_supplier':
  2189. $this->updateline(
  2190. $line->id,
  2191. ($line->description ? $line->description : $line->desc),
  2192. $line->subprice,
  2193. $line->qty,
  2194. $line->remise_percent,
  2195. $line->tva_tx,
  2196. $line->localtax1_tx,
  2197. $line->localtax2_tx,
  2198. 'HT',
  2199. $line->info_bits,
  2200. $line->product_type,
  2201. false,
  2202. $line->date_start,
  2203. $line->date_end,
  2204. $line->array_options,
  2205. $line->fk_unit,
  2206. $line->multicurrency_subprice,
  2207. $line->ref_supplier
  2208. );
  2209. break;
  2210. case 'invoice_supplier':
  2211. $this->updateline(
  2212. $line->id,
  2213. ($line->description ? $line->description : $line->desc),
  2214. $line->subprice,
  2215. $line->tva_tx,
  2216. $line->localtax1_tx,
  2217. $line->localtax2_tx,
  2218. $line->qty,
  2219. 0,
  2220. 'HT',
  2221. $line->info_bits,
  2222. $line->product_type,
  2223. $line->remise_percent,
  2224. false,
  2225. $line->date_start,
  2226. $line->date_end,
  2227. $line->array_options,
  2228. $line->fk_unit,
  2229. $line->multicurrency_subprice,
  2230. $line->ref_supplier
  2231. );
  2232. break;
  2233. default:
  2234. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  2235. break;
  2236. }
  2237. }
  2238. }
  2239. return 1;
  2240. } else {
  2241. dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
  2242. $this->error = $this->db->error();
  2243. return -1;
  2244. }
  2245. } else {
  2246. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  2247. $this->error = 'Status of the object is incompatible '.$this->statut;
  2248. return -2;
  2249. }
  2250. }
  2251. /**
  2252. * Change the payments terms
  2253. *
  2254. * @param int $id Id of new payment terms
  2255. * @return int >0 if OK, <0 if KO
  2256. */
  2257. public function setPaymentTerms($id)
  2258. {
  2259. dol_syslog(get_class($this).'::setPaymentTerms('.$id.')');
  2260. if ($this->statut >= 0 || $this->element == 'societe') {
  2261. // TODO uniformize field name
  2262. $fieldname = 'fk_cond_reglement';
  2263. if ($this->element == 'societe') {
  2264. $fieldname = 'cond_reglement';
  2265. }
  2266. if (get_class($this) == 'Fournisseur') {
  2267. $fieldname = 'cond_reglement_supplier';
  2268. }
  2269. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2270. $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL');
  2271. $sql .= ' WHERE rowid='.((int) $this->id);
  2272. if ($this->db->query($sql)) {
  2273. $this->cond_reglement_id = $id;
  2274. // for supplier
  2275. if (get_class($this) == 'Fournisseur') {
  2276. $this->cond_reglement_supplier_id = $id;
  2277. }
  2278. $this->cond_reglement = $id; // for compatibility
  2279. return 1;
  2280. } else {
  2281. dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
  2282. $this->error = $this->db->error();
  2283. return -1;
  2284. }
  2285. } else {
  2286. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  2287. $this->error = 'Status of the object is incompatible '.$this->statut;
  2288. return -2;
  2289. }
  2290. }
  2291. /**
  2292. * Change the transport mode methods
  2293. *
  2294. * @param int $id Id of transport mode
  2295. * @return int >0 if OK, <0 if KO
  2296. */
  2297. public function setTransportMode($id)
  2298. {
  2299. dol_syslog(get_class($this).'::setTransportMode('.$id.')');
  2300. if ($this->statut >= 0 || $this->element == 'societe') {
  2301. $fieldname = 'fk_transport_mode';
  2302. if ($this->element == 'societe') {
  2303. $fieldname = 'transport_mode';
  2304. }
  2305. if (get_class($this) == 'Fournisseur') {
  2306. $fieldname = 'transport_mode_supplier';
  2307. }
  2308. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2309. $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL');
  2310. $sql .= ' WHERE rowid='.((int) $this->id);
  2311. if ($this->db->query($sql)) {
  2312. $this->transport_mode_id = $id;
  2313. // for supplier
  2314. if (get_class($this) == 'Fournisseur') {
  2315. $this->transport_mode_supplier_id = $id;
  2316. }
  2317. return 1;
  2318. } else {
  2319. dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
  2320. $this->error = $this->db->error();
  2321. return -1;
  2322. }
  2323. } else {
  2324. dol_syslog(get_class($this).'::setTransportMode, 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 retained warranty payments terms
  2331. *
  2332. * @param int $id Id of new payment terms
  2333. * @return int >0 if OK, <0 if KO
  2334. */
  2335. public function setRetainedWarrantyPaymentTerms($id)
  2336. {
  2337. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
  2338. if ($this->statut >= 0 || $this->element == 'societe') {
  2339. $fieldname = 'retained_warranty_fk_cond_reglement';
  2340. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2341. $sql .= ' SET '.$fieldname.' = '.((int) $id);
  2342. $sql .= ' WHERE rowid='.((int) $this->id);
  2343. if ($this->db->query($sql)) {
  2344. $this->retained_warranty_fk_cond_reglement = $id;
  2345. return 1;
  2346. } else {
  2347. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
  2348. $this->error = $this->db->error();
  2349. return -1;
  2350. }
  2351. } else {
  2352. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  2353. $this->error = 'Status of the object is incompatible '.$this->statut;
  2354. return -2;
  2355. }
  2356. }
  2357. /**
  2358. * Define delivery address
  2359. * @deprecated
  2360. *
  2361. * @param int $id Address id
  2362. * @return int <0 si ko, >0 si ok
  2363. */
  2364. public function setDeliveryAddress($id)
  2365. {
  2366. $fieldname = 'fk_delivery_address';
  2367. if ($this->element == 'delivery' || $this->element == 'shipping') {
  2368. $fieldname = 'fk_address';
  2369. }
  2370. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".((int) $id);
  2371. $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0";
  2372. if ($this->db->query($sql)) {
  2373. $this->fk_delivery_address = $id;
  2374. return 1;
  2375. } else {
  2376. $this->error = $this->db->error();
  2377. dol_syslog(get_class($this).'::setDeliveryAddress Error '.$sql.' - '.$this->error);
  2378. return -1;
  2379. }
  2380. }
  2381. /**
  2382. * Change the shipping method
  2383. *
  2384. * @param int $shipping_method_id Id of shipping method
  2385. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2386. * @param User $userused Object user
  2387. *
  2388. * @return int 1 if OK, 0 if KO
  2389. */
  2390. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  2391. {
  2392. global $user;
  2393. if (empty($userused)) {
  2394. $userused = $user;
  2395. }
  2396. $error = 0;
  2397. if (!$this->table_element) {
  2398. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2399. return -1;
  2400. }
  2401. $this->db->begin();
  2402. if ($shipping_method_id < 0) {
  2403. $shipping_method_id = 'NULL';
  2404. }
  2405. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  2406. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2407. $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
  2408. $sql .= " WHERE rowid=".((int) $this->id);
  2409. $resql = $this->db->query($sql);
  2410. if (!$resql) {
  2411. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  2412. $this->error = $this->db->lasterror();
  2413. $error++;
  2414. } else {
  2415. if (!$notrigger) {
  2416. // Call trigger
  2417. $this->context = array('shippingmethodupdate'=>1);
  2418. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2419. if ($result < 0) {
  2420. $error++;
  2421. }
  2422. // End call trigger
  2423. }
  2424. }
  2425. if ($error) {
  2426. $this->db->rollback();
  2427. return -1;
  2428. } else {
  2429. $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
  2430. $this->db->commit();
  2431. return 1;
  2432. }
  2433. }
  2434. /**
  2435. * Change the warehouse
  2436. *
  2437. * @param int $warehouse_id Id of warehouse
  2438. * @return int 1 if OK, 0 if KO
  2439. */
  2440. public function setWarehouse($warehouse_id)
  2441. {
  2442. if (!$this->table_element) {
  2443. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2444. return -1;
  2445. }
  2446. if ($warehouse_id < 0) {
  2447. $warehouse_id = 'NULL';
  2448. }
  2449. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  2450. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2451. $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
  2452. $sql .= " WHERE rowid=".((int) $this->id);
  2453. if ($this->db->query($sql)) {
  2454. $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
  2455. return 1;
  2456. } else {
  2457. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  2458. $this->error = $this->db->error();
  2459. return 0;
  2460. }
  2461. }
  2462. /**
  2463. * Set last model used by doc generator
  2464. *
  2465. * @param User $user User object that make change
  2466. * @param string $modelpdf Modele name
  2467. * @return int <0 if KO, >0 if OK
  2468. */
  2469. public function setDocModel($user, $modelpdf)
  2470. {
  2471. if (!$this->table_element) {
  2472. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2473. return -1;
  2474. }
  2475. $newmodelpdf = dol_trunc($modelpdf, 255);
  2476. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2477. $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  2478. $sql .= " WHERE rowid = ".$this->id;
  2479. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  2480. $resql = $this->db->query($sql);
  2481. if ($resql) {
  2482. $this->model_pdf = $modelpdf;
  2483. $this->modelpdf = $modelpdf; // For bakward compatibility
  2484. return 1;
  2485. } else {
  2486. dol_print_error($this->db);
  2487. return 0;
  2488. }
  2489. }
  2490. /**
  2491. * Change the bank account
  2492. *
  2493. * @param int $fk_account Id of bank account
  2494. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2495. * @param User $userused Object user
  2496. * @return int 1 if OK, 0 if KO
  2497. */
  2498. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2499. {
  2500. global $user;
  2501. if (empty($userused)) {
  2502. $userused = $user;
  2503. }
  2504. $error = 0;
  2505. if (!$this->table_element) {
  2506. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2507. return -1;
  2508. }
  2509. $this->db->begin();
  2510. if ($fk_account < 0) {
  2511. $fk_account = 'NULL';
  2512. }
  2513. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  2514. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2515. $sql .= " SET fk_account = ".((int) $fk_account);
  2516. $sql .= " WHERE rowid=".((int) $this->id);
  2517. $resql = $this->db->query($sql);
  2518. if (!$resql) {
  2519. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  2520. $this->error = $this->db->lasterror();
  2521. $error++;
  2522. } else {
  2523. if (!$notrigger) {
  2524. // Call trigger
  2525. $this->context = array('bankaccountupdate'=>1);
  2526. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2527. if ($result < 0) {
  2528. $error++;
  2529. }
  2530. // End call trigger
  2531. }
  2532. }
  2533. if ($error) {
  2534. $this->db->rollback();
  2535. return -1;
  2536. } else {
  2537. $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
  2538. $this->db->commit();
  2539. return 1;
  2540. }
  2541. }
  2542. // TODO: Move line related operations to CommonObjectLine?
  2543. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2544. /**
  2545. * Save a new position (field rang) for details lines.
  2546. * You can choose to set position for lines with already a position or lines without any position defined.
  2547. *
  2548. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2549. * @param string $rowidorder ASC or DESC
  2550. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2551. * @return int <0 if KO, >0 if OK
  2552. */
  2553. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2554. {
  2555. // phpcs:enable
  2556. if (!$this->table_element_line) {
  2557. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2558. return -1;
  2559. }
  2560. if (!$this->fk_element) {
  2561. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2562. return -1;
  2563. }
  2564. // Count number of lines to reorder (according to choice $renum)
  2565. $nl = 0;
  2566. $sql = 'SELECT count(rowid) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2567. $sql .= ' WHERE '.$this->fk_element.'='.$this->id;
  2568. if (!$renum) {
  2569. $sql .= ' AND rang = 0';
  2570. }
  2571. if ($renum) {
  2572. $sql .= ' AND rang <> 0';
  2573. }
  2574. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  2575. $resql = $this->db->query($sql);
  2576. if ($resql) {
  2577. $row = $this->db->fetch_row($resql);
  2578. $nl = $row[0];
  2579. } else {
  2580. dol_print_error($this->db);
  2581. }
  2582. if ($nl > 0) {
  2583. // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
  2584. $rows = array();
  2585. // We first search all lines that are parent lines (for multilevel details lines)
  2586. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2587. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2588. if ($fk_parent_line) {
  2589. $sql .= ' AND fk_parent_line IS NULL';
  2590. }
  2591. $sql .= ' ORDER BY rang ASC, rowid '.$rowidorder;
  2592. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  2593. $resql = $this->db->query($sql);
  2594. if ($resql) {
  2595. $i = 0;
  2596. $num = $this->db->num_rows($resql);
  2597. while ($i < $num) {
  2598. $row = $this->db->fetch_row($resql);
  2599. $rows[] = $row[0]; // Add parent line into array rows
  2600. $childrens = $this->getChildrenOfLine($row[0]);
  2601. if (!empty($childrens)) {
  2602. foreach ($childrens as $child) {
  2603. array_push($rows, $child);
  2604. }
  2605. }
  2606. $i++;
  2607. }
  2608. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2609. if (!empty($rows)) {
  2610. foreach ($rows as $key => $row) {
  2611. $this->updateRangOfLine($row, ($key + 1));
  2612. }
  2613. }
  2614. } else {
  2615. dol_print_error($this->db);
  2616. }
  2617. }
  2618. return 1;
  2619. }
  2620. /**
  2621. * Get children of line
  2622. *
  2623. * @param int $id Id of parent line
  2624. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2625. * @return array Array with list of children lines id
  2626. */
  2627. public function getChildrenOfLine($id, $includealltree = 0)
  2628. {
  2629. $rows = array();
  2630. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2631. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2632. $sql .= ' AND fk_parent_line = '.$id;
  2633. $sql .= ' ORDER BY rang ASC';
  2634. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id."", LOG_DEBUG);
  2635. $resql = $this->db->query($sql);
  2636. if ($resql) {
  2637. if ($this->db->num_rows($resql) > 0) {
  2638. while ($row = $this->db->fetch_row($resql)) {
  2639. $rows[] = $row[0];
  2640. if (!empty($includealltree)) {
  2641. $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2642. }
  2643. }
  2644. }
  2645. }
  2646. return $rows;
  2647. }
  2648. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2649. /**
  2650. * Update a line to have a lower rank
  2651. *
  2652. * @param int $rowid Id of line
  2653. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2654. * @return void
  2655. */
  2656. public function line_up($rowid, $fk_parent_line = true)
  2657. {
  2658. // phpcs:enable
  2659. $this->line_order(false, 'ASC', $fk_parent_line);
  2660. // Get rang of line
  2661. $rang = $this->getRangOfLine($rowid);
  2662. // Update position of line
  2663. $this->updateLineUp($rowid, $rang);
  2664. }
  2665. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2666. /**
  2667. * Update a line to have a higher rank
  2668. *
  2669. * @param int $rowid Id of line
  2670. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2671. * @return void
  2672. */
  2673. public function line_down($rowid, $fk_parent_line = true)
  2674. {
  2675. // phpcs:enable
  2676. $this->line_order(false, 'ASC', $fk_parent_line);
  2677. // Get rang of line
  2678. $rang = $this->getRangOfLine($rowid);
  2679. // Get max value for rang
  2680. $max = $this->line_max();
  2681. // Update position of line
  2682. $this->updateLineDown($rowid, $rang, $max);
  2683. }
  2684. /**
  2685. * Update position of line (rang)
  2686. *
  2687. * @param int $rowid Id of line
  2688. * @param int $rang Position
  2689. * @return void
  2690. */
  2691. public function updateRangOfLine($rowid, $rang)
  2692. {
  2693. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2694. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction'))) {
  2695. $fieldposition = 'position';
  2696. }
  2697. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.((int) $rang);
  2698. $sql .= ' WHERE rowid = '.((int) $rowid);
  2699. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2700. if (!$this->db->query($sql)) {
  2701. dol_print_error($this->db);
  2702. }
  2703. }
  2704. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2705. /**
  2706. * Update position of line with ajax (rang)
  2707. *
  2708. * @param array $rows Array of rows
  2709. * @return void
  2710. */
  2711. public function line_ajaxorder($rows)
  2712. {
  2713. // phpcs:enable
  2714. $num = count($rows);
  2715. for ($i = 0; $i < $num; $i++) {
  2716. $this->updateRangOfLine($rows[$i], ($i + 1));
  2717. }
  2718. }
  2719. /**
  2720. * Update position of line up (rang)
  2721. *
  2722. * @param int $rowid Id of line
  2723. * @param int $rang Position
  2724. * @return void
  2725. */
  2726. public function updateLineUp($rowid, $rang)
  2727. {
  2728. if ($rang > 1) {
  2729. $fieldposition = 'rang';
  2730. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
  2731. $fieldposition = 'position';
  2732. }
  2733. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.((int) $rang);
  2734. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2735. $sql .= ' AND rang = '.($rang - 1);
  2736. if ($this->db->query($sql)) {
  2737. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.((int) ($rang - 1));
  2738. $sql .= ' WHERE rowid = '.((int) $rowid);
  2739. if (!$this->db->query($sql)) {
  2740. dol_print_error($this->db);
  2741. }
  2742. } else {
  2743. dol_print_error($this->db);
  2744. }
  2745. }
  2746. }
  2747. /**
  2748. * Update position of line down (rang)
  2749. *
  2750. * @param int $rowid Id of line
  2751. * @param int $rang Position
  2752. * @param int $max Max
  2753. * @return void
  2754. */
  2755. public function updateLineDown($rowid, $rang, $max)
  2756. {
  2757. if ($rang < $max) {
  2758. $fieldposition = 'rang';
  2759. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
  2760. $fieldposition = 'position';
  2761. }
  2762. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.((int) $rang);
  2763. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2764. $sql .= ' AND rang = '.((int) ($rang + 1));
  2765. if ($this->db->query($sql)) {
  2766. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.((int) ($rang + 1));
  2767. $sql .= ' WHERE rowid = '.((int) $rowid);
  2768. if (!$this->db->query($sql)) {
  2769. dol_print_error($this->db);
  2770. }
  2771. } else {
  2772. dol_print_error($this->db);
  2773. }
  2774. }
  2775. }
  2776. /**
  2777. * Get position of line (rang)
  2778. *
  2779. * @param int $rowid Id of line
  2780. * @return int Value of rang in table of lines
  2781. */
  2782. public function getRangOfLine($rowid)
  2783. {
  2784. $sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2785. $sql .= ' WHERE rowid ='.((int) $rowid);
  2786. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  2787. $resql = $this->db->query($sql);
  2788. if ($resql) {
  2789. $row = $this->db->fetch_row($resql);
  2790. return $row[0];
  2791. }
  2792. }
  2793. /**
  2794. * Get rowid of the line relative to its position
  2795. *
  2796. * @param int $rang Rang value
  2797. * @return int Rowid of the line
  2798. */
  2799. public function getIdOfLine($rang)
  2800. {
  2801. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2802. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2803. $sql .= ' AND rang = '.((int) $rang);
  2804. $resql = $this->db->query($sql);
  2805. if ($resql) {
  2806. $row = $this->db->fetch_row($resql);
  2807. return $row[0];
  2808. }
  2809. }
  2810. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2811. /**
  2812. * Get max value used for position of line (rang)
  2813. *
  2814. * @param int $fk_parent_line Parent line id
  2815. * @return int Max value of rang in table of lines
  2816. */
  2817. public function line_max($fk_parent_line = 0)
  2818. {
  2819. // phpcs:enable
  2820. $positionfield = 'rang';
  2821. if ($this->table_element == 'bom_bom') {
  2822. $positionfield = 'position';
  2823. }
  2824. // Search the last rang with fk_parent_line
  2825. if ($fk_parent_line) {
  2826. $sql = 'SELECT max('.$positionfield.') FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2827. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2828. $sql .= ' AND fk_parent_line = '.$fk_parent_line;
  2829. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2830. $resql = $this->db->query($sql);
  2831. if ($resql) {
  2832. $row = $this->db->fetch_row($resql);
  2833. if (!empty($row[0])) {
  2834. return $row[0];
  2835. } else {
  2836. return $this->getRangOfLine($fk_parent_line);
  2837. }
  2838. }
  2839. } else {
  2840. // If not, search the last rang of element
  2841. $sql = 'SELECT max('.$positionfield.') FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2842. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2843. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2844. $resql = $this->db->query($sql);
  2845. if ($resql) {
  2846. $row = $this->db->fetch_row($resql);
  2847. return $row[0];
  2848. }
  2849. }
  2850. }
  2851. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2852. /**
  2853. * Update external ref of element
  2854. *
  2855. * @param string $ref_ext Update field ref_ext
  2856. * @return int <0 if KO, >0 if OK
  2857. */
  2858. public function update_ref_ext($ref_ext)
  2859. {
  2860. // phpcs:enable
  2861. if (!$this->table_element) {
  2862. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  2863. return -1;
  2864. }
  2865. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2866. $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  2867. $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".$this->id;
  2868. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  2869. if ($this->db->query($sql)) {
  2870. $this->ref_ext = $ref_ext;
  2871. return 1;
  2872. } else {
  2873. $this->error = $this->db->error();
  2874. return -1;
  2875. }
  2876. }
  2877. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2878. /**
  2879. * Update note of element
  2880. *
  2881. * @param string $note New value for note
  2882. * @param string $suffix '', '_public' or '_private'
  2883. * @return int <0 if KO, >0 if OK
  2884. */
  2885. public function update_note($note, $suffix = '')
  2886. {
  2887. // phpcs:enable
  2888. global $user;
  2889. if (!$this->table_element) {
  2890. $this->error = 'update_note was called on objet with property table_element not defined';
  2891. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  2892. return -1;
  2893. }
  2894. if (!in_array($suffix, array('', '_public', '_private'))) {
  2895. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  2896. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  2897. return -2;
  2898. }
  2899. $newsuffix = $suffix;
  2900. // Special cas
  2901. if ($this->table_element == 'product' && $newsuffix == '_private') {
  2902. $newsuffix = '';
  2903. }
  2904. if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  2905. $fieldusermod = "fk_user_mod";
  2906. } elseif ($this->table_element == 'ecm_files') {
  2907. $fieldusermod = "fk_user_m";
  2908. } else {
  2909. $fieldusermod = "fk_user_modif";
  2910. }
  2911. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2912. $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
  2913. $sql .= " ,".$fieldusermod." = ".$user->id;
  2914. $sql .= " WHERE rowid =".$this->id;
  2915. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  2916. if ($this->db->query($sql)) {
  2917. if ($suffix == '_public') {
  2918. $this->note_public = $note;
  2919. } elseif ($suffix == '_private') {
  2920. $this->note_private = $note;
  2921. } else {
  2922. $this->note = $note; // deprecated
  2923. $this->note_private = $note;
  2924. }
  2925. return 1;
  2926. } else {
  2927. $this->error = $this->db->lasterror();
  2928. return -1;
  2929. }
  2930. }
  2931. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2932. /**
  2933. * Update public note (kept for backward compatibility)
  2934. *
  2935. * @param string $note New value for note
  2936. * @return int <0 if KO, >0 if OK
  2937. * @deprecated
  2938. * @see update_note()
  2939. */
  2940. public function update_note_public($note)
  2941. {
  2942. // phpcs:enable
  2943. return $this->update_note($note, '_public');
  2944. }
  2945. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2946. /**
  2947. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  2948. * Must be called at end of methods addline or updateline.
  2949. *
  2950. * @param int $exclspec >0 = Exclude special product (product_type=9)
  2951. * @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
  2952. * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object.
  2953. * @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.
  2954. * @return int <0 if KO, >0 if OK
  2955. */
  2956. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  2957. {
  2958. // phpcs:enable
  2959. global $conf, $hookmanager, $action;
  2960. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  2961. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  2962. if ($reshook > 0) {
  2963. return 1; // replacement code
  2964. } elseif ($reshook < 0) {
  2965. return -1; // failure
  2966. } // reshook = 0 => execute normal code
  2967. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  2968. $MODULE = "";
  2969. if ($this->element == 'propal') {
  2970. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  2971. } elseif ($this->element == 'commande' || $this->element == 'order') {
  2972. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  2973. } elseif ($this->element == 'facture' || $this->element == 'invoice') {
  2974. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  2975. } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier') {
  2976. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  2977. } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
  2978. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  2979. } elseif ($this->element == 'supplier_proposal') {
  2980. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  2981. }
  2982. if (!empty($MODULE)) {
  2983. if (!empty($conf->global->$MODULE)) {
  2984. $modsactivated = explode(',', $conf->global->$MODULE);
  2985. foreach ($modsactivated as $mod) {
  2986. if ($conf->$mod->enabled) {
  2987. return 1; // update was disabled by specific setup
  2988. }
  2989. }
  2990. }
  2991. }
  2992. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  2993. if ($roundingadjust == '-1') {
  2994. $roundingadjust = 'auto'; // For backward compatibility
  2995. }
  2996. $forcedroundingmode = $roundingadjust;
  2997. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
  2998. $forcedroundingmode = $conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
  2999. } elseif ($forcedroundingmode == 'auto') {
  3000. $forcedroundingmode = '0';
  3001. }
  3002. $error = 0;
  3003. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  3004. // Define constants to find lines to sum
  3005. $fieldtva = 'total_tva';
  3006. $fieldlocaltax1 = 'total_localtax1';
  3007. $fieldlocaltax2 = 'total_localtax2';
  3008. $fieldup = 'subprice';
  3009. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3010. $fieldtva = 'tva';
  3011. $fieldup = 'pu_ht';
  3012. }
  3013. if ($this->element == 'expensereport') {
  3014. $fieldup = 'value_unit';
  3015. }
  3016. $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,';
  3017. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  3018. if ($this->table_element_line == 'facturedet') {
  3019. $sql .= ', situation_percent';
  3020. }
  3021. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3022. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  3023. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  3024. if ($exclspec) {
  3025. $product_field = 'product_type';
  3026. if ($this->table_element_line == 'contratdet') {
  3027. $product_field = ''; // contratdet table has no product_type field
  3028. }
  3029. if ($product_field) {
  3030. $sql .= ' AND '.$product_field.' <> 9';
  3031. }
  3032. }
  3033. $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
  3034. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3035. $resql = $this->db->query($sql);
  3036. if ($resql) {
  3037. $this->total_ht = 0;
  3038. $this->total_tva = 0;
  3039. $this->total_localtax1 = 0;
  3040. $this->total_localtax2 = 0;
  3041. $this->total_ttc = 0;
  3042. $total_ht_by_vats = array();
  3043. $total_tva_by_vats = array();
  3044. $total_ttc_by_vats = array();
  3045. $this->multicurrency_total_ht = 0;
  3046. $this->multicurrency_total_tva = 0;
  3047. $this->multicurrency_total_ttc = 0;
  3048. $num = $this->db->num_rows($resql);
  3049. $i = 0;
  3050. while ($i < $num) {
  3051. $obj = $this->db->fetch_object($resql);
  3052. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  3053. $parameters = array('fk_element' => $obj->rowid);
  3054. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3055. 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'
  3056. // This part of code is to fix data. We should not call it too often.
  3057. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  3058. $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);
  3059. $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.
  3060. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  3061. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
  3062. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  3063. if ($diff_when_using_price_ht && $diff_on_current_total) {
  3064. $sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
  3065. 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);
  3066. $resqlfix = $this->db->query($sqlfix);
  3067. if (!$resqlfix) {
  3068. dol_print_error($this->db, 'Failed to update line');
  3069. }
  3070. $obj->total_tva = $tmpcal[1];
  3071. $obj->total_ttc = $tmpcal[2];
  3072. }
  3073. }
  3074. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  3075. $this->total_tva += $obj->total_tva;
  3076. $this->total_localtax1 += $obj->total_localtax1;
  3077. $this->total_localtax2 += $obj->total_localtax2;
  3078. $this->total_ttc += $obj->total_ttc;
  3079. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  3080. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  3081. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  3082. if (!isset($total_ht_by_vats[$obj->vatrate])) {
  3083. $total_ht_by_vats[$obj->vatrate] = 0;
  3084. }
  3085. if (!isset($total_tva_by_vats[$obj->vatrate])) {
  3086. $total_tva_by_vats[$obj->vatrate] = 0;
  3087. }
  3088. if (!isset($total_ttc_by_vats[$obj->vatrate])) {
  3089. $total_ttc_by_vats[$obj->vatrate] = 0;
  3090. }
  3091. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  3092. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  3093. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  3094. if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  3095. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  3096. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  3097. //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";
  3098. if ($diff) {
  3099. if (abs($diff) > 0.1) {
  3100. $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.';
  3101. dol_syslog($errmsg, LOG_WARNING);
  3102. dol_print_error('', $errmsg);
  3103. exit;
  3104. }
  3105. $sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".($obj->total_tva - $diff).", total_ttc = ".($obj->total_ttc - $diff)." WHERE rowid = ".$obj->rowid;
  3106. 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);
  3107. $resqlfix = $this->db->query($sqlfix);
  3108. if (!$resqlfix) {
  3109. dol_print_error($this->db, 'Failed to update line');
  3110. }
  3111. $this->total_tva -= $diff;
  3112. $this->total_ttc -= $diff;
  3113. $total_tva_by_vats[$obj->vatrate] -= $diff;
  3114. $total_ttc_by_vats[$obj->vatrate] -= $diff;
  3115. }
  3116. }
  3117. $i++;
  3118. }
  3119. // Add revenue stamp to total
  3120. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  3121. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  3122. // Situations totals
  3123. if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
  3124. $prev_sits = $this->get_prev_sits();
  3125. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  3126. $this->total_ht -= $sit->total_ht;
  3127. $this->total_tva -= $sit->total_tva;
  3128. $this->total_localtax1 -= $sit->total_localtax1;
  3129. $this->total_localtax2 -= $sit->total_localtax2;
  3130. $this->total_ttc -= $sit->total_ttc;
  3131. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  3132. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  3133. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  3134. }
  3135. }
  3136. $this->db->free($resql);
  3137. // Now update global field total_ht, total_ttc and tva
  3138. $fieldht = 'total_ht';
  3139. $fieldtva = 'tva';
  3140. $fieldlocaltax1 = 'localtax1';
  3141. $fieldlocaltax2 = 'localtax2';
  3142. $fieldttc = 'total_ttc';
  3143. // Specific code for backward compatibility with old field names
  3144. if ($this->element == 'facture' || $this->element == 'facturerec') {
  3145. $fieldtva = 'total_tva';
  3146. }
  3147. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3148. $fieldtva = 'total_tva';
  3149. }
  3150. if ($this->element == 'propal') {
  3151. $fieldtva = 'total_tva';
  3152. }
  3153. if ($this->element == 'expensereport') {
  3154. $fieldtva = 'total_tva';
  3155. }
  3156. if ($this->element == 'supplier_proposal') {
  3157. $fieldtva = 'total_tva';
  3158. }
  3159. if ($this->element == 'commande') {
  3160. $fieldtva = 'total_tva';
  3161. }
  3162. if ($this->element == 'order_supplier') {
  3163. $fieldtva = 'total_tva';
  3164. }
  3165. if (empty($nodatabaseupdate)) {
  3166. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
  3167. $sql .= " ".$fieldht." = ".price2num($this->total_ht).",";
  3168. $sql .= " ".$fieldtva." = ".price2num($this->total_tva).",";
  3169. $sql .= " ".$fieldlocaltax1." = ".price2num($this->total_localtax1).",";
  3170. $sql .= " ".$fieldlocaltax2." = ".price2num($this->total_localtax2).",";
  3171. $sql .= " ".$fieldttc." = ".price2num($this->total_ttc);
  3172. $sql .= ", multicurrency_total_ht = ".price2num($this->multicurrency_total_ht, 'MT', 1);
  3173. $sql .= ", multicurrency_total_tva = ".price2num($this->multicurrency_total_tva, 'MT', 1);
  3174. $sql .= ", multicurrency_total_ttc = ".price2num($this->multicurrency_total_ttc, 'MT', 1);
  3175. $sql .= ' WHERE rowid = '.$this->id;
  3176. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3177. $resql = $this->db->query($sql);
  3178. if (!$resql) {
  3179. $error++;
  3180. $this->error = $this->db->lasterror();
  3181. $this->errors[] = $this->db->lasterror();
  3182. }
  3183. }
  3184. if (!$error) {
  3185. return 1;
  3186. } else {
  3187. return -1;
  3188. }
  3189. } else {
  3190. dol_print_error($this->db, 'Bad request in update_price');
  3191. return -1;
  3192. }
  3193. }
  3194. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3195. /**
  3196. * Add objects linked in llx_element_element.
  3197. *
  3198. * @param string $origin Linked element type
  3199. * @param int $origin_id Linked element id
  3200. * @param User $f_user User that create
  3201. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3202. * @return int <=0 if KO, >0 if OK
  3203. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  3204. */
  3205. public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
  3206. {
  3207. // phpcs:enable
  3208. global $user;
  3209. $origin = (!empty($origin) ? $origin : $this->origin);
  3210. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  3211. $f_user = isset($f_user) ? $f_user : $user;
  3212. // Special case
  3213. if ($origin == 'order') {
  3214. $origin = 'commande';
  3215. }
  3216. if ($origin == 'invoice') {
  3217. $origin = 'facture';
  3218. }
  3219. if ($origin == 'invoice_template') {
  3220. $origin = 'facturerec';
  3221. }
  3222. if ($origin == 'supplierorder') {
  3223. $origin = 'order_supplier';
  3224. }
  3225. $this->db->begin();
  3226. $error = 0;
  3227. $sql = "INSERT INTO " . MAIN_DB_PREFIX . "element_element (";
  3228. $sql .= "fk_source";
  3229. $sql .= ", sourcetype";
  3230. $sql .= ", fk_target";
  3231. $sql .= ", targettype";
  3232. $sql .= ") VALUES (";
  3233. $sql .= $origin_id;
  3234. $sql .= ", '" . $this->db->escape($origin) . "'";
  3235. $sql .= ", " . $this->id;
  3236. $sql .= ", '" . $this->db->escape($this->element) . "'";
  3237. $sql .= ")";
  3238. dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
  3239. if ($this->db->query($sql)) {
  3240. if (!$notrigger) {
  3241. // Call trigger
  3242. $this->context['link_origin'] = $origin;
  3243. $this->context['link_origin_id'] = $origin_id;
  3244. $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
  3245. if ($result < 0) {
  3246. $error++;
  3247. }
  3248. // End call triggers
  3249. }
  3250. } else {
  3251. $this->error = $this->db->lasterror();
  3252. $error++;
  3253. }
  3254. if (!$error) {
  3255. $this->db->commit();
  3256. return 1;
  3257. } else {
  3258. $this->db->rollback();
  3259. return 0;
  3260. }
  3261. }
  3262. /**
  3263. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  3264. * this->linkedObjectsIds array +
  3265. * this->linkedObjects array if $loadalsoobjects = 1
  3266. * Possible usage for parameters:
  3267. * - all parameters empty -> we look all link to current object (current object can be source or target)
  3268. * - source id+type -> will get target list linked to source
  3269. * - target id+type -> will get source list linked to target
  3270. * - source id+type + target type -> will get target list of the type
  3271. * - target id+type + target source -> will get source list of the type
  3272. *
  3273. * @param int $sourceid Object source id (if not defined, id of object)
  3274. * @param string $sourcetype Object source type (if not defined, element name of object)
  3275. * @param int $targetid Object target id (if not defined, id of object)
  3276. * @param string $targettype Object target type (if not defined, elemennt name of object)
  3277. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  3278. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  3279. * @param string $orderby SQL 'ORDER BY' clause
  3280. * @param int $loadalsoobjects Load also array this->linkedObjects (Use 0 to increase performances)
  3281. * @return int <0 if KO, >0 if OK
  3282. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  3283. */
  3284. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  3285. {
  3286. global $conf;
  3287. $this->linkedObjectsIds = array();
  3288. $this->linkedObjects = array();
  3289. $justsource = false;
  3290. $justtarget = false;
  3291. $withtargettype = false;
  3292. $withsourcetype = false;
  3293. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
  3294. $justsource = true; // the source (id and type) is a search criteria
  3295. if (!empty($targettype)) {
  3296. $withtargettype = true;
  3297. }
  3298. }
  3299. if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
  3300. $justtarget = true; // the target (id and type) is a search criteria
  3301. if (!empty($sourcetype)) {
  3302. $withsourcetype = true;
  3303. }
  3304. }
  3305. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3306. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3307. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3308. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3309. /*if (empty($sourceid) && empty($targetid))
  3310. {
  3311. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  3312. return -1;
  3313. }*/
  3314. // Links between objects are stored in table element_element
  3315. $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype';
  3316. $sql .= ' FROM '.MAIN_DB_PREFIX.'element_element';
  3317. $sql .= " WHERE ";
  3318. if ($justsource || $justtarget) {
  3319. if ($justsource) {
  3320. $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3321. if ($withtargettype) {
  3322. $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
  3323. }
  3324. } elseif ($justtarget) {
  3325. $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
  3326. if ($withsourcetype) {
  3327. $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3328. }
  3329. }
  3330. } else {
  3331. $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
  3332. $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
  3333. }
  3334. $sql .= ' ORDER BY '.$orderby;
  3335. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  3336. $resql = $this->db->query($sql);
  3337. if ($resql) {
  3338. $num = $this->db->num_rows($resql);
  3339. $i = 0;
  3340. while ($i < $num) {
  3341. $obj = $this->db->fetch_object($resql);
  3342. if ($justsource || $justtarget) {
  3343. if ($justsource) {
  3344. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3345. } elseif ($justtarget) {
  3346. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3347. }
  3348. } else {
  3349. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
  3350. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3351. }
  3352. if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
  3353. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3354. }
  3355. }
  3356. $i++;
  3357. }
  3358. if (!empty($this->linkedObjectsIds)) {
  3359. $tmparray = $this->linkedObjectsIds;
  3360. foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  3361. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  3362. $module = $element = $subelement = $objecttype;
  3363. $regs = array();
  3364. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  3365. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  3366. $module = $element = $regs[1];
  3367. $subelement = $regs[2];
  3368. }
  3369. $classpath = $element.'/class';
  3370. // To work with non standard classpath or module name
  3371. if ($objecttype == 'facture') {
  3372. $classpath = 'compta/facture/class';
  3373. } elseif ($objecttype == 'facturerec') {
  3374. $classpath = 'compta/facture/class';
  3375. $module = 'facture';
  3376. } elseif ($objecttype == 'propal') {
  3377. $classpath = 'comm/propal/class';
  3378. } elseif ($objecttype == 'supplier_proposal') {
  3379. $classpath = 'supplier_proposal/class';
  3380. } elseif ($objecttype == 'shipping') {
  3381. $classpath = 'expedition/class';
  3382. $subelement = 'expedition';
  3383. $module = 'expedition_bon';
  3384. } elseif ($objecttype == 'delivery') {
  3385. $classpath = 'delivery/class';
  3386. $subelement = 'delivery';
  3387. $module = 'delivery_note';
  3388. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  3389. $classpath = 'fourn/class';
  3390. $module = 'fournisseur';
  3391. } elseif ($objecttype == 'fichinter') {
  3392. $classpath = 'fichinter/class';
  3393. $subelement = 'fichinter';
  3394. $module = 'ficheinter';
  3395. } elseif ($objecttype == 'subscription') {
  3396. $classpath = 'adherents/class';
  3397. $module = 'adherent';
  3398. } elseif ($objecttype == 'contact') {
  3399. $module = 'societe';
  3400. }
  3401. // Set classfile
  3402. $classfile = strtolower($subelement);
  3403. $classname = ucfirst($subelement);
  3404. if ($objecttype == 'order') {
  3405. $classfile = 'commande';
  3406. $classname = 'Commande';
  3407. } elseif ($objecttype == 'invoice_supplier') {
  3408. $classfile = 'fournisseur.facture';
  3409. $classname = 'FactureFournisseur';
  3410. } elseif ($objecttype == 'order_supplier') {
  3411. $classfile = 'fournisseur.commande';
  3412. $classname = 'CommandeFournisseur';
  3413. } elseif ($objecttype == 'supplier_proposal') {
  3414. $classfile = 'supplier_proposal';
  3415. $classname = 'SupplierProposal';
  3416. } elseif ($objecttype == 'facturerec') {
  3417. $classfile = 'facture-rec';
  3418. $classname = 'FactureRec';
  3419. } elseif ($objecttype == 'subscription') {
  3420. $classfile = 'subscription';
  3421. $classname = 'Subscription';
  3422. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  3423. $classpath = 'projet/class';
  3424. $classfile = 'project';
  3425. $classname = 'Project';
  3426. } elseif ($objecttype == 'conferenceorboothattendee') {
  3427. $classpath = 'eventorganization/class';
  3428. $classfile = 'conferenceorboothattendee';
  3429. $classname = 'ConferenceOrBoothAttendee';
  3430. $module = 'eventorganization';
  3431. }
  3432. // Here $module, $classfile and $classname are set
  3433. if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
  3434. if ($loadalsoobjects) {
  3435. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  3436. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  3437. if (class_exists($classname)) {
  3438. foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
  3439. $object = new $classname($this->db);
  3440. $ret = $object->fetch($objectid);
  3441. if ($ret >= 0) {
  3442. $this->linkedObjects[$objecttype][$i] = $object;
  3443. }
  3444. }
  3445. }
  3446. }
  3447. } else {
  3448. unset($this->linkedObjectsIds[$objecttype]);
  3449. }
  3450. }
  3451. }
  3452. return 1;
  3453. } else {
  3454. dol_print_error($this->db);
  3455. return -1;
  3456. }
  3457. }
  3458. /**
  3459. * Update object linked of a current object
  3460. *
  3461. * @param int $sourceid Object source id
  3462. * @param string $sourcetype Object source type
  3463. * @param int $targetid Object target id
  3464. * @param string $targettype Object target type
  3465. * @param User $f_user User that create
  3466. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3467. * @return int >0 if OK, <0 if KO
  3468. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3469. */
  3470. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
  3471. {
  3472. global $user;
  3473. $updatesource = false;
  3474. $updatetarget = false;
  3475. $f_user = isset($f_user) ? $f_user : $user;
  3476. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3477. $updatesource = true;
  3478. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3479. $updatetarget = true;
  3480. }
  3481. $this->db->begin();
  3482. $error = 0;
  3483. $sql = "UPDATE " . MAIN_DB_PREFIX . "element_element SET ";
  3484. if ($updatesource) {
  3485. $sql .= "fk_source = " . $sourceid;
  3486. $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3487. $sql .= " WHERE fk_target = " . $this->id;
  3488. $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
  3489. } elseif ($updatetarget) {
  3490. $sql .= "fk_target = " . $targetid;
  3491. $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
  3492. $sql .= " WHERE fk_source = " . $this->id;
  3493. $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3494. }
  3495. dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
  3496. if ($this->db->query($sql)) {
  3497. if (!$notrigger) {
  3498. // Call trigger
  3499. $this->context['link_source_id'] = $sourceid;
  3500. $this->context['link_source_type'] = $sourcetype;
  3501. $this->context['link_target_id'] = $targetid;
  3502. $this->context['link_target_type'] = $targettype;
  3503. $result = $this->call_trigger('OBJECT_LINK_UPDATE', $f_user);
  3504. if ($result < 0) {
  3505. $error++;
  3506. }
  3507. // End call triggers
  3508. }
  3509. } else {
  3510. $this->error = $this->db->lasterror();
  3511. $error++;
  3512. }
  3513. if (!$error) {
  3514. $this->db->commit();
  3515. return 1;
  3516. } else {
  3517. $this->db->rollback();
  3518. return -1;
  3519. }
  3520. }
  3521. /**
  3522. * Delete all links between an object $this
  3523. *
  3524. * @param int $sourceid Object source id
  3525. * @param string $sourcetype Object source type
  3526. * @param int $targetid Object target id
  3527. * @param string $targettype Object target type
  3528. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3529. * @param User $f_user User that create
  3530. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3531. * @return int >0 if OK, <0 if KO
  3532. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3533. */
  3534. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
  3535. {
  3536. global $user;
  3537. $deletesource = false;
  3538. $deletetarget = false;
  3539. $f_user = isset($f_user) ? $f_user : $user;
  3540. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3541. $deletesource = true;
  3542. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3543. $deletetarget = true;
  3544. }
  3545. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3546. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3547. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3548. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3549. $this->db->begin();
  3550. $error = 0;
  3551. if (!$notrigger) {
  3552. // Call trigger
  3553. $this->context['link_id'] = $rowid;
  3554. $this->context['link_source_id'] = $sourceid;
  3555. $this->context['link_source_type'] = $sourcetype;
  3556. $this->context['link_target_id'] = $targetid;
  3557. $this->context['link_target_type'] = $targettype;
  3558. $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
  3559. if ($result < 0) {
  3560. $error++;
  3561. }
  3562. // End call triggers
  3563. }
  3564. if (!$error) {
  3565. $sql = "DELETE FROM " . MAIN_DB_PREFIX . "element_element";
  3566. $sql .= " WHERE";
  3567. if ($rowid > 0) {
  3568. $sql .= " rowid = " . ((int) $rowid);
  3569. } else {
  3570. if ($deletesource) {
  3571. $sql .= " fk_source = " . $sourceid . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3572. $sql .= " AND fk_target = " . $this->id . " AND targettype = '" . $this->db->escape($this->element) . "'";
  3573. } elseif ($deletetarget) {
  3574. $sql .= " fk_target = " . $targetid . " AND targettype = '" . $this->db->escape($targettype) . "'";
  3575. $sql .= " AND fk_source = " . $this->id . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3576. } else {
  3577. $sql .= " (fk_source = " . $this->id . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
  3578. $sql .= " OR";
  3579. $sql .= " (fk_target = " . $this->id . " AND targettype = '" . $this->db->escape($this->element) . "')";
  3580. }
  3581. }
  3582. dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
  3583. if (!$this->db->query($sql)) {
  3584. $this->error = $this->db->lasterror();
  3585. $this->errors[] = $this->error;
  3586. $error++;
  3587. }
  3588. }
  3589. if (!$error) {
  3590. $this->db->commit();
  3591. return 1;
  3592. } else {
  3593. $this->db->rollback();
  3594. return 0;
  3595. }
  3596. }
  3597. /**
  3598. * Function used to get an array with all items linked to an object id in association table
  3599. *
  3600. * @param int $fk_object_where id of object we need to get linked items
  3601. * @param string $field_select name of field we need to get a list
  3602. * @param string $field_where name of field of object we need to get linked items
  3603. * @param string $table_element name of association table
  3604. * @return array Array of record
  3605. */
  3606. public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
  3607. {
  3608. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3609. return -1;
  3610. }
  3611. global $db;
  3612. $sql = 'SELECT '.$field_select.' FROM '.MAIN_DB_PREFIX.$table_element.' WHERE '.$field_where.' = '.((int) $fk_object_where);
  3613. $resql = $db->query($sql);
  3614. $TRes = array();
  3615. if (!empty($resql)) {
  3616. while ($res = $db->fetch_object($resql)) {
  3617. $TRes[] = $res->{$field_select};
  3618. }
  3619. }
  3620. return $TRes;
  3621. }
  3622. /**
  3623. * Function used to remove all items linked to an object id in association table
  3624. *
  3625. * @param int $fk_object_where id of object we need to remove linked items
  3626. * @param string $field_where name of field of object we need to delete linked items
  3627. * @param string $table_element name of association table
  3628. * @return int <0 if KO, 0 if nothing done, >0 if OK and something done
  3629. */
  3630. public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
  3631. {
  3632. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3633. return -1;
  3634. }
  3635. global $db;
  3636. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table_element.' WHERE '.$field_where.' = '.((int) $fk_object_where);
  3637. $resql = $db->query($sql);
  3638. if (empty($resql)) {
  3639. return 0;
  3640. }
  3641. return 1;
  3642. }
  3643. /**
  3644. * Set status of an object
  3645. *
  3646. * @param int $status Status to set
  3647. * @param int $elementId Id of element to force (use this->id by default)
  3648. * @param string $elementType Type of element to force (use this->table_element by default)
  3649. * @param string $trigkey Trigger key to use for trigger
  3650. * @return int <0 if KO, >0 if OK
  3651. */
  3652. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '')
  3653. {
  3654. global $user, $langs, $conf;
  3655. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3656. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3657. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3658. $this->db->begin();
  3659. $fieldstatus = "fk_statut";
  3660. if ($elementTable == 'facture_rec') {
  3661. $fieldstatus = "suspended";
  3662. }
  3663. if ($elementTable == 'mailing') {
  3664. $fieldstatus = "statut";
  3665. }
  3666. if ($elementTable == 'cronjob') {
  3667. $fieldstatus = "status";
  3668. }
  3669. if ($elementTable == 'user') {
  3670. $fieldstatus = "statut";
  3671. }
  3672. if ($elementTable == 'expensereport') {
  3673. $fieldstatus = "fk_statut";
  3674. }
  3675. if ($elementTable == 'commande_fournisseur_dispatch') {
  3676. $fieldstatus = "status";
  3677. }
  3678. if (is_array($this->fields) && array_key_exists('status', $this->fields)) {
  3679. $fieldstatus = 'status';
  3680. }
  3681. $sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable;
  3682. $sql .= " SET ".$fieldstatus." = ".((int) $status);
  3683. // If status = 1 = validated, update also fk_user_valid
  3684. if ($status == 1 && $elementTable == 'expensereport') {
  3685. $sql .= ", fk_user_valid = ".$user->id;
  3686. }
  3687. $sql .= " WHERE rowid=".((int) $elementId);
  3688. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  3689. if ($this->db->query($sql)) {
  3690. $error = 0;
  3691. // Try autoset of trigkey
  3692. if (empty($trigkey)) {
  3693. if ($this->element == 'supplier_proposal' && $status == 2) {
  3694. $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3695. }
  3696. if ($this->element == 'supplier_proposal' && $status == 3) {
  3697. $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3698. }
  3699. if ($this->element == 'supplier_proposal' && $status == 4) {
  3700. $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3701. }
  3702. if ($this->element == 'fichinter' && $status == 3) {
  3703. $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3704. }
  3705. if ($this->element == 'fichinter' && $status == 2) {
  3706. $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3707. }
  3708. if ($this->element == 'fichinter' && $status == 1) {
  3709. $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3710. }
  3711. }
  3712. if ($trigkey) {
  3713. // Call trigger
  3714. $result = $this->call_trigger($trigkey, $user);
  3715. if ($result < 0) {
  3716. $error++;
  3717. }
  3718. // End call triggers
  3719. }
  3720. if (!$error) {
  3721. $this->db->commit();
  3722. if (empty($savElementId)) { // If the element we update was $this (so $elementId is null)
  3723. $this->statut = $status;
  3724. $this->status = $status;
  3725. }
  3726. return 1;
  3727. } else {
  3728. $this->db->rollback();
  3729. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  3730. return -1;
  3731. }
  3732. } else {
  3733. $this->error = $this->db->lasterror();
  3734. $this->db->rollback();
  3735. return -1;
  3736. }
  3737. }
  3738. /**
  3739. * Load type of canvas of an object if it exists
  3740. *
  3741. * @param int $id Record id
  3742. * @param string $ref Record ref
  3743. * @return int <0 if KO, 0 if nothing done, >0 if OK
  3744. */
  3745. public function getCanvas($id = 0, $ref = '')
  3746. {
  3747. global $conf;
  3748. if (empty($id) && empty($ref)) {
  3749. return 0;
  3750. }
  3751. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
  3752. return 0; // To increase speed. Not enabled by default.
  3753. }
  3754. // Clean parameters
  3755. $ref = trim($ref);
  3756. $sql = "SELECT rowid, canvas";
  3757. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
  3758. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  3759. if (!empty($id)) {
  3760. $sql .= " AND rowid = ".((int) $id);
  3761. }
  3762. if (!empty($ref)) {
  3763. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  3764. }
  3765. $resql = $this->db->query($sql);
  3766. if ($resql) {
  3767. $obj = $this->db->fetch_object($resql);
  3768. if ($obj) {
  3769. $this->canvas = $obj->canvas;
  3770. return 1;
  3771. } else {
  3772. return 0;
  3773. }
  3774. } else {
  3775. dol_print_error($this->db);
  3776. return -1;
  3777. }
  3778. }
  3779. /**
  3780. * Get special code of a line
  3781. *
  3782. * @param int $lineid Id of line
  3783. * @return int Special code
  3784. */
  3785. public function getSpecialCode($lineid)
  3786. {
  3787. $sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  3788. $sql .= ' WHERE rowid = '.((int) $lineid);
  3789. $resql = $this->db->query($sql);
  3790. if ($resql) {
  3791. $row = $this->db->fetch_row($resql);
  3792. return $row[0];
  3793. }
  3794. }
  3795. /**
  3796. * Function to check if an object is used by others.
  3797. * Check is done into this->childtables. There is no check into llx_element_element.
  3798. *
  3799. * @param int $id Force id of object
  3800. * @return int <0 if KO, 0 if not used, >0 if already used
  3801. */
  3802. public function isObjectUsed($id = 0)
  3803. {
  3804. global $langs;
  3805. if (empty($id)) {
  3806. $id = $this->id;
  3807. }
  3808. // Check parameters
  3809. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
  3810. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  3811. return -1;
  3812. }
  3813. $arraytoscan = $this->childtables;
  3814. // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
  3815. $tmparray = array_keys($this->childtables);
  3816. if (is_numeric($tmparray[0])) {
  3817. $arraytoscan = array_flip($this->childtables);
  3818. }
  3819. // Test if child exists
  3820. $haschild = 0;
  3821. foreach ($arraytoscan as $table => $elementname) {
  3822. //print $id.'-'.$table.'-'.$elementname.'<br>';
  3823. // Check if third party can be deleted
  3824. $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table;
  3825. $sql .= " WHERE ".$this->fk_element." = ".((int) $id);
  3826. $resql = $this->db->query($sql);
  3827. if ($resql) {
  3828. $obj = $this->db->fetch_object($resql);
  3829. if ($obj->nb > 0) {
  3830. $langs->load("errors");
  3831. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  3832. $haschild += $obj->nb;
  3833. if (is_numeric($elementname)) { // old usage
  3834. $this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table);
  3835. } else // new usage: $elementname=Translation key
  3836. {
  3837. $this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname));
  3838. }
  3839. break; // We found at least one, we stop here
  3840. }
  3841. } else {
  3842. $this->errors[] = $this->db->lasterror();
  3843. return -1;
  3844. }
  3845. }
  3846. if ($haschild > 0) {
  3847. $this->errors[] = "ErrorRecordHasChildren";
  3848. return $haschild;
  3849. } else {
  3850. return 0;
  3851. }
  3852. }
  3853. /**
  3854. * Function to say how many lines object contains
  3855. *
  3856. * @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
  3857. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  3858. */
  3859. public function hasProductsOrServices($predefined = -1)
  3860. {
  3861. $nb = 0;
  3862. foreach ($this->lines as $key => $val) {
  3863. $qualified = 0;
  3864. if ($predefined == -1) {
  3865. $qualified = 1;
  3866. }
  3867. if ($predefined == 1 && $val->fk_product > 0) {
  3868. $qualified = 1;
  3869. }
  3870. if ($predefined == 0 && $val->fk_product <= 0) {
  3871. $qualified = 1;
  3872. }
  3873. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
  3874. $qualified = 1;
  3875. }
  3876. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
  3877. $qualified = 1;
  3878. }
  3879. if ($qualified) {
  3880. $nb++;
  3881. }
  3882. }
  3883. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  3884. return $nb;
  3885. }
  3886. /**
  3887. * Function that returns the total amount HT of discounts applied for all lines.
  3888. *
  3889. * @return float|string Total amout of discount
  3890. */
  3891. public function getTotalDiscount()
  3892. {
  3893. if (!empty($this->table_element_line) ) {
  3894. $total_discount = 0.00;
  3895. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  3896. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  3897. $sql .= " WHERE ".$this->fk_element." = ".$this->id;
  3898. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  3899. $resql = $this->db->query($sql);
  3900. if ($resql) {
  3901. $num = $this->db->num_rows($resql);
  3902. $i = 0;
  3903. while ($i < $num) {
  3904. $obj = $this->db->fetch_object($resql);
  3905. $pu_ht = $obj->pu_ht;
  3906. $qty = $obj->qty;
  3907. $total_ht = $obj->total_ht;
  3908. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  3909. $total_discount += $total_discount_line;
  3910. $i++;
  3911. }
  3912. }
  3913. //print $total_discount; exit;
  3914. return price2num($total_discount);
  3915. }
  3916. return null;
  3917. }
  3918. /**
  3919. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  3920. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  3921. *
  3922. * @return array array('weight'=>...,'volume'=>...)
  3923. */
  3924. public function getTotalWeightVolume()
  3925. {
  3926. $totalWeight = 0;
  3927. $totalVolume = 0;
  3928. // defined for shipment only
  3929. $totalOrdered = '';
  3930. // defined for shipment only
  3931. $totalToShip = '';
  3932. foreach ($this->lines as $line) {
  3933. if (isset($line->qty_asked)) {
  3934. if (empty($totalOrdered)) {
  3935. $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  3936. }
  3937. $totalOrdered += $line->qty_asked; // defined for shipment only
  3938. }
  3939. if (isset($line->qty_shipped)) {
  3940. if (empty($totalToShip)) {
  3941. $totalToShip = 0; // Avoid warning because $totalToShip is ''
  3942. }
  3943. $totalToShip += $line->qty_shipped; // defined for shipment only
  3944. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
  3945. if (empty($totalToShip)) {
  3946. $totalToShip = 0;
  3947. }
  3948. $totalToShip += $line->qty; // defined for reception only
  3949. }
  3950. // Define qty, weight, volume, weight_units, volume_units
  3951. if ($this->element == 'shipping') {
  3952. // for shipments
  3953. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  3954. } else {
  3955. $qty = $line->qty ? $line->qty : 0;
  3956. }
  3957. $weight = $line->weight ? $line->weight : 0;
  3958. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  3959. $volume = $line->volume ? $line->volume : 0;
  3960. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  3961. $weight_units = $line->weight_units;
  3962. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  3963. $volume_units = $line->volume_units;
  3964. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  3965. $weightUnit = 0;
  3966. $volumeUnit = 0;
  3967. if (!empty($weight_units)) {
  3968. $weightUnit = $weight_units;
  3969. }
  3970. if (!empty($volume_units)) {
  3971. $volumeUnit = $volume_units;
  3972. }
  3973. if (empty($totalWeight)) {
  3974. $totalWeight = 0; // Avoid warning because $totalWeight is ''
  3975. }
  3976. if (empty($totalVolume)) {
  3977. $totalVolume = 0; // Avoid warning because $totalVolume is ''
  3978. }
  3979. //var_dump($line->volume_units);
  3980. if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  3981. $trueWeightUnit = pow(10, $weightUnit);
  3982. $totalWeight += $weight * $qty * $trueWeightUnit;
  3983. } else {
  3984. if ($weight_units == 99) {
  3985. // conversion 1 Pound = 0.45359237 KG
  3986. $trueWeightUnit = 0.45359237;
  3987. $totalWeight += $weight * $qty * $trueWeightUnit;
  3988. } elseif ($weight_units == 98) {
  3989. // conversion 1 Ounce = 0.0283495 KG
  3990. $trueWeightUnit = 0.0283495;
  3991. $totalWeight += $weight * $qty * $trueWeightUnit;
  3992. } else {
  3993. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  3994. }
  3995. }
  3996. if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  3997. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  3998. $trueVolumeUnit = pow(10, $volumeUnit);
  3999. //print $line->volume;
  4000. $totalVolume += $volume * $qty * $trueVolumeUnit;
  4001. } else {
  4002. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  4003. }
  4004. }
  4005. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  4006. }
  4007. /**
  4008. * Set extra parameters
  4009. *
  4010. * @return int <0 if KO, >0 if OK
  4011. */
  4012. public function setExtraParameters()
  4013. {
  4014. $this->db->begin();
  4015. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  4016. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  4017. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  4018. $sql .= " WHERE rowid = ".$this->id;
  4019. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  4020. $resql = $this->db->query($sql);
  4021. if (!$resql) {
  4022. $this->error = $this->db->lasterror();
  4023. $this->db->rollback();
  4024. return -1;
  4025. } else {
  4026. $this->db->commit();
  4027. return 1;
  4028. }
  4029. }
  4030. // --------------------
  4031. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  4032. // --------------------
  4033. /* This is to show add lines */
  4034. /**
  4035. * Show add free and predefined products/services form
  4036. *
  4037. * @param int $dateSelector 1=Show also date range input fields
  4038. * @param Societe $seller Object thirdparty who sell
  4039. * @param Societe $buyer Object thirdparty who buy
  4040. * @param string $defaulttpldir Directory where to find the template
  4041. * @return void
  4042. */
  4043. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  4044. {
  4045. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  4046. global $form;
  4047. // Line extrafield
  4048. if (!is_object($extrafields)) {
  4049. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4050. $extrafields = new ExtraFields($this->db);
  4051. }
  4052. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4053. // Output template part (modules that overwrite templates must declare this into descriptor)
  4054. // Use global variables + $dateSelector + $seller and $buyer
  4055. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  4056. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4057. foreach ($dirtpls as $module => $reldir) {
  4058. if (!empty($module)) {
  4059. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  4060. } else {
  4061. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  4062. }
  4063. if (empty($conf->file->strict_mode)) {
  4064. $res = @include $tpl;
  4065. } else {
  4066. $res = include $tpl; // for debug
  4067. }
  4068. if ($res) {
  4069. break;
  4070. }
  4071. }
  4072. }
  4073. /* This is to show array of line of details */
  4074. /**
  4075. * Return HTML table for object lines
  4076. * TODO Move this into an output class file (htmlline.class.php)
  4077. * If lines are into a template, title must also be into a template
  4078. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4079. *
  4080. * @param string $action Action code
  4081. * @param string $seller Object of seller third party
  4082. * @param string $buyer Object of buyer third party
  4083. * @param int $selected Object line selected
  4084. * @param int $dateSelector 1=Show also date range input fields
  4085. * @param string $defaulttpldir Directory where to find the template
  4086. * @return void
  4087. */
  4088. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  4089. {
  4090. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  4091. // TODO We should not use global var for this
  4092. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  4093. // Define usemargins
  4094. $usemargins = 0;
  4095. if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
  4096. $usemargins = 1;
  4097. }
  4098. $num = count($this->lines);
  4099. // Line extrafield
  4100. if (!is_object($extrafields)) {
  4101. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4102. $extrafields = new ExtraFields($this->db);
  4103. }
  4104. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4105. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  4106. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4107. if (empty($reshook)) {
  4108. // Output template part (modules that overwrite templates must declare this into descriptor)
  4109. // Use global variables + $dateSelector + $seller and $buyer
  4110. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  4111. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4112. foreach ($dirtpls as $module => $reldir) {
  4113. if (!empty($module)) {
  4114. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  4115. } else {
  4116. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  4117. }
  4118. if (empty($conf->file->strict_mode)) {
  4119. $res = @include $tpl;
  4120. } else {
  4121. $res = include $tpl; // for debug
  4122. }
  4123. if ($res) {
  4124. break;
  4125. }
  4126. }
  4127. }
  4128. $i = 0;
  4129. print "<!-- begin printObjectLines() --><tbody>\n";
  4130. foreach ($this->lines as $line) {
  4131. //Line extrafield
  4132. $line->fetch_optionals();
  4133. //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  4134. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4135. if (empty($line->fk_parent_line)) {
  4136. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  4137. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4138. } else {
  4139. $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);
  4140. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4141. }
  4142. }
  4143. if (empty($reshook)) {
  4144. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  4145. }
  4146. $i++;
  4147. }
  4148. print "</tbody><!-- end printObjectLines() -->\n";
  4149. }
  4150. /**
  4151. * Return HTML content of a detail line
  4152. * TODO Move this into an output class file (htmlline.class.php)
  4153. *
  4154. * @param string $action GET/POST action
  4155. * @param CommonObjectLine $line Selected object line to output
  4156. * @param string $var Is it a an odd line (true)
  4157. * @param int $num Number of line (0)
  4158. * @param int $i I
  4159. * @param int $dateSelector 1=Show also date range input fields
  4160. * @param string $seller Object of seller third party
  4161. * @param string $buyer Object of buyer third party
  4162. * @param int $selected Object line selected
  4163. * @param Extrafields $extrafields Object of extrafields
  4164. * @param string $defaulttpldir Directory where to find the template (deprecated)
  4165. * @return void
  4166. */
  4167. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  4168. {
  4169. global $conf, $langs, $user, $object, $hookmanager;
  4170. global $form;
  4171. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  4172. $object_rights = $this->getRights();
  4173. $element = $this->element;
  4174. $text = '';
  4175. $description = '';
  4176. // Line in view mode
  4177. if ($action != 'editline' || $selected != $line->id) {
  4178. // Product
  4179. if ($line->fk_product > 0) {
  4180. $product_static = new Product($this->db);
  4181. $product_static->fetch($line->fk_product);
  4182. $product_static->ref = $line->ref; //can change ref in hook
  4183. $product_static->label = $line->label; //can change label in hook
  4184. $text = $product_static->getNomUrl(1);
  4185. // Define output language and label
  4186. if (!empty($conf->global->MAIN_MULTILANGS)) {
  4187. if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
  4188. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  4189. return;
  4190. }
  4191. $prod = new Product($this->db);
  4192. $prod->fetch($line->fk_product);
  4193. $outputlangs = $langs;
  4194. $newlang = '';
  4195. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  4196. $newlang = GETPOST('lang_id', 'aZ09');
  4197. }
  4198. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
  4199. $newlang = $this->thirdparty->default_lang; // To use language of customer
  4200. }
  4201. if (!empty($newlang)) {
  4202. $outputlangs = new Translate("", $conf);
  4203. $outputlangs->setDefaultLang($newlang);
  4204. }
  4205. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  4206. } else {
  4207. $label = $line->product_label;
  4208. }
  4209. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  4210. $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.
  4211. }
  4212. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4213. // Output template part (modules that overwrite templates must declare this into descriptor)
  4214. // Use global variables + $dateSelector + $seller and $buyer
  4215. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4216. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4217. foreach ($dirtpls as $module => $reldir) {
  4218. if (!empty($module)) {
  4219. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  4220. } else {
  4221. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  4222. }
  4223. if (empty($conf->file->strict_mode)) {
  4224. $res = @include $tpl;
  4225. } else {
  4226. $res = include $tpl; // for debug
  4227. }
  4228. if ($res) {
  4229. break;
  4230. }
  4231. }
  4232. }
  4233. // Line in update mode
  4234. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
  4235. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  4236. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4237. // Output template part (modules that overwrite templates must declare this into descriptor)
  4238. // Use global variables + $dateSelector + $seller and $buyer
  4239. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4240. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4241. foreach ($dirtpls as $module => $reldir) {
  4242. if (!empty($module)) {
  4243. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  4244. } else {
  4245. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  4246. }
  4247. if (empty($conf->file->strict_mode)) {
  4248. $res = @include $tpl;
  4249. } else {
  4250. $res = include $tpl; // for debug
  4251. }
  4252. if ($res) {
  4253. break;
  4254. }
  4255. }
  4256. }
  4257. }
  4258. /* This is to show array of line of details of source object */
  4259. /**
  4260. * Return HTML table table of source object lines
  4261. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4262. * If lines are into a template, title must also be into a template
  4263. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  4264. *
  4265. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  4266. * @param array $selectedLines Array of lines id for selected lines
  4267. * @return void
  4268. */
  4269. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  4270. {
  4271. global $langs, $hookmanager, $conf, $form;
  4272. print '<tr class="liste_titre">';
  4273. print '<td>'.$langs->trans('Ref').'</td>';
  4274. print '<td>'.$langs->trans('Description').'</td>';
  4275. print '<td class="right">'.$langs->trans('VATRate').'</td>';
  4276. print '<td class="right">'.$langs->trans('PriceUHT').'</td>';
  4277. if (!empty($conf->multicurrency->enabled)) {
  4278. print '<td class="right">'.$langs->trans('PriceUHTCurrency').'</td>';
  4279. }
  4280. print '<td class="right">'.$langs->trans('Qty').'</td>';
  4281. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4282. print '<td class="left">'.$langs->trans('Unit').'</td>';
  4283. }
  4284. print '<td class="right">'.$langs->trans('ReductionShort').'</td>';
  4285. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  4286. print '</tr>';
  4287. $i = 0;
  4288. if (!empty($this->lines)) {
  4289. foreach ($this->lines as $line) {
  4290. if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
  4291. if (empty($line->fk_parent_line)) {
  4292. $parameters = array('line'=>$line, 'i'=>$i);
  4293. $action = '';
  4294. $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4295. }
  4296. } else {
  4297. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  4298. }
  4299. $i++;
  4300. }
  4301. }
  4302. }
  4303. /**
  4304. * Return HTML with a line of table array of source object lines
  4305. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4306. * If lines are into a template, title must also be into a template
  4307. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4308. *
  4309. * @param CommonObjectLine $line Line
  4310. * @param string $var Var
  4311. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  4312. * @param string $defaulttpldir Directory where to find the template
  4313. * @param array $selectedLines Array of lines id for selected lines
  4314. * @return void
  4315. */
  4316. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  4317. {
  4318. global $langs, $conf;
  4319. //var_dump($line);
  4320. if (!empty($line->date_start)) {
  4321. $date_start = $line->date_start;
  4322. } else {
  4323. $date_start = $line->date_debut_prevue;
  4324. if ($line->date_debut_reel) {
  4325. $date_start = $line->date_debut_reel;
  4326. }
  4327. }
  4328. if (!empty($line->date_end)) {
  4329. $date_end = $line->date_end;
  4330. } else {
  4331. $date_end = $line->date_fin_prevue;
  4332. if ($line->date_fin_reel) {
  4333. $date_end = $line->date_fin_reel;
  4334. }
  4335. }
  4336. $this->tpl['id'] = $line->id;
  4337. $this->tpl['label'] = '';
  4338. if (!empty($line->fk_parent_line)) {
  4339. $this->tpl['label'] .= img_picto('', 'rightarrow');
  4340. }
  4341. if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
  4342. $discount = new DiscountAbsolute($this->db);
  4343. $discount->fk_soc = $this->socid;
  4344. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  4345. } elseif (!empty($line->fk_product)) {
  4346. $productstatic = new Product($this->db);
  4347. $productstatic->id = $line->fk_product;
  4348. $productstatic->ref = $line->ref;
  4349. $productstatic->type = $line->fk_product_type;
  4350. if (empty($productstatic->ref)) {
  4351. $line->fetch_product();
  4352. $productstatic = $line->product;
  4353. }
  4354. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  4355. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  4356. // Dates
  4357. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4358. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4359. }
  4360. } else {
  4361. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  4362. if (!empty($line->desc)) {
  4363. $this->tpl['label'] .= $line->desc;
  4364. } else {
  4365. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  4366. }
  4367. // Dates
  4368. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4369. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4370. }
  4371. }
  4372. if (!empty($line->desc)) {
  4373. if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
  4374. $discount = new DiscountAbsolute($this->db);
  4375. $discount->fetch($line->fk_remise_except);
  4376. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  4377. } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
  4378. $discount = new DiscountAbsolute($this->db);
  4379. $discount->fetch($line->fk_remise_except);
  4380. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  4381. } elseif ($line->desc == '(EXCESS RECEIVED)') {
  4382. $discount = new DiscountAbsolute($this->db);
  4383. $discount->fetch($line->fk_remise_except);
  4384. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  4385. } elseif ($line->desc == '(EXCESS PAID)') {
  4386. $discount = new DiscountAbsolute($this->db);
  4387. $discount->fetch($line->fk_remise_except);
  4388. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  4389. } else {
  4390. $this->tpl['description'] = dol_trunc($line->desc, 60);
  4391. }
  4392. } else {
  4393. $this->tpl['description'] = '&nbsp;';
  4394. }
  4395. // VAT Rate
  4396. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  4397. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  4398. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
  4399. $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  4400. }
  4401. $this->tpl['price'] = price($line->subprice);
  4402. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  4403. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  4404. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4405. $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  4406. }
  4407. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  4408. // Is the line strike or not
  4409. $this->tpl['strike'] = 0;
  4410. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
  4411. $this->tpl['strike'] = 1;
  4412. }
  4413. // Output template part (modules that overwrite templates must declare this into descriptor)
  4414. // Use global variables + $dateSelector + $seller and $buyer
  4415. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4416. foreach ($dirtpls as $module => $reldir) {
  4417. if (!empty($module)) {
  4418. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  4419. } else {
  4420. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  4421. }
  4422. if (empty($conf->file->strict_mode)) {
  4423. $res = @include $tpl;
  4424. } else {
  4425. $res = include $tpl; // for debug
  4426. }
  4427. if ($res) {
  4428. break;
  4429. }
  4430. }
  4431. }
  4432. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4433. /**
  4434. * Add resources to the current object : add entry into llx_element_resources
  4435. * Need $this->element & $this->id
  4436. *
  4437. * @param int $resource_id Resource id
  4438. * @param string $resource_type 'resource'
  4439. * @param int $busy Busy or not
  4440. * @param int $mandatory Mandatory or not
  4441. * @return int <=0 if KO, >0 if OK
  4442. */
  4443. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  4444. {
  4445. // phpcs:enable
  4446. $this->db->begin();
  4447. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources (";
  4448. $sql .= "resource_id";
  4449. $sql .= ", resource_type";
  4450. $sql .= ", element_id";
  4451. $sql .= ", element_type";
  4452. $sql .= ", busy";
  4453. $sql .= ", mandatory";
  4454. $sql .= ") VALUES (";
  4455. $sql .= $resource_id;
  4456. $sql .= ", '".$this->db->escape($resource_type)."'";
  4457. $sql .= ", '".$this->db->escape($this->id)."'";
  4458. $sql .= ", '".$this->db->escape($this->element)."'";
  4459. $sql .= ", '".$this->db->escape($busy)."'";
  4460. $sql .= ", '".$this->db->escape($mandatory)."'";
  4461. $sql .= ")";
  4462. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  4463. if ($this->db->query($sql)) {
  4464. $this->db->commit();
  4465. return 1;
  4466. } else {
  4467. $this->error = $this->db->lasterror();
  4468. $this->db->rollback();
  4469. return 0;
  4470. }
  4471. }
  4472. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4473. /**
  4474. * Delete a link to resource line
  4475. *
  4476. * @param int $rowid Id of resource line to delete
  4477. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  4478. * @param int $notrigger Disable all triggers
  4479. * @return int >0 if OK, <0 if KO
  4480. */
  4481. public function delete_resource($rowid, $element, $notrigger = 0)
  4482. {
  4483. // phpcs:enable
  4484. global $user;
  4485. $this->db->begin();
  4486. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
  4487. $sql .= " WHERE rowid = ".((int) $rowid);
  4488. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  4489. $resql = $this->db->query($sql);
  4490. if (!$resql) {
  4491. $this->error = $this->db->lasterror();
  4492. $this->db->rollback();
  4493. return -1;
  4494. } else {
  4495. if (!$notrigger) {
  4496. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  4497. if ($result < 0) {
  4498. $this->db->rollback();
  4499. return -1;
  4500. }
  4501. }
  4502. $this->db->commit();
  4503. return 1;
  4504. }
  4505. }
  4506. /**
  4507. * Overwrite magic function to solve problem of cloning object that are kept as references
  4508. *
  4509. * @return void
  4510. */
  4511. public function __clone()
  4512. {
  4513. // Force a copy of this->lines, otherwise it will point to same object.
  4514. if (isset($this->lines) && is_array($this->lines)) {
  4515. $nboflines = count($this->lines);
  4516. for ($i = 0; $i < $nboflines; $i++) {
  4517. $this->lines[$i] = clone $this->lines[$i];
  4518. }
  4519. }
  4520. }
  4521. /**
  4522. * Common function for all objects extending CommonObject for generating documents
  4523. *
  4524. * @param string $modelspath Relative folder where generators are placed
  4525. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4526. * @param Translate $outputlangs Output language to use
  4527. * @param int $hidedetails 1 to hide details. 0 by default
  4528. * @param int $hidedesc 1 to hide product description. 0 by default
  4529. * @param int $hideref 1 to hide product reference. 0 by default
  4530. * @param null|array $moreparams Array to provide more information
  4531. * @return int >0 if OK, <0 if KO
  4532. * @see addFileIntoDatabaseIndex()
  4533. */
  4534. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4535. {
  4536. global $conf, $langs, $user, $hookmanager, $action;
  4537. $srctemplatepath = '';
  4538. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  4539. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4540. if (empty($reshook)) {
  4541. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4542. if (empty($modele)) {
  4543. $this->error = 'BadValueForParameterModele';
  4544. return -1;
  4545. }
  4546. // Increase limit for PDF build
  4547. $err = error_reporting();
  4548. error_reporting(0);
  4549. @set_time_limit(120);
  4550. error_reporting($err);
  4551. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4552. $tmp = explode(':', $modele, 2);
  4553. if (!empty($tmp[1])) {
  4554. $modele = $tmp[0];
  4555. $srctemplatepath = $tmp[1];
  4556. }
  4557. // Search template files
  4558. $file = '';
  4559. $classname = '';
  4560. $filefound = '';
  4561. $dirmodels = array('/');
  4562. if (is_array($conf->modules_parts['models'])) {
  4563. $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4564. }
  4565. foreach ($dirmodels as $reldir) {
  4566. foreach (array('doc', 'pdf') as $prefix) {
  4567. if (in_array(get_class($this), array('Adherent'))) {
  4568. // Member module use prefix_modele.class.php
  4569. $file = $prefix."_".$modele.".class.php";
  4570. } else {
  4571. // Other module use prefix_modele.modules.php
  4572. $file = $prefix."_".$modele.".modules.php";
  4573. }
  4574. // On verifie l'emplacement du modele
  4575. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  4576. if (file_exists($file)) {
  4577. $filefound = $file;
  4578. $classname = $prefix.'_'.$modele;
  4579. break;
  4580. }
  4581. }
  4582. if ($filefound) {
  4583. break;
  4584. }
  4585. }
  4586. // If generator was found
  4587. if ($filefound) {
  4588. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4589. require_once $file;
  4590. $obj = new $classname($this->db);
  4591. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4592. if ($obj->type == 'odt' && empty($srctemplatepath)) {
  4593. $varfortemplatedir = $obj->scandir;
  4594. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
  4595. $dirtoscan = $conf->global->$varfortemplatedir;
  4596. $listoffiles = array();
  4597. // Now we add first model found in directories scanned
  4598. $listofdir = explode(',', $dirtoscan);
  4599. foreach ($listofdir as $key => $tmpdir) {
  4600. $tmpdir = trim($tmpdir);
  4601. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4602. if (!$tmpdir) {
  4603. unset($listofdir[$key]);
  4604. continue;
  4605. }
  4606. if (is_dir($tmpdir)) {
  4607. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4608. if (count($tmpfiles)) {
  4609. $listoffiles = array_merge($listoffiles, $tmpfiles);
  4610. }
  4611. }
  4612. }
  4613. if (count($listoffiles)) {
  4614. foreach ($listoffiles as $record) {
  4615. $srctemplatepath = $record['fullname'];
  4616. break;
  4617. }
  4618. }
  4619. }
  4620. if (empty($srctemplatepath)) {
  4621. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4622. return -1;
  4623. }
  4624. }
  4625. if ($obj->type == 'odt' && !empty($srctemplatepath)) {
  4626. if (!dol_is_file($srctemplatepath)) {
  4627. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  4628. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4629. return -1;
  4630. }
  4631. }
  4632. // We save charset_output to restore it because write_file can change it if needed for
  4633. // output format that does not support UTF8.
  4634. $sav_charset_output = $outputlangs->charset_output;
  4635. if (in_array(get_class($this), array('Adherent'))) {
  4636. $arrayofrecords = array(); // The write_file of templates of adherent class need this var
  4637. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams);
  4638. } else {
  4639. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4640. }
  4641. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4642. if ($resultwritefile > 0) {
  4643. $outputlangs->charset_output = $sav_charset_output;
  4644. // We delete old preview
  4645. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4646. dol_delete_preview($this);
  4647. // Index file in database
  4648. if (!empty($obj->result['fullpath'])) {
  4649. $destfull = $obj->result['fullpath'];
  4650. $upload_dir = dirname($destfull);
  4651. $destfile = basename($destfull);
  4652. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  4653. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  4654. $filename = basename($destfile);
  4655. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4656. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4657. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4658. $ecmfile = new EcmFiles($this->db);
  4659. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  4660. // Set the public "share" key
  4661. $setsharekey = false;
  4662. if ($this->element == 'propal') {
  4663. $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok
  4664. if ($useonlinesignature) {
  4665. $setsharekey = true;
  4666. }
  4667. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4668. $setsharekey = true;
  4669. }
  4670. }
  4671. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  4672. $setsharekey = true;
  4673. }
  4674. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  4675. $setsharekey = true;
  4676. }
  4677. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4678. $setsharekey = true;
  4679. }
  4680. if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4681. $setsharekey = true;
  4682. }
  4683. if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4684. $setsharekey = true;
  4685. }
  4686. if ($setsharekey) {
  4687. if (empty($ecmfile->share)) { // Because object not found or share not set yet
  4688. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  4689. $ecmfile->share = getRandomPassword(true);
  4690. }
  4691. }
  4692. if ($result > 0) {
  4693. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4694. $ecmfile->fullpath_orig = '';
  4695. $ecmfile->gen_or_uploaded = 'generated';
  4696. $ecmfile->description = ''; // indexed content
  4697. $ecmfile->keywords = ''; // keyword content
  4698. $result = $ecmfile->update($user);
  4699. if ($result < 0) {
  4700. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4701. }
  4702. } else {
  4703. $ecmfile->entity = $conf->entity;
  4704. $ecmfile->filepath = $rel_dir;
  4705. $ecmfile->filename = $filename;
  4706. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4707. $ecmfile->fullpath_orig = '';
  4708. $ecmfile->gen_or_uploaded = 'generated';
  4709. $ecmfile->description = ''; // indexed content
  4710. $ecmfile->keywords = ''; // keyword content
  4711. $ecmfile->src_object_type = $this->table_element;
  4712. $ecmfile->src_object_id = $this->id;
  4713. $result = $ecmfile->create($user);
  4714. if ($result < 0) {
  4715. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4716. }
  4717. }
  4718. /*$this->result['fullname']=$destfull;
  4719. $this->result['filepath']=$ecmfile->filepath;
  4720. $this->result['filename']=$ecmfile->filename;*/
  4721. //var_dump($obj->update_main_doc_field);exit;
  4722. // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
  4723. $update_main_doc_field = 0;
  4724. if (!empty($obj->update_main_doc_field)) {
  4725. $update_main_doc_field = 1;
  4726. }
  4727. if ($update_main_doc_field && !empty($this->table_element)) {
  4728. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath.'/'.$ecmfile->filename)."'";
  4729. $sql .= ' WHERE rowid = '.$this->id;
  4730. $resql = $this->db->query($sql);
  4731. if (!$resql) {
  4732. dol_print_error($this->db);
  4733. } else {
  4734. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  4735. }
  4736. }
  4737. }
  4738. } else {
  4739. 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);
  4740. }
  4741. // Success in building document. We build meta file.
  4742. dol_meta_create($this);
  4743. return 1;
  4744. } else {
  4745. $outputlangs->charset_output = $sav_charset_output;
  4746. dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
  4747. return -1;
  4748. }
  4749. } else {
  4750. if (!$filefound) {
  4751. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4752. dol_print_error('', $this->error);
  4753. } else {
  4754. $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
  4755. dol_print_error('', $this->error);
  4756. }
  4757. return -1;
  4758. }
  4759. } else {
  4760. return $reshook;
  4761. }
  4762. }
  4763. /**
  4764. * Build thumb
  4765. * @todo Move this into files.lib.php
  4766. *
  4767. * @param string $file Path file in UTF8 to original file to create thumbs from.
  4768. * @return void
  4769. */
  4770. public function addThumbs($file)
  4771. {
  4772. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  4773. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  4774. $file_osencoded = dol_osencode($file);
  4775. if (file_exists($file_osencoded)) {
  4776. // Create small thumbs for company (Ratio is near 16/9)
  4777. // Used on logon for example
  4778. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  4779. // Create mini thumbs for company (Ratio is near 16/9)
  4780. // Used on menu or for setup page for example
  4781. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  4782. }
  4783. }
  4784. /* Functions common to commonobject and commonobjectline */
  4785. /* For default values */
  4786. /**
  4787. * Return the default value to use for a field when showing the create form of object.
  4788. * Return values in this order:
  4789. * 1) If parameter is available into POST, we return it first.
  4790. * 2) If not but an alternate value was provided as parameter of function, we return it.
  4791. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  4792. * 4) Return value found into database (TODO No yet implemented)
  4793. *
  4794. * @param string $fieldname Name of field
  4795. * @param string $alternatevalue Alternate value to use
  4796. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  4797. **/
  4798. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
  4799. {
  4800. global $conf, $_POST;
  4801. // If param here has been posted, we use this value first.
  4802. if (GETPOSTISSET($fieldname)) {
  4803. return GETPOST($fieldname, 'alphanohtml', 3);
  4804. }
  4805. if (isset($alternatevalue)) {
  4806. return $alternatevalue;
  4807. }
  4808. $newelement = $this->element;
  4809. if ($newelement == 'facture') {
  4810. $newelement = 'invoice';
  4811. }
  4812. if ($newelement == 'commande') {
  4813. $newelement = 'order';
  4814. }
  4815. if (empty($newelement)) {
  4816. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  4817. return '';
  4818. }
  4819. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  4820. //var_dump($keyforfieldname);
  4821. if (isset($conf->global->$keyforfieldname)) {
  4822. return $conf->global->$keyforfieldname;
  4823. }
  4824. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  4825. }
  4826. /* For triggers */
  4827. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4828. /**
  4829. * Call trigger based on this instance.
  4830. * Some context information may also be provided into array property this->context.
  4831. * NB: Error from trigger are stacked in interface->errors
  4832. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  4833. *
  4834. * @param string $triggerName trigger's name to execute
  4835. * @param User $user Object user
  4836. * @return int Result of run_triggers
  4837. */
  4838. public function call_trigger($triggerName, $user)
  4839. {
  4840. // phpcs:enable
  4841. global $langs, $conf;
  4842. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  4843. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4844. $langs = new Translate('', $conf);
  4845. }
  4846. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  4847. $interface = new Interfaces($this->db);
  4848. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  4849. if ($result < 0) {
  4850. if (!empty($this->errors)) {
  4851. $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.
  4852. } else {
  4853. $this->errors = $interface->errors;
  4854. }
  4855. }
  4856. return $result;
  4857. }
  4858. /* Functions for data in other language */
  4859. /**
  4860. * Function to get alternative languages of a data into $this->array_languages
  4861. * This method is NOT called by method fetch of objects but must be called separately.
  4862. *
  4863. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  4864. * @see fetch_optionnals()
  4865. */
  4866. public function fetchValuesForExtraLanguages()
  4867. {
  4868. // To avoid SQL errors. Probably not the better solution though
  4869. if (!$this->element) {
  4870. return 0;
  4871. }
  4872. if (!($this->id > 0)) {
  4873. return 0;
  4874. }
  4875. if (is_array($this->array_languages)) {
  4876. return 1;
  4877. }
  4878. $this->array_languages = array();
  4879. $element = $this->element;
  4880. if ($element == 'categorie') {
  4881. $element = 'categories'; // For compatibility
  4882. }
  4883. // Request to get translation values for object
  4884. $sql = "SELECT rowid, property, lang , value";
  4885. $sql .= " FROM ".MAIN_DB_PREFIX."object_lang";
  4886. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  4887. $sql .= " AND fk_object = ".$this->id;
  4888. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  4889. $resql = $this->db->query($sql);
  4890. if ($resql) {
  4891. $numrows = $this->db->num_rows($resql);
  4892. if ($numrows) {
  4893. $i = 0;
  4894. while ($i < $numrows) {
  4895. $obj = $this->db->fetch_object($resql);
  4896. $key = $obj->property;
  4897. $value = $obj->value;
  4898. $codelang = $obj->lang;
  4899. $type = $this->fields[$key]['type'];
  4900. // we can add this attribute to object
  4901. if (preg_match('/date/', $type)) {
  4902. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  4903. } else {
  4904. $this->array_languages[$key][$codelang] = $value;
  4905. }
  4906. $i++;
  4907. }
  4908. }
  4909. $this->db->free($resql);
  4910. if ($numrows) {
  4911. return $numrows;
  4912. } else {
  4913. return 0;
  4914. }
  4915. } else {
  4916. dol_print_error($this->db);
  4917. return -1;
  4918. }
  4919. }
  4920. /**
  4921. * Fill array_options property of object by extrafields value (using for data sent by forms)
  4922. *
  4923. * @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.
  4924. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  4925. */
  4926. public function setValuesForExtraLanguages($onlykey = '')
  4927. {
  4928. global $_POST, $langs;
  4929. // Get extra fields
  4930. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  4931. $tmparray = explode('-', $postfieldkey);
  4932. if ($tmparray[0] != 'field') {
  4933. continue;
  4934. }
  4935. $element = $tmparray[1];
  4936. $key = $tmparray[2];
  4937. $codelang = $tmparray[3];
  4938. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  4939. if (!empty($onlykey) && $key != $onlykey) {
  4940. continue;
  4941. }
  4942. if ($element != $this->element) {
  4943. continue;
  4944. }
  4945. $key_type = $this->fields[$key]['type'];
  4946. $enabled = 1;
  4947. if (isset($this->fields[$key]['enabled'])) {
  4948. $enabled = dol_eval($this->fields[$key]['enabled'], 1);
  4949. }
  4950. /*$perms = 1;
  4951. if (isset($this->fields[$key]['perms']))
  4952. {
  4953. $perms = dol_eval($this->fields[$key]['perms'], 1);
  4954. }*/
  4955. if (empty($enabled)) {
  4956. continue;
  4957. }
  4958. //if (empty($perms)) continue;
  4959. if (in_array($key_type, array('date'))) {
  4960. // Clean parameters
  4961. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  4962. $value_key = dol_mktime(0, 0, 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]);
  4963. } elseif (in_array($key_type, array('datetime'))) {
  4964. // Clean parameters
  4965. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  4966. $value_key = dol_mktime($_POST[$postfieldkey."hour"], $_POST[$postfieldkey."min"], 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]);
  4967. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  4968. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  4969. if (!empty($value_arr)) {
  4970. $value_key = implode(',', $value_arr);
  4971. } else {
  4972. $value_key = '';
  4973. }
  4974. } elseif (in_array($key_type, array('price', 'double'))) {
  4975. $value_arr = GETPOST($postfieldkey, 'alpha');
  4976. $value_key = price2num($value_arr);
  4977. } else {
  4978. $value_key = GETPOST($postfieldkey);
  4979. if (in_array($key_type, array('link')) && $value_key == '-1') {
  4980. $value_key = '';
  4981. }
  4982. }
  4983. $this->array_languages[$key][$codelang] = $value_key;
  4984. /*if ($nofillrequired) {
  4985. $langs->load('errors');
  4986. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  4987. return -1;
  4988. }*/
  4989. }
  4990. return 1;
  4991. }
  4992. /* Functions for extrafields */
  4993. /**
  4994. * Function to make a fetch but set environment to avoid to load computed values before.
  4995. *
  4996. * @param int $id ID of object
  4997. * @return int >0 if OK, 0 if not found, <0 if KO
  4998. */
  4999. public function fetchNoCompute($id)
  5000. {
  5001. global $conf;
  5002. $savDisableCompute = $conf->disable_compute;
  5003. $conf->disable_compute = 1;
  5004. $ret = $this->fetch($id);
  5005. $conf->disable_compute = $savDisableCompute;
  5006. return $ret;
  5007. }
  5008. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5009. /**
  5010. * Function to get extra fields of an object into $this->array_options
  5011. * This method is in most cases called by method fetch of objects but you can call it separately.
  5012. *
  5013. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  5014. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  5015. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  5016. * @see fetchValuesForExtraLanguages()
  5017. */
  5018. public function fetch_optionals($rowid = null, $optionsArray = null)
  5019. {
  5020. // phpcs:enable
  5021. global $conf, $extrafields;
  5022. if (empty($rowid)) {
  5023. $rowid = $this->id;
  5024. }
  5025. if (empty($rowid) && isset($this->rowid)) {
  5026. $rowid = $this->rowid; // deprecated
  5027. }
  5028. // To avoid SQL errors. Probably not the better solution though
  5029. if (!$this->table_element) {
  5030. return 0;
  5031. }
  5032. $this->array_options = array();
  5033. if (!is_array($optionsArray)) {
  5034. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  5035. if (!isset($extrafields) || !is_object($extrafields)) {
  5036. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5037. $extrafields = new ExtraFields($this->db);
  5038. }
  5039. // Load array of extrafields for elementype = $this->table_element
  5040. if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
  5041. $extrafields->fetch_name_optionals_label($this->table_element);
  5042. }
  5043. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  5044. } else {
  5045. global $extrafields;
  5046. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  5047. }
  5048. $table_element = $this->table_element;
  5049. if ($table_element == 'categorie') {
  5050. $table_element = 'categories'; // For compatibility
  5051. }
  5052. // Request to get complementary values
  5053. if (is_array($optionsArray) && count($optionsArray) > 0) {
  5054. $sql = "SELECT rowid";
  5055. foreach ($optionsArray as $name => $label) {
  5056. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
  5057. $sql .= ", ".$name;
  5058. }
  5059. }
  5060. $sql .= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
  5061. $sql .= " WHERE fk_object = ".((int) $rowid);
  5062. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5063. $resql = $this->db->query($sql);
  5064. if ($resql) {
  5065. $numrows = $this->db->num_rows($resql);
  5066. if ($numrows) {
  5067. $tab = $this->db->fetch_array($resql);
  5068. foreach ($tab as $key => $value) {
  5069. // 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)
  5070. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
  5071. // we can add this attribute to object
  5072. if (!empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
  5073. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  5074. $this->array_options["options_".$key] = $this->db->jdate($value);
  5075. } else {
  5076. $this->array_options["options_".$key] = $value;
  5077. }
  5078. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  5079. }
  5080. }
  5081. // If field is a computed field, value must become result of compute
  5082. foreach ($tab as $key => $value) {
  5083. if (!empty($extrafields) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
  5084. //var_dump($conf->disable_compute);
  5085. if (empty($conf->disable_compute)) {
  5086. $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0);
  5087. }
  5088. }
  5089. }
  5090. }
  5091. $this->db->free($resql);
  5092. if ($numrows) {
  5093. return $numrows;
  5094. } else {
  5095. return 0;
  5096. }
  5097. } else {
  5098. $this->errors[]=$this->db->lasterror;
  5099. return -1;
  5100. }
  5101. }
  5102. return 0;
  5103. }
  5104. /**
  5105. * Delete all extra fields values for the current object.
  5106. *
  5107. * @return int <0 if KO, >0 if OK
  5108. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  5109. */
  5110. public function deleteExtraFields()
  5111. {
  5112. global $conf;
  5113. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5114. return 0;
  5115. }
  5116. $this->db->begin();
  5117. $table_element = $this->table_element;
  5118. if ($table_element == 'categorie') {
  5119. $table_element = 'categories'; // For compatibility
  5120. }
  5121. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  5122. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
  5123. $resql = $this->db->query($sql_del);
  5124. if (!$resql) {
  5125. $this->error = $this->db->lasterror();
  5126. $this->db->rollback();
  5127. return -1;
  5128. } else {
  5129. $this->db->commit();
  5130. return 1;
  5131. }
  5132. }
  5133. /**
  5134. * Add/Update all extra fields values for the current object.
  5135. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5136. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5137. *
  5138. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5139. * @param User $userused Object user
  5140. * @return int -1=error, O=did nothing, 1=OK
  5141. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  5142. */
  5143. public function insertExtraFields($trigger = '', $userused = null)
  5144. {
  5145. global $conf, $langs, $user;
  5146. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5147. return 0;
  5148. }
  5149. if (empty($userused)) {
  5150. $userused = $user;
  5151. }
  5152. $error = 0;
  5153. if (!empty($this->array_options)) {
  5154. // Check parameters
  5155. $langs->load('admin');
  5156. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5157. $extrafields = new ExtraFields($this->db);
  5158. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  5159. // Eliminate copied source object extra fields that do not exist in target object
  5160. $new_array_options = array();
  5161. foreach ($this->array_options as $key => $value) {
  5162. if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
  5163. $new_array_options[$key] = $value;
  5164. } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
  5165. $new_array_options['options_'.$key] = $value;
  5166. }
  5167. }
  5168. foreach ($new_array_options as $key => $value) {
  5169. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5170. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  5171. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  5172. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  5173. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  5174. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  5175. // Similar code than into insertExtraFields
  5176. if ($attributeRequired) {
  5177. $mandatorypb = false;
  5178. if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
  5179. $mandatorypb = true;
  5180. }
  5181. if ($this->array_options[$key] === '') {
  5182. $mandatorypb = true;
  5183. }
  5184. if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
  5185. $mandatorypb = true;
  5186. }
  5187. if ($mandatorypb) {
  5188. $langs->load("errors");
  5189. dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
  5190. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5191. return -1;
  5192. }
  5193. }
  5194. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5195. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5196. if (!empty($attrfieldcomputed)) {
  5197. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5198. $value = dol_eval($attrfieldcomputed, 1, 0);
  5199. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5200. $new_array_options[$key] = $value;
  5201. } else {
  5202. $new_array_options[$key] = null;
  5203. }
  5204. }
  5205. switch ($attributeType) {
  5206. case 'int':
  5207. if (!is_numeric($value) && $value != '') {
  5208. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5209. return -1;
  5210. } elseif ($value == '') {
  5211. $new_array_options[$key] = null;
  5212. }
  5213. break;
  5214. case 'price':
  5215. case 'double':
  5216. $value = price2num($value);
  5217. if (!is_numeric($value) && $value != '') {
  5218. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5219. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5220. return -1;
  5221. } elseif ($value == '') {
  5222. $new_array_options[$key] = null;
  5223. }
  5224. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5225. $new_array_options[$key] = $value;
  5226. break;
  5227. /*case 'select': // Not required, we chosed value='0' for undefined values
  5228. if ($value=='-1')
  5229. {
  5230. $this->array_options[$key] = null;
  5231. }
  5232. break;*/
  5233. case 'password':
  5234. $algo = '';
  5235. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
  5236. // If there is an encryption choice, we use it to crypt data before insert
  5237. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  5238. $algo = reset($tmparrays);
  5239. if ($algo != '') {
  5240. //global $action; // $action may be 'create', 'update', 'update_extras'...
  5241. //var_dump($action);
  5242. //var_dump($this->oldcopy);exit;
  5243. 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
  5244. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  5245. 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.
  5246. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5247. } else {
  5248. // var_dump($algo);
  5249. $newvalue = dol_hash($this->array_options[$key], $algo);
  5250. $new_array_options[$key] = $newvalue;
  5251. }
  5252. } else {
  5253. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5254. }
  5255. }
  5256. } else // Common usage
  5257. {
  5258. $new_array_options[$key] = $this->array_options[$key];
  5259. }
  5260. break;
  5261. case 'date':
  5262. case 'datetime':
  5263. // If data is a string instead of a timestamp, we convert it
  5264. if (!is_int($this->array_options[$key])) {
  5265. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5266. }
  5267. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  5268. break;
  5269. case 'link':
  5270. $param_list = array_keys($attributeParam['options']);
  5271. // 0 : ObjectName
  5272. // 1 : classPath
  5273. $InfoFieldList = explode(":", $param_list[0]);
  5274. dol_include_once($InfoFieldList[1]);
  5275. if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
  5276. if ($value == '-1') { // -1 is key for no defined in combo list of objects
  5277. $new_array_options[$key] = '';
  5278. } elseif ($value) {
  5279. $object = new $InfoFieldList[0]($this->db);
  5280. if (is_numeric($value)) {
  5281. $res = $object->fetch($value); // Common case
  5282. } else {
  5283. $res = $object->fetch('', $value); // For compatibility
  5284. }
  5285. if ($res > 0) {
  5286. $new_array_options[$key] = $object->id;
  5287. } else {
  5288. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5289. $this->db->rollback();
  5290. return -1;
  5291. }
  5292. }
  5293. } else {
  5294. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5295. }
  5296. break;
  5297. }
  5298. }
  5299. $this->db->begin();
  5300. $table_element = $this->table_element;
  5301. if ($table_element == 'categorie') {
  5302. $table_element = 'categories'; // For compatibility
  5303. }
  5304. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  5305. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
  5306. $this->db->query($sql_del);
  5307. $sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object";
  5308. foreach ($new_array_options as $key => $value) {
  5309. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5310. // Add field of attribut
  5311. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
  5312. $sql .= ",".$attributeKey;
  5313. }
  5314. }
  5315. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5316. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5317. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5318. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5319. $sql .= ",".$tmpkey;
  5320. }
  5321. }
  5322. }
  5323. $sql .= ") VALUES (".$this->id;
  5324. foreach ($new_array_options as $key => $value) {
  5325. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5326. // Add field of attribute
  5327. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
  5328. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
  5329. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  5330. } else {
  5331. $sql .= ",null";
  5332. }
  5333. }
  5334. }
  5335. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5336. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5337. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5338. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5339. if (in_array($tmpval, array('int', 'double', 'price'))) {
  5340. $sql .= ", 0";
  5341. } else {
  5342. $sql .= ", ''";
  5343. }
  5344. }
  5345. }
  5346. }
  5347. $sql .= ")";
  5348. $resql = $this->db->query($sql);
  5349. if (!$resql) {
  5350. $this->error = $this->db->lasterror();
  5351. $error++;
  5352. }
  5353. if (!$error && $trigger) {
  5354. // Call trigger
  5355. $this->context = array('extrafieldaddupdate'=>1);
  5356. $result = $this->call_trigger($trigger, $userused);
  5357. if ($result < 0) {
  5358. $error++;
  5359. }
  5360. // End call trigger
  5361. }
  5362. if ($error) {
  5363. $this->db->rollback();
  5364. return -1;
  5365. } else {
  5366. $this->db->commit();
  5367. return 1;
  5368. }
  5369. } else {
  5370. return 0;
  5371. }
  5372. }
  5373. /**
  5374. * Add/Update all extra fields values for the current object.
  5375. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5376. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5377. *
  5378. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5379. * @param User $userused Object user
  5380. * @return int -1=error, O=did nothing, 1=OK
  5381. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  5382. */
  5383. public function insertExtraLanguages($trigger = '', $userused = null)
  5384. {
  5385. global $conf, $langs, $user;
  5386. if (empty($userused)) {
  5387. $userused = $user;
  5388. }
  5389. $error = 0;
  5390. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5391. return 0; // For avoid conflicts if trigger used
  5392. }
  5393. if (is_array($this->array_languages)) {
  5394. $new_array_languages = $this->array_languages;
  5395. foreach ($new_array_languages as $key => $value) {
  5396. $attributeKey = $key;
  5397. $attributeType = $this->fields[$attributeKey]['type'];
  5398. $attributeLabel = $this->fields[$attributeKey]['label'];
  5399. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5400. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5401. switch ($attributeType) {
  5402. case 'int':
  5403. if (!is_numeric($value) && $value != '') {
  5404. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5405. return -1;
  5406. } elseif ($value == '') {
  5407. $new_array_languages[$key] = null;
  5408. }
  5409. break;
  5410. case 'double':
  5411. $value = price2num($value);
  5412. if (!is_numeric($value) && $value != '') {
  5413. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5414. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5415. return -1;
  5416. } elseif ($value == '') {
  5417. $new_array_languages[$key] = null;
  5418. }
  5419. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5420. $new_array_languages[$key] = $value;
  5421. break;
  5422. /*case 'select': // Not required, we chosed value='0' for undefined values
  5423. if ($value=='-1')
  5424. {
  5425. $this->array_options[$key] = null;
  5426. }
  5427. break;*/
  5428. }
  5429. }
  5430. $this->db->begin();
  5431. $table_element = $this->table_element;
  5432. if ($table_element == 'categorie') {
  5433. $table_element = 'categories'; // For compatibility
  5434. }
  5435. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  5436. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  5437. foreach ($langcodearray as $langcode => $value) {
  5438. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX."object_lang";
  5439. $sql_del .= " WHERE fk_object = ".$this->id." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  5440. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  5441. $this->db->query($sql_del);
  5442. if ($value !== '') {
  5443. $sql = "INSERT INTO ".MAIN_DB_PREFIX."object_lang (fk_object, property, type_object, lang, value";
  5444. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  5445. $sql .= ")";
  5446. $resql = $this->db->query($sql);
  5447. if (!$resql) {
  5448. $this->error = $this->db->lasterror();
  5449. $error++;
  5450. break;
  5451. }
  5452. }
  5453. }
  5454. }
  5455. if (!$error && $trigger) {
  5456. // Call trigger
  5457. $this->context = array('extralanguagesaddupdate'=>1);
  5458. $result = $this->call_trigger($trigger, $userused);
  5459. if ($result < 0) {
  5460. $error++;
  5461. }
  5462. // End call trigger
  5463. }
  5464. if ($error) {
  5465. $this->db->rollback();
  5466. return -1;
  5467. } else {
  5468. $this->db->commit();
  5469. return 1;
  5470. }
  5471. } else {
  5472. return 0;
  5473. }
  5474. }
  5475. /**
  5476. * Update 1 extra field value for the current object. Keep other fields unchanged.
  5477. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5478. *
  5479. * @param string $key Key of the extrafield to update (without starting 'options_')
  5480. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5481. * @param User $userused Object user
  5482. * @return int -1=error, O=did nothing, 1=OK
  5483. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  5484. */
  5485. public function updateExtraField($key, $trigger = null, $userused = null)
  5486. {
  5487. global $conf, $langs, $user;
  5488. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5489. return 0;
  5490. }
  5491. if (empty($userused)) {
  5492. $userused = $user;
  5493. }
  5494. $error = 0;
  5495. if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
  5496. // Check parameters
  5497. $langs->load('admin');
  5498. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5499. $extrafields = new ExtraFields($this->db);
  5500. $extrafields->fetch_name_optionals_label($this->table_element);
  5501. $value = $this->array_options["options_".$key];
  5502. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  5503. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  5504. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  5505. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  5506. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  5507. // Similar code than into insertExtraFields
  5508. if ($attributeRequired) {
  5509. $mandatorypb = false;
  5510. if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
  5511. $mandatorypb = true;
  5512. }
  5513. if ($this->array_options["options_".$key] === '') {
  5514. $mandatorypb = true;
  5515. }
  5516. if ($mandatorypb) {
  5517. $langs->load("errors");
  5518. dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
  5519. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5520. return -1;
  5521. }
  5522. }
  5523. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5524. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5525. if (!empty($attrfieldcomputed)) {
  5526. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5527. $value = dol_eval($attrfieldcomputed, 1, 0);
  5528. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5529. $this->array_options["options_".$key] = $value;
  5530. } else {
  5531. $this->array_options["options_".$key] = null;
  5532. }
  5533. }
  5534. switch ($attributeType) {
  5535. case 'int':
  5536. if (!is_numeric($value) && $value != '') {
  5537. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5538. return -1;
  5539. } elseif ($value === '') {
  5540. $this->array_options["options_".$key] = null;
  5541. }
  5542. break;
  5543. case 'double':
  5544. $value = price2num($value);
  5545. if (!is_numeric($value) && $value != '') {
  5546. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5547. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5548. return -1;
  5549. } elseif ($value === '') {
  5550. $this->array_options["options_".$key] = null;
  5551. }
  5552. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5553. $this->array_options["options_".$key] = $value;
  5554. break;
  5555. /*case 'select': // Not required, we chosed value='0' for undefined values
  5556. if ($value=='-1')
  5557. {
  5558. $this->array_options[$key] = null;
  5559. }
  5560. break;*/
  5561. case 'price':
  5562. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  5563. break;
  5564. case 'date':
  5565. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5566. break;
  5567. case 'datetime':
  5568. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5569. break;
  5570. /*
  5571. case 'link':
  5572. $param_list = array_keys($attributeParam['options']);
  5573. // 0 : ObjectName
  5574. // 1 : classPath
  5575. $InfoFieldList = explode(":", $param_list[0]);
  5576. dol_include_once($InfoFieldList[1]);
  5577. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  5578. {
  5579. if ($value == '-1') // -1 is key for no defined in combo list of objects
  5580. {
  5581. $new_array_options[$key] = '';
  5582. } elseif ($value) {
  5583. $object = new $InfoFieldList[0]($this->db);
  5584. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  5585. else $res = $object->fetch('', $value); // For compatibility
  5586. if ($res > 0) $new_array_options[$key] = $object->id;
  5587. else {
  5588. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5589. $this->db->rollback();
  5590. return -1;
  5591. }
  5592. }
  5593. } else {
  5594. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5595. }
  5596. break;
  5597. */
  5598. }
  5599. $this->db->begin();
  5600. $linealreadyfound = 0;
  5601. // 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)
  5602. $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields WHERE fk_object = ".$this->id;
  5603. $resql = $this->db->query($sql);
  5604. if ($resql) {
  5605. $tmpobj = $this->db->fetch_object($resql);
  5606. if ($tmpobj) {
  5607. $linealreadyfound = $tmpobj->nb;
  5608. }
  5609. }
  5610. if ($linealreadyfound) {
  5611. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
  5612. $sql .= " WHERE fk_object = ".$this->id;
  5613. } else {
  5614. $result = $this->insertExtraFields('', $user);
  5615. if ($result < 0) {
  5616. $error++;
  5617. }
  5618. }
  5619. $resql = $this->db->query($sql);
  5620. if (!$resql) {
  5621. $error++;
  5622. $this->error = $this->db->lasterror();
  5623. }
  5624. if (!$error && $trigger) {
  5625. // Call trigger
  5626. $this->context = array('extrafieldupdate'=>1);
  5627. $result = $this->call_trigger($trigger, $userused);
  5628. if ($result < 0) {
  5629. $error++;
  5630. }
  5631. // End call trigger
  5632. }
  5633. if ($error) {
  5634. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  5635. $this->db->rollback();
  5636. return -1;
  5637. } else {
  5638. $this->db->commit();
  5639. return 1;
  5640. }
  5641. } else {
  5642. return 0;
  5643. }
  5644. }
  5645. /**
  5646. * Update an extra language value for the current object.
  5647. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5648. *
  5649. * @param string $key Key of the extrafield (without starting 'options_')
  5650. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5651. * @param User $userused Object user
  5652. * @return int -1=error, O=did nothing, 1=OK
  5653. * @see updateExtraFields(), insertExtraLanguages()
  5654. */
  5655. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  5656. {
  5657. global $conf, $langs, $user;
  5658. if (empty($userused)) {
  5659. $userused = $user;
  5660. }
  5661. $error = 0;
  5662. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5663. return 0; // For avoid conflicts if trigger used
  5664. }
  5665. return 0;
  5666. }
  5667. /**
  5668. * Return HTML string to put an input field into a page
  5669. * Code very similar with showInputField of extra fields
  5670. *
  5671. * @param array $val Array of properties for field to show (used only if ->fields not defined)
  5672. * @param string $key Key of attribute
  5673. * @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)
  5674. * @param string $moreparam To add more parameters on html input tag
  5675. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5676. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5677. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  5678. * @param int $nonewbutton Force to not show the new button on field that are links to object
  5679. * @return string
  5680. */
  5681. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  5682. {
  5683. global $conf, $langs, $form;
  5684. if (!is_object($form)) {
  5685. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  5686. $form = new Form($this->db);
  5687. }
  5688. if (!empty($this->fields)) {
  5689. $val = $this->fields[$key];
  5690. }
  5691. $out = '';
  5692. $type = '';
  5693. $isDependList=0;
  5694. $param = array();
  5695. $param['options'] = array();
  5696. $reg = array();
  5697. $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
  5698. // Because we work on extrafields
  5699. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5700. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5701. $type = 'link';
  5702. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5703. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5704. $type = 'link';
  5705. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  5706. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5707. $type = 'link';
  5708. } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5709. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5710. $type = 'sellist';
  5711. } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5712. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5713. $type = 'sellist';
  5714. } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
  5715. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5716. $type = 'sellist';
  5717. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  5718. $param['options'] = array();
  5719. $type = 'varchar';
  5720. $size = $reg[1];
  5721. } elseif (preg_match('/varchar/', $val['type'])) {
  5722. $param['options'] = array();
  5723. $type = 'varchar';
  5724. } else {
  5725. $param['options'] = array();
  5726. $type = $this->fields[$key]['type'];
  5727. }
  5728. // Special case that force options and type ($type can be integer, varchar, ...)
  5729. if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
  5730. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  5731. $type = 'select';
  5732. }
  5733. $label = $this->fields[$key]['label'];
  5734. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  5735. $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
  5736. $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
  5737. $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
  5738. $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
  5739. $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
  5740. $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
  5741. $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
  5742. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  5743. $objectid = $this->id;
  5744. if ($computed) {
  5745. if (!preg_match('/^search_/', $keyprefix)) {
  5746. return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  5747. } else {
  5748. return '';
  5749. }
  5750. }
  5751. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  5752. if (empty($morecss) && !empty($val['css'])) {
  5753. $morecss = $val['css'];
  5754. } elseif (empty($morecss)) {
  5755. if ($type == 'date') {
  5756. $morecss = 'minwidth100imp';
  5757. } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
  5758. $morecss = 'minwidth200imp';
  5759. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  5760. $morecss = 'maxwidth75';
  5761. } elseif ($type == 'url') {
  5762. $morecss = 'minwidth400';
  5763. } elseif ($type == 'boolean') {
  5764. $morecss = '';
  5765. } else {
  5766. if (round($size) < 12) {
  5767. $morecss = 'minwidth100';
  5768. } elseif (round($size) <= 48) {
  5769. $morecss = 'minwidth200';
  5770. } else {
  5771. $morecss = 'minwidth400';
  5772. }
  5773. }
  5774. }
  5775. if (in_array($type, array('date'))) {
  5776. $tmp = explode(',', $size);
  5777. $newsize = $tmp[0];
  5778. $showtime = 0;
  5779. // Do not show current date when field not required (see selectDate() method)
  5780. if (!$required && $value == '') {
  5781. $value = '-1';
  5782. }
  5783. // TODO Must also support $moreparam
  5784. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  5785. } elseif (in_array($type, array('datetime'))) {
  5786. $tmp = explode(',', $size);
  5787. $newsize = $tmp[0];
  5788. $showtime = 1;
  5789. // Do not show current date when field not required (see selectDate() method)
  5790. if (!$required && $value == '') $value = '-1';
  5791. // TODO Must also support $moreparam
  5792. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
  5793. } elseif (in_array($type, array('duration'))) {
  5794. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  5795. } elseif (in_array($type, array('int', 'integer'))) {
  5796. $tmp = explode(',', $size);
  5797. $newsize = $tmp[0];
  5798. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$newsize.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5799. } elseif (in_array($type, array('real'))) {
  5800. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5801. } elseif (preg_match('/varchar/', $type)) {
  5802. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$size.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5803. } elseif (in_array($type, array('mail', 'phone', 'url'))) {
  5804. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5805. } elseif (preg_match('/^text/', $type)) {
  5806. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  5807. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5808. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  5809. $out = $doleditor->Create(1);
  5810. } else {
  5811. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5812. }
  5813. } elseif (preg_match('/^html/', $type)) {
  5814. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  5815. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5816. $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%');
  5817. $out = $doleditor->Create(1);
  5818. } else {
  5819. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5820. }
  5821. } elseif ($type == 'boolean') {
  5822. $checked = '';
  5823. if (!empty($value)) {
  5824. $checked = ' checked value="1" ';
  5825. } else {
  5826. $checked = ' value="1" ';
  5827. }
  5828. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  5829. } elseif ($type == 'price') {
  5830. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5831. $value = price($value);
  5832. }
  5833. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  5834. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  5835. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5836. $value = price($value);
  5837. }
  5838. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  5839. } elseif ($type == 'select') {
  5840. $out = '';
  5841. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  5842. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5843. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  5844. }
  5845. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  5846. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
  5847. $out .= '<option value="0">&nbsp;</option>';
  5848. }
  5849. foreach ($param['options'] as $key => $val) {
  5850. if ((string) $key == '') {
  5851. continue;
  5852. }
  5853. list($val, $parent) = explode('|', $val);
  5854. $out .= '<option value="'.$key.'"';
  5855. $out .= (((string) $value == (string) $key) ? ' selected' : '');
  5856. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  5857. $out .= '>'.$val.'</option>';
  5858. }
  5859. $out .= '</select>';
  5860. } elseif ($type == 'sellist') {
  5861. $out = '';
  5862. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  5863. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5864. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  5865. }
  5866. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  5867. if (is_array($param['options'])) {
  5868. $param_list = array_keys($param['options']);
  5869. $InfoFieldList = explode(":", $param_list[0]);
  5870. $parentName = '';
  5871. $parentField = '';
  5872. // 0 : tableName
  5873. // 1 : label field name
  5874. // 2 : key fields name (if differ of rowid)
  5875. // 3 : key field parent (for dependent lists)
  5876. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  5877. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  5878. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  5879. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  5880. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  5881. } else {
  5882. $keyList = $InfoFieldList[2].' as rowid';
  5883. }
  5884. }
  5885. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  5886. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  5887. $keyList .= ', '.$parentField;
  5888. }
  5889. $fields_label = explode('|', $InfoFieldList[1]);
  5890. if (is_array($fields_label)) {
  5891. $keyList .= ', ';
  5892. $keyList .= implode(', ', $fields_label);
  5893. }
  5894. $sqlwhere = '';
  5895. $sql = 'SELECT '.$keyList;
  5896. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  5897. if (!empty($InfoFieldList[4])) {
  5898. // can use SELECT request
  5899. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  5900. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  5901. }
  5902. // current object id can be use into filter
  5903. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  5904. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  5905. } else {
  5906. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  5907. }
  5908. //We have to join on extrafield table
  5909. if (strpos($InfoFieldList[4], 'extra') !== false) {
  5910. $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
  5911. $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
  5912. } else {
  5913. $sqlwhere .= ' WHERE '.$InfoFieldList[4];
  5914. }
  5915. } else {
  5916. $sqlwhere .= ' WHERE 1=1';
  5917. }
  5918. // Some tables may have field, some other not. For the moment we disable it.
  5919. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  5920. $sqlwhere .= ' AND entity = '.$conf->entity;
  5921. }
  5922. $sql .= $sqlwhere;
  5923. //print $sql;
  5924. $sql .= ' ORDER BY '.implode(', ', $fields_label);
  5925. dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
  5926. $resql = $this->db->query($sql);
  5927. if ($resql) {
  5928. $out .= '<option value="0">&nbsp;</option>';
  5929. $num = $this->db->num_rows($resql);
  5930. $i = 0;
  5931. while ($i < $num) {
  5932. $labeltoshow = '';
  5933. $obj = $this->db->fetch_object($resql);
  5934. // Several field into label (eq table:code|libelle:rowid)
  5935. $notrans = false;
  5936. $fields_label = explode('|', $InfoFieldList[1]);
  5937. if (count($fields_label) > 1) {
  5938. $notrans = true;
  5939. foreach ($fields_label as $field_toshow) {
  5940. $labeltoshow .= $obj->$field_toshow.' ';
  5941. }
  5942. } else {
  5943. $labeltoshow = $obj->{$InfoFieldList[1]};
  5944. }
  5945. $labeltoshow = dol_trunc($labeltoshow, 45);
  5946. if ($value == $obj->rowid) {
  5947. foreach ($fields_label as $field_toshow) {
  5948. $translabel = $langs->trans($obj->$field_toshow);
  5949. if ($translabel != $obj->$field_toshow) {
  5950. $labeltoshow = dol_trunc($translabel, 18).' ';
  5951. } else {
  5952. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  5953. }
  5954. }
  5955. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  5956. } else {
  5957. if (!$notrans) {
  5958. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  5959. if ($translabel != $obj->{$InfoFieldList[1]}) {
  5960. $labeltoshow = dol_trunc($translabel, 18);
  5961. } else {
  5962. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  5963. }
  5964. }
  5965. if (empty($labeltoshow)) {
  5966. $labeltoshow = '(not defined)';
  5967. }
  5968. if ($value == $obj->rowid) {
  5969. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  5970. }
  5971. if (!empty($InfoFieldList[3]) && $parentField) {
  5972. $parent = $parentName.':'.$obj->{$parentField};
  5973. $isDependList=1;
  5974. }
  5975. $out .= '<option value="'.$obj->rowid.'"';
  5976. $out .= ($value == $obj->rowid ? ' selected' : '');
  5977. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  5978. $out .= '>'.$labeltoshow.'</option>';
  5979. }
  5980. $i++;
  5981. }
  5982. $this->db->free($resql);
  5983. } else {
  5984. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  5985. }
  5986. }
  5987. $out .= '</select>';
  5988. } elseif ($type == 'checkbox') {
  5989. $value_arr = explode(',', $value);
  5990. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
  5991. } elseif ($type == 'radio') {
  5992. $out = '';
  5993. foreach ($param['options'] as $keyopt => $val) {
  5994. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  5995. $out .= ' value="'.$keyopt.'"';
  5996. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  5997. $out .= ($value == $keyopt ? 'checked' : '');
  5998. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
  5999. }
  6000. } elseif ($type == 'chkbxlst') {
  6001. if (is_array($value)) {
  6002. $value_arr = $value;
  6003. } else {
  6004. $value_arr = explode(',', $value);
  6005. }
  6006. if (is_array($param['options'])) {
  6007. $param_list = array_keys($param['options']);
  6008. $InfoFieldList = explode(":", $param_list[0]);
  6009. $parentName = '';
  6010. $parentField = '';
  6011. // 0 : tableName
  6012. // 1 : label field name
  6013. // 2 : key fields name (if differ of rowid)
  6014. // 3 : key field parent (for dependent lists)
  6015. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6016. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6017. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6018. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6019. $keyList .= ', '.$parentField;
  6020. }
  6021. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6022. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6023. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6024. } else {
  6025. $keyList = $InfoFieldList[2].' as rowid';
  6026. }
  6027. }
  6028. $fields_label = explode('|', $InfoFieldList[1]);
  6029. if (is_array($fields_label)) {
  6030. $keyList .= ', ';
  6031. $keyList .= implode(', ', $fields_label);
  6032. }
  6033. $sqlwhere = '';
  6034. $sql = 'SELECT '.$keyList;
  6035. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6036. if (!empty($InfoFieldList[4])) {
  6037. // can use SELECT request
  6038. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6039. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6040. }
  6041. // current object id can be use into filter
  6042. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6043. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6044. } else {
  6045. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6046. }
  6047. // We have to join on extrafield table
  6048. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6049. $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
  6050. $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
  6051. } else {
  6052. $sqlwhere .= ' WHERE '.$InfoFieldList[4];
  6053. }
  6054. } else {
  6055. $sqlwhere .= ' WHERE 1=1';
  6056. }
  6057. // Some tables may have field, some other not. For the moment we disable it.
  6058. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6059. $sqlwhere .= ' AND entity = '.$conf->entity;
  6060. }
  6061. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  6062. // print $sql;
  6063. $sql .= $sqlwhere;
  6064. dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
  6065. $resql = $this->db->query($sql);
  6066. if ($resql) {
  6067. $num = $this->db->num_rows($resql);
  6068. $i = 0;
  6069. $data = array();
  6070. while ($i < $num) {
  6071. $labeltoshow = '';
  6072. $obj = $this->db->fetch_object($resql);
  6073. $notrans = false;
  6074. // Several field into label (eq table:code|libelle:rowid)
  6075. $fields_label = explode('|', $InfoFieldList[1]);
  6076. if (count($fields_label) > 1) {
  6077. $notrans = true;
  6078. foreach ($fields_label as $field_toshow) {
  6079. $labeltoshow .= $obj->$field_toshow.' ';
  6080. }
  6081. } else {
  6082. $labeltoshow = $obj->{$InfoFieldList[1]};
  6083. }
  6084. $labeltoshow = dol_trunc($labeltoshow, 45);
  6085. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6086. foreach ($fields_label as $field_toshow) {
  6087. $translabel = $langs->trans($obj->$field_toshow);
  6088. if ($translabel != $obj->$field_toshow) {
  6089. $labeltoshow = dol_trunc($translabel, 18).' ';
  6090. } else {
  6091. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  6092. }
  6093. }
  6094. $data[$obj->rowid] = $labeltoshow;
  6095. } else {
  6096. if (!$notrans) {
  6097. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6098. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6099. $labeltoshow = dol_trunc($translabel, 18);
  6100. } else {
  6101. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  6102. }
  6103. }
  6104. if (empty($labeltoshow)) {
  6105. $labeltoshow = '(not defined)';
  6106. }
  6107. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6108. $data[$obj->rowid] = $labeltoshow;
  6109. }
  6110. if (!empty($InfoFieldList[3]) && $parentField) {
  6111. $parent = $parentName.':'.$obj->{$parentField};
  6112. $isDependList=1;
  6113. }
  6114. $data[$obj->rowid] = $labeltoshow;
  6115. }
  6116. $i++;
  6117. }
  6118. $this->db->free($resql);
  6119. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
  6120. } else {
  6121. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6122. }
  6123. }
  6124. } elseif ($type == 'link') {
  6125. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter]]'
  6126. $param_list_array = explode(':', $param_list[0]);
  6127. $showempty = (($required && $default != '') ? 0 : 1);
  6128. if (!preg_match('/search_/', $keyprefix)) {
  6129. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6130. if (!empty($this->fields[$key]['picto'])) {
  6131. $morecss .= ' widthcentpercentminusxx';
  6132. } else {
  6133. $morecss .= ' widthcentpercentminusx';
  6134. }
  6135. } else {
  6136. if (!empty($this->fields[$key]['picto'])) {
  6137. $morecss .= ' widthcentpercentminusx';
  6138. }
  6139. }
  6140. }
  6141. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  6142. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6143. 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".
  6144. list($class, $classfile) = explode(':', $param_list[0]);
  6145. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
  6146. $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  6147. } else {
  6148. $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  6149. }
  6150. $paramforthenewlink = '';
  6151. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  6152. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  6153. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  6154. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  6155. $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>';
  6156. }
  6157. }
  6158. } elseif ($type == 'password') {
  6159. // If prefix is 'search_', field is used as a filter, we use a common text field.
  6160. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  6161. } elseif ($type == 'array') {
  6162. $newval = $val;
  6163. $newval['type'] = 'varchar(256)';
  6164. $out = '';
  6165. if (!empty($value)) {
  6166. foreach ($value as $option) {
  6167. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6168. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  6169. }
  6170. }
  6171. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6172. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6173. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  6174. if (!empty($conf->use_javascript_ajax)) {
  6175. $out .= '
  6176. <script>
  6177. $(document).ready(function() {
  6178. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  6179. $("'.dol_escape_js($newInput).'").insertBefore(this);
  6180. });
  6181. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  6182. $(this).parent().remove();
  6183. });
  6184. });
  6185. </script>';
  6186. }
  6187. }
  6188. if (!empty($hidden)) {
  6189. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  6190. }
  6191. if ($isDependList==1) {
  6192. $out .= $this->getJSListDependancies('_common');
  6193. }
  6194. /* Add comments
  6195. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  6196. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  6197. */
  6198. return $out;
  6199. }
  6200. /**
  6201. * Return HTML string to show a field into a page
  6202. * Code very similar with showOutputField of extra fields
  6203. *
  6204. * @param array $val Array of properties of field to show
  6205. * @param string $key Key of attribute
  6206. * @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)
  6207. * @param string $moreparam To add more parametes on html input tag
  6208. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6209. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6210. * @param mixed $morecss Value for css to define size. May also be a numeric.
  6211. * @return string
  6212. */
  6213. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  6214. {
  6215. global $conf, $langs, $form;
  6216. if (!is_object($form)) {
  6217. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6218. $form = new Form($this->db);
  6219. }
  6220. $objectid = $this->id; // Not used ???
  6221. $label = empty($val['label']) ? '' : $val['label'];
  6222. $type = empty($val['type']) ? '' : $val['type'];
  6223. $size = empty($val['css']) ? '' : $val['css'];
  6224. $reg = array();
  6225. // Convert var to be able to share same code than showOutputField of extrafields
  6226. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6227. $type = 'varchar'; // convert varchar(xx) int varchar
  6228. $size = $reg[1];
  6229. } elseif (preg_match('/varchar/', $type)) {
  6230. $type = 'varchar'; // convert varchar(xx) int varchar
  6231. }
  6232. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6233. $type = 'select';
  6234. }
  6235. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6236. $type = 'link';
  6237. }
  6238. $default = empty($val['default']) ? '' : $val['default'];
  6239. $computed = empty($val['computed']) ? '' : $val['computed'];
  6240. $unique = empty($val['unique']) ? '' : $val['unique'];
  6241. $required = empty($val['required']) ? '' : $val['required'];
  6242. $param = array();
  6243. $param['options'] = array();
  6244. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6245. $param['options'] = $val['arrayofkeyval'];
  6246. }
  6247. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6248. $type = 'link';
  6249. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6250. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6251. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6252. $type = 'sellist';
  6253. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6254. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6255. $type = 'sellist';
  6256. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6257. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6258. $type = 'sellist';
  6259. }
  6260. $langfile = empty($val['langfile']) ? '' : $val['langfile'];
  6261. $list = (empty($val['list']) ? '' : $val['list']);
  6262. $help = (empty($val['help']) ? '' : $val['help']);
  6263. $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)
  6264. if ($hidden) {
  6265. return '';
  6266. }
  6267. // If field is a computed field, value must become result of compute
  6268. if ($computed) {
  6269. // Make the eval of compute string
  6270. //var_dump($computed);
  6271. $value = dol_eval($computed, 1, 0);
  6272. }
  6273. if (empty($morecss)) {
  6274. if ($type == 'date') {
  6275. $morecss = 'minwidth100imp';
  6276. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6277. $morecss = 'minwidth200imp';
  6278. } elseif (in_array($type, array('int', 'double', 'price'))) {
  6279. $morecss = 'maxwidth75';
  6280. } elseif ($type == 'url') {
  6281. $morecss = 'minwidth400';
  6282. } elseif ($type == 'boolean') {
  6283. $morecss = '';
  6284. } else {
  6285. if (is_numeric($size) && round($size) < 12) {
  6286. $morecss = 'minwidth100';
  6287. } elseif (is_numeric($size) && round($size) <= 48) {
  6288. $morecss = 'minwidth200';
  6289. } else {
  6290. $morecss = 'minwidth400';
  6291. }
  6292. }
  6293. }
  6294. // Format output value differently according to properties of field
  6295. if ($key == 'ref' && method_exists($this, 'getNomUrl')) {
  6296. $value = $this->getNomUrl(1, '', 0, '', 1);
  6297. } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
  6298. $value = $this->getLibStatut(3);
  6299. } elseif ($type == 'date') {
  6300. if (!empty($value)) {
  6301. $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
  6302. } else {
  6303. $value = '';
  6304. }
  6305. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6306. if (!empty($value)) {
  6307. $value = dol_print_date($value, 'dayhour', 'tzuserrel');
  6308. } else {
  6309. $value = '';
  6310. }
  6311. } elseif ($type == 'duration') {
  6312. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6313. if (!is_null($value) && $value !== '') {
  6314. $value = convertSecondToTime($value, 'allhourmin');
  6315. }
  6316. } elseif ($type == 'double' || $type == 'real') {
  6317. if (!is_null($value) && $value !== '') {
  6318. $value = price($value);
  6319. }
  6320. } elseif ($type == 'boolean') {
  6321. $checked = '';
  6322. if (!empty($value)) {
  6323. $checked = ' checked ';
  6324. }
  6325. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  6326. } elseif ($type == 'mail') {
  6327. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  6328. } elseif ($type == 'url') {
  6329. $value = dol_print_url($value, '_blank', 32, 1);
  6330. } elseif ($type == 'phone') {
  6331. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
  6332. } elseif ($type == 'price') {
  6333. if (!is_null($value) && $value !== '') {
  6334. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  6335. }
  6336. } elseif ($type == 'select') {
  6337. $value = $param['options'][$value];
  6338. } elseif ($type == 'sellist') {
  6339. $param_list = array_keys($param['options']);
  6340. $InfoFieldList = explode(":", $param_list[0]);
  6341. $selectkey = "rowid";
  6342. $keyList = 'rowid';
  6343. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6344. $selectkey = $InfoFieldList[2];
  6345. $keyList = $InfoFieldList[2].' as rowid';
  6346. }
  6347. $fields_label = explode('|', $InfoFieldList[1]);
  6348. if (is_array($fields_label)) {
  6349. $keyList .= ', ';
  6350. $keyList .= implode(', ', $fields_label);
  6351. }
  6352. $sql = 'SELECT '.$keyList;
  6353. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6354. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6355. $sql .= ' as main';
  6356. }
  6357. if ($selectkey == 'rowid' && empty($value)) {
  6358. $sql .= " WHERE ".$selectkey." = 0";
  6359. } elseif ($selectkey == 'rowid') {
  6360. $sql .= " WHERE ".$selectkey." = ".((int) $value);
  6361. } else {
  6362. $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
  6363. }
  6364. //$sql.= ' AND entity = '.$conf->entity;
  6365. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  6366. $resql = $this->db->query($sql);
  6367. if ($resql) {
  6368. $value = ''; // value was used, so now we reste it to use it to build final output
  6369. $obj = $this->db->fetch_object($resql);
  6370. // Several field into label (eq table:code|libelle:rowid)
  6371. $fields_label = explode('|', $InfoFieldList[1]);
  6372. if (is_array($fields_label) && count($fields_label) > 1) {
  6373. foreach ($fields_label as $field_toshow) {
  6374. $translabel = '';
  6375. if (!empty($obj->$field_toshow)) {
  6376. $translabel = $langs->trans($obj->$field_toshow);
  6377. }
  6378. if ($translabel != $field_toshow) {
  6379. $value .= dol_trunc($translabel, 18).' ';
  6380. } else {
  6381. $value .= $obj->$field_toshow.' ';
  6382. }
  6383. }
  6384. } else {
  6385. $translabel = '';
  6386. if (!empty($obj->{$InfoFieldList[1]})) {
  6387. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6388. }
  6389. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6390. $value = dol_trunc($translabel, 18);
  6391. } else {
  6392. $value = $obj->{$InfoFieldList[1]};
  6393. }
  6394. }
  6395. } else {
  6396. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6397. }
  6398. } elseif ($type == 'radio') {
  6399. $value = $param['options'][$value];
  6400. } elseif ($type == 'checkbox') {
  6401. $value_arr = explode(',', $value);
  6402. $value = '';
  6403. if (is_array($value_arr) && count($value_arr) > 0) {
  6404. $toprint = array();
  6405. foreach ($value_arr as $keyval => $valueval) {
  6406. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  6407. }
  6408. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6409. }
  6410. } elseif ($type == 'chkbxlst') {
  6411. $value_arr = explode(',', $value);
  6412. $param_list = array_keys($param['options']);
  6413. $InfoFieldList = explode(":", $param_list[0]);
  6414. $selectkey = "rowid";
  6415. $keyList = 'rowid';
  6416. if (count($InfoFieldList) >= 3) {
  6417. $selectkey = $InfoFieldList[2];
  6418. $keyList = $InfoFieldList[2].' as rowid';
  6419. }
  6420. $fields_label = explode('|', $InfoFieldList[1]);
  6421. if (is_array($fields_label)) {
  6422. $keyList .= ', ';
  6423. $keyList .= implode(', ', $fields_label);
  6424. }
  6425. $sql = 'SELECT '.$keyList;
  6426. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6427. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6428. $sql .= ' as main';
  6429. }
  6430. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  6431. // $sql.= ' AND entity = '.$conf->entity;
  6432. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  6433. $resql = $this->db->query($sql);
  6434. if ($resql) {
  6435. $value = ''; // value was used, so now we reste it to use it to build final output
  6436. $toprint = array();
  6437. while ($obj = $this->db->fetch_object($resql)) {
  6438. // Several field into label (eq table:code|libelle:rowid)
  6439. $fields_label = explode('|', $InfoFieldList[1]);
  6440. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6441. if (is_array($fields_label) && count($fields_label) > 1) {
  6442. foreach ($fields_label as $field_toshow) {
  6443. $translabel = '';
  6444. if (!empty($obj->$field_toshow)) {
  6445. $translabel = $langs->trans($obj->$field_toshow);
  6446. }
  6447. if ($translabel != $field_toshow) {
  6448. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6449. } else {
  6450. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->$field_toshow.'</li>';
  6451. }
  6452. }
  6453. } else {
  6454. $translabel = '';
  6455. if (!empty($obj->{$InfoFieldList[1]})) {
  6456. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6457. }
  6458. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6459. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6460. } else {
  6461. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->{$InfoFieldList[1]}.'</li>';
  6462. }
  6463. }
  6464. }
  6465. }
  6466. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6467. } else {
  6468. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6469. }
  6470. } elseif ($type == 'link') {
  6471. $out = '';
  6472. // only if something to display (perf)
  6473. if ($value) {
  6474. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6475. $InfoFieldList = explode(":", $param_list[0]);
  6476. $classname = $InfoFieldList[0];
  6477. $classpath = $InfoFieldList[1];
  6478. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  6479. $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
  6480. if (!empty($classpath)) {
  6481. dol_include_once($InfoFieldList[1]);
  6482. if ($classname && class_exists($classname)) {
  6483. $object = new $classname($this->db);
  6484. $object->fetch($value);
  6485. $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
  6486. }
  6487. } else {
  6488. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  6489. return 'Error bad setup of extrafield';
  6490. }
  6491. } else {
  6492. $value = '';
  6493. }
  6494. } elseif (preg_match('/^(text|html)/', $type)) {
  6495. $value = dol_htmlentitiesbr($value);
  6496. } elseif ($type == 'password') {
  6497. $value = preg_replace('/./i', '*', $value);
  6498. } elseif ($type == 'array') {
  6499. $value = implode('<br>', $value);
  6500. }
  6501. //print $type.'-'.$size.'-'.$value;
  6502. $out = $value;
  6503. return $out;
  6504. }
  6505. /**
  6506. * Function to show lines of extrafields with output datas.
  6507. * 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
  6508. *
  6509. * @param Extrafields $extrafields Extrafield Object
  6510. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  6511. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  6512. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  6513. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  6514. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  6515. * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...)
  6516. * @return string
  6517. */
  6518. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
  6519. {
  6520. global $db, $conf, $langs, $action, $form, $hookmanager;
  6521. if (!is_object($form)) {
  6522. $form = new Form($db);
  6523. }
  6524. $out = '';
  6525. $parameters = array();
  6526. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  6527. if (empty($reshook)) {
  6528. 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) {
  6529. $out .= "\n";
  6530. $out .= '<!-- showOptionals --> ';
  6531. $out .= "\n";
  6532. $extrafields_collapse_num = '';
  6533. $e = 0;
  6534. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
  6535. // Show only the key field in params
  6536. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
  6537. continue;
  6538. }
  6539. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  6540. $enabled = 1;
  6541. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  6542. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1);
  6543. }
  6544. if (empty($enabled)) {
  6545. continue;
  6546. }
  6547. $visibility = 1;
  6548. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  6549. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1);
  6550. }
  6551. $perms = 1;
  6552. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  6553. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1);
  6554. }
  6555. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
  6556. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  6557. } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
  6558. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  6559. } elseif ($mode == 'view' && empty($visibility)) {
  6560. continue;
  6561. }
  6562. if (empty($perms)) {
  6563. continue;
  6564. }
  6565. // Load language if required
  6566. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  6567. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  6568. }
  6569. $colspan = '';
  6570. if (is_array($params) && count($params) > 0 && $display_type=='card') {
  6571. if (array_key_exists('cols', $params)) {
  6572. $colspan = $params['cols'];
  6573. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  6574. $reg = array();
  6575. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  6576. $colspan = $reg[1];
  6577. } else {
  6578. $colspan = $params['colspan'];
  6579. }
  6580. }
  6581. }
  6582. switch ($mode) {
  6583. case "view":
  6584. $value = $this->array_options["options_".$key.$keysuffix]; // Value may be clean or formated later
  6585. break;
  6586. case "create":
  6587. case "edit":
  6588. // We get the value of property found with GETPOST so it takes into account:
  6589. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  6590. $check = 'alphanohtml';
  6591. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  6592. $check = 'restricthtml';
  6593. }
  6594. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  6595. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  6596. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
  6597. if (is_array($getposttemp)) {
  6598. // $getposttemp is an array but following code expects a comma separated string
  6599. $value = implode(",", $getposttemp);
  6600. } else {
  6601. $value = $getposttemp;
  6602. }
  6603. } else {
  6604. $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.
  6605. }
  6606. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  6607. break;
  6608. }
  6609. // Output value of the current field
  6610. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  6611. $extrafields_collapse_num = '';
  6612. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  6613. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  6614. $extrafield_param_list = array_keys($extrafield_param['options']);
  6615. if (count($extrafield_param_list) > 0) {
  6616. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  6617. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  6618. $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  6619. }
  6620. }
  6621. }
  6622. $out .= $extrafields->showSeparator($key, $this, ($colspan + 1), $display_type);
  6623. } else {
  6624. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  6625. $csstyle = '';
  6626. if (is_array($params) && count($params) > 0) {
  6627. if (array_key_exists('class', $params)) {
  6628. $class .= $params['class'].' ';
  6629. }
  6630. if (array_key_exists('style', $params)) {
  6631. $csstyle = $params['style'];
  6632. }
  6633. }
  6634. // add html5 elements
  6635. $domData = ' data-element="extrafield"';
  6636. $domData .= ' data-targetelement="'.$this->element.'"';
  6637. $domData .= ' data-targetid="'.$this->id.'"';
  6638. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  6639. if ($display_type=='card') {
  6640. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
  6641. $colspan = '0';
  6642. }
  6643. if ($action == 'selectlines') {
  6644. $colspan++;
  6645. }
  6646. }
  6647. // Convert date into timestamp format (value in memory must be a timestamp)
  6648. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
  6649. $datenotinstring = $this->array_options['options_'.$key];
  6650. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  6651. $datenotinstring = $this->db->jdate($datenotinstring);
  6652. }
  6653. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) ? dol_mktime(12, 0, 0, GETPOST($keyprefix.'options_'.$key.$keysuffix."month", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."day", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."year", 'int', 3)) : $datenotinstring;
  6654. }
  6655. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
  6656. $datenotinstring = $this->array_options['options_'.$key];
  6657. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  6658. $datenotinstring = $this->db->jdate($datenotinstring);
  6659. }
  6660. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) ? dol_mktime(GETPOST($keyprefix.'options_'.$key.$keysuffix."hour", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."min", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."sec", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."month", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."day", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."year", 'int', 3), 'tzuserrel') : $datenotinstring;
  6661. }
  6662. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  6663. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
  6664. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? price2num($value) : $this->array_options['options_'.$key];
  6665. }
  6666. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  6667. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int'))) {
  6668. if ($action == 'create') {
  6669. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  6670. }
  6671. }
  6672. $labeltoshow = $langs->trans($label);
  6673. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  6674. if ($display_type == 'card') {
  6675. $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.' >';
  6676. $out .= '<td class="wordbreak';
  6677. } elseif ($display_type == 'line') {
  6678. $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.' >';
  6679. $out .= '<div style="display: inline-block; padding-right:4px" class="wordbreak';
  6680. }
  6681. //$out .= "titlefield";
  6682. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  6683. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  6684. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  6685. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  6686. $out .= '">';
  6687. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  6688. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  6689. } else {
  6690. $out .= $labeltoshow;
  6691. }
  6692. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  6693. $out .= '&nbsp;<font color="red">*</font>';
  6694. }
  6695. } else {
  6696. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  6697. $out .= ' fieldrequired';
  6698. }
  6699. $out .= '">';
  6700. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  6701. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  6702. } else {
  6703. $out .= $labeltoshow;
  6704. }
  6705. }
  6706. $out .= ($display_type == 'card' ? '</td>' : '</div>');
  6707. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  6708. if ($display_type == 'card') {
  6709. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="'.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  6710. } elseif ($display_type == 'line') {
  6711. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').' style="display: inline-block" class="'.$this->element.'_extras_'.$key.'">';
  6712. }
  6713. switch ($mode) {
  6714. case "view":
  6715. $out .= $extrafields->showOutputField($key, $value);
  6716. break;
  6717. case "create":
  6718. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  6719. break;
  6720. case "edit":
  6721. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  6722. break;
  6723. }
  6724. $out .= ($display_type=='card' ? '</td>' : '</div>');
  6725. /*for($ii = 0; $ii < ($colspan - 1); $ii++)
  6726. {
  6727. $out .='<td class="'.$this->element.'_extras_'.$key.'"></td>';
  6728. }*/
  6729. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
  6730. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  6731. } else {
  6732. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  6733. }
  6734. $e++;
  6735. }
  6736. }
  6737. $out .= "\n";
  6738. // Add code to manage list depending on others
  6739. if (!empty($conf->use_javascript_ajax)) {
  6740. $out .= $this->getJSListDependancies();
  6741. }
  6742. $out .= '<!-- /showOptionals --> '."\n";
  6743. }
  6744. }
  6745. $out .= $hookmanager->resPrint;
  6746. return $out;
  6747. }
  6748. /**
  6749. * @param string $type Type for prefix
  6750. * @return string Javacript code to manage dependency
  6751. */
  6752. public function getJSListDependancies($type = '_extra')
  6753. {
  6754. $out = '
  6755. <script>
  6756. jQuery(document).ready(function() {
  6757. function showOptions'.$type.'(child_list, parent_list, orig_select)
  6758. {
  6759. var val = $("select[name=\""+parent_list+"\"]").val();
  6760. var parentVal = parent_list + ":" + val;
  6761. if(typeof val == "string"){
  6762. if(val != "") {
  6763. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  6764. $("select[name=\""+child_list+"\"] option[parent]").remove();
  6765. $("select[name=\""+child_list+"\"]").append(options);
  6766. } else {
  6767. var options = orig_select.find("option[parent]").clone();
  6768. $("select[name=\""+child_list+"\"] option[parent]").remove();
  6769. $("select[name=\""+child_list+"\"]").append(options);
  6770. }
  6771. } else if(val > 0) {
  6772. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  6773. $("select[name=\""+child_list+"\"] option[parent]").remove();
  6774. $("select[name=\""+child_list+"\"]").append(options);
  6775. } else {
  6776. var options = orig_select.find("option[parent]").clone();
  6777. $("select[name=\""+child_list+"\"] option[parent]").remove();
  6778. $("select[name=\""+child_list+"\"]").append(options);
  6779. }
  6780. }
  6781. function setListDependencies'.$type.'() {
  6782. jQuery("select option[parent]").parent().each(function() {
  6783. var orig_select = {};
  6784. var child_list = $(this).attr("name");
  6785. orig_select[child_list] = $(this).clone();
  6786. var parent = $(this).find("option[parent]:first").attr("parent");
  6787. var infos = parent.split(":");
  6788. var parent_list = infos[0];
  6789. //Hide daughters lists
  6790. if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
  6791. $("#"+child_list).hide();
  6792. //Show mother lists
  6793. } else if ($("#"+parent_list).val() != 0){
  6794. $("#"+parent_list).show();
  6795. }
  6796. //Show the child list if the parent list value is selected
  6797. $("select[name=\""+parent_list+"\"]").click(function() {
  6798. if ($(this).val() != 0){
  6799. $("#"+child_list).show()
  6800. }
  6801. });
  6802. //When we change parent list
  6803. $("select[name=\""+parent_list+"\"]").change(function() {
  6804. showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
  6805. //Select the value 0 on child list after a change on the parent list
  6806. $("#"+child_list).val(0).trigger("change");
  6807. //Hide child lists if the parent value is set to 0
  6808. if ($(this).val() == 0){
  6809. $("#"+child_list).hide();
  6810. }
  6811. });
  6812. });
  6813. }
  6814. setListDependencies'.$type.'();
  6815. });
  6816. </script>'."\n";
  6817. return $out;
  6818. }
  6819. /**
  6820. * Returns the rights used for this class
  6821. * @return stdClass
  6822. */
  6823. public function getRights()
  6824. {
  6825. global $user;
  6826. $element = $this->element;
  6827. if ($element == 'facturerec') {
  6828. $element = 'facture';
  6829. }
  6830. return $user->rights->{$element};
  6831. }
  6832. /**
  6833. * Function used to replace a thirdparty id with another one.
  6834. * This function is meant to be called from replaceThirdparty with the appropiate tables
  6835. * Column name fk_soc MUST be used to identify thirdparties
  6836. *
  6837. * @param DoliDB $db Database handler
  6838. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  6839. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  6840. * @param string[] $tables Tables that need to be changed
  6841. * @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)
  6842. * @return bool True if success, False if error
  6843. */
  6844. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  6845. {
  6846. foreach ($tables as $table) {
  6847. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
  6848. if (!$db->query($sql)) {
  6849. if ($ignoreerrors) {
  6850. 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.
  6851. }
  6852. //$this->errors = $db->lasterror();
  6853. return false;
  6854. }
  6855. }
  6856. return true;
  6857. }
  6858. /**
  6859. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  6860. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  6861. * else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  6862. * else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  6863. * else set min buy price as buy price
  6864. *
  6865. * @param float $unitPrice Product unit price
  6866. * @param float $discountPercent Line discount percent
  6867. * @param int $fk_product Product id
  6868. * @return float <0 if KO, buyprice if OK
  6869. */
  6870. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  6871. {
  6872. global $conf;
  6873. $buyPrice = 0;
  6874. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
  6875. // When ForceBuyingPriceIfNull is set
  6876. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  6877. } else {
  6878. // Get cost price for margin calculation
  6879. if (!empty($fk_product)) {
  6880. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
  6881. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6882. $product = new Product($this->db);
  6883. $result = $product->fetch($fk_product);
  6884. if ($result <= 0) {
  6885. $this->errors[] = 'ErrorProductIdDoesNotExists';
  6886. return -1;
  6887. }
  6888. if ($product->cost_price > 0) {
  6889. $buyPrice = $product->cost_price;
  6890. } elseif ($product->pmp > 0) {
  6891. $buyPrice = $product->pmp;
  6892. }
  6893. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
  6894. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6895. $product = new Product($this->db);
  6896. $result = $product->fetch($fk_product);
  6897. if ($result <= 0) {
  6898. $this->errors[] = 'ErrorProductIdDoesNotExists';
  6899. return -1;
  6900. }
  6901. if ($product->pmp > 0) {
  6902. $buyPrice = $product->pmp;
  6903. }
  6904. }
  6905. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
  6906. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  6907. $productFournisseur = new ProductFournisseur($this->db);
  6908. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
  6909. $buyPrice = $productFournisseur->fourn_unitprice;
  6910. } elseif ($result < 0) {
  6911. $this->errors[] = $productFournisseur->error;
  6912. return -2;
  6913. }
  6914. }
  6915. }
  6916. }
  6917. return $buyPrice;
  6918. }
  6919. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6920. /**
  6921. * Show photos of an object (nbmax maximum), into several columns
  6922. *
  6923. * @param string $modulepart 'product', 'ticket', ...
  6924. * @param string $sdir Directory to scan (full absolute path)
  6925. * @param int $size 0=original size, 1='small' use thumbnail if possible
  6926. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  6927. * @param int $nbbyrow Number of image per line or -1 to use div. Used only if size=1.
  6928. * @param int $showfilename 1=Show filename
  6929. * @param int $showaction 1=Show icon with action links (resize, delete)
  6930. * @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.
  6931. * @param int $maxWidth Max width of original image when size='small'
  6932. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  6933. * @param int $notitle Do not add title tag on image
  6934. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  6935. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  6936. */
  6937. 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)
  6938. {
  6939. // phpcs:enable
  6940. global $conf, $user, $langs;
  6941. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  6942. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  6943. $sortfield = 'position_name';
  6944. $sortorder = 'asc';
  6945. $dir = $sdir.'/';
  6946. $pdir = '/';
  6947. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  6948. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  6949. // For backward compatibility
  6950. if ($modulepart == 'product') {
  6951. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  6952. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  6953. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  6954. }
  6955. }
  6956. // Defined relative dir to DOL_DATA_ROOT
  6957. $relativedir = '';
  6958. if ($dir) {
  6959. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  6960. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  6961. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  6962. }
  6963. $dirthumb = $dir.'thumbs/';
  6964. $pdirthumb = $pdir.'thumbs/';
  6965. $return = '<!-- Photo -->'."\n";
  6966. $nbphoto = 0;
  6967. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  6968. /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
  6969. {
  6970. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  6971. $filearray=array_merge($filearray, $filearrayold);
  6972. }*/
  6973. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  6974. if (count($filearray)) {
  6975. if ($sortfield && $sortorder) {
  6976. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  6977. }
  6978. foreach ($filearray as $key => $val) {
  6979. $photo = '';
  6980. $file = $val['name'];
  6981. //if (! utf8_check($file)) $file=utf8_encode($file); // To be sure file is stored in UTF8 in memory
  6982. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  6983. if (image_format_supported($file) >= 0) {
  6984. $nbphoto++;
  6985. $photo = $file;
  6986. $viewfilename = $file;
  6987. if ($size == 1 || $size == 'small') { // Format vignette
  6988. // Find name of thumb file
  6989. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  6990. if (!dol_is_file($dirthumb.$photo_vignette)) {
  6991. $photo_vignette = '';
  6992. }
  6993. // Get filesize of original file
  6994. $imgarray = dol_getImageSize($dir.$photo);
  6995. if ($nbbyrow > 0) {
  6996. if ($nbphoto == 1) {
  6997. $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  6998. }
  6999. if ($nbphoto % $nbbyrow == 1) {
  7000. $return .= '<tr class="center valignmiddle" style="border: 1px">';
  7001. }
  7002. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
  7003. } elseif ($nbbyrow < 0) {
  7004. $return .= '<div class="inline-block">';
  7005. }
  7006. $return .= "\n";
  7007. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  7008. if (empty($nolink)) {
  7009. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  7010. if ($urladvanced) {
  7011. $return .= '<a href="'.$urladvanced.'">';
  7012. } else {
  7013. $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
  7014. }
  7015. }
  7016. // Show image (width height=$maxHeight)
  7017. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  7018. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  7019. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  7020. if ($notitle) {
  7021. $alt = '';
  7022. }
  7023. if ($usesharelink) {
  7024. if ($val['share']) {
  7025. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7026. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  7027. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7028. } else {
  7029. $return .= '<!-- Show original file -->';
  7030. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7031. }
  7032. } else {
  7033. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  7034. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  7035. }
  7036. } else {
  7037. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7038. $return .= '<!-- Show thumb -->';
  7039. $return .= '<img class="photo photowithmargin maxwidth150onsmartphone" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdirthumb.$photo_vignette).'" title="'.dol_escape_htmltag($alt).'">';
  7040. } else {
  7041. $return .= '<!-- Show original file -->';
  7042. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" title="'.dol_escape_htmltag($alt).'">';
  7043. }
  7044. }
  7045. if (empty($nolink)) {
  7046. $return .= '</a>';
  7047. }
  7048. $return .= "\n";
  7049. if ($showfilename) {
  7050. $return .= '<br>'.$viewfilename;
  7051. }
  7052. if ($showaction) {
  7053. $return .= '<br>';
  7054. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  7055. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
  7056. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=addthumb&amp;file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'), 'refresh').'&nbsp;&nbsp;</a>';
  7057. }
  7058. // Special cas for product
  7059. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7060. // Link to resize
  7061. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&amp;file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  7062. // Link to delete
  7063. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;token='.newToken().'&amp;file='.urlencode($pdir.$viewfilename).'">';
  7064. $return .= img_delete().'</a>';
  7065. }
  7066. }
  7067. $return .= "\n";
  7068. if ($nbbyrow > 0) {
  7069. $return .= '</td>';
  7070. if (($nbphoto % $nbbyrow) == 0) {
  7071. $return .= '</tr>';
  7072. }
  7073. } elseif ($nbbyrow < 0) {
  7074. $return .= '</div>';
  7075. }
  7076. }
  7077. if (empty($size)) { // Format origine
  7078. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  7079. if ($showfilename) {
  7080. $return .= '<br>'.$viewfilename;
  7081. }
  7082. if ($showaction) {
  7083. // Special case for product
  7084. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7085. // Link to resize
  7086. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&amp;file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  7087. // Link to delete
  7088. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;token='.newToken().'&amp;file='.urlencode($pdir.$viewfilename).'">';
  7089. $return .= img_delete().'</a>';
  7090. }
  7091. }
  7092. }
  7093. // On continue ou on arrete de boucler ?
  7094. if ($nbmax && $nbphoto >= $nbmax) {
  7095. break;
  7096. }
  7097. }
  7098. }
  7099. if ($size == 1 || $size == 'small') {
  7100. if ($nbbyrow > 0) {
  7101. // Ferme tableau
  7102. while ($nbphoto % $nbbyrow) {
  7103. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  7104. $nbphoto++;
  7105. }
  7106. if ($nbphoto) {
  7107. $return .= '</table>';
  7108. }
  7109. }
  7110. }
  7111. }
  7112. $this->nbphoto = $nbphoto;
  7113. return $return;
  7114. }
  7115. /**
  7116. * Function test if type is array
  7117. *
  7118. * @param array $info content informations of field
  7119. * @return bool true if array
  7120. */
  7121. protected function isArray($info)
  7122. {
  7123. if (is_array($info)) {
  7124. if (isset($info['type']) && $info['type'] == 'array') {
  7125. return true;
  7126. } else {
  7127. return false;
  7128. }
  7129. }
  7130. return false;
  7131. }
  7132. /**
  7133. * Function test if type is date
  7134. *
  7135. * @param array $info content informations of field
  7136. * @return bool true if date
  7137. */
  7138. public function isDate($info)
  7139. {
  7140. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
  7141. return true;
  7142. }
  7143. return false;
  7144. }
  7145. /**
  7146. * Function test if type is duration
  7147. *
  7148. * @param array $info content informations of field
  7149. * @return bool true if field of type duration
  7150. */
  7151. public function isDuration($info)
  7152. {
  7153. if (is_array($info)) {
  7154. if (isset($info['type']) && ($info['type'] == 'duration')) {
  7155. return true;
  7156. } else {
  7157. return false;
  7158. }
  7159. } else {
  7160. return false;
  7161. }
  7162. }
  7163. /**
  7164. * Function test if type is integer
  7165. *
  7166. * @param array $info content informations of field
  7167. * @return bool true if integer
  7168. */
  7169. public function isInt($info)
  7170. {
  7171. if (is_array($info)) {
  7172. if (isset($info['type']) && ($info['type'] == 'int' || preg_match('/^integer/i', $info['type']))) {
  7173. return true;
  7174. } else {
  7175. return false;
  7176. }
  7177. } else {
  7178. return false;
  7179. }
  7180. }
  7181. /**
  7182. * Function test if type is float
  7183. *
  7184. * @param array $info content informations of field
  7185. * @return bool true if float
  7186. */
  7187. public function isFloat($info)
  7188. {
  7189. if (is_array($info)) {
  7190. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
  7191. return true;
  7192. } else {
  7193. return false;
  7194. }
  7195. }
  7196. return false;
  7197. }
  7198. /**
  7199. * Function test if type is text
  7200. *
  7201. * @param array $info content informations of field
  7202. * @return bool true if type text
  7203. */
  7204. public function isText($info)
  7205. {
  7206. if (is_array($info)) {
  7207. if (isset($info['type']) && $info['type'] == 'text') {
  7208. return true;
  7209. } else {
  7210. return false;
  7211. }
  7212. }
  7213. return false;
  7214. }
  7215. /**
  7216. * Function test if field can be null
  7217. *
  7218. * @param array $info content informations of field
  7219. * @return bool true if it can be null
  7220. */
  7221. protected function canBeNull($info)
  7222. {
  7223. if (is_array($info)) {
  7224. if (isset($info['notnull']) && $info['notnull'] != '1') {
  7225. return true;
  7226. } else {
  7227. return false;
  7228. }
  7229. }
  7230. return true;
  7231. }
  7232. /**
  7233. * Function test if field is forced to null if zero or empty
  7234. *
  7235. * @param array $info content informations of field
  7236. * @return bool true if forced to null
  7237. */
  7238. protected function isForcedToNullIfZero($info)
  7239. {
  7240. if (is_array($info)) {
  7241. if (isset($info['notnull']) && $info['notnull'] == '-1') {
  7242. return true;
  7243. } else {
  7244. return false;
  7245. }
  7246. }
  7247. return false;
  7248. }
  7249. /**
  7250. * Function test if is indexed
  7251. *
  7252. * @param array $info content informations of field
  7253. * @return bool
  7254. */
  7255. protected function isIndex($info)
  7256. {
  7257. if (is_array($info)) {
  7258. if (isset($info['index']) && $info['index'] == true) {
  7259. return true;
  7260. } else {
  7261. return false;
  7262. }
  7263. }
  7264. return false;
  7265. }
  7266. /**
  7267. * Function to prepare a part of the query for insert.
  7268. * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
  7269. * $this->${field} should be a clean value. The page can run
  7270. *
  7271. * @return array
  7272. */
  7273. protected function setSaveQuery()
  7274. {
  7275. global $conf;
  7276. $queryarray = array();
  7277. foreach ($this->fields as $field => $info) { // Loop on definition of fields
  7278. // Depending on field type ('datetime', ...)
  7279. if ($this->isDate($info)) {
  7280. if (empty($this->{$field})) {
  7281. $queryarray[$field] = null;
  7282. } else {
  7283. $queryarray[$field] = $this->db->idate($this->{$field});
  7284. }
  7285. } elseif ($this->isDuration($info)) {
  7286. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7287. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7288. if (!isset($this->{$field})) {
  7289. $queryarray[$field] = 0;
  7290. } else {
  7291. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7292. }
  7293. } else {
  7294. $queryarray[$field] = null;
  7295. }
  7296. } elseif ($this->isInt($info) || $this->isFloat($info)) {
  7297. if ($field == 'entity' && is_null($this->{$field})) {
  7298. $queryarray[$field] = $conf->entity;
  7299. } else {
  7300. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7301. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7302. if (!isset($this->{$field})) {
  7303. $queryarray[$field] = 0;
  7304. } elseif ($this->isInt($info)) {
  7305. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7306. } elseif ($this->isFloat($info)) {
  7307. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7308. }
  7309. } else {
  7310. $queryarray[$field] = null;
  7311. }
  7312. }
  7313. } else {
  7314. $queryarray[$field] = $this->{$field};
  7315. }
  7316. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
  7317. unset($queryarray[$field]);
  7318. }
  7319. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
  7320. $queryarray[$field] = null; // May force 0 to null
  7321. }
  7322. }
  7323. return $queryarray;
  7324. }
  7325. /**
  7326. * Function to load data from a SQL pointer into properties of current object $this
  7327. *
  7328. * @param stdClass $obj Contain data of object from database
  7329. * @return void
  7330. */
  7331. public function setVarsFromFetchObj(&$obj)
  7332. {
  7333. global $db;
  7334. foreach ($this->fields as $field => $info) {
  7335. if ($this->isDate($info)) {
  7336. if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
  7337. $this->{$field} = '';
  7338. } else {
  7339. $this->{$field} = $db->jdate($obj->{$field});
  7340. }
  7341. } elseif ($this->isInt($info)) {
  7342. if ($field == 'rowid') {
  7343. $this->id = (int) $obj->{$field};
  7344. } else {
  7345. if ($this->isForcedToNullIfZero($info)) {
  7346. if (empty($obj->{$field})) {
  7347. $this->{$field} = null;
  7348. } else {
  7349. $this->{$field} = (double) $obj->{$field};
  7350. }
  7351. } else {
  7352. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7353. $this->{$field} = (int) $obj->{$field};
  7354. } else {
  7355. $this->{$field} = null;
  7356. }
  7357. }
  7358. }
  7359. } elseif ($this->isFloat($info)) {
  7360. if ($this->isForcedToNullIfZero($info)) {
  7361. if (empty($obj->{$field})) {
  7362. $this->{$field} = null;
  7363. } else {
  7364. $this->{$field} = (double) $obj->{$field};
  7365. }
  7366. } else {
  7367. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7368. $this->{$field} = (double) $obj->{$field};
  7369. } else {
  7370. $this->{$field} = null;
  7371. }
  7372. }
  7373. } else {
  7374. $this->{$field} = $obj->{$field};
  7375. }
  7376. }
  7377. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  7378. if (!isset($this->fields['ref']) && isset($this->id)) {
  7379. $this->ref = $this->id;
  7380. }
  7381. }
  7382. /**
  7383. * Function to concat keys of fields
  7384. *
  7385. * @param string $alias String of alias of table for fields. For example 't'.
  7386. * @return string list of alias fields
  7387. */
  7388. public function getFieldList($alias = '')
  7389. {
  7390. $keys = array_keys($this->fields);
  7391. if (!empty($alias)) {
  7392. $keys_with_alias = array();
  7393. foreach ($keys as $fieldname) {
  7394. $keys_with_alias[] = $alias . '.' . $fieldname;
  7395. }
  7396. return implode(',', $keys_with_alias);
  7397. } else {
  7398. return implode(',', $keys);
  7399. }
  7400. }
  7401. /**
  7402. * Add quote to field value if necessary
  7403. *
  7404. * @param string|int $value Value to protect
  7405. * @param array $fieldsentry Properties of field
  7406. * @return string
  7407. */
  7408. protected function quote($value, $fieldsentry)
  7409. {
  7410. if (is_null($value)) {
  7411. return 'NULL';
  7412. } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
  7413. return $this->db->escape("$value");
  7414. } elseif ($fieldsentry['type'] == 'boolean') {
  7415. if ($value) {
  7416. return 'true';
  7417. } else {
  7418. return 'false';
  7419. }
  7420. } else {
  7421. return "'".$this->db->escape($value)."'";
  7422. }
  7423. }
  7424. /**
  7425. * Create object into database
  7426. *
  7427. * @param User $user User that creates
  7428. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7429. * @return int <0 if KO, Id of created object if OK
  7430. */
  7431. public function createCommon(User $user, $notrigger = false)
  7432. {
  7433. global $langs;
  7434. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  7435. $error = 0;
  7436. $now = dol_now();
  7437. $fieldvalues = $this->setSaveQuery();
  7438. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
  7439. $fieldvalues['date_creation'] = $this->db->idate($now);
  7440. }
  7441. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
  7442. $fieldvalues['fk_user_creat'] = $user->id;
  7443. }
  7444. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  7445. if (array_key_exists('ref', $fieldvalues)) {
  7446. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  7447. }
  7448. $keys = array();
  7449. $values = array(); // Array to store string forged for SQL syntax
  7450. foreach ($fieldvalues as $k => $v) {
  7451. $keys[$k] = $k;
  7452. $value = $this->fields[$k];
  7453. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  7454. }
  7455. // Clean and check mandatory
  7456. foreach ($keys as $key) {
  7457. // If field is an implicit foreign key field
  7458. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  7459. $values[$key] = '';
  7460. }
  7461. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  7462. $values[$key] = '';
  7463. }
  7464. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
  7465. $error++;
  7466. $langs->load("errors");
  7467. dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
  7468. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  7469. }
  7470. // If value is null and there is a default value for field
  7471. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
  7472. $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
  7473. }
  7474. // If field is an implicit foreign key field
  7475. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  7476. if (isset($this->fields[$key]['default'])) {
  7477. $values[$key] = $this->fields[$key]['default'];
  7478. } else {
  7479. $values[$key] = 'null';
  7480. }
  7481. }
  7482. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
  7483. $values[$key] = 'null';
  7484. }
  7485. }
  7486. if ($error) {
  7487. return -1;
  7488. }
  7489. $this->db->begin();
  7490. if (!$error) {
  7491. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
  7492. $sql .= ' ('.implode(", ", $keys).')';
  7493. $sql .= ' VALUES ('.implode(", ", $values).')';
  7494. $res = $this->db->query($sql);
  7495. if ($res === false) {
  7496. $error++;
  7497. $this->errors[] = $this->db->lasterror();
  7498. }
  7499. }
  7500. if (!$error) {
  7501. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
  7502. }
  7503. // If we have a field ref with a default value of (PROV)
  7504. if (!$error) {
  7505. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
  7506. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ref = '(PROV".$this->id.")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
  7507. $resqlupdate = $this->db->query($sql);
  7508. if ($resqlupdate === false) {
  7509. $error++;
  7510. $this->errors[] = $this->db->lasterror();
  7511. } else {
  7512. $this->ref = '(PROV'.$this->id.')';
  7513. }
  7514. }
  7515. }
  7516. // Create extrafields
  7517. if (!$error) {
  7518. $result = $this->insertExtraFields();
  7519. if ($result < 0) {
  7520. $error++;
  7521. }
  7522. }
  7523. // Create lines
  7524. if (!empty($this->table_element_line) && !empty($this->fk_element)) {
  7525. $num = (is_array($this->lines) ? count($this->lines) : 0);
  7526. for ($i = 0; $i < $num; $i++) {
  7527. $line = $this->lines[$i];
  7528. $keyforparent = $this->fk_element;
  7529. $line->$keyforparent = $this->id;
  7530. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  7531. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  7532. if (!is_object($line)) {
  7533. $line = (object) $line;
  7534. }
  7535. $result = $line->create($user, 1);
  7536. if ($result < 0) {
  7537. $this->error = $line->error;
  7538. $this->db->rollback();
  7539. return -1;
  7540. }
  7541. }
  7542. }
  7543. // Triggers
  7544. if (!$error && !$notrigger) {
  7545. // Call triggers
  7546. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  7547. if ($result < 0) {
  7548. $error++;
  7549. }
  7550. // End call triggers
  7551. }
  7552. // Commit or rollback
  7553. if ($error) {
  7554. $this->db->rollback();
  7555. return -1;
  7556. } else {
  7557. $this->db->commit();
  7558. return $this->id;
  7559. }
  7560. }
  7561. /**
  7562. * Load object in memory from the database
  7563. *
  7564. * @param int $id Id object
  7565. * @param string $ref Ref
  7566. * @param string $morewhere More SQL filters (' AND ...')
  7567. * @return int <0 if KO, 0 if not found, >0 if OK
  7568. */
  7569. public function fetchCommon($id, $ref = null, $morewhere = '')
  7570. {
  7571. if (empty($id) && empty($ref) && empty($morewhere)) {
  7572. return -1;
  7573. }
  7574. $fieldlist = $this->getFieldList('t');
  7575. if (empty($fieldlist)) {
  7576. return 0;
  7577. }
  7578. $sql = 'SELECT '.$fieldlist;
  7579. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  7580. if (!empty($id)) {
  7581. $sql .= ' WHERE t.rowid = '.((int) $id);
  7582. } elseif (!empty($ref)) {
  7583. $sql .= " WHERE t.ref = ".$this->quote($ref, $this->fields['ref']);
  7584. } else {
  7585. $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  7586. }
  7587. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  7588. $sql .= ' AND t.entity IN ('.getEntity($this->table_element).')';
  7589. }
  7590. if ($morewhere) {
  7591. $sql .= $morewhere;
  7592. }
  7593. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  7594. $res = $this->db->query($sql);
  7595. if ($res) {
  7596. $obj = $this->db->fetch_object($res);
  7597. if ($obj) {
  7598. $this->setVarsFromFetchObj($obj);
  7599. // Retrieve all extrafield
  7600. // fetch optionals attributes and labels
  7601. $this->fetch_optionals();
  7602. dol_syslog("aaa=".$this->id);
  7603. return $this->id;
  7604. } else {
  7605. return 0;
  7606. }
  7607. } else {
  7608. $this->error = $this->db->lasterror();
  7609. $this->errors[] = $this->error;
  7610. return -1;
  7611. }
  7612. }
  7613. /**
  7614. * Load object in memory from the database
  7615. *
  7616. * @param string $morewhere More SQL filters (' AND ...')
  7617. * @return int <0 if KO, 0 if not found, >0 if OK
  7618. */
  7619. public function fetchLinesCommon($morewhere = '')
  7620. {
  7621. $objectlineclassname = get_class($this).'Line';
  7622. if (!class_exists($objectlineclassname)) {
  7623. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  7624. return -1;
  7625. }
  7626. $objectline = new $objectlineclassname($this->db);
  7627. $sql = 'SELECT '.$objectline->getFieldList('l');
  7628. $sql .= ' FROM '.MAIN_DB_PREFIX.$objectline->table_element.' as l';
  7629. $sql .= ' WHERE l.fk_'.$this->element.' = '.$this->id;
  7630. if ($morewhere) {
  7631. $sql .= $morewhere;
  7632. }
  7633. if (isset($objectline->fields['position'])) {
  7634. $sql .= $this->db->order('position', 'ASC');
  7635. }
  7636. $resql = $this->db->query($sql);
  7637. if ($resql) {
  7638. $num_rows = $this->db->num_rows($resql);
  7639. $i = 0;
  7640. while ($i < $num_rows) {
  7641. $obj = $this->db->fetch_object($resql);
  7642. if ($obj) {
  7643. $newline = new $objectlineclassname($this->db);
  7644. $newline->setVarsFromFetchObj($obj);
  7645. $this->lines[] = $newline;
  7646. }
  7647. $i++;
  7648. }
  7649. return 1;
  7650. } else {
  7651. $this->error = $this->db->lasterror();
  7652. $this->errors[] = $this->error;
  7653. return -1;
  7654. }
  7655. }
  7656. /**
  7657. * Update object into database
  7658. *
  7659. * @param User $user User that modifies
  7660. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7661. * @return int <0 if KO, >0 if OK
  7662. */
  7663. public function updateCommon(User $user, $notrigger = false)
  7664. {
  7665. global $conf, $langs;
  7666. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  7667. $error = 0;
  7668. $now = dol_now();
  7669. $fieldvalues = $this->setSaveQuery();
  7670. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
  7671. $fieldvalues['date_modification'] = $this->db->idate($now);
  7672. }
  7673. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
  7674. $fieldvalues['fk_user_modif'] = $user->id;
  7675. }
  7676. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  7677. if (array_key_exists('ref', $fieldvalues)) {
  7678. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  7679. }
  7680. // Add quotes and escape on fields with type string
  7681. $keys = array();
  7682. $values = array();
  7683. $tmp = array();
  7684. foreach ($fieldvalues as $k => $v) {
  7685. $keys[$k] = $k;
  7686. $value = $this->fields[$k];
  7687. $values[$k] = $this->quote($v, $value);
  7688. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  7689. }
  7690. // Clean and check mandatory fields
  7691. foreach ($keys as $key) {
  7692. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  7693. $values[$key] = ''; // This is an implicit foreign key field
  7694. }
  7695. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  7696. $values[$key] = ''; // This is an explicit foreign key field
  7697. }
  7698. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  7699. /*
  7700. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  7701. {
  7702. $error++;
  7703. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  7704. }*/
  7705. }
  7706. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
  7707. $this->db->begin();
  7708. if (!$error) {
  7709. $res = $this->db->query($sql);
  7710. if ($res === false) {
  7711. $error++;
  7712. $this->errors[] = $this->db->lasterror();
  7713. }
  7714. }
  7715. // Update extrafield
  7716. if (!$error) {
  7717. $result = $this->insertExtraFields();
  7718. if ($result < 0) {
  7719. $error++;
  7720. }
  7721. }
  7722. // Triggers
  7723. if (!$error && !$notrigger) {
  7724. // Call triggers
  7725. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  7726. if ($result < 0) {
  7727. $error++;
  7728. } //Do also here what you must do to rollback action if trigger fail
  7729. // End call triggers
  7730. }
  7731. // Commit or rollback
  7732. if ($error) {
  7733. $this->db->rollback();
  7734. return -1;
  7735. } else {
  7736. $this->db->commit();
  7737. return $this->id;
  7738. }
  7739. }
  7740. /**
  7741. * Delete object in database
  7742. *
  7743. * @param User $user User that deletes
  7744. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7745. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  7746. * @return int <=0 if KO, >0 if OK
  7747. */
  7748. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  7749. {
  7750. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  7751. $error = 0;
  7752. $this->db->begin();
  7753. if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
  7754. foreach ($this->childtables as $table) {
  7755. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
  7756. $resql = $this->db->query($sql);
  7757. if (!$resql) {
  7758. $this->error = $this->db->lasterror();
  7759. $this->errors[] = $this->error;
  7760. $this->db->rollback();
  7761. return -1;
  7762. }
  7763. }
  7764. } elseif (!empty($this->fk_element) && !empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
  7765. $objectisused = $this->isObjectUsed($this->id);
  7766. if (!empty($objectisused)) {
  7767. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  7768. $this->error = 'ErrorRecordHasChildren';
  7769. $this->errors[] = $this->error;
  7770. $this->db->rollback();
  7771. return 0;
  7772. }
  7773. }
  7774. // Delete cascade first
  7775. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  7776. foreach ($this->childtablesoncascade as $table) {
  7777. $deleteFromObject = explode(':', $table);
  7778. if (count($deleteFromObject) >= 2) {
  7779. $className = str_replace('@', '', $deleteFromObject[0]);
  7780. $filePath = $deleteFromObject[1];
  7781. $columnName = $deleteFromObject[2];
  7782. if (dol_include_once($filePath)) {
  7783. $childObject = new $className($this->db);
  7784. if (method_exists($childObject, 'deleteByParentField')) {
  7785. $result = $childObject->deleteByParentField($this->id, $columnName);
  7786. if ($result < 0) {
  7787. $error++;
  7788. $this->errors[] = $childObject->error;
  7789. break;
  7790. }
  7791. } else {
  7792. $error++;
  7793. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  7794. break;
  7795. }
  7796. } else {
  7797. $error++;
  7798. $this->errors[] = 'Cannot include child class file '.$filePath;
  7799. break;
  7800. }
  7801. } else {
  7802. // Delete record in child table
  7803. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
  7804. $resql = $this->db->query($sql);
  7805. if (!$resql) {
  7806. $error++;
  7807. $this->error = $this->db->lasterror();
  7808. $this->errors[] = $this->error;
  7809. break;
  7810. }
  7811. }
  7812. }
  7813. }
  7814. if (!$error) {
  7815. if (!$notrigger) {
  7816. // Call triggers
  7817. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  7818. if ($result < 0) {
  7819. $error++;
  7820. } // Do also here what you must do to rollback action if trigger fail
  7821. // End call triggers
  7822. }
  7823. }
  7824. // Delete llx_ecm_files
  7825. if (!$error) {
  7826. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  7827. if (!$res) {
  7828. $error++;
  7829. }
  7830. }
  7831. if (!$error && !empty($this->isextrafieldmanaged)) {
  7832. $result = $this->deleteExtraFields();
  7833. if ($result < 0) {
  7834. $error++;
  7835. }
  7836. }
  7837. if (!$error) {
  7838. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.((int) $this->id);
  7839. $resql = $this->db->query($sql);
  7840. if (!$resql) {
  7841. $error++;
  7842. $this->errors[] = $this->db->lasterror();
  7843. }
  7844. }
  7845. // Commit or rollback
  7846. if ($error) {
  7847. $this->db->rollback();
  7848. return -1;
  7849. } else {
  7850. $this->db->commit();
  7851. return 1;
  7852. }
  7853. }
  7854. /**
  7855. * Delete all child object from a parent ID
  7856. *
  7857. * @param int $parentId Parent Id
  7858. * @param string $parentField Name of Foreign key parent column
  7859. * @return int <0 if KO, >0 if OK
  7860. * @throws Exception
  7861. */
  7862. public function deleteByParentField($parentId = 0, $parentField = '')
  7863. {
  7864. global $user;
  7865. $error = 0;
  7866. $deleted = 0;
  7867. if (!empty($parentId) && !empty($parentField)) {
  7868. $this->db->begin();
  7869. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$this->table_element;
  7870. $sql .= ' WHERE '.$parentField.' = '.(int) $parentId;
  7871. $resql = $this->db->query($sql);
  7872. if (!$resql) {
  7873. $this->errors[] = $this->db->lasterror();
  7874. $error++;
  7875. } else {
  7876. while ($obj = $this->db->fetch_object($resql)) {
  7877. $result = $this->fetch($obj->rowid);
  7878. if ($result < 0) {
  7879. $error++;
  7880. $this->errors[] = $this->error;
  7881. } else {
  7882. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  7883. $result = $this->delete();
  7884. } else {
  7885. $result = $this->delete($user);
  7886. }
  7887. if ($result < 0) {
  7888. $error++;
  7889. $this->errors[] = $this->error;
  7890. } else {
  7891. $deleted++;
  7892. }
  7893. }
  7894. }
  7895. }
  7896. if (empty($error)) {
  7897. $this->db->commit();
  7898. return $deleted;
  7899. } else {
  7900. $this->error = implode(', ', $this->errors);
  7901. $this->db->rollback();
  7902. return $error * -1;
  7903. }
  7904. }
  7905. return $deleted;
  7906. }
  7907. /**
  7908. * Delete a line of object in database
  7909. *
  7910. * @param User $user User that delete
  7911. * @param int $idline Id of line to delete
  7912. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7913. * @return int >0 if OK, <0 if KO
  7914. */
  7915. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  7916. {
  7917. global $conf;
  7918. $error = 0;
  7919. $tmpforobjectclass = get_class($this);
  7920. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  7921. // Call trigger
  7922. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  7923. if ($result < 0) {
  7924. return -1;
  7925. }
  7926. // End call triggers
  7927. $this->db->begin();
  7928. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  7929. $sql .= " WHERE rowid = ".((int) $idline);
  7930. dol_syslog(get_class($this)."::deleteLineCommon", LOG_DEBUG);
  7931. $resql = $this->db->query($sql);
  7932. if (!$resql) {
  7933. $this->error = "Error ".$this->db->lasterror();
  7934. $error++;
  7935. }
  7936. if (empty($error)) {
  7937. // Remove extrafields
  7938. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  7939. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  7940. $tmpobjectline->id = $idline;
  7941. $result = $tmpobjectline->deleteExtraFields();
  7942. if ($result < 0) {
  7943. $error++;
  7944. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  7945. }
  7946. }
  7947. }
  7948. if (empty($error)) {
  7949. $this->db->commit();
  7950. return 1;
  7951. } else {
  7952. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  7953. $this->db->rollback();
  7954. return -1;
  7955. }
  7956. }
  7957. /**
  7958. * Set to a status
  7959. *
  7960. * @param User $user Object user that modify
  7961. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  7962. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  7963. * @param string $triggercode Trigger code to use
  7964. * @return int <0 if KO, >0 if OK
  7965. */
  7966. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  7967. {
  7968. $error = 0;
  7969. $this->db->begin();
  7970. $statusfield = 'status';
  7971. if ($this->element == 'don' || $this->element == 'donation') {
  7972. $statusfield = 'fk_statut';
  7973. }
  7974. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  7975. $sql .= " SET ".$statusfield." = ".((int) $status);
  7976. $sql .= " WHERE rowid = ".$this->id;
  7977. if ($this->db->query($sql)) {
  7978. if (!$error) {
  7979. $this->oldcopy = clone $this;
  7980. }
  7981. if (!$error && !$notrigger) {
  7982. // Call trigger
  7983. $result = $this->call_trigger($triggercode, $user);
  7984. if ($result < 0) {
  7985. $error++;
  7986. }
  7987. }
  7988. if (!$error) {
  7989. $this->status = $status;
  7990. $this->db->commit();
  7991. return 1;
  7992. } else {
  7993. $this->db->rollback();
  7994. return -1;
  7995. }
  7996. } else {
  7997. $this->error = $this->db->error();
  7998. $this->db->rollback();
  7999. return -1;
  8000. }
  8001. }
  8002. /**
  8003. * Initialise object with example values
  8004. * Id must be 0 if object instance is a specimen
  8005. *
  8006. * @return int
  8007. */
  8008. public function initAsSpecimenCommon()
  8009. {
  8010. global $user;
  8011. $this->id = 0;
  8012. $this->specimen = 1;
  8013. $fields = array(
  8014. 'label' => 'This is label',
  8015. 'ref' => 'ABCD1234',
  8016. 'description' => 'This is a description',
  8017. 'qty' => 123.12,
  8018. 'note_public' => 'Public note',
  8019. 'note_private' => 'Private note',
  8020. 'date_creation' => (dol_now() - 3600 * 48),
  8021. 'date_modification' => (dol_now() - 3600 * 24),
  8022. 'fk_user_creat' => $user->id,
  8023. 'fk_user_modif' => $user->id,
  8024. 'date' => dol_now(),
  8025. );
  8026. foreach ($fields as $key => $value) {
  8027. if (array_key_exists($key, $this->fields)) {
  8028. $this->{$key} = $value;
  8029. }
  8030. }
  8031. return 1;
  8032. }
  8033. /* Part for comments */
  8034. /**
  8035. * Load comments linked with current task
  8036. * @return boolean 1 if ok
  8037. */
  8038. public function fetchComments()
  8039. {
  8040. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  8041. $comment = new Comment($this->db);
  8042. $result = $comment->fetchAllFor($this->element, $this->id);
  8043. if ($result < 0) {
  8044. $this->errors = array_merge($this->errors, $comment->errors);
  8045. return -1;
  8046. } else {
  8047. $this->comments = $comment->comments;
  8048. }
  8049. return count($this->comments);
  8050. }
  8051. /**
  8052. * Return nb comments already posted
  8053. *
  8054. * @return int
  8055. */
  8056. public function getNbComments()
  8057. {
  8058. return count($this->comments);
  8059. }
  8060. /**
  8061. * Trim object parameters
  8062. *
  8063. * @param string[] $parameters array of parameters to trim
  8064. * @return void
  8065. */
  8066. public function trimParameters($parameters)
  8067. {
  8068. if (!is_array($parameters)) {
  8069. return;
  8070. }
  8071. foreach ($parameters as $parameter) {
  8072. if (isset($this->$parameter)) {
  8073. $this->$parameter = trim($this->$parameter);
  8074. }
  8075. }
  8076. }
  8077. /* Part for categories/tags */
  8078. /**
  8079. * Sets object to given categories.
  8080. *
  8081. * Deletes object from existing categories not supplied.
  8082. * Adds it to non existing supplied categories.
  8083. * Existing categories are left untouch.
  8084. *
  8085. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  8086. * @return int Array of category objects or < 0 if KO
  8087. */
  8088. public function getCategoriesCommon($type_categ)
  8089. {
  8090. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8091. // Get current categories
  8092. $c = new Categorie($this->db);
  8093. $existing = $c->containing($this->id, $type_categ, 'id');
  8094. return $existing;
  8095. }
  8096. /**
  8097. * Sets object to given categories.
  8098. *
  8099. * Adds it to non existing supplied categories.
  8100. * Deletes object from existing categories not supplied (if remove_existing==true).
  8101. * Existing categories are left untouch.
  8102. *
  8103. * @param int[]|int $categories Category ID or array of Categories IDs
  8104. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) definied into const class Categorie type
  8105. * @param boolean $remove_existing True: Remove existings categories from Object if not supplies by $categories, False: let them
  8106. * @return int <0 if KO, >0 if OK
  8107. */
  8108. public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
  8109. {
  8110. dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
  8111. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8112. if (empty($type_categ)) {
  8113. dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
  8114. return -1;
  8115. }
  8116. // Handle single category
  8117. if (!is_array($categories)) {
  8118. $categories = array($categories);
  8119. }
  8120. // Get current categories
  8121. $c = new Categorie($this->db);
  8122. $existing = $c->containing($this->id, $type_categ, 'id');
  8123. if ($remove_existing) {
  8124. // Diff
  8125. if (is_array($existing)) {
  8126. $to_del = array_diff($existing, $categories);
  8127. $to_add = array_diff($categories, $existing);
  8128. } else {
  8129. $to_del = array(); // Nothing to delete
  8130. $to_add = $categories;
  8131. }
  8132. } else {
  8133. $to_del = array(); // Nothing to delete
  8134. $to_add = array_diff($categories, $existing);
  8135. }
  8136. $error = 0;
  8137. $ok=0;
  8138. // Process
  8139. foreach ($to_del as $del) {
  8140. if ($c->fetch($del) > 0) {
  8141. $result=$c->del_type($this, $type_categ);
  8142. if ($result < 0) {
  8143. $error++;
  8144. $this->error = $c->error;
  8145. $this->errors = $c->errors;
  8146. break;
  8147. } else {
  8148. $ok+=$result;
  8149. }
  8150. }
  8151. }
  8152. foreach ($to_add as $add) {
  8153. if ($c->fetch($add) > 0) {
  8154. $result = $c->add_type($this, $type_categ);
  8155. if ($result < 0) {
  8156. $error++;
  8157. $this->error = $c->error;
  8158. $this->errors = $c->errors;
  8159. break;
  8160. } else {
  8161. $ok+=$result;
  8162. }
  8163. }
  8164. }
  8165. return $error ? -1 * $error : $ok;
  8166. }
  8167. /**
  8168. * Copy related categories to another object
  8169. *
  8170. * @param int $fromId Id object source
  8171. * @param int $toId Id object cible
  8172. * @param string $type Type of category ('product', ...)
  8173. * @return int < 0 if error, > 0 if ok
  8174. */
  8175. public function cloneCategories($fromId, $toId, $type = '')
  8176. {
  8177. $this->db->begin();
  8178. if (empty($type)) {
  8179. $type = $this->table_element;
  8180. }
  8181. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8182. $categorystatic = new Categorie($this->db);
  8183. $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  8184. $sql .= " SELECT fk_categorie, $toId FROM ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  8185. $sql .= " WHERE fk_product = ".((int) $fromId);
  8186. if (!$this->db->query($sql)) {
  8187. $this->error = $this->db->lasterror();
  8188. $this->db->rollback();
  8189. return -1;
  8190. }
  8191. $this->db->commit();
  8192. return 1;
  8193. }
  8194. /**
  8195. * Delete related files of object in database
  8196. *
  8197. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  8198. * @return bool True if OK, False if KO
  8199. */
  8200. public function deleteEcmFiles($mode = 0)
  8201. {
  8202. global $conf;
  8203. $this->db->begin();
  8204. // Delete in database with mode 0
  8205. if ($mode == 0) {
  8206. switch ($this->element) {
  8207. case 'propal':
  8208. $element = 'propale';
  8209. break;
  8210. case 'product':
  8211. $element = 'produit';
  8212. break;
  8213. case 'order_supplier':
  8214. $element = 'fournisseur/commande';
  8215. break;
  8216. case 'invoice_supplier':
  8217. $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  8218. break;
  8219. case 'shipping':
  8220. $element = 'expedition/sending';
  8221. break;
  8222. default:
  8223. $element = $this->element;
  8224. }
  8225. // Delete ecm_files extrafields
  8226. $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files_extrafields WHERE fk_object IN (";
  8227. $sql .= " SELECT rowid FROM ".MAIN_DB_PREFIX."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8228. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".$conf->entity; // No need of getEntity here
  8229. $sql .= ")";
  8230. if (!$this->db->query($sql)) {
  8231. $this->error = $this->db->lasterror();
  8232. $this->db->rollback();
  8233. return false;
  8234. }
  8235. // Delete ecm_files
  8236. $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files";
  8237. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8238. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".$conf->entity; // No need of getEntity here
  8239. if (!$this->db->query($sql)) {
  8240. $this->error = $this->db->lasterror();
  8241. $this->db->rollback();
  8242. return false;
  8243. }
  8244. }
  8245. // Delete in database with mode 1
  8246. if ($mode == 1) {
  8247. $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files_extrafields";
  8248. $sql .= " WHERE fk_object IN (SELECT rowid FROM ".MAIN_DB_PREFIX."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? '' : '@'.$this->module))."' AND src_object_id = ".$this->id.")";
  8249. $resql = $this->db->query($sql);
  8250. if (!$resql) {
  8251. $this->error = $this->db->lasterror();
  8252. $this->db->rollback();
  8253. return false;
  8254. }
  8255. $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files";
  8256. $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? '' : '@'.$this->module))."' AND src_object_id = ".((int) $this->id);
  8257. $resql = $this->db->query($sql);
  8258. if (!$resql) {
  8259. $this->error = $this->db->lasterror();
  8260. $this->db->rollback();
  8261. return false;
  8262. }
  8263. }
  8264. $this->db->commit();
  8265. return true;
  8266. }
  8267. }