commonobject.class.php 340 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860
  1. <?php
  2. /* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
  5. * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
  6. * Copyright (C) 2011-2019 Philippe Grand <philippe.grand@atoo-net.com>
  7. * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
  8. * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  9. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  10. * Copyright (C) 2015-2022 Alexandre Spangaro <aspangaro@open-dsi.fr>
  11. * Copyright (C) 2016 Bahfir abbes <dolipar@dolipar.org>
  12. * Copyright (C) 2017 ATM Consulting <support@atm-consulting.fr>
  13. * Copyright (C) 2017-2019 Nicolas ZABOURI <info@inovea-conseil.com>
  14. * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
  15. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  16. * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
  17. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  18. * Copyright (C) 2021 Grégory Blémand <gregory.blemand@atm-consulting.fr>
  19. *
  20. * This program is free software; you can redistribute it and/or modify
  21. * it under the terms of the GNU General Public License as published by
  22. * the Free Software Foundation; either version 3 of the License, or
  23. * (at your option) any later version.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU General Public License
  31. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  32. */
  33. /**
  34. * \file htdocs/core/class/commonobject.class.php
  35. * \ingroup core
  36. * \brief File of parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  37. */
  38. /**
  39. * Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  40. */
  41. abstract class CommonObject
  42. {
  43. const TRIGGER_PREFIX = ''; // to be overriden in child class implementations, i.e. 'BILL', 'TASK', 'PROPAL', etc.
  44. /**
  45. * @var DoliDb Database handler (result of a new DoliDB)
  46. */
  47. public $db;
  48. /**
  49. * @var int The object identifier
  50. */
  51. public $id;
  52. /**
  53. * @var int The environment ID when using a multicompany module
  54. */
  55. public $entity;
  56. /**
  57. * @var string Error string
  58. * @see $errors
  59. */
  60. public $error;
  61. /**
  62. * @var string Error string that is hidden but can be used to store complementatry technical code.
  63. */
  64. public $errorhidden;
  65. /**
  66. * @var string[] Array of error strings
  67. */
  68. public $errors = array();
  69. /**
  70. * @var array To store error results of ->validateField()
  71. */
  72. public $validateFieldsErrors = array();
  73. /**
  74. * @var string ID to identify managed object
  75. */
  76. public $element;
  77. /**
  78. * @var string Name to use for 'features' parameter to check module permissions with restrictedArea(). Undefined means same value than $element.
  79. */
  80. public $element_for_permission;
  81. /**
  82. * @var string Name of table without prefix where object is stored
  83. */
  84. public $table_element;
  85. /**
  86. * @var string Name of subtable line
  87. */
  88. public $table_element_line = '';
  89. /**
  90. * @var string Key value used to track if data is coming from import wizard
  91. */
  92. public $import_key;
  93. /**
  94. * @var mixed Contains data to manage extrafields
  95. */
  96. public $array_options = array();
  97. /**
  98. * @var mixed Array to store alternative languages values of object
  99. */
  100. public $array_languages = null; // Value is array() when load already tried
  101. /**
  102. * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked
  103. */
  104. public $linkedObjectsIds;
  105. /**
  106. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  107. */
  108. public $linkedObjects;
  109. /**
  110. * @var boolean Array of boolean with object id as key and value as true if linkedObjects full loaded. Loaded by ->fetchObjectLinked. Important for pdf generation time reduction.
  111. */
  112. public $linkedObjectsFullLoaded = array();
  113. /**
  114. * @var Object To store a cloned copy of object before to edit it and keep track of old properties
  115. */
  116. public $oldcopy;
  117. /**
  118. * @var string Column name of the ref field.
  119. */
  120. protected $table_ref_field = '';
  121. /**
  122. * @var integer 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user
  123. */
  124. public $restrictiononfksoc = 0;
  125. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  126. /**
  127. * @var array<string,mixed> Can be used to pass information when only object is provided to method
  128. */
  129. public $context = array();
  130. /**
  131. * @var string Contains canvas name if record is an alternative canvas record
  132. */
  133. public $canvas;
  134. /**
  135. * @var Project The related project
  136. * @see fetch_projet()
  137. */
  138. public $project;
  139. /**
  140. * @var int The related project ID
  141. * @see setProject(), project
  142. */
  143. public $fk_project;
  144. /**
  145. * @deprecated
  146. * @see project
  147. */
  148. public $projet;
  149. /**
  150. * @var Contact a related contact
  151. * @see fetch_contact()
  152. */
  153. public $contact;
  154. /**
  155. * @var int The related contact ID
  156. * @see fetch_contact()
  157. */
  158. public $contact_id;
  159. /**
  160. * @var Societe A related thirdparty
  161. * @see fetch_thirdparty()
  162. */
  163. public $thirdparty;
  164. /**
  165. * @var User A related user
  166. * @see fetch_user()
  167. */
  168. public $user;
  169. /**
  170. * @var string The type of originating object ('commande', 'facture', ...). Note: on some object this field is called $origin_type
  171. * @see fetch_origin()
  172. */
  173. public $origin;
  174. /**
  175. * @var int The id of originating object
  176. * @see fetch_origin()
  177. */
  178. public $origin_id;
  179. /**
  180. * @var string The object's reference
  181. */
  182. public $ref;
  183. /**
  184. * @var string An external reference for the object
  185. */
  186. public $ref_ext;
  187. /**
  188. * @var string The object's previous reference
  189. */
  190. public $ref_previous;
  191. /**
  192. * @var string The object's next reference
  193. */
  194. public $ref_next;
  195. /**
  196. * @var string Ref to store on object to save the new ref to use for example when making a validate() of an object
  197. */
  198. public $newref;
  199. /**
  200. * @var int The object's status
  201. * @see setStatut()
  202. */
  203. public $statut;
  204. /**
  205. * @var int The object's status
  206. * @see setStatut()
  207. */
  208. public $status;
  209. /**
  210. * @var string
  211. * @see getFullAddress()
  212. */
  213. public $country;
  214. /**
  215. * @var int
  216. * @see getFullAddress(), country
  217. */
  218. public $country_id;
  219. /**
  220. * @var string
  221. * @see getFullAddress(), isInEEC(), country
  222. */
  223. public $country_code;
  224. /**
  225. * @var string
  226. * @see getFullAddress()
  227. */
  228. public $state;
  229. /**
  230. * @var int
  231. * @see getFullAddress(), state
  232. */
  233. public $state_id;
  234. /**
  235. * @var string
  236. * @see getFullAddress(), $state
  237. */
  238. public $state_code;
  239. /**
  240. * @var int
  241. * @see getFullAddress(), $region_code, $region
  242. */
  243. public $region_id;
  244. /**
  245. * @var string
  246. * @see getFullAddress(), $region_id, $region
  247. */
  248. public $region_code;
  249. /**
  250. * @var string
  251. * @see getFullAddress(), $region_id, $region_code
  252. */
  253. public $region;
  254. /**
  255. * @var int
  256. * @see fetch_barcode()
  257. */
  258. public $barcode_type;
  259. /**
  260. * @var string
  261. * @see fetch_barcode(), barcode_type
  262. */
  263. public $barcode_type_code;
  264. /**
  265. * @var string
  266. * @see fetch_barcode(), barcode_type
  267. */
  268. public $barcode_type_label;
  269. /**
  270. * @var string
  271. * @see fetch_barcode(), barcode_type
  272. */
  273. public $barcode_type_coder;
  274. /**
  275. * @var int Payment method ID (cheque, cash, ...)
  276. * @see setPaymentMethods()
  277. */
  278. public $mode_reglement_id;
  279. /**
  280. * @var int Payment terms ID
  281. * @see setPaymentTerms()
  282. */
  283. public $cond_reglement_id;
  284. /**
  285. * @var int Demand reason ID
  286. */
  287. public $demand_reason_id;
  288. /**
  289. * @var int Transport mode ID (For module intracomm report)
  290. * @see setTransportMode()
  291. */
  292. public $transport_mode_id;
  293. /**
  294. * @var int Payment terms ID
  295. * @deprecated Kept for compatibility
  296. * @see cond_reglement_id;
  297. */
  298. public $cond_reglement;
  299. /**
  300. * @var int Delivery address ID
  301. * @see setDeliveryAddress()
  302. * @deprecated
  303. */
  304. public $fk_delivery_address;
  305. /**
  306. * @var int Shipping method ID
  307. * @see setShippingMethod()
  308. */
  309. public $shipping_method_id;
  310. /**
  311. * @var string
  312. * @see SetDocModel()
  313. */
  314. public $model_pdf;
  315. /**
  316. * @var string
  317. * @deprecated
  318. * @see $model_pdf
  319. */
  320. public $modelpdf;
  321. /**
  322. * @var string
  323. * Contains relative path of last generated main file
  324. */
  325. public $last_main_doc;
  326. /**
  327. * @var int Bank account ID sometimes, ID of record into llx_bank sometimes
  328. * @deprecated
  329. * @see $fk_account
  330. */
  331. public $fk_bank;
  332. /**
  333. * @var int Bank account ID
  334. * @see SetBankAccount()
  335. */
  336. public $fk_account;
  337. /**
  338. * @var string Open ID
  339. */
  340. public $openid;
  341. /**
  342. * @var string Public note
  343. * @see update_note()
  344. */
  345. public $note_public;
  346. /**
  347. * @var string Private note
  348. * @see update_note()
  349. */
  350. public $note_private;
  351. /**
  352. * @deprecated
  353. * @see $note_private
  354. */
  355. public $note;
  356. /**
  357. * @var float Total amount before taxes
  358. * @see update_price()
  359. */
  360. public $total_ht;
  361. /**
  362. * @var float Total VAT amount
  363. * @see update_price()
  364. */
  365. public $total_tva;
  366. /**
  367. * @var float Total local tax 1 amount
  368. * @see update_price()
  369. */
  370. public $total_localtax1;
  371. /**
  372. * @var float Total local tax 2 amount
  373. * @see update_price()
  374. */
  375. public $total_localtax2;
  376. /**
  377. * @var float Total amount with taxes
  378. * @see update_price()
  379. */
  380. public $total_ttc;
  381. /**
  382. * @var CommonObjectLine[]
  383. */
  384. public $lines;
  385. /**
  386. * @var mixed Contains comments
  387. * @see fetchComments()
  388. */
  389. public $comments = array();
  390. /**
  391. * @var string The name
  392. */
  393. public $name;
  394. /**
  395. * @var string The lastname
  396. */
  397. public $lastname;
  398. /**
  399. * @var string The firstname
  400. */
  401. public $firstname;
  402. /**
  403. * @var string The civility code, not an integer
  404. */
  405. public $civility_id;
  406. // Dates
  407. /**
  408. * @var integer|string date_creation
  409. */
  410. public $date_creation;
  411. /**
  412. * @var integer|string $date_validation;
  413. */
  414. public $date_validation; // Date validation
  415. /**
  416. * @var integer|string $date_modification;
  417. */
  418. public $date_modification; // Date last change (tms field)
  419. public $next_prev_filter;
  420. /**
  421. * @var int 1 if object is specimen
  422. */
  423. public $specimen = 0;
  424. /**
  425. * @var int Id of contact to send object (used by the trigger of module Agenda)
  426. */
  427. public $sendtoid;
  428. /**
  429. * @var float Amount already paid (used to show correct status)
  430. */
  431. public $alreadypaid;
  432. /**
  433. * @var array List of child tables. To test if we can delete object.
  434. */
  435. protected $childtables = array();
  436. /**
  437. * @var array List of child tables. To know object to delete on cascade.
  438. * If name is like '@ClassName:FilePathClass:ParentFkFieldName', it will
  439. * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object.
  440. */
  441. protected $childtablesoncascade = array();
  442. // No constructor as it is an abstract class
  443. /**
  444. * Check an object id/ref exists
  445. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  446. *
  447. * @param string $element String of element ('product', 'facture', ...)
  448. * @param int $id Id of object
  449. * @param string $ref Ref of object to check
  450. * @param string $ref_ext Ref ext of object to check
  451. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  452. */
  453. public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
  454. {
  455. global $db, $conf;
  456. $sql = "SELECT rowid, ref, ref_ext";
  457. $sql .= " FROM ".$db->prefix().$element;
  458. $sql .= " WHERE entity IN (".getEntity($element).")";
  459. if ($id > 0) {
  460. $sql .= " AND rowid = ".((int) $id);
  461. } elseif ($ref) {
  462. $sql .= " AND ref = '".$db->escape($ref)."'";
  463. } elseif ($ref_ext) {
  464. $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
  465. } else {
  466. $error = 'ErrorWrongParameters';
  467. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  468. return -1;
  469. }
  470. if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
  471. $sql .= " AND entity = ".((int) $conf->entity);
  472. }
  473. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  474. $resql = $db->query($sql);
  475. if ($resql) {
  476. $num = $db->num_rows($resql);
  477. if ($num > 0) {
  478. return 1;
  479. } else {
  480. return 0;
  481. }
  482. }
  483. return -1;
  484. }
  485. /**
  486. * Method to output saved errors
  487. *
  488. * @return string String with errors
  489. */
  490. public function errorsToString()
  491. {
  492. return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
  493. }
  494. /**
  495. * Return customer ref for screen output.
  496. *
  497. * @param string $objref Customer ref
  498. * @return string Customer ref formated
  499. */
  500. public function getFormatedCustomerRef($objref)
  501. {
  502. global $hookmanager;
  503. $parameters = array('objref'=>$objref);
  504. $action = '';
  505. $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  506. if ($reshook > 0) {
  507. return $hookmanager->resArray['objref'];
  508. }
  509. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  510. }
  511. /**
  512. * Return supplier ref for screen output.
  513. *
  514. * @param string $objref Supplier ref
  515. * @return string Supplier ref formated
  516. */
  517. public function getFormatedSupplierRef($objref)
  518. {
  519. global $hookmanager;
  520. $parameters = array('objref'=>$objref);
  521. $action = '';
  522. $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  523. if ($reshook > 0) {
  524. return $hookmanager->resArray['objref'];
  525. }
  526. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  527. }
  528. /**
  529. * Return full name (civility+' '+name+' '+lastname)
  530. *
  531. * @param Translate $langs Language object for translation of civility (used only if option is 1)
  532. * @param int $option 0=No option, 1=Add civility
  533. * @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
  534. * @param int $maxlen Maximum length
  535. * @return string String with full name
  536. */
  537. public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
  538. {
  539. //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
  540. $lastname = $this->lastname;
  541. $firstname = $this->firstname;
  542. if (empty($lastname)) {
  543. $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 : '')))));
  544. }
  545. $ret = '';
  546. if (!empty($option) && !empty($this->civility_code)) {
  547. if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) {
  548. $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
  549. } else {
  550. $ret .= $this->civility_code.' ';
  551. }
  552. }
  553. $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
  554. return dol_trunc($ret, $maxlen);
  555. }
  556. /**
  557. * Set to upper or ucwords/lower if needed
  558. *
  559. * @return void;
  560. */
  561. public function setUpperOrLowerCase()
  562. {
  563. global $conf;
  564. if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
  565. $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
  566. $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
  567. $this->name = dol_ucwords(dol_strtolower($this->name));
  568. $this->name_alias = dol_ucwords(dol_strtolower($this->name_alias));
  569. }
  570. if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
  571. $this->lastname = dol_strtoupper($this->lastname);
  572. $this->name = dol_strtoupper($this->name);
  573. $this->name_alias = dol_strtoupper($this->name_alias);
  574. }
  575. if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
  576. $this->address = dol_strtoupper($this->address);
  577. $this->town = dol_strtoupper($this->town);
  578. }
  579. }
  580. /**
  581. * Return clicable link of object (with eventually picto)
  582. *
  583. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  584. * @return string HTML Code for Kanban thumb.
  585. */
  586. public function getKanbanView($option = '')
  587. {
  588. $return = '<div class="box-flex-item box-flex-grow-zero">';
  589. $return .= '<div class="info-box info-box-sm">';
  590. $return .= '<span class="info-box-icon bg-infobox-action">';
  591. $return .= img_picto('', $this->picto);
  592. //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
  593. $return .= '</span>';
  594. $return .= '<div class="info-box-content">';
  595. $return .= '<span class="info-box-ref">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  596. if (property_exists($this, 'label')) {
  597. $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
  598. }
  599. if (method_exists($this, 'getLibStatut')) {
  600. $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(5).'</div>';
  601. }
  602. $return .= '</div>';
  603. $return .= '</div>';
  604. $return .= '</div>';
  605. return $return;
  606. }
  607. /**
  608. * Return full address of contact
  609. *
  610. * @param int $withcountry 1=Add country into address string
  611. * @param string $sep Separator to use to build string
  612. * @param int $withregion 1=Add region into address string
  613. * @param string $extralangcode User extralanguages as value
  614. * @return string Full address string
  615. */
  616. public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
  617. {
  618. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
  619. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  620. $tmparray = getCountry($this->country_id, 'all');
  621. $this->country_code = $tmparray['code'];
  622. $this->country = $tmparray['label'];
  623. }
  624. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
  625. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  626. $tmparray = getState($this->state_id, 'all', 0, 1);
  627. $this->state_code = $tmparray['code'];
  628. $this->state = $tmparray['label'];
  629. $this->region_code = $tmparray['region_code'];
  630. $this->region = $tmparray['region'];
  631. }
  632. return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
  633. }
  634. /**
  635. * Return full address for banner
  636. *
  637. * @param string $htmlkey HTML id to make banner content unique
  638. * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member)
  639. * @return string Full address string
  640. */
  641. public function getBannerAddress($htmlkey, $object)
  642. {
  643. global $conf, $langs, $form, $extralanguages;
  644. $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
  645. $contactid = 0;
  646. $thirdpartyid = 0;
  647. $elementforaltlanguage = $this->element;
  648. if ($this->element == 'societe') {
  649. $thirdpartyid = $this->id;
  650. }
  651. if ($this->element == 'contact') {
  652. $contactid = $this->id;
  653. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  654. }
  655. if ($this->element == 'user') {
  656. $contactid = $this->contact_id;
  657. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  658. }
  659. $out = '';
  660. $outdone = 0;
  661. $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
  662. if ($coords) {
  663. if (!empty($conf->use_javascript_ajax)) {
  664. // Add picto with tooltip on map
  665. $namecoords = '';
  666. if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
  667. $namecoords .= $object->name.'<br>';
  668. }
  669. $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
  670. // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
  671. $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
  672. $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
  673. $out .= '</a> ';
  674. }
  675. $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  676. $outdone++;
  677. $outdone++;
  678. // List of extra languages
  679. $arrayoflangcode = array();
  680. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  681. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  682. }
  683. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  684. if (!is_object($extralanguages)) {
  685. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  686. $extralanguages = new ExtraLanguages($this->db);
  687. }
  688. $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
  689. if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
  690. $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
  691. $this->fetchValuesForExtraLanguages();
  692. if (!is_object($form)) {
  693. $form = new Form($this->db);
  694. }
  695. $htmltext = '';
  696. // If there is extra languages
  697. foreach ($arrayoflangcode as $extralangcode) {
  698. $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  699. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
  700. $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  701. }
  702. $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  703. }
  704. }
  705. }
  706. 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
  707. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
  708. if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
  709. $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
  710. } else {
  711. $out .= ($outdone ? ' - ' : '').$this->state;
  712. }
  713. $outdone++;
  714. }
  715. 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)) {
  716. $out .= ($outdone ? '<br>' : '');
  717. }
  718. if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  719. $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  720. $outdone++;
  721. }
  722. if (!empty($this->phone_pro)) {
  723. $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  724. $outdone++;
  725. }
  726. if (!empty($this->phone_mobile)) {
  727. $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  728. $outdone++;
  729. }
  730. if (!empty($this->phone_perso)) {
  731. $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
  732. $outdone++;
  733. }
  734. if (!empty($this->office_phone)) {
  735. $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  736. $outdone++;
  737. }
  738. if (!empty($this->user_mobile)) {
  739. $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  740. $outdone++;
  741. }
  742. if (!empty($this->fax)) {
  743. $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  744. $outdone++;
  745. }
  746. if (!empty($this->office_fax)) {
  747. $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  748. $outdone++;
  749. }
  750. if ($out) {
  751. $out .= '<div style="clear: both;"></div>';
  752. }
  753. $outdone = 0;
  754. if (!empty($this->email)) {
  755. $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
  756. $outdone++;
  757. }
  758. if (!empty($this->url)) {
  759. //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
  760. $out .= dol_print_url($this->url, '_blank', 0, 1);
  761. $outdone++;
  762. }
  763. if (!empty($conf->socialnetworks->enabled)) {
  764. $outsocialnetwork = '';
  765. if (!empty($this->socialnetworks) && is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
  766. $socialnetworksdict = getArrayOfSocialNetworks();
  767. foreach ($this->socialnetworks as $key => $value) {
  768. if ($value) {
  769. $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
  770. }
  771. $outdone++;
  772. }
  773. } else { // Old code to remove
  774. if (!empty($this->skype)) {
  775. $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
  776. }
  777. $outdone++;
  778. if (!empty($this->jabberid)) {
  779. $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
  780. }
  781. $outdone++;
  782. if (!empty($this->twitter)) {
  783. $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
  784. }
  785. $outdone++;
  786. if (!empty($this->facebook)) {
  787. $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
  788. }
  789. $outdone++;
  790. if (!empty($this->linkedin)) {
  791. $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
  792. }
  793. $outdone++;
  794. }
  795. if ($outsocialnetwork) {
  796. $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
  797. }
  798. }
  799. if ($out) {
  800. return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
  801. } else {
  802. return '';
  803. }
  804. }
  805. /**
  806. * Return the link of last main doc file for direct public download.
  807. *
  808. * @param string $modulepart Module related to document
  809. * @param int $initsharekey Init the share key if it was not yet defined
  810. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  811. * @return string Link or empty string if there is no download link
  812. */
  813. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  814. {
  815. global $user, $dolibarr_main_url_root;
  816. if (empty($this->last_main_doc)) {
  817. return ''; // No way to known which document name to use
  818. }
  819. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  820. $ecmfile = new EcmFiles($this->db);
  821. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  822. if ($result < 0) {
  823. $this->error = $ecmfile->error;
  824. $this->errors = $ecmfile->errors;
  825. return -1;
  826. }
  827. if (empty($ecmfile->id)) {
  828. // Add entry into index
  829. if ($initsharekey) {
  830. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  831. // TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first
  832. /*
  833. $ecmfile->filepath = $rel_dir;
  834. $ecmfile->filename = $filename;
  835. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  836. $ecmfile->fullpath_orig = '';
  837. $ecmfile->gen_or_uploaded = 'generated';
  838. $ecmfile->description = ''; // indexed content
  839. $ecmfile->keywords = ''; // keyword content
  840. $ecmfile->share = getRandomPassword(true);
  841. $result = $ecmfile->create($user);
  842. if ($result < 0)
  843. {
  844. $this->error = $ecmfile->error;
  845. $this->errors = $ecmfile->errors;
  846. }
  847. */
  848. } else {
  849. return '';
  850. }
  851. } elseif (empty($ecmfile->share)) {
  852. // Add entry into index
  853. if ($initsharekey) {
  854. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  855. $ecmfile->share = getRandomPassword(true);
  856. $ecmfile->update($user);
  857. } else {
  858. return '';
  859. }
  860. }
  861. // Define $urlwithroot
  862. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  863. // This is to use external domain name found into config file
  864. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  865. //else
  866. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  867. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  868. $forcedownload = 0;
  869. $paramlink = '';
  870. //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  871. //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  872. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  873. if (!empty($ecmfile->share)) {
  874. $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
  875. }
  876. if ($forcedownload) {
  877. $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  878. }
  879. if ($relativelink) {
  880. $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
  881. } else {
  882. $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  883. }
  884. // Here $ecmfile->share is defined
  885. return $linktoreturn;
  886. }
  887. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  888. /**
  889. * Add a link between element $this->element and a contact
  890. *
  891. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  892. * @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
  893. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  894. * @param int $notrigger Disable all triggers
  895. * @return int <0 if KO, 0 if already added, >0 if OK
  896. */
  897. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  898. {
  899. // phpcs:enable
  900. global $user, $langs;
  901. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  902. // Check parameters
  903. if ($fk_socpeople <= 0) {
  904. $langs->load("errors");
  905. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  906. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  907. return -1;
  908. }
  909. if (!$type_contact) {
  910. $langs->load("errors");
  911. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  912. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  913. return -2;
  914. }
  915. $id_type_contact = 0;
  916. if (is_numeric($type_contact)) {
  917. $id_type_contact = $type_contact;
  918. } else {
  919. // We look for id type_contact
  920. $sql = "SELECT tc.rowid";
  921. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  922. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  923. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  924. $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  925. //print $sql;
  926. $resql = $this->db->query($sql);
  927. if ($resql) {
  928. $obj = $this->db->fetch_object($resql);
  929. if ($obj) {
  930. $id_type_contact = $obj->rowid;
  931. }
  932. }
  933. }
  934. if ($id_type_contact == 0) {
  935. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  936. 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");
  937. return -3;
  938. }
  939. $datecreate = dol_now();
  940. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  941. $TListeContacts = $this->liste_contact(-1, $source);
  942. $already_added = false;
  943. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  944. foreach ($TListeContacts as $array_contact) {
  945. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  946. $already_added = true;
  947. break;
  948. }
  949. }
  950. }
  951. if (!$already_added) {
  952. $this->db->begin();
  953. // Insert into database
  954. $sql = "INSERT INTO ".$this->db->prefix()."element_contact";
  955. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  956. $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
  957. $sql .= "'".$this->db->idate($datecreate)."'";
  958. $sql .= ", 4, ".((int) $id_type_contact);
  959. $sql .= ")";
  960. $resql = $this->db->query($sql);
  961. if ($resql) {
  962. if (!$notrigger) {
  963. $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  964. if ($result < 0) {
  965. $this->db->rollback();
  966. return -1;
  967. }
  968. }
  969. $this->db->commit();
  970. return 1;
  971. } else {
  972. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  973. $this->error = $this->db->errno();
  974. $this->db->rollback();
  975. return -2;
  976. } else {
  977. $this->error = $this->db->lasterror();
  978. $this->db->rollback();
  979. return -1;
  980. }
  981. }
  982. } else {
  983. return 0;
  984. }
  985. }
  986. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  987. /**
  988. * Copy contact from one element to current
  989. *
  990. * @param CommonObject $objFrom Source element
  991. * @param string $source Nature of contact ('internal' or 'external')
  992. * @return int >0 if OK, <0 if KO
  993. */
  994. public function copy_linked_contact($objFrom, $source = 'internal')
  995. {
  996. // phpcs:enable
  997. $contacts = $objFrom->liste_contact(-1, $source);
  998. foreach ($contacts as $contact) {
  999. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
  1000. return -1;
  1001. }
  1002. }
  1003. return 1;
  1004. }
  1005. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1006. /**
  1007. * Update a link to contact line
  1008. *
  1009. * @param int $rowid Id of line contact-element
  1010. * @param int $statut New status of link
  1011. * @param int $type_contact_id Id of contact type (not modified if 0)
  1012. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  1013. * @return int <0 if KO, >= 0 if OK
  1014. */
  1015. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  1016. {
  1017. // phpcs:enable
  1018. // Insert into database
  1019. $sql = "UPDATE ".$this->db->prefix()."element_contact set";
  1020. $sql .= " statut = ".$statut;
  1021. if ($type_contact_id) {
  1022. $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
  1023. }
  1024. if ($fk_socpeople) {
  1025. $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
  1026. }
  1027. $sql .= " where rowid = ".((int) $rowid);
  1028. $resql = $this->db->query($sql);
  1029. if ($resql) {
  1030. return 0;
  1031. } else {
  1032. $this->error = $this->db->lasterror();
  1033. return -1;
  1034. }
  1035. }
  1036. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1037. /**
  1038. * Delete a link to contact line
  1039. *
  1040. * @param int $rowid Id of contact link line to delete
  1041. * @param int $notrigger Disable all triggers
  1042. * @return int >0 if OK, <0 if KO
  1043. */
  1044. public function delete_contact($rowid, $notrigger = 0)
  1045. {
  1046. // phpcs:enable
  1047. global $user;
  1048. $this->db->begin();
  1049. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1050. $sql .= " WHERE rowid = ".((int) $rowid);
  1051. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  1052. if ($this->db->query($sql)) {
  1053. if (!$notrigger) {
  1054. $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  1055. if ($result < 0) {
  1056. $this->db->rollback();
  1057. return -1;
  1058. }
  1059. }
  1060. $this->db->commit();
  1061. return 1;
  1062. } else {
  1063. $this->error = $this->db->lasterror();
  1064. $this->db->rollback();
  1065. return -1;
  1066. }
  1067. }
  1068. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1069. /**
  1070. * Delete all links between an object $this and all its contacts
  1071. *
  1072. * @param string $source '' or 'internal' or 'external'
  1073. * @param string $code Type of contact (code or id)
  1074. * @return int >0 if OK, <0 if KO
  1075. */
  1076. public function delete_linked_contact($source = '', $code = '')
  1077. {
  1078. // phpcs:enable
  1079. $listId = '';
  1080. $temp = array();
  1081. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  1082. if (!empty($typeContact)) {
  1083. foreach ($typeContact as $key => $value) {
  1084. array_push($temp, $key);
  1085. }
  1086. $listId = implode(",", $temp);
  1087. }
  1088. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1089. $sql .= " WHERE element_id = ".((int) $this->id);
  1090. if (!empty($listId)) {
  1091. $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
  1092. }
  1093. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  1094. if ($this->db->query($sql)) {
  1095. return 1;
  1096. } else {
  1097. $this->error = $this->db->lasterror();
  1098. return -1;
  1099. }
  1100. }
  1101. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1102. /**
  1103. * Get array of all contacts for an object
  1104. *
  1105. * @param int $status Status of links to get (-1=all)
  1106. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  1107. * @param int $list 0:Return array contains all properties, 1:Return array contains just id
  1108. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1109. * @return array|int Array of contacts, -1 if error
  1110. */
  1111. public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
  1112. {
  1113. // phpcs:enable
  1114. global $langs;
  1115. $tab = array();
  1116. $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
  1117. if ($source == 'internal') {
  1118. $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  1119. }
  1120. if ($source == 'external' || $source == 'thirdparty') {
  1121. $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1122. }
  1123. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  1124. $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
  1125. $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
  1126. $sql .= ", ".$this->db->prefix()."element_contact ec";
  1127. if ($source == 'internal') {
  1128. $sql .= " LEFT JOIN ".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid";
  1129. }
  1130. if ($source == 'external' || $source == 'thirdparty') {
  1131. $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid";
  1132. }
  1133. $sql .= " WHERE ec.element_id = ".((int) $this->id);
  1134. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1135. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1136. if ($code) {
  1137. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1138. }
  1139. if ($source == 'internal') {
  1140. $sql .= " AND tc.source = 'internal'";
  1141. }
  1142. if ($source == 'external' || $source == 'thirdparty') {
  1143. $sql .= " AND tc.source = 'external'";
  1144. }
  1145. $sql .= " AND tc.active=1";
  1146. if ($status >= 0) {
  1147. $sql .= " AND ec.statut = ".((int) $status);
  1148. }
  1149. $sql .= " ORDER BY t.lastname ASC";
  1150. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  1151. $resql = $this->db->query($sql);
  1152. if ($resql) {
  1153. $num = $this->db->num_rows($resql);
  1154. $i = 0;
  1155. while ($i < $num) {
  1156. $obj = $this->db->fetch_object($resql);
  1157. if (!$list) {
  1158. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1159. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1160. $tab[$i] = array(
  1161. 'source' => $obj->source,
  1162. 'socid' => $obj->socid,
  1163. 'id' => $obj->id,
  1164. 'nom' => $obj->lastname, // For backward compatibility
  1165. 'civility' => $obj->civility,
  1166. 'lastname' => $obj->lastname,
  1167. 'firstname' => $obj->firstname,
  1168. 'email'=>$obj->email,
  1169. 'login'=> (empty($obj->login) ? '' : $obj->login),
  1170. 'photo' => (empty($obj->photo) ? '' : $obj->photo),
  1171. 'statuscontact' => $obj->statuscontact,
  1172. 'rowid' => $obj->rowid,
  1173. 'code' => $obj->code,
  1174. 'libelle' => $libelle_type,
  1175. 'status' => $obj->statuslink,
  1176. 'fk_c_type_contact' => $obj->fk_c_type_contact
  1177. );
  1178. } else {
  1179. $tab[$i] = $obj->id;
  1180. }
  1181. $i++;
  1182. }
  1183. return $tab;
  1184. } else {
  1185. $this->error = $this->db->lasterror();
  1186. dol_print_error($this->db);
  1187. return -1;
  1188. }
  1189. }
  1190. /**
  1191. * Update status of a contact linked to object
  1192. *
  1193. * @param int $rowid Id of link between object and contact
  1194. * @return int <0 if KO, >=0 if OK
  1195. */
  1196. public function swapContactStatus($rowid)
  1197. {
  1198. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1199. $sql .= " tc.code, tc.libelle";
  1200. $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
  1201. $sql .= " WHERE ec.rowid =".((int) $rowid);
  1202. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1203. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1204. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  1205. $resql = $this->db->query($sql);
  1206. if ($resql) {
  1207. $obj = $this->db->fetch_object($resql);
  1208. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1209. $result = $this->update_contact($rowid, $newstatut);
  1210. $this->db->free($resql);
  1211. return $result;
  1212. } else {
  1213. $this->error = $this->db->error();
  1214. dol_print_error($this->db);
  1215. return -1;
  1216. }
  1217. }
  1218. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1219. /**
  1220. * Return array with list of possible values for type of contacts
  1221. *
  1222. * @param string $source 'internal', 'external' or 'all'
  1223. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  1224. * @param int $option 0=Return array id->label, 1=Return array code->label
  1225. * @param int $activeonly 0=all status of contact, 1=only the active
  1226. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1227. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1228. */
  1229. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1230. {
  1231. // phpcs:enable
  1232. global $langs;
  1233. if (empty($order)) {
  1234. $order = 'position';
  1235. }
  1236. if ($order == 'position') {
  1237. $order .= ',code';
  1238. }
  1239. $tab = array();
  1240. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  1241. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1242. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1243. if ($activeonly == 1) {
  1244. $sql .= " AND tc.active=1"; // only the active types
  1245. }
  1246. if (!empty($source) && $source != 'all') {
  1247. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1248. }
  1249. if (!empty($code)) {
  1250. $sql .= " AND tc.code='".$this->db->escape($code)."'";
  1251. }
  1252. $sql .= $this->db->order($order, 'ASC');
  1253. //print "sql=".$sql;
  1254. $resql = $this->db->query($sql);
  1255. if ($resql) {
  1256. $num = $this->db->num_rows($resql);
  1257. $i = 0;
  1258. while ($i < $num) {
  1259. $obj = $this->db->fetch_object($resql);
  1260. $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
  1261. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1262. if (empty($option)) {
  1263. $tab[$obj->rowid] = $libelle_type;
  1264. } else {
  1265. $tab[$obj->code] = $libelle_type;
  1266. }
  1267. $i++;
  1268. }
  1269. return $tab;
  1270. } else {
  1271. $this->error = $this->db->lasterror();
  1272. //dol_print_error($this->db);
  1273. return null;
  1274. }
  1275. }
  1276. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1277. /**
  1278. * Return array with list of possible values for type of contacts
  1279. *
  1280. * @param string $source 'internal', 'external' or 'all'
  1281. * @param int $option 0=Return array id->label, 1=Return array code->label
  1282. * @param int $activeonly 0=all status of contact, 1=only the active
  1283. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1284. * @param string $element Filter on 1 element type
  1285. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1286. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1287. */
  1288. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1289. {
  1290. // phpcs:enable
  1291. global $langs, $conf;
  1292. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1293. $tab = array();
  1294. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
  1295. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1296. $sqlWhere = array();
  1297. if (!empty($element)) {
  1298. $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
  1299. }
  1300. if (!empty($excludeelement)) {
  1301. $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
  1302. }
  1303. if ($activeonly == 1) {
  1304. $sqlWhere[] = " tc.active=1"; // only the active types
  1305. }
  1306. if (!empty($source) && $source != 'all') {
  1307. $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
  1308. }
  1309. if (!empty($code)) {
  1310. $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
  1311. }
  1312. if (count($sqlWhere) > 0) {
  1313. $sql .= " WHERE ".implode(' AND ', $sqlWhere);
  1314. }
  1315. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1316. dol_syslog(__METHOD__, LOG_DEBUG);
  1317. $resql = $this->db->query($sql);
  1318. if ($resql) {
  1319. $num = $this->db->num_rows($resql);
  1320. if ($num > 0) {
  1321. $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
  1322. while ($obj = $this->db->fetch_object($resql)) {
  1323. $modulename = $obj->element;
  1324. if (strpos($obj->element, 'project') !== false) {
  1325. $modulename = 'projet';
  1326. } elseif ($obj->element == 'contrat') {
  1327. $element = 'contract';
  1328. } elseif ($obj->element == 'action') {
  1329. $modulename = 'agenda';
  1330. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1331. $modulename = 'fournisseur';
  1332. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1333. $modulename = 'fournisseur';
  1334. }
  1335. if (!empty($conf->{$modulename}->enabled)) {
  1336. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1337. $tmpelement = $obj->element;
  1338. $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
  1339. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1340. if (empty($option)) {
  1341. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1342. } else {
  1343. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1344. }
  1345. }
  1346. }
  1347. }
  1348. return $tab;
  1349. } else {
  1350. $this->error = $this->db->lasterror();
  1351. return null;
  1352. }
  1353. }
  1354. /**
  1355. * Return id of contacts for a source and a contact code.
  1356. * Example: contact client de facturation ('external', 'BILLING')
  1357. * Example: contact client de livraison ('external', 'SHIPPING')
  1358. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1359. *
  1360. * @param string $source 'external' or 'internal'
  1361. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1362. * @param int $status limited to a certain status
  1363. * @return array List of id for such contacts
  1364. */
  1365. public function getIdContact($source, $code, $status = 0)
  1366. {
  1367. global $conf;
  1368. $result = array();
  1369. $i = 0;
  1370. //cas particulier pour les expeditions
  1371. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1372. $id = $this->origin_id;
  1373. $element = 'commande';
  1374. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1375. $id = $this->origin_id;
  1376. $element = 'order_supplier';
  1377. } else {
  1378. $id = $this->id;
  1379. $element = $this->element;
  1380. }
  1381. $sql = "SELECT ec.fk_socpeople";
  1382. $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
  1383. if ($source == 'internal') {
  1384. $sql .= " ".$this->db->prefix()."user as c,";
  1385. }
  1386. if ($source == 'external') {
  1387. $sql .= " ".$this->db->prefix()."socpeople as c,";
  1388. }
  1389. $sql .= " ".$this->db->prefix()."c_type_contact as tc";
  1390. $sql .= " WHERE ec.element_id = ".((int) $id);
  1391. $sql .= " AND ec.fk_socpeople = c.rowid";
  1392. if ($source == 'internal') {
  1393. $sql .= " AND c.entity IN (".getEntity('user').")";
  1394. }
  1395. if ($source == 'external') {
  1396. $sql .= " AND c.entity IN (".getEntity('societe').")";
  1397. }
  1398. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1399. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1400. $sql .= " AND tc.source = '".$this->db->escape($source)."'";
  1401. if ($code) {
  1402. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1403. }
  1404. $sql .= " AND tc.active = 1";
  1405. if ($status) {
  1406. $sql .= " AND ec.statut = ".((int) $status);
  1407. }
  1408. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1409. $resql = $this->db->query($sql);
  1410. if ($resql) {
  1411. while ($obj = $this->db->fetch_object($resql)) {
  1412. $result[$i] = $obj->fk_socpeople;
  1413. $i++;
  1414. }
  1415. } else {
  1416. $this->error = $this->db->error();
  1417. return null;
  1418. }
  1419. return $result;
  1420. }
  1421. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1422. /**
  1423. * Load object contact with id=$this->contact_id into $this->contact
  1424. *
  1425. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1426. * @return int <0 if KO, >0 if OK
  1427. */
  1428. public function fetch_contact($contactid = null)
  1429. {
  1430. // phpcs:enable
  1431. if (empty($contactid)) {
  1432. $contactid = $this->contact_id;
  1433. }
  1434. if (empty($contactid)) {
  1435. return 0;
  1436. }
  1437. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1438. $contact = new Contact($this->db);
  1439. $result = $contact->fetch($contactid);
  1440. $this->contact = $contact;
  1441. return $result;
  1442. }
  1443. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1444. /**
  1445. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1446. *
  1447. * @param int $force_thirdparty_id Force thirdparty id
  1448. * @return int <0 if KO, >0 if OK
  1449. */
  1450. public function fetch_thirdparty($force_thirdparty_id = 0)
  1451. {
  1452. // phpcs:enable
  1453. global $conf;
  1454. if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) {
  1455. return 0;
  1456. }
  1457. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1458. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
  1459. if ($force_thirdparty_id) {
  1460. $idtofetch = $force_thirdparty_id;
  1461. }
  1462. if ($idtofetch) {
  1463. $thirdparty = new Societe($this->db);
  1464. $result = $thirdparty->fetch($idtofetch);
  1465. if ($result<0) {
  1466. $this->errors=array_merge($this->errors, $thirdparty->errors);
  1467. }
  1468. $this->thirdparty = $thirdparty;
  1469. // Use first price level if level not defined for third party
  1470. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1471. $this->thirdparty->price_level = 1;
  1472. }
  1473. return $result;
  1474. } else {
  1475. return -1;
  1476. }
  1477. }
  1478. /**
  1479. * Looks for an object with ref matching the wildcard provided
  1480. * It does only work when $this->table_ref_field is set
  1481. *
  1482. * @param string $ref Wildcard
  1483. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1484. */
  1485. public function fetchOneLike($ref)
  1486. {
  1487. if (!$this->table_ref_field) {
  1488. return 0;
  1489. }
  1490. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element." WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."' LIMIT 1";
  1491. $query = $this->db->query($sql);
  1492. if (!$this->db->num_rows($query)) {
  1493. return 0;
  1494. }
  1495. $result = $this->db->fetch_object($query);
  1496. return $this->fetch($result->rowid);
  1497. }
  1498. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1499. /**
  1500. * Load data for barcode into properties ->barcode_type*
  1501. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1502. * if it is not defined, ->element must be defined to know default barcode type.
  1503. *
  1504. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1505. */
  1506. public function fetch_barcode()
  1507. {
  1508. // phpcs:enable
  1509. global $conf;
  1510. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1511. $idtype = $this->barcode_type;
  1512. 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
  1513. if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
  1514. $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1515. } elseif ($this->element == 'societe') {
  1516. $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1517. } else {
  1518. dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1519. }
  1520. }
  1521. if ($idtype > 0) {
  1522. 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
  1523. $sql = "SELECT rowid, code, libelle as label, coder";
  1524. $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
  1525. $sql .= " WHERE rowid = ".((int) $idtype);
  1526. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1527. $resql = $this->db->query($sql);
  1528. if ($resql) {
  1529. $obj = $this->db->fetch_object($resql);
  1530. $this->barcode_type = $obj->rowid;
  1531. $this->barcode_type_code = $obj->code;
  1532. $this->barcode_type_label = $obj->label;
  1533. $this->barcode_type_coder = $obj->coder;
  1534. return 1;
  1535. } else {
  1536. dol_print_error($this->db);
  1537. return -1;
  1538. }
  1539. }
  1540. }
  1541. return 0;
  1542. }
  1543. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1544. /**
  1545. * Load the project with id $this->fk_project into this->project
  1546. *
  1547. * @return int <0 if KO, >=0 if OK
  1548. */
  1549. public function fetch_project()
  1550. {
  1551. // phpcs:enable
  1552. return $this->fetch_projet();
  1553. }
  1554. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1555. /**
  1556. * Load the project with id $this->fk_project into this->project
  1557. *
  1558. * @return int <0 if KO, >=0 if OK
  1559. */
  1560. public function fetch_projet()
  1561. {
  1562. // phpcs:enable
  1563. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1564. if (empty($this->fk_project) && !empty($this->fk_projet)) {
  1565. $this->fk_project = $this->fk_projet; // For backward compatibility
  1566. }
  1567. if (empty($this->fk_project)) {
  1568. return 0;
  1569. }
  1570. $project = new Project($this->db);
  1571. $result = $project->fetch($this->fk_project);
  1572. $this->projet = $project; // deprecated
  1573. $this->project = $project;
  1574. return $result;
  1575. }
  1576. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1577. /**
  1578. * Load the product with id $this->fk_product into this->product
  1579. *
  1580. * @return int <0 if KO, >=0 if OK
  1581. */
  1582. public function fetch_product()
  1583. {
  1584. // phpcs:enable
  1585. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1586. if (empty($this->fk_product)) {
  1587. return 0;
  1588. }
  1589. $product = new Product($this->db);
  1590. $result = $product->fetch($this->fk_product);
  1591. $this->product = $product;
  1592. return $result;
  1593. }
  1594. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1595. /**
  1596. * Load the user with id $userid into this->user
  1597. *
  1598. * @param int $userid Id du contact
  1599. * @return int <0 if KO, >0 if OK
  1600. */
  1601. public function fetch_user($userid)
  1602. {
  1603. // phpcs:enable
  1604. $user = new User($this->db);
  1605. $result = $user->fetch($userid);
  1606. $this->user = $user;
  1607. return $result;
  1608. }
  1609. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1610. /**
  1611. * Read linked origin object
  1612. *
  1613. * @return void
  1614. */
  1615. public function fetch_origin()
  1616. {
  1617. // phpcs:enable
  1618. if ($this->origin == 'shipping') {
  1619. $this->origin = 'expedition';
  1620. }
  1621. if ($this->origin == 'delivery') {
  1622. $this->origin = 'livraison';
  1623. }
  1624. if ($this->origin == 'order_supplier') {
  1625. $this->origin = 'commandeFournisseur';
  1626. }
  1627. $origin = $this->origin;
  1628. $classname = ucfirst($origin);
  1629. $this->$origin = new $classname($this->db);
  1630. $this->$origin->fetch($this->origin_id);
  1631. }
  1632. /**
  1633. * Load object from specific field
  1634. *
  1635. * @param string $table Table element or element line
  1636. * @param string $field Field selected
  1637. * @param string $key Import key
  1638. * @param string $element Element name
  1639. * @return int <0 if KO, >0 if OK
  1640. */
  1641. public function fetchObjectFrom($table, $field, $key, $element = null)
  1642. {
  1643. global $conf;
  1644. $result = false;
  1645. $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
  1646. $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
  1647. if (!empty($element)) {
  1648. $sql .= " AND entity IN (".getEntity($element).")";
  1649. } else {
  1650. $sql .= " AND entity = ".((int) $conf->entity);
  1651. }
  1652. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1653. $resql = $this->db->query($sql);
  1654. if ($resql) {
  1655. $row = $this->db->fetch_row($resql);
  1656. // Test for avoid error -1
  1657. if ($row[0] > 0) {
  1658. $result = $this->fetch($row[0]);
  1659. }
  1660. }
  1661. return $result;
  1662. }
  1663. /**
  1664. * Getter generic. Load value from a specific field
  1665. *
  1666. * @param string $table Table of element or element line
  1667. * @param int $id Element id
  1668. * @param string $field Field selected
  1669. * @return int <0 if KO, >0 if OK
  1670. */
  1671. public function getValueFrom($table, $id, $field)
  1672. {
  1673. $result = false;
  1674. if (!empty($id) && !empty($field) && !empty($table)) {
  1675. $sql = "SELECT ".$field." FROM ".$this->db->prefix().$table;
  1676. $sql .= " WHERE rowid = ".((int) $id);
  1677. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1678. $resql = $this->db->query($sql);
  1679. if ($resql) {
  1680. $row = $this->db->fetch_row($resql);
  1681. $result = $row[0];
  1682. }
  1683. }
  1684. return $result;
  1685. }
  1686. /**
  1687. * Setter generic. Update a specific field into database.
  1688. * Warning: Trigger is run only if param trigkey is provided.
  1689. *
  1690. * @param string $field Field to update
  1691. * @param mixed $value New value
  1692. * @param string $table To force other table element or element line (should not be used)
  1693. * @param int $id To force other object id (should not be used)
  1694. * @param string $format Data format ('text', 'date'). 'text' is used if not defined
  1695. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1696. * @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'
  1697. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1698. * @param string $fk_user_field Name of field to save user id making change
  1699. * @return int <0 if KO, >0 if OK
  1700. * @see updateExtraField()
  1701. */
  1702. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1703. {
  1704. global $user, $langs, $conf;
  1705. if (empty($table)) {
  1706. $table = $this->table_element;
  1707. }
  1708. if (empty($id)) {
  1709. $id = $this->id;
  1710. }
  1711. if (empty($format)) {
  1712. $format = 'text';
  1713. }
  1714. if (empty($id_field)) {
  1715. $id_field = 'rowid';
  1716. }
  1717. $error = 0;
  1718. $this->db->begin();
  1719. // Special case
  1720. if ($table == 'product' && $field == 'note_private') {
  1721. $field = 'note';
  1722. }
  1723. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  1724. $fk_user_field = 'fk_user_mod';
  1725. }
  1726. $sql = "UPDATE ".$this->db->prefix().$table." SET ";
  1727. if ($format == 'text') {
  1728. $sql .= $field." = '".$this->db->escape($value)."'";
  1729. } elseif ($format == 'int') {
  1730. $sql .= $field." = ".((int) $value);
  1731. } elseif ($format == 'date') {
  1732. $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1733. }
  1734. if ($fk_user_field) {
  1735. if (!empty($fuser) && is_object($fuser)) {
  1736. $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
  1737. } elseif (empty($fuser) || $fuser != 'none') {
  1738. $sql .= ", ".$fk_user_field." = ".((int) $user->id);
  1739. }
  1740. }
  1741. $sql .= " WHERE ".$id_field." = ".((int) $id);
  1742. dol_syslog(__METHOD__."", LOG_DEBUG);
  1743. $resql = $this->db->query($sql);
  1744. if ($resql) {
  1745. if ($trigkey) {
  1746. // call trigger with updated object values
  1747. if (empty($this->fields) && method_exists($this, 'fetch')) {
  1748. $result = $this->fetch($id);
  1749. } else {
  1750. $result = $this->fetchCommon($id);
  1751. }
  1752. if ($result >= 0) {
  1753. $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1754. }
  1755. if ($result < 0) {
  1756. $error++;
  1757. }
  1758. }
  1759. if (!$error) {
  1760. if (property_exists($this, $field)) {
  1761. $this->$field = $value;
  1762. }
  1763. $this->db->commit();
  1764. return 1;
  1765. } else {
  1766. $this->db->rollback();
  1767. return -2;
  1768. }
  1769. } else {
  1770. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1771. $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
  1772. } else {
  1773. $this->error = $this->db->lasterror();
  1774. }
  1775. $this->db->rollback();
  1776. return -1;
  1777. }
  1778. }
  1779. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1780. /**
  1781. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1782. *
  1783. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')". Do not allow user input data here.
  1784. * @param string $fieldid Name of field to use for the select MAX and MIN
  1785. * @param int $nodbprefix Do not include DB prefix to forge table name
  1786. * @return int <0 if KO, >0 if OK
  1787. */
  1788. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1789. {
  1790. // phpcs:enable
  1791. global $conf, $user;
  1792. if (!$this->table_element) {
  1793. dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1794. return -1;
  1795. }
  1796. if ($fieldid == 'none') {
  1797. return 1;
  1798. }
  1799. // For backward compatibility
  1800. if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
  1801. $fieldid = 'titre';
  1802. }
  1803. // Security on socid
  1804. $socid = 0;
  1805. if ($user->socid > 0) {
  1806. $socid = $user->socid;
  1807. }
  1808. // this->ismultientitymanaged contains
  1809. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1810. $aliastablesociete = 's';
  1811. if ($this->element == 'societe') {
  1812. $aliastablesociete = 'te'; // te as table_element
  1813. }
  1814. $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
  1815. $sql = "SELECT MAX(te.".$fieldid.")";
  1816. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1817. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1818. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1819. }
  1820. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1821. $tmparray = explode('@', $this->ismultientitymanaged);
  1822. $sql .= ", ".$this->db->prefix().$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1823. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1824. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1825. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1826. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1827. }
  1828. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1829. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1830. }
  1831. $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)
  1832. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1833. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1834. }
  1835. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1836. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1837. }
  1838. if (!empty($filter)) {
  1839. if (!preg_match('/^\s*AND/i', $filter)) {
  1840. $sql .= " AND "; // For backward compatibility
  1841. }
  1842. $sql .= $filter;
  1843. }
  1844. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1845. $tmparray = explode('@', $this->ismultientitymanaged);
  1846. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1847. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1848. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1849. }
  1850. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1851. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1852. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1853. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1854. } else {
  1855. $sql .= " AND ug.fk_user = te.rowid";
  1856. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1857. }
  1858. } else {
  1859. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1860. }
  1861. }
  1862. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1863. $tmparray = explode('@', $this->ismultientitymanaged);
  1864. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1865. }
  1866. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1867. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1868. }
  1869. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1870. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1871. }
  1872. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1873. $sql .= ' AND te.rowid = '.((int) $socid);
  1874. }
  1875. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1876. $result = $this->db->query($sql);
  1877. if (!$result) {
  1878. $this->error = $this->db->lasterror();
  1879. return -1;
  1880. }
  1881. $row = $this->db->fetch_row($result);
  1882. $this->ref_previous = $row[0];
  1883. $sql = "SELECT MIN(te.".$fieldid.")";
  1884. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1885. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1886. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1887. }
  1888. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1889. $tmparray = explode('@', $this->ismultientitymanaged);
  1890. $sql .= ", ".$this->db->prefix().$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1891. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1892. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1893. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1894. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1895. }
  1896. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1897. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1898. }
  1899. $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)
  1900. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1901. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1902. }
  1903. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1904. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1905. }
  1906. if (!empty($filter)) {
  1907. if (!preg_match('/^\s*AND/i', $filter)) {
  1908. $sql .= " AND "; // For backward compatibility
  1909. }
  1910. $sql .= $filter;
  1911. }
  1912. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1913. $tmparray = explode('@', $this->ismultientitymanaged);
  1914. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1915. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1916. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1917. }
  1918. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1919. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1920. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1921. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1922. } else {
  1923. $sql .= " AND ug.fk_user = te.rowid";
  1924. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1925. }
  1926. } else {
  1927. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1928. }
  1929. }
  1930. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1931. $tmparray = explode('@', $this->ismultientitymanaged);
  1932. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1933. }
  1934. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1935. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1936. }
  1937. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1938. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1939. }
  1940. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1941. $sql .= ' AND te.rowid = '.((int) $socid);
  1942. }
  1943. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1944. // 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
  1945. $result = $this->db->query($sql);
  1946. if (!$result) {
  1947. $this->error = $this->db->lasterror();
  1948. return -2;
  1949. }
  1950. $row = $this->db->fetch_row($result);
  1951. $this->ref_next = $row[0];
  1952. return 1;
  1953. }
  1954. /**
  1955. * Return list of id of contacts of object
  1956. *
  1957. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  1958. * @return array Array of id of contacts (if source=external or internal)
  1959. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  1960. */
  1961. public function getListContactId($source = 'external')
  1962. {
  1963. $contactAlreadySelected = array();
  1964. $tab = $this->liste_contact(-1, $source);
  1965. $num = count($tab);
  1966. $i = 0;
  1967. while ($i < $num) {
  1968. if ($source == 'thirdparty') {
  1969. $contactAlreadySelected[$i] = $tab[$i]['socid'];
  1970. } else {
  1971. $contactAlreadySelected[$i] = $tab[$i]['id'];
  1972. }
  1973. $i++;
  1974. }
  1975. return $contactAlreadySelected;
  1976. }
  1977. /**
  1978. * Link element with a project
  1979. *
  1980. * @param int $projectid Project id to link element to
  1981. * @param int $notrigger Disable the trigger
  1982. * @return int <0 if KO, >0 if OK
  1983. */
  1984. public function setProject($projectid, $notrigger = 0)
  1985. {
  1986. global $user;
  1987. $error = 0;
  1988. if (!$this->table_element) {
  1989. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  1990. return -1;
  1991. }
  1992. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  1993. if (!empty($this->fields['fk_project'])) { // Common case
  1994. if ($projectid) {
  1995. $sql .= " SET fk_project = ".((int) $projectid);
  1996. } else {
  1997. $sql .= " SET fk_project = NULL";
  1998. }
  1999. $sql .= ' WHERE rowid = '.((int) $this->id);
  2000. } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
  2001. if ($projectid) {
  2002. $sql .= " SET fk_project = ".((int) $projectid);
  2003. } else {
  2004. $sql .= " SET fk_project = NULL";
  2005. }
  2006. $sql .= ' WHERE id = '.((int) $this->id);
  2007. } else // Special case for old architecture objects
  2008. {
  2009. if ($projectid) {
  2010. $sql .= ' SET fk_projet = '.((int) $projectid);
  2011. } else {
  2012. $sql .= ' SET fk_projet = NULL';
  2013. }
  2014. $sql .= " WHERE rowid = ".((int) $this->id);
  2015. }
  2016. $this->db->begin();
  2017. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  2018. if ($this->db->query($sql)) {
  2019. $this->fk_project = ((int) $projectid);
  2020. } else {
  2021. dol_print_error($this->db);
  2022. $error++;
  2023. }
  2024. // Triggers
  2025. if (!$error && !$notrigger) {
  2026. // Call triggers
  2027. $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
  2028. if ($result < 0) {
  2029. $error++;
  2030. } //Do also here what you must do to rollback action if trigger fail
  2031. // End call triggers
  2032. }
  2033. // Commit or rollback
  2034. if ($error) {
  2035. $this->db->rollback();
  2036. return -1;
  2037. } else {
  2038. $this->db->commit();
  2039. return 1;
  2040. }
  2041. }
  2042. /**
  2043. * Change the payments methods
  2044. *
  2045. * @param int $id Id of new payment method
  2046. * @return int >0 if OK, <0 if KO
  2047. */
  2048. public function setPaymentMethods($id)
  2049. {
  2050. global $user;
  2051. $error = 0; $notrigger = 0;
  2052. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  2053. if ($this->statut >= 0 || $this->element == 'societe') {
  2054. // TODO uniformize field name
  2055. $fieldname = 'fk_mode_reglement';
  2056. if ($this->element == 'societe') {
  2057. $fieldname = 'mode_reglement';
  2058. }
  2059. if (get_class($this) == 'Fournisseur') {
  2060. $fieldname = 'mode_reglement_supplier';
  2061. }
  2062. if (get_class($this) == 'Tva') {
  2063. $fieldname = 'fk_typepayment';
  2064. }
  2065. if (get_class($this) == 'Salary') {
  2066. $fieldname = 'fk_typepayment';
  2067. }
  2068. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2069. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2070. $sql .= ' WHERE rowid='.((int) $this->id);
  2071. if ($this->db->query($sql)) {
  2072. $this->mode_reglement_id = $id;
  2073. // for supplier
  2074. if (get_class($this) == 'Fournisseur') {
  2075. $this->mode_reglement_supplier_id = $id;
  2076. }
  2077. // Triggers
  2078. if (!$error && !$notrigger) {
  2079. // Call triggers
  2080. if (get_class($this) == 'Commande') {
  2081. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2082. } else {
  2083. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  2084. }
  2085. if ($result < 0) {
  2086. $error++;
  2087. }
  2088. // End call triggers
  2089. }
  2090. return 1;
  2091. } else {
  2092. dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
  2093. $this->error = $this->db->error();
  2094. return -1;
  2095. }
  2096. } else {
  2097. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  2098. $this->error = 'Status of the object is incompatible '.$this->statut;
  2099. return -2;
  2100. }
  2101. }
  2102. /**
  2103. * Change the multicurrency code
  2104. *
  2105. * @param string $code multicurrency code
  2106. * @return int >0 if OK, <0 if KO
  2107. */
  2108. public function setMulticurrencyCode($code)
  2109. {
  2110. dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
  2111. if ($this->statut >= 0 || $this->element == 'societe') {
  2112. $fieldname = 'multicurrency_code';
  2113. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2114. $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
  2115. $sql .= ' WHERE rowid='.((int) $this->id);
  2116. if ($this->db->query($sql)) {
  2117. $this->multicurrency_code = $code;
  2118. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  2119. if ($rate) {
  2120. $this->setMulticurrencyRate($rate, 2);
  2121. }
  2122. return 1;
  2123. } else {
  2124. dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
  2125. $this->error = $this->db->error();
  2126. return -1;
  2127. }
  2128. } else {
  2129. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  2130. $this->error = 'Status of the object is incompatible '.$this->statut;
  2131. return -2;
  2132. }
  2133. }
  2134. /**
  2135. * Change the multicurrency rate
  2136. *
  2137. * @param double $rate multicurrency rate
  2138. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  2139. * @return int >0 if OK, <0 if KO
  2140. */
  2141. public function setMulticurrencyRate($rate, $mode = 1)
  2142. {
  2143. dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
  2144. if ($this->statut >= 0 || $this->element == 'societe') {
  2145. $fieldname = 'multicurrency_tx';
  2146. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2147. $sql .= " SET ".$fieldname." = ".((float) $rate);
  2148. $sql .= ' WHERE rowid='.((int) $this->id);
  2149. if ($this->db->query($sql)) {
  2150. $this->multicurrency_tx = $rate;
  2151. // Update line price
  2152. if (!empty($this->lines)) {
  2153. foreach ($this->lines as &$line) {
  2154. // Amounts in company currency will be recalculated
  2155. if ($mode == 1) {
  2156. $line->subprice = 0;
  2157. }
  2158. // Amounts in foreign currency will be recalculated
  2159. if ($mode == 2) {
  2160. $line->multicurrency_subprice = 0;
  2161. }
  2162. switch ($this->element) {
  2163. case 'propal':
  2164. $this->updateline(
  2165. $line->id,
  2166. $line->subprice,
  2167. $line->qty,
  2168. $line->remise_percent,
  2169. $line->tva_tx,
  2170. $line->localtax1_tx,
  2171. $line->localtax2_tx,
  2172. ($line->description ? $line->description : $line->desc),
  2173. 'HT',
  2174. $line->info_bits,
  2175. $line->special_code,
  2176. $line->fk_parent_line,
  2177. $line->skip_update_total,
  2178. $line->fk_fournprice,
  2179. $line->pa_ht,
  2180. $line->label,
  2181. $line->product_type,
  2182. $line->date_start,
  2183. $line->date_end,
  2184. $line->array_options,
  2185. $line->fk_unit,
  2186. $line->multicurrency_subprice
  2187. );
  2188. break;
  2189. case 'commande':
  2190. $this->updateline(
  2191. $line->id,
  2192. ($line->description ? $line->description : $line->desc),
  2193. $line->subprice,
  2194. $line->qty,
  2195. $line->remise_percent,
  2196. $line->tva_tx,
  2197. $line->localtax1_tx,
  2198. $line->localtax2_tx,
  2199. 'HT',
  2200. $line->info_bits,
  2201. $line->date_start,
  2202. $line->date_end,
  2203. $line->product_type,
  2204. $line->fk_parent_line,
  2205. $line->skip_update_total,
  2206. $line->fk_fournprice,
  2207. $line->pa_ht,
  2208. $line->label,
  2209. $line->special_code,
  2210. $line->array_options,
  2211. $line->fk_unit,
  2212. $line->multicurrency_subprice
  2213. );
  2214. break;
  2215. case 'facture':
  2216. $this->updateline(
  2217. $line->id,
  2218. ($line->description ? $line->description : $line->desc),
  2219. $line->subprice,
  2220. $line->qty,
  2221. $line->remise_percent,
  2222. $line->date_start,
  2223. $line->date_end,
  2224. $line->tva_tx,
  2225. $line->localtax1_tx,
  2226. $line->localtax2_tx,
  2227. 'HT',
  2228. $line->info_bits,
  2229. $line->product_type,
  2230. $line->fk_parent_line,
  2231. $line->skip_update_total,
  2232. $line->fk_fournprice,
  2233. $line->pa_ht,
  2234. $line->label,
  2235. $line->special_code,
  2236. $line->array_options,
  2237. $line->situation_percent,
  2238. $line->fk_unit,
  2239. $line->multicurrency_subprice
  2240. );
  2241. break;
  2242. case 'supplier_proposal':
  2243. $this->updateline(
  2244. $line->id,
  2245. $line->subprice,
  2246. $line->qty,
  2247. $line->remise_percent,
  2248. $line->tva_tx,
  2249. $line->localtax1_tx,
  2250. $line->localtax2_tx,
  2251. ($line->description ? $line->description : $line->desc),
  2252. 'HT',
  2253. $line->info_bits,
  2254. $line->special_code,
  2255. $line->fk_parent_line,
  2256. $line->skip_update_total,
  2257. $line->fk_fournprice,
  2258. $line->pa_ht,
  2259. $line->label,
  2260. $line->product_type,
  2261. $line->array_options,
  2262. $line->ref_fourn,
  2263. $line->multicurrency_subprice
  2264. );
  2265. break;
  2266. case 'order_supplier':
  2267. $this->updateline(
  2268. $line->id,
  2269. ($line->description ? $line->description : $line->desc),
  2270. $line->subprice,
  2271. $line->qty,
  2272. $line->remise_percent,
  2273. $line->tva_tx,
  2274. $line->localtax1_tx,
  2275. $line->localtax2_tx,
  2276. 'HT',
  2277. $line->info_bits,
  2278. $line->product_type,
  2279. false,
  2280. $line->date_start,
  2281. $line->date_end,
  2282. $line->array_options,
  2283. $line->fk_unit,
  2284. $line->multicurrency_subprice,
  2285. $line->ref_supplier
  2286. );
  2287. break;
  2288. case 'invoice_supplier':
  2289. $this->updateline(
  2290. $line->id,
  2291. ($line->description ? $line->description : $line->desc),
  2292. $line->subprice,
  2293. $line->tva_tx,
  2294. $line->localtax1_tx,
  2295. $line->localtax2_tx,
  2296. $line->qty,
  2297. 0,
  2298. 'HT',
  2299. $line->info_bits,
  2300. $line->product_type,
  2301. $line->remise_percent,
  2302. false,
  2303. $line->date_start,
  2304. $line->date_end,
  2305. $line->array_options,
  2306. $line->fk_unit,
  2307. $line->multicurrency_subprice,
  2308. $line->ref_supplier
  2309. );
  2310. break;
  2311. default:
  2312. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  2313. break;
  2314. }
  2315. }
  2316. }
  2317. return 1;
  2318. } else {
  2319. dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
  2320. $this->error = $this->db->error();
  2321. return -1;
  2322. }
  2323. } else {
  2324. dol_syslog(get_class($this).'::setMulticurrencyRate, 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 payments terms
  2331. *
  2332. * @param int $id Id of new payment terms
  2333. * @param string $deposit_percent % of deposit if needed by payment terms
  2334. * @return int >0 if OK, <0 if KO
  2335. */
  2336. public function setPaymentTerms($id, $deposit_percent = null)
  2337. {
  2338. dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
  2339. if ($this->statut >= 0 || $this->element == 'societe') {
  2340. // TODO uniformize field name
  2341. $fieldname = 'fk_cond_reglement';
  2342. if ($this->element == 'societe') {
  2343. $fieldname = 'cond_reglement';
  2344. }
  2345. if (get_class($this) == 'Fournisseur') {
  2346. $fieldname = 'cond_reglement_supplier';
  2347. }
  2348. if (empty($deposit_percent) || $deposit_percent < 0) {
  2349. $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id);
  2350. }
  2351. if ($deposit_percent > 100) {
  2352. $deposit_percent = 100;
  2353. }
  2354. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2355. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2356. $sql .= " , deposit_percent = " . (! empty($deposit_percent) ? "'".$this->db->escape($deposit_percent)."'" : 'NULL');
  2357. $sql .= ' WHERE rowid='.((int) $this->id);
  2358. if ($this->db->query($sql)) {
  2359. $this->cond_reglement_id = $id;
  2360. // for supplier
  2361. if (get_class($this) == 'Fournisseur') {
  2362. $this->cond_reglement_supplier_id = $id;
  2363. }
  2364. $this->cond_reglement = $id; // for compatibility
  2365. $this->deposit_percent = $deposit_percent;
  2366. return 1;
  2367. } else {
  2368. dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
  2369. $this->error = $this->db->error();
  2370. return -1;
  2371. }
  2372. } else {
  2373. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  2374. $this->error = 'Status of the object is incompatible '.$this->statut;
  2375. return -2;
  2376. }
  2377. }
  2378. /**
  2379. * Change the transport mode methods
  2380. *
  2381. * @param int $id Id of transport mode
  2382. * @return int >0 if OK, <0 if KO
  2383. */
  2384. public function setTransportMode($id)
  2385. {
  2386. dol_syslog(get_class($this).'::setTransportMode('.$id.')');
  2387. if ($this->statut >= 0 || $this->element == 'societe') {
  2388. $fieldname = 'fk_transport_mode';
  2389. if ($this->element == 'societe') {
  2390. $fieldname = 'transport_mode';
  2391. }
  2392. if (get_class($this) == 'Fournisseur') {
  2393. $fieldname = 'transport_mode_supplier';
  2394. }
  2395. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2396. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2397. $sql .= ' WHERE rowid='.((int) $this->id);
  2398. if ($this->db->query($sql)) {
  2399. $this->transport_mode_id = $id;
  2400. // for supplier
  2401. if (get_class($this) == 'Fournisseur') {
  2402. $this->transport_mode_supplier_id = $id;
  2403. }
  2404. return 1;
  2405. } else {
  2406. dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
  2407. $this->error = $this->db->error();
  2408. return -1;
  2409. }
  2410. } else {
  2411. dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
  2412. $this->error = 'Status of the object is incompatible '.$this->statut;
  2413. return -2;
  2414. }
  2415. }
  2416. /**
  2417. * Change the retained warranty payments terms
  2418. *
  2419. * @param int $id Id of new payment terms
  2420. * @return int >0 if OK, <0 if KO
  2421. */
  2422. public function setRetainedWarrantyPaymentTerms($id)
  2423. {
  2424. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
  2425. if ($this->statut >= 0 || $this->element == 'societe') {
  2426. $fieldname = 'retained_warranty_fk_cond_reglement';
  2427. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2428. $sql .= " SET ".$fieldname." = ".((int) $id);
  2429. $sql .= ' WHERE rowid='.((int) $this->id);
  2430. if ($this->db->query($sql)) {
  2431. $this->retained_warranty_fk_cond_reglement = $id;
  2432. return 1;
  2433. } else {
  2434. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
  2435. $this->error = $this->db->error();
  2436. return -1;
  2437. }
  2438. } else {
  2439. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  2440. $this->error = 'Status of the object is incompatible '.$this->statut;
  2441. return -2;
  2442. }
  2443. }
  2444. /**
  2445. * Define delivery address
  2446. * @deprecated
  2447. *
  2448. * @param int $id Address id
  2449. * @return int <0 si ko, >0 si ok
  2450. */
  2451. public function setDeliveryAddress($id)
  2452. {
  2453. $fieldname = 'fk_delivery_address';
  2454. if ($this->element == 'delivery' || $this->element == 'shipping') {
  2455. $fieldname = 'fk_address';
  2456. }
  2457. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$fieldname." = ".((int) $id);
  2458. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
  2459. if ($this->db->query($sql)) {
  2460. $this->fk_delivery_address = $id;
  2461. return 1;
  2462. } else {
  2463. $this->error = $this->db->error();
  2464. dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
  2465. return -1;
  2466. }
  2467. }
  2468. /**
  2469. * Change the shipping method
  2470. *
  2471. * @param int $shipping_method_id Id of shipping method
  2472. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2473. * @param User $userused Object user
  2474. *
  2475. * @return int 1 if OK, 0 if KO
  2476. */
  2477. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  2478. {
  2479. global $user;
  2480. if (empty($userused)) {
  2481. $userused = $user;
  2482. }
  2483. $error = 0;
  2484. if (!$this->table_element) {
  2485. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2486. return -1;
  2487. }
  2488. $this->db->begin();
  2489. if ($shipping_method_id < 0) {
  2490. $shipping_method_id = 'NULL';
  2491. }
  2492. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  2493. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2494. $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
  2495. $sql .= " WHERE rowid=".((int) $this->id);
  2496. $resql = $this->db->query($sql);
  2497. if (!$resql) {
  2498. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  2499. $this->error = $this->db->lasterror();
  2500. $error++;
  2501. } else {
  2502. if (!$notrigger) {
  2503. // Call trigger
  2504. $this->context = array('shippingmethodupdate'=>1);
  2505. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2506. if ($result < 0) {
  2507. $error++;
  2508. }
  2509. // End call trigger
  2510. }
  2511. }
  2512. if ($error) {
  2513. $this->db->rollback();
  2514. return -1;
  2515. } else {
  2516. $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
  2517. $this->db->commit();
  2518. return 1;
  2519. }
  2520. }
  2521. /**
  2522. * Change the warehouse
  2523. *
  2524. * @param int $warehouse_id Id of warehouse
  2525. * @return int 1 if OK, 0 if KO
  2526. */
  2527. public function setWarehouse($warehouse_id)
  2528. {
  2529. if (!$this->table_element) {
  2530. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2531. return -1;
  2532. }
  2533. if ($warehouse_id < 0) {
  2534. $warehouse_id = 'NULL';
  2535. }
  2536. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  2537. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2538. $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
  2539. $sql .= " WHERE rowid=".((int) $this->id);
  2540. if ($this->db->query($sql)) {
  2541. $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
  2542. return 1;
  2543. } else {
  2544. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  2545. $this->error = $this->db->error();
  2546. return 0;
  2547. }
  2548. }
  2549. /**
  2550. * Set last model used by doc generator
  2551. *
  2552. * @param User $user User object that make change
  2553. * @param string $modelpdf Modele name
  2554. * @return int <0 if KO, >0 if OK
  2555. */
  2556. public function setDocModel($user, $modelpdf)
  2557. {
  2558. if (!$this->table_element) {
  2559. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2560. return -1;
  2561. }
  2562. $newmodelpdf = dol_trunc($modelpdf, 255);
  2563. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2564. $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  2565. $sql .= " WHERE rowid = ".((int) $this->id);
  2566. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  2567. $resql = $this->db->query($sql);
  2568. if ($resql) {
  2569. $this->model_pdf = $modelpdf;
  2570. $this->modelpdf = $modelpdf; // For bakward compatibility
  2571. return 1;
  2572. } else {
  2573. dol_print_error($this->db);
  2574. return 0;
  2575. }
  2576. }
  2577. /**
  2578. * Change the bank account
  2579. *
  2580. * @param int $fk_account Id of bank account
  2581. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2582. * @param User $userused Object user
  2583. * @return int 1 if OK, 0 if KO
  2584. */
  2585. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2586. {
  2587. global $user;
  2588. if (empty($userused)) {
  2589. $userused = $user;
  2590. }
  2591. $error = 0;
  2592. if (!$this->table_element) {
  2593. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2594. return -1;
  2595. }
  2596. $this->db->begin();
  2597. if ($fk_account < 0) {
  2598. $fk_account = 'NULL';
  2599. }
  2600. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  2601. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2602. $sql .= " SET fk_account = ".((int) $fk_account);
  2603. $sql .= " WHERE rowid=".((int) $this->id);
  2604. $resql = $this->db->query($sql);
  2605. if (!$resql) {
  2606. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  2607. $this->error = $this->db->lasterror();
  2608. $error++;
  2609. } else {
  2610. if (!$notrigger) {
  2611. // Call trigger
  2612. $this->context = array('bankaccountupdate'=>1);
  2613. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2614. if ($result < 0) {
  2615. $error++;
  2616. }
  2617. // End call trigger
  2618. }
  2619. }
  2620. if ($error) {
  2621. $this->db->rollback();
  2622. return -1;
  2623. } else {
  2624. $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
  2625. $this->db->commit();
  2626. return 1;
  2627. }
  2628. }
  2629. // TODO: Move line related operations to CommonObjectLine?
  2630. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2631. /**
  2632. * Save a new position (field rang) for details lines.
  2633. * You can choose to set position for lines with already a position or lines without any position defined.
  2634. *
  2635. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2636. * @param string $rowidorder ASC or DESC
  2637. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2638. * @return int <0 if KO, >0 if OK
  2639. */
  2640. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2641. {
  2642. // phpcs:enable
  2643. if (!$this->table_element_line) {
  2644. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2645. return -1;
  2646. }
  2647. if (!$this->fk_element) {
  2648. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2649. return -1;
  2650. }
  2651. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2652. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2653. $fieldposition = 'position';
  2654. }
  2655. // Count number of lines to reorder (according to choice $renum)
  2656. $nl = 0;
  2657. $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
  2658. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2659. if (!$renum) {
  2660. $sql .= " AND " . $fieldposition . " = 0";
  2661. }
  2662. if ($renum) {
  2663. $sql .= " AND " . $fieldposition . " <> 0";
  2664. }
  2665. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  2666. $resql = $this->db->query($sql);
  2667. if ($resql) {
  2668. $row = $this->db->fetch_row($resql);
  2669. $nl = $row[0];
  2670. } else {
  2671. dol_print_error($this->db);
  2672. }
  2673. if ($nl > 0) {
  2674. // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
  2675. $rows = array();
  2676. // We first search all lines that are parent lines (for multilevel details lines)
  2677. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2678. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2679. if ($fk_parent_line) {
  2680. $sql .= ' AND fk_parent_line IS NULL';
  2681. }
  2682. $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder;
  2683. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  2684. $resql = $this->db->query($sql);
  2685. if ($resql) {
  2686. $i = 0;
  2687. $num = $this->db->num_rows($resql);
  2688. while ($i < $num) {
  2689. $row = $this->db->fetch_row($resql);
  2690. $rows[] = $row[0]; // Add parent line into array rows
  2691. $childrens = $this->getChildrenOfLine($row[0]);
  2692. if (!empty($childrens)) {
  2693. foreach ($childrens as $child) {
  2694. array_push($rows, $child);
  2695. }
  2696. }
  2697. $i++;
  2698. }
  2699. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2700. if (!empty($rows)) {
  2701. foreach ($rows as $key => $row) {
  2702. $this->updateRangOfLine($row, ($key + 1));
  2703. }
  2704. }
  2705. } else {
  2706. dol_print_error($this->db);
  2707. }
  2708. }
  2709. return 1;
  2710. }
  2711. /**
  2712. * Get children of line
  2713. *
  2714. * @param int $id Id of parent line
  2715. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2716. * @return array Array with list of children lines id
  2717. */
  2718. public function getChildrenOfLine($id, $includealltree = 0)
  2719. {
  2720. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2721. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2722. $fieldposition = 'position';
  2723. }
  2724. $rows = array();
  2725. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2726. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2727. $sql .= ' AND fk_parent_line = '.((int) $id);
  2728. $sql .= " ORDER BY " . $fieldposition . " ASC";
  2729. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
  2730. $resql = $this->db->query($sql);
  2731. if ($resql) {
  2732. if ($this->db->num_rows($resql) > 0) {
  2733. while ($row = $this->db->fetch_row($resql)) {
  2734. $rows[] = $row[0];
  2735. if (!empty($includealltree)) {
  2736. $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2737. }
  2738. }
  2739. }
  2740. }
  2741. return $rows;
  2742. }
  2743. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2744. /**
  2745. * Update a line to have a lower rank
  2746. *
  2747. * @param int $rowid Id of line
  2748. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2749. * @return void
  2750. */
  2751. public function line_up($rowid, $fk_parent_line = true)
  2752. {
  2753. // phpcs:enable
  2754. $this->line_order(false, 'ASC', $fk_parent_line);
  2755. // Get rang of line
  2756. $rang = $this->getRangOfLine($rowid);
  2757. // Update position of line
  2758. $this->updateLineUp($rowid, $rang);
  2759. }
  2760. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2761. /**
  2762. * Update a line to have a higher rank
  2763. *
  2764. * @param int $rowid Id of line
  2765. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2766. * @return void
  2767. */
  2768. public function line_down($rowid, $fk_parent_line = true)
  2769. {
  2770. // phpcs:enable
  2771. $this->line_order(false, 'ASC', $fk_parent_line);
  2772. // Get rang of line
  2773. $rang = $this->getRangOfLine($rowid);
  2774. // Get max value for rang
  2775. $max = $this->line_max();
  2776. // Update position of line
  2777. $this->updateLineDown($rowid, $rang, $max);
  2778. }
  2779. /**
  2780. * Update position of line (rang)
  2781. *
  2782. * @param int $rowid Id of line
  2783. * @param int $rang Position
  2784. * @return int <0 if KO, >0 if OK
  2785. */
  2786. public function updateRangOfLine($rowid, $rang)
  2787. {
  2788. global $hookmanager;
  2789. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2790. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2791. $fieldposition = 'position';
  2792. }
  2793. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2794. $sql .= ' WHERE rowid = '.((int) $rowid);
  2795. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2796. if (!$this->db->query($sql)) {
  2797. dol_print_error($this->db);
  2798. return -1;
  2799. } else {
  2800. $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
  2801. $action='';
  2802. $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
  2803. return 1;
  2804. }
  2805. }
  2806. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2807. /**
  2808. * Update position of line with ajax (rang)
  2809. *
  2810. * @param array $rows Array of rows
  2811. * @return void
  2812. */
  2813. public function line_ajaxorder($rows)
  2814. {
  2815. // phpcs:enable
  2816. $num = count($rows);
  2817. for ($i = 0; $i < $num; $i++) {
  2818. $this->updateRangOfLine($rows[$i], ($i + 1));
  2819. }
  2820. }
  2821. /**
  2822. * Update position of line up (rang)
  2823. *
  2824. * @param int $rowid Id of line
  2825. * @param int $rang Position
  2826. * @return void
  2827. */
  2828. public function updateLineUp($rowid, $rang)
  2829. {
  2830. if ($rang > 1) {
  2831. $fieldposition = 'rang';
  2832. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2833. $fieldposition = 'position';
  2834. }
  2835. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2836. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2837. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1));
  2838. if ($this->db->query($sql)) {
  2839. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
  2840. $sql .= ' WHERE rowid = '.((int) $rowid);
  2841. if (!$this->db->query($sql)) {
  2842. dol_print_error($this->db);
  2843. }
  2844. } else {
  2845. dol_print_error($this->db);
  2846. }
  2847. }
  2848. }
  2849. /**
  2850. * Update position of line down (rang)
  2851. *
  2852. * @param int $rowid Id of line
  2853. * @param int $rang Position
  2854. * @param int $max Max
  2855. * @return void
  2856. */
  2857. public function updateLineDown($rowid, $rang, $max)
  2858. {
  2859. if ($rang < $max) {
  2860. $fieldposition = 'rang';
  2861. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2862. $fieldposition = 'position';
  2863. }
  2864. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2865. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2866. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1));
  2867. if ($this->db->query($sql)) {
  2868. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
  2869. $sql .= ' WHERE rowid = '.((int) $rowid);
  2870. if (!$this->db->query($sql)) {
  2871. dol_print_error($this->db);
  2872. }
  2873. } else {
  2874. dol_print_error($this->db);
  2875. }
  2876. }
  2877. }
  2878. /**
  2879. * Get position of line (rang)
  2880. *
  2881. * @param int $rowid Id of line
  2882. * @return int Value of rang in table of lines
  2883. */
  2884. public function getRangOfLine($rowid)
  2885. {
  2886. $fieldposition = 'rang';
  2887. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2888. $fieldposition = 'position';
  2889. }
  2890. $sql = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line;
  2891. $sql .= " WHERE rowid = ".((int) $rowid);
  2892. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  2893. $resql = $this->db->query($sql);
  2894. if ($resql) {
  2895. $row = $this->db->fetch_row($resql);
  2896. return $row[0];
  2897. }
  2898. }
  2899. /**
  2900. * Get rowid of the line relative to its position
  2901. *
  2902. * @param int $rang Rang value
  2903. * @return int Rowid of the line
  2904. */
  2905. public function getIdOfLine($rang)
  2906. {
  2907. $fieldposition = 'rang';
  2908. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2909. $fieldposition = 'position';
  2910. }
  2911. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2912. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2913. $sql .= " AND " . $fieldposition . " = ".((int) $rang);
  2914. $resql = $this->db->query($sql);
  2915. if ($resql) {
  2916. $row = $this->db->fetch_row($resql);
  2917. return $row[0];
  2918. }
  2919. }
  2920. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2921. /**
  2922. * Get max value used for position of line (rang)
  2923. *
  2924. * @param int $fk_parent_line Parent line id
  2925. * @return int Max value of rang in table of lines
  2926. */
  2927. public function line_max($fk_parent_line = 0)
  2928. {
  2929. // phpcs:enable
  2930. $positionfield = 'rang';
  2931. if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
  2932. $positionfield = 'position';
  2933. }
  2934. // Search the last rang with fk_parent_line
  2935. if ($fk_parent_line) {
  2936. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  2937. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2938. $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
  2939. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2940. $resql = $this->db->query($sql);
  2941. if ($resql) {
  2942. $row = $this->db->fetch_row($resql);
  2943. if (!empty($row[0])) {
  2944. return $row[0];
  2945. } else {
  2946. return $this->getRangOfLine($fk_parent_line);
  2947. }
  2948. }
  2949. } else {
  2950. // If not, search the last rang of element
  2951. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  2952. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2953. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2954. $resql = $this->db->query($sql);
  2955. if ($resql) {
  2956. $row = $this->db->fetch_row($resql);
  2957. return $row[0];
  2958. }
  2959. }
  2960. }
  2961. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2962. /**
  2963. * Update external ref of element
  2964. *
  2965. * @param string $ref_ext Update field ref_ext
  2966. * @return int <0 if KO, >0 if OK
  2967. */
  2968. public function update_ref_ext($ref_ext)
  2969. {
  2970. // phpcs:enable
  2971. if (!$this->table_element) {
  2972. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  2973. return -1;
  2974. }
  2975. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2976. $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  2977. $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
  2978. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  2979. if ($this->db->query($sql)) {
  2980. $this->ref_ext = $ref_ext;
  2981. return 1;
  2982. } else {
  2983. $this->error = $this->db->error();
  2984. return -1;
  2985. }
  2986. }
  2987. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2988. /**
  2989. * Update note of element
  2990. *
  2991. * @param string $note New value for note
  2992. * @param string $suffix '', '_public' or '_private'
  2993. * @return int <0 if KO, >0 if OK
  2994. */
  2995. public function update_note($note, $suffix = '')
  2996. {
  2997. // phpcs:enable
  2998. global $user;
  2999. if (!$this->table_element) {
  3000. $this->error = 'update_note was called on objet with property table_element not defined';
  3001. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  3002. return -1;
  3003. }
  3004. if (!in_array($suffix, array('', '_public', '_private'))) {
  3005. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  3006. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  3007. return -2;
  3008. }
  3009. $newsuffix = $suffix;
  3010. // Special cas
  3011. if ($this->table_element == 'product' && $newsuffix == '_private') {
  3012. $newsuffix = '';
  3013. }
  3014. if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  3015. $fieldusermod = "fk_user_mod";
  3016. } elseif ($this->table_element == 'ecm_files') {
  3017. $fieldusermod = "fk_user_m";
  3018. } else {
  3019. $fieldusermod = "fk_user_modif";
  3020. }
  3021. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  3022. $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
  3023. $sql .= ", ".$fieldusermod." = ".((int) $user->id);
  3024. $sql .= " WHERE rowid = ".((int) $this->id);
  3025. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  3026. if ($this->db->query($sql)) {
  3027. if ($suffix == '_public') {
  3028. $this->note_public = $note;
  3029. } elseif ($suffix == '_private') {
  3030. $this->note_private = $note;
  3031. } else {
  3032. $this->note = $note; // deprecated
  3033. $this->note_private = $note;
  3034. }
  3035. return 1;
  3036. } else {
  3037. $this->error = $this->db->lasterror();
  3038. return -1;
  3039. }
  3040. }
  3041. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3042. /**
  3043. * Update public note (kept for backward compatibility)
  3044. *
  3045. * @param string $note New value for note
  3046. * @return int <0 if KO, >0 if OK
  3047. * @deprecated
  3048. * @see update_note()
  3049. */
  3050. public function update_note_public($note)
  3051. {
  3052. // phpcs:enable
  3053. return $this->update_note($note, '_public');
  3054. }
  3055. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3056. /**
  3057. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  3058. * Must be called at end of methods addline or updateline.
  3059. *
  3060. * @param int $exclspec >0 = Exclude special product (product_type=9)
  3061. * @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
  3062. * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object.
  3063. * @param Societe $seller If roundingadjust is '0' or '1' or maybe 'auto', it means we recalculate total for lines before calculating total for object and for this, we need seller object (used to analyze lines to check corrupted data).
  3064. * @return int <0 if KO, >0 if OK
  3065. */
  3066. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  3067. {
  3068. // phpcs:enable
  3069. global $conf, $hookmanager, $action;
  3070. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  3071. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3072. if ($reshook > 0) {
  3073. return 1; // replacement code
  3074. } elseif ($reshook < 0) {
  3075. return -1; // failure
  3076. } // reshook = 0 => execute normal code
  3077. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  3078. $MODULE = "";
  3079. if ($this->element == 'propal') {
  3080. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  3081. } elseif ($this->element == 'commande' || $this->element == 'order') {
  3082. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  3083. } elseif ($this->element == 'facture' || $this->element == 'invoice') {
  3084. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  3085. } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
  3086. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  3087. } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
  3088. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  3089. } elseif ($this->element == 'supplier_proposal') {
  3090. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  3091. }
  3092. if (!empty($MODULE)) {
  3093. if (!empty($conf->global->$MODULE)) {
  3094. $modsactivated = explode(',', $conf->global->$MODULE);
  3095. foreach ($modsactivated as $mod) {
  3096. if ($conf->$mod->enabled) {
  3097. return 1; // update was disabled by specific setup
  3098. }
  3099. }
  3100. }
  3101. }
  3102. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  3103. if ($roundingadjust == '-1') {
  3104. $roundingadjust = 'auto'; // For backward compatibility
  3105. }
  3106. $forcedroundingmode = $roundingadjust;
  3107. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
  3108. $forcedroundingmode = $conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
  3109. } elseif ($forcedroundingmode == 'auto') {
  3110. $forcedroundingmode = '0';
  3111. }
  3112. $error = 0;
  3113. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  3114. // Define constants to find lines to sum
  3115. $fieldtva = 'total_tva';
  3116. $fieldlocaltax1 = 'total_localtax1';
  3117. $fieldlocaltax2 = 'total_localtax2';
  3118. $fieldup = 'subprice';
  3119. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3120. $fieldtva = 'tva';
  3121. $fieldup = 'pu_ht';
  3122. }
  3123. if ($this->element == 'invoice_supplier_rec') {
  3124. $fieldup = 'pu_ht';
  3125. }
  3126. if ($this->element == 'expensereport') {
  3127. $fieldup = 'value_unit';
  3128. }
  3129. $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,";
  3130. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  3131. if ($this->table_element_line == 'facturedet') {
  3132. $sql .= ', situation_percent';
  3133. }
  3134. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3135. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  3136. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3137. if ($exclspec) {
  3138. $product_field = 'product_type';
  3139. if ($this->table_element_line == 'contratdet') {
  3140. $product_field = ''; // contratdet table has no product_type field
  3141. }
  3142. if ($product_field) {
  3143. $sql .= " AND ".$product_field." <> 9";
  3144. }
  3145. }
  3146. $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
  3147. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3148. $resql = $this->db->query($sql);
  3149. if ($resql) {
  3150. $this->total_ht = 0;
  3151. $this->total_tva = 0;
  3152. $this->total_localtax1 = 0;
  3153. $this->total_localtax2 = 0;
  3154. $this->total_ttc = 0;
  3155. $total_ht_by_vats = array();
  3156. $total_tva_by_vats = array();
  3157. $total_ttc_by_vats = array();
  3158. $this->multicurrency_total_ht = 0;
  3159. $this->multicurrency_total_tva = 0;
  3160. $this->multicurrency_total_ttc = 0;
  3161. $num = $this->db->num_rows($resql);
  3162. $i = 0;
  3163. while ($i < $num) {
  3164. $obj = $this->db->fetch_object($resql);
  3165. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  3166. $parameters = array('fk_element' => $obj->rowid);
  3167. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3168. 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'
  3169. // This part of code is to fix data. We should not call it too often.
  3170. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  3171. $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);
  3172. $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.
  3173. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  3174. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
  3175. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  3176. if ($diff_when_using_price_ht && $diff_on_current_total) {
  3177. $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2])." WHERE rowid = ".((int) $obj->rowid);
  3178. 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);
  3179. $resqlfix = $this->db->query($sqlfix);
  3180. if (!$resqlfix) {
  3181. dol_print_error($this->db, 'Failed to update line');
  3182. }
  3183. $obj->total_tva = $tmpcal[1];
  3184. $obj->total_ttc = $tmpcal[2];
  3185. }
  3186. }
  3187. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  3188. $this->total_tva += $obj->total_tva;
  3189. $this->total_localtax1 += $obj->total_localtax1;
  3190. $this->total_localtax2 += $obj->total_localtax2;
  3191. $this->total_ttc += $obj->total_ttc;
  3192. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  3193. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  3194. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  3195. if (!isset($total_ht_by_vats[$obj->vatrate])) {
  3196. $total_ht_by_vats[$obj->vatrate] = 0;
  3197. }
  3198. if (!isset($total_tva_by_vats[$obj->vatrate])) {
  3199. $total_tva_by_vats[$obj->vatrate] = 0;
  3200. }
  3201. if (!isset($total_ttc_by_vats[$obj->vatrate])) {
  3202. $total_ttc_by_vats[$obj->vatrate] = 0;
  3203. }
  3204. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  3205. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  3206. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  3207. if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  3208. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  3209. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  3210. //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";
  3211. if ($diff) {
  3212. if (abs($diff) > 0.1) {
  3213. $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.';
  3214. dol_syslog($errmsg, LOG_WARNING);
  3215. dol_print_error('', $errmsg);
  3216. exit;
  3217. }
  3218. $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num($obj->total_tva - $diff).", total_ttc = ".price2num($obj->total_ttc - $diff)." WHERE rowid = ".((int) $obj->rowid);
  3219. 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);
  3220. $resqlfix = $this->db->query($sqlfix);
  3221. if (!$resqlfix) {
  3222. dol_print_error($this->db, 'Failed to update line');
  3223. }
  3224. $this->total_tva -= $diff;
  3225. $this->total_ttc -= $diff;
  3226. $total_tva_by_vats[$obj->vatrate] -= $diff;
  3227. $total_ttc_by_vats[$obj->vatrate] -= $diff;
  3228. }
  3229. }
  3230. $i++;
  3231. }
  3232. // Add revenue stamp to total
  3233. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  3234. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  3235. // Situations totals
  3236. if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
  3237. $prev_sits = $this->get_prev_sits();
  3238. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  3239. $this->total_ht -= $sit->total_ht;
  3240. $this->total_tva -= $sit->total_tva;
  3241. $this->total_localtax1 -= $sit->total_localtax1;
  3242. $this->total_localtax2 -= $sit->total_localtax2;
  3243. $this->total_ttc -= $sit->total_ttc;
  3244. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  3245. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  3246. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  3247. }
  3248. }
  3249. $this->db->free($resql);
  3250. // Now update global field total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_*
  3251. $fieldht = 'total_ht';
  3252. $fieldtva = 'tva';
  3253. $fieldlocaltax1 = 'localtax1';
  3254. $fieldlocaltax2 = 'localtax2';
  3255. $fieldttc = 'total_ttc';
  3256. // Specific code for backward compatibility with old field names
  3257. if ($this->element == 'facture' || $this->element == 'facturerec') {
  3258. $fieldtva = 'total_tva';
  3259. }
  3260. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
  3261. $fieldtva = 'total_tva';
  3262. }
  3263. if ($this->element == 'propal') {
  3264. $fieldtva = 'total_tva';
  3265. }
  3266. if ($this->element == 'expensereport') {
  3267. $fieldtva = 'total_tva';
  3268. }
  3269. if ($this->element == 'supplier_proposal') {
  3270. $fieldtva = 'total_tva';
  3271. }
  3272. if ($this->element == 'commande') {
  3273. $fieldtva = 'total_tva';
  3274. }
  3275. if ($this->element == 'order_supplier') {
  3276. $fieldtva = 'total_tva';
  3277. }
  3278. if (empty($nodatabaseupdate)) {
  3279. $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
  3280. $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht)).",";
  3281. $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva)).",";
  3282. $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1)).",";
  3283. $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2)).",";
  3284. $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc));
  3285. $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
  3286. $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
  3287. $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
  3288. $sql .= " WHERE rowid = ".((int) $this->id);
  3289. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3290. $resql = $this->db->query($sql);
  3291. if (!$resql) {
  3292. $error++;
  3293. $this->error = $this->db->lasterror();
  3294. $this->errors[] = $this->db->lasterror();
  3295. }
  3296. }
  3297. if (!$error) {
  3298. return 1;
  3299. } else {
  3300. return -1;
  3301. }
  3302. } else {
  3303. dol_print_error($this->db, 'Bad request in update_price');
  3304. return -1;
  3305. }
  3306. }
  3307. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3308. /**
  3309. * Add objects linked in llx_element_element.
  3310. *
  3311. * @param string $origin Linked element type
  3312. * @param int $origin_id Linked element id
  3313. * @param User $f_user User that create
  3314. * @param int $notrigger 1=Does not execute triggers, 0=execute triggers
  3315. * @return int <=0 if KO, >0 if OK
  3316. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  3317. */
  3318. public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
  3319. {
  3320. // phpcs:enable
  3321. global $user, $hookmanager, $action;
  3322. $origin = (!empty($origin) ? $origin : $this->origin);
  3323. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  3324. $f_user = isset($f_user) ? $f_user : $user;
  3325. // Special case
  3326. if ($origin == 'order') {
  3327. $origin = 'commande';
  3328. }
  3329. if ($origin == 'invoice') {
  3330. $origin = 'facture';
  3331. }
  3332. if ($origin == 'invoice_template') {
  3333. $origin = 'facturerec';
  3334. }
  3335. if ($origin == 'supplierorder') {
  3336. $origin = 'order_supplier';
  3337. }
  3338. // Elements of the core modules which have `$module` property but may to which we don't want to prefix module part to the element name for finding the linked object in llx_element_element.
  3339. // It's because an entry for this element may be exist in llx_element_element before this modification (version <=14.2) and ave named only with their element name in fk_source or fk_target.
  3340. $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
  3341. // Add module part to target type if object has $module property and isn't in core modules.
  3342. $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
  3343. $parameters = array('targettype'=>$targettype);
  3344. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3345. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3346. if ($reshook > 0) {
  3347. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3348. }
  3349. $this->db->begin();
  3350. $error = 0;
  3351. $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
  3352. $sql .= "fk_source";
  3353. $sql .= ", sourcetype";
  3354. $sql .= ", fk_target";
  3355. $sql .= ", targettype";
  3356. $sql .= ") VALUES (";
  3357. $sql .= ((int) $origin_id);
  3358. $sql .= ", '" . $this->db->escape($origin) . "'";
  3359. $sql .= ", " . ((int) $this->id);
  3360. $sql .= ", '" . $this->db->escape($targettype) . "'";
  3361. $sql .= ")";
  3362. dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
  3363. if ($this->db->query($sql)) {
  3364. if (!$notrigger) {
  3365. // Call trigger
  3366. $this->context['link_origin'] = $origin;
  3367. $this->context['link_origin_id'] = $origin_id;
  3368. $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
  3369. if ($result < 0) {
  3370. $error++;
  3371. }
  3372. // End call triggers
  3373. }
  3374. } else {
  3375. $this->error = $this->db->lasterror();
  3376. $error++;
  3377. }
  3378. if (!$error) {
  3379. $this->db->commit();
  3380. return 1;
  3381. } else {
  3382. $this->db->rollback();
  3383. return 0;
  3384. }
  3385. }
  3386. /**
  3387. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  3388. * this->linkedObjectsIds array +
  3389. * this->linkedObjects array if $loadalsoobjects = 1 or $loadalsoobjects = type
  3390. * Possible usage for parameters:
  3391. * - all parameters empty -> we look all link to current object (current object can be source or target)
  3392. * - source id+type -> will get list of targets linked to source
  3393. * - target id+type -> will get list of sources linked to target
  3394. * - source id+type + target type -> will get list of targets of the type linked to source
  3395. * - target id+type + source type -> will get list of sources of the type linked to target
  3396. *
  3397. * @param int $sourceid Object source id (if not defined, id of object)
  3398. * @param string $sourcetype Object source type (if not defined, element name of object)
  3399. * @param int $targetid Object target id (if not defined, id of object)
  3400. * @param string $targettype Object target type (if not defined, element name of object)
  3401. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  3402. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  3403. * @param string $orderby SQL 'ORDER BY' clause
  3404. * @param int|string $loadalsoobjects Load also array this->linkedObjects. Use 0 to increase performances, Use 1 to load all, Use value of type ('facture', 'facturerec', ...) to load only a type of object.
  3405. * @return int <0 if KO, >0 if OK
  3406. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  3407. */
  3408. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  3409. {
  3410. global $conf, $hookmanager, $action;
  3411. // Important for pdf generation time reduction
  3412. // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
  3413. if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
  3414. return 1;
  3415. }
  3416. $this->linkedObjectsIds = array();
  3417. $this->linkedObjects = array();
  3418. $justsource = false;
  3419. $justtarget = false;
  3420. $withtargettype = false;
  3421. $withsourcetype = false;
  3422. $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
  3423. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3424. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3425. if ($reshook > 0) {
  3426. if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
  3427. if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
  3428. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3429. if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
  3430. }
  3431. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
  3432. $justsource = true; // the source (id and type) is a search criteria
  3433. if (!empty($targettype)) {
  3434. $withtargettype = true;
  3435. }
  3436. }
  3437. if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
  3438. $justtarget = true; // the target (id and type) is a search criteria
  3439. if (!empty($sourcetype)) {
  3440. $withsourcetype = true;
  3441. }
  3442. }
  3443. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3444. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3445. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3446. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3447. /*if (empty($sourceid) && empty($targetid))
  3448. {
  3449. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  3450. return -1;
  3451. }*/
  3452. // Links between objects are stored in table element_element
  3453. $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
  3454. $sql .= " FROM ".$this->db->prefix()."element_element";
  3455. $sql .= " WHERE ";
  3456. if ($justsource || $justtarget) {
  3457. if ($justsource) {
  3458. $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3459. if ($withtargettype) {
  3460. $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
  3461. }
  3462. } elseif ($justtarget) {
  3463. $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
  3464. if ($withsourcetype) {
  3465. $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3466. }
  3467. }
  3468. } else {
  3469. $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
  3470. $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
  3471. if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
  3472. $this->linkedObjectsFullLoaded[$this->id] = true;
  3473. }
  3474. }
  3475. $sql .= " ORDER BY ".$orderby;
  3476. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  3477. $resql = $this->db->query($sql);
  3478. if ($resql) {
  3479. $num = $this->db->num_rows($resql);
  3480. $i = 0;
  3481. while ($i < $num) {
  3482. $obj = $this->db->fetch_object($resql);
  3483. if ($justsource || $justtarget) {
  3484. if ($justsource) {
  3485. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3486. } elseif ($justtarget) {
  3487. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3488. }
  3489. } else {
  3490. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
  3491. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3492. }
  3493. if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
  3494. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3495. }
  3496. }
  3497. $i++;
  3498. }
  3499. if (!empty($this->linkedObjectsIds)) {
  3500. $tmparray = $this->linkedObjectsIds;
  3501. foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  3502. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  3503. $module = $element = $subelement = $objecttype;
  3504. $regs = array();
  3505. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  3506. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  3507. $module = $element = $regs[1];
  3508. $subelement = $regs[2];
  3509. }
  3510. $classpath = $element.'/class';
  3511. // To work with non standard classpath or module name
  3512. if ($objecttype == 'facture') {
  3513. $classpath = 'compta/facture/class';
  3514. } elseif ($objecttype == 'facturerec') {
  3515. $classpath = 'compta/facture/class';
  3516. $module = 'facture';
  3517. } elseif ($objecttype == 'propal') {
  3518. $classpath = 'comm/propal/class';
  3519. } elseif ($objecttype == 'supplier_proposal') {
  3520. $classpath = 'supplier_proposal/class';
  3521. } elseif ($objecttype == 'shipping') {
  3522. $classpath = 'expedition/class';
  3523. $subelement = 'expedition';
  3524. $module = 'expedition_bon';
  3525. } elseif ($objecttype == 'delivery') {
  3526. $classpath = 'delivery/class';
  3527. $subelement = 'delivery';
  3528. $module = 'delivery_note';
  3529. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  3530. $classpath = 'fourn/class';
  3531. $module = 'fournisseur';
  3532. } elseif ($objecttype == 'fichinter') {
  3533. $classpath = 'fichinter/class';
  3534. $subelement = 'fichinter';
  3535. $module = 'ficheinter';
  3536. } elseif ($objecttype == 'subscription') {
  3537. $classpath = 'adherents/class';
  3538. $module = 'adherent';
  3539. } elseif ($objecttype == 'contact') {
  3540. $module = 'societe';
  3541. }
  3542. // Set classfile
  3543. $classfile = strtolower($subelement);
  3544. $classname = ucfirst($subelement);
  3545. if ($objecttype == 'order') {
  3546. $classfile = 'commande';
  3547. $classname = 'Commande';
  3548. } elseif ($objecttype == 'invoice_supplier') {
  3549. $classfile = 'fournisseur.facture';
  3550. $classname = 'FactureFournisseur';
  3551. } elseif ($objecttype == 'order_supplier') {
  3552. $classfile = 'fournisseur.commande';
  3553. $classname = 'CommandeFournisseur';
  3554. } elseif ($objecttype == 'supplier_proposal') {
  3555. $classfile = 'supplier_proposal';
  3556. $classname = 'SupplierProposal';
  3557. } elseif ($objecttype == 'facturerec') {
  3558. $classfile = 'facture-rec';
  3559. $classname = 'FactureRec';
  3560. } elseif ($objecttype == 'subscription') {
  3561. $classfile = 'subscription';
  3562. $classname = 'Subscription';
  3563. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  3564. $classpath = 'projet/class';
  3565. $classfile = 'project';
  3566. $classname = 'Project';
  3567. } elseif ($objecttype == 'conferenceorboothattendee') {
  3568. $classpath = 'eventorganization/class';
  3569. $classfile = 'conferenceorboothattendee';
  3570. $classname = 'ConferenceOrBoothAttendee';
  3571. $module = 'eventorganization';
  3572. } elseif ($objecttype == 'conferenceorbooth') {
  3573. $classpath = 'eventorganization/class';
  3574. $classfile = 'conferenceorbooth';
  3575. $classname = 'ConferenceOrBooth';
  3576. $module = 'eventorganization';
  3577. } elseif ($objecttype == 'mo') {
  3578. $classpath = 'mrp/class';
  3579. $classfile = 'mo';
  3580. $classname = 'Mo';
  3581. $module = 'mrp';
  3582. }
  3583. // Here $module, $classfile and $classname are set, we can use them.
  3584. if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
  3585. if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
  3586. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  3587. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  3588. if (class_exists($classname)) {
  3589. foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
  3590. $object = new $classname($this->db);
  3591. $ret = $object->fetch($objectid);
  3592. if ($ret >= 0) {
  3593. $this->linkedObjects[$objecttype][$i] = $object;
  3594. }
  3595. }
  3596. }
  3597. }
  3598. } else {
  3599. unset($this->linkedObjectsIds[$objecttype]);
  3600. }
  3601. }
  3602. }
  3603. return 1;
  3604. } else {
  3605. dol_print_error($this->db);
  3606. return -1;
  3607. }
  3608. }
  3609. /**
  3610. * Update object linked of a current object
  3611. *
  3612. * @param int $sourceid Object source id
  3613. * @param string $sourcetype Object source type
  3614. * @param int $targetid Object target id
  3615. * @param string $targettype Object target type
  3616. * @param User $f_user User that create
  3617. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3618. * @return int >0 if OK, <0 if KO
  3619. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3620. */
  3621. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
  3622. {
  3623. global $user;
  3624. $updatesource = false;
  3625. $updatetarget = false;
  3626. $f_user = isset($f_user) ? $f_user : $user;
  3627. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3628. $updatesource = true;
  3629. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3630. $updatetarget = true;
  3631. }
  3632. $this->db->begin();
  3633. $error = 0;
  3634. $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
  3635. if ($updatesource) {
  3636. $sql .= "fk_source = " . ((int) $sourceid);
  3637. $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3638. $sql .= " WHERE fk_target = " . ((int) $this->id);
  3639. $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
  3640. } elseif ($updatetarget) {
  3641. $sql .= "fk_target = " . ((int) $targetid);
  3642. $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
  3643. $sql .= " WHERE fk_source = " . ((int) $this->id);
  3644. $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3645. }
  3646. dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
  3647. if ($this->db->query($sql)) {
  3648. if (!$notrigger) {
  3649. // Call trigger
  3650. $this->context['link_source_id'] = $sourceid;
  3651. $this->context['link_source_type'] = $sourcetype;
  3652. $this->context['link_target_id'] = $targetid;
  3653. $this->context['link_target_type'] = $targettype;
  3654. $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
  3655. if ($result < 0) {
  3656. $error++;
  3657. }
  3658. // End call triggers
  3659. }
  3660. } else {
  3661. $this->error = $this->db->lasterror();
  3662. $error++;
  3663. }
  3664. if (!$error) {
  3665. $this->db->commit();
  3666. return 1;
  3667. } else {
  3668. $this->db->rollback();
  3669. return -1;
  3670. }
  3671. }
  3672. /**
  3673. * Delete all links between an object $this
  3674. *
  3675. * @param int $sourceid Object source id
  3676. * @param string $sourcetype Object source type
  3677. * @param int $targetid Object target id
  3678. * @param string $targettype Object target type
  3679. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3680. * @param User $f_user User that create
  3681. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3682. * @return int >0 if OK, <0 if KO
  3683. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3684. */
  3685. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
  3686. {
  3687. global $user;
  3688. $deletesource = false;
  3689. $deletetarget = false;
  3690. $f_user = isset($f_user) ? $f_user : $user;
  3691. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3692. $deletesource = true;
  3693. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3694. $deletetarget = true;
  3695. }
  3696. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3697. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3698. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3699. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3700. $this->db->begin();
  3701. $error = 0;
  3702. if (!$notrigger) {
  3703. // Call trigger
  3704. $this->context['link_id'] = $rowid;
  3705. $this->context['link_source_id'] = $sourceid;
  3706. $this->context['link_source_type'] = $sourcetype;
  3707. $this->context['link_target_id'] = $targetid;
  3708. $this->context['link_target_type'] = $targettype;
  3709. $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
  3710. if ($result < 0) {
  3711. $error++;
  3712. }
  3713. // End call triggers
  3714. }
  3715. if (!$error) {
  3716. $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
  3717. $sql .= " WHERE";
  3718. if ($rowid > 0) {
  3719. $sql .= " rowid = " . ((int) $rowid);
  3720. } else {
  3721. if ($deletesource) {
  3722. $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3723. $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
  3724. } elseif ($deletetarget) {
  3725. $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
  3726. $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3727. } else {
  3728. $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
  3729. $sql .= " OR";
  3730. $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
  3731. }
  3732. }
  3733. dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
  3734. if (!$this->db->query($sql)) {
  3735. $this->error = $this->db->lasterror();
  3736. $this->errors[] = $this->error;
  3737. $error++;
  3738. }
  3739. }
  3740. if (!$error) {
  3741. $this->db->commit();
  3742. return 1;
  3743. } else {
  3744. $this->db->rollback();
  3745. return 0;
  3746. }
  3747. }
  3748. /**
  3749. * Function used to get an array with all items linked to an object id in association table
  3750. *
  3751. * @param int $fk_object_where id of object we need to get linked items
  3752. * @param string $field_select name of field we need to get a list
  3753. * @param string $field_where name of field of object we need to get linked items
  3754. * @param string $table_element name of association table
  3755. * @return array Array of record
  3756. */
  3757. public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
  3758. {
  3759. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3760. return -1;
  3761. }
  3762. global $db;
  3763. $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3764. $resql = $db->query($sql);
  3765. $TRes = array();
  3766. if (!empty($resql)) {
  3767. while ($res = $db->fetch_object($resql)) {
  3768. $TRes[] = $res->{$field_select};
  3769. }
  3770. }
  3771. return $TRes;
  3772. }
  3773. /**
  3774. * Function used to remove all items linked to an object id in association table
  3775. *
  3776. * @param int $fk_object_where id of object we need to remove linked items
  3777. * @param string $field_where name of field of object we need to delete linked items
  3778. * @param string $table_element name of association table
  3779. * @return int <0 if KO, 0 if nothing done, >0 if OK and something done
  3780. */
  3781. public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
  3782. {
  3783. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3784. return -1;
  3785. }
  3786. global $db;
  3787. $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3788. $resql = $db->query($sql);
  3789. if (empty($resql)) {
  3790. return 0;
  3791. }
  3792. return 1;
  3793. }
  3794. /**
  3795. * Set status of an object
  3796. *
  3797. * @param int $status Status to set
  3798. * @param int $elementId Id of element to force (use this->id by default if null)
  3799. * @param string $elementType Type of element to force (use this->table_element by default)
  3800. * @param string $trigkey Trigger key to use for trigger. Use '' means automatic but it not recommended and is deprecated.
  3801. * @param string $fieldstatus Name of status field in this->table_element
  3802. * @return int <0 if KO, >0 if OK
  3803. */
  3804. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
  3805. {
  3806. global $user, $langs, $conf;
  3807. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3808. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3809. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3810. $this->db->begin();
  3811. if ($elementTable == 'facture_rec') {
  3812. $fieldstatus = "suspended";
  3813. }
  3814. if ($elementTable == 'mailing') {
  3815. $fieldstatus = "statut";
  3816. }
  3817. if ($elementTable == 'cronjob') {
  3818. $fieldstatus = "status";
  3819. }
  3820. if ($elementTable == 'user') {
  3821. $fieldstatus = "statut";
  3822. }
  3823. if ($elementTable == 'expensereport') {
  3824. $fieldstatus = "fk_statut";
  3825. }
  3826. if ($elementTable == 'commande_fournisseur_dispatch') {
  3827. $fieldstatus = "status";
  3828. }
  3829. if (is_array($this->fields) && array_key_exists('status', $this->fields)) {
  3830. $fieldstatus = 'status';
  3831. }
  3832. $sql = "UPDATE ".$this->db->prefix().$elementTable;
  3833. $sql .= " SET ".$fieldstatus." = ".((int) $status);
  3834. // If status = 1 = validated, update also fk_user_valid
  3835. // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
  3836. if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
  3837. $sql .= ", fk_user_valid = ".((int) $user->id);
  3838. }
  3839. if ($status == 1 && in_array($elementTable, array('expensereport'))) {
  3840. $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
  3841. }
  3842. if ($status == 1 && in_array($elementTable, array('inventory'))) {
  3843. $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
  3844. }
  3845. $sql .= " WHERE rowid=".((int) $elementId);
  3846. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  3847. if ($this->db->query($sql)) {
  3848. $error = 0;
  3849. // Try autoset of trigkey
  3850. if (empty($trigkey)) {
  3851. if ($this->element == 'supplier_proposal' && $status == 2) {
  3852. $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3853. }
  3854. if ($this->element == 'supplier_proposal' && $status == 3) {
  3855. $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3856. }
  3857. if ($this->element == 'supplier_proposal' && $status == 4) {
  3858. $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3859. }
  3860. if ($this->element == 'fichinter' && $status == 3) {
  3861. $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3862. }
  3863. if ($this->element == 'fichinter' && $status == 2) {
  3864. $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3865. }
  3866. if ($this->element == 'fichinter' && $status == 1) {
  3867. $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3868. }
  3869. }
  3870. if ($trigkey) {
  3871. // Call trigger
  3872. $result = $this->call_trigger($trigkey, $user);
  3873. if ($result < 0) {
  3874. $error++;
  3875. }
  3876. // End call triggers
  3877. }
  3878. if (!$error) {
  3879. $this->db->commit();
  3880. if (empty($savElementId)) {
  3881. // If the element we update is $this (so $elementId was provided as null)
  3882. if ($fieldstatus == 'tosell') {
  3883. $this->status = $status;
  3884. } elseif ($fieldstatus == 'tobuy') {
  3885. $this->status_buy = $status;
  3886. } else {
  3887. $this->statut = $status;
  3888. $this->status = $status;
  3889. }
  3890. }
  3891. return 1;
  3892. } else {
  3893. $this->db->rollback();
  3894. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  3895. return -1;
  3896. }
  3897. } else {
  3898. $this->error = $this->db->lasterror();
  3899. $this->db->rollback();
  3900. return -1;
  3901. }
  3902. }
  3903. /**
  3904. * Load type of canvas of an object if it exists
  3905. *
  3906. * @param int $id Record id
  3907. * @param string $ref Record ref
  3908. * @return int <0 if KO, 0 if nothing done, >0 if OK
  3909. */
  3910. public function getCanvas($id = 0, $ref = '')
  3911. {
  3912. global $conf;
  3913. if (empty($id) && empty($ref)) {
  3914. return 0;
  3915. }
  3916. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
  3917. return 0; // To increase speed. Not enabled by default.
  3918. }
  3919. // Clean parameters
  3920. $ref = trim($ref);
  3921. $sql = "SELECT rowid, canvas";
  3922. $sql .= " FROM ".$this->db->prefix().$this->table_element;
  3923. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  3924. if (!empty($id)) {
  3925. $sql .= " AND rowid = ".((int) $id);
  3926. }
  3927. if (!empty($ref)) {
  3928. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  3929. }
  3930. $resql = $this->db->query($sql);
  3931. if ($resql) {
  3932. $obj = $this->db->fetch_object($resql);
  3933. if ($obj) {
  3934. $this->canvas = $obj->canvas;
  3935. return 1;
  3936. } else {
  3937. return 0;
  3938. }
  3939. } else {
  3940. dol_print_error($this->db);
  3941. return -1;
  3942. }
  3943. }
  3944. /**
  3945. * Get special code of a line
  3946. *
  3947. * @param int $lineid Id of line
  3948. * @return int Special code
  3949. */
  3950. public function getSpecialCode($lineid)
  3951. {
  3952. $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
  3953. $sql .= " WHERE rowid = ".((int) $lineid);
  3954. $resql = $this->db->query($sql);
  3955. if ($resql) {
  3956. $row = $this->db->fetch_row($resql);
  3957. return $row[0];
  3958. }
  3959. }
  3960. /**
  3961. * Function to check if an object is used by others.
  3962. * Check is done into this->childtables. There is no check into llx_element_element.
  3963. *
  3964. * @param int $id Force id of object
  3965. * @param int $entity Force entity to check
  3966. * @return int <0 if KO, 0 if not used, >0 if already used
  3967. */
  3968. public function isObjectUsed($id = 0, $entity = 0)
  3969. {
  3970. global $langs;
  3971. if (empty($id)) {
  3972. $id = $this->id;
  3973. }
  3974. // Check parameters
  3975. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
  3976. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  3977. return -1;
  3978. }
  3979. $arraytoscan = $this->childtables;
  3980. // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
  3981. $tmparray = array_keys($this->childtables);
  3982. if (is_numeric($tmparray[0])) {
  3983. $arraytoscan = array_flip($this->childtables);
  3984. }
  3985. // Test if child exists
  3986. $haschild = 0;
  3987. foreach ($arraytoscan as $table => $element) {
  3988. //print $id.'-'.$table.'-'.$elementname.'<br>';
  3989. // Check if element can be deleted
  3990. $sql = "SELECT COUNT(*) as nb";
  3991. $sql.= " FROM ".$this->db->prefix().$table." as c";
  3992. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  3993. $sql.= ", ".$this->db->prefix().$element['parent']." as p";
  3994. }
  3995. $sql.= " WHERE c.".$this->fk_element." = ".((int) $id);
  3996. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  3997. $sql.= " AND c.".$element['parentkey']." = p.rowid";
  3998. }
  3999. if (!empty($entity)) {
  4000. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4001. $sql.= " AND p.entity = ".((int) $entity);
  4002. } else {
  4003. $sql.= " AND c.entity = ".((int) $entity);
  4004. }
  4005. }
  4006. $resql = $this->db->query($sql);
  4007. if ($resql) {
  4008. $obj = $this->db->fetch_object($resql);
  4009. if ($obj->nb > 0) {
  4010. $langs->load("errors");
  4011. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  4012. $haschild += $obj->nb;
  4013. if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
  4014. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
  4015. } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
  4016. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
  4017. } else { // new usage: $element['name']=Translation key
  4018. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
  4019. }
  4020. break; // We found at least one, we stop here
  4021. }
  4022. } else {
  4023. $this->errors[] = $this->db->lasterror();
  4024. return -1;
  4025. }
  4026. }
  4027. if ($haschild > 0) {
  4028. $this->errors[] = "ErrorRecordHasChildren";
  4029. return $haschild;
  4030. } else {
  4031. return 0;
  4032. }
  4033. }
  4034. /**
  4035. * Function to say how many lines object contains
  4036. *
  4037. * @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
  4038. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  4039. */
  4040. public function hasProductsOrServices($predefined = -1)
  4041. {
  4042. $nb = 0;
  4043. foreach ($this->lines as $key => $val) {
  4044. $qualified = 0;
  4045. if ($predefined == -1) {
  4046. $qualified = 1;
  4047. }
  4048. if ($predefined == 1 && $val->fk_product > 0) {
  4049. $qualified = 1;
  4050. }
  4051. if ($predefined == 0 && $val->fk_product <= 0) {
  4052. $qualified = 1;
  4053. }
  4054. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
  4055. $qualified = 1;
  4056. }
  4057. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
  4058. $qualified = 1;
  4059. }
  4060. if ($qualified) {
  4061. $nb++;
  4062. }
  4063. }
  4064. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  4065. return $nb;
  4066. }
  4067. /**
  4068. * Function that returns the total amount HT of discounts applied for all lines.
  4069. *
  4070. * @return float|string Total amout of discount
  4071. */
  4072. public function getTotalDiscount()
  4073. {
  4074. if (!empty($this->table_element_line) ) {
  4075. $total_discount = 0.00;
  4076. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  4077. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  4078. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  4079. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  4080. $resql = $this->db->query($sql);
  4081. if ($resql) {
  4082. $num = $this->db->num_rows($resql);
  4083. $i = 0;
  4084. while ($i < $num) {
  4085. $obj = $this->db->fetch_object($resql);
  4086. $pu_ht = $obj->pu_ht;
  4087. $qty = $obj->qty;
  4088. $total_ht = $obj->total_ht;
  4089. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  4090. $total_discount += $total_discount_line;
  4091. $i++;
  4092. }
  4093. }
  4094. //print $total_discount; exit;
  4095. return price2num($total_discount);
  4096. }
  4097. return null;
  4098. }
  4099. /**
  4100. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  4101. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  4102. *
  4103. * @return array array('weight'=>...,'volume'=>...)
  4104. */
  4105. public function getTotalWeightVolume()
  4106. {
  4107. $totalWeight = 0;
  4108. $totalVolume = 0;
  4109. // defined for shipment only
  4110. $totalOrdered = '';
  4111. // defined for shipment only
  4112. $totalToShip = '';
  4113. foreach ($this->lines as $line) {
  4114. if (isset($line->qty_asked)) {
  4115. if (empty($totalOrdered)) {
  4116. $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  4117. }
  4118. $totalOrdered += $line->qty_asked; // defined for shipment only
  4119. }
  4120. if (isset($line->qty_shipped)) {
  4121. if (empty($totalToShip)) {
  4122. $totalToShip = 0; // Avoid warning because $totalToShip is ''
  4123. }
  4124. $totalToShip += $line->qty_shipped; // defined for shipment only
  4125. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
  4126. if (empty($totalToShip)) {
  4127. $totalToShip = 0;
  4128. }
  4129. $totalToShip += $line->qty; // defined for reception only
  4130. }
  4131. // Define qty, weight, volume, weight_units, volume_units
  4132. if ($this->element == 'shipping') {
  4133. // for shipments
  4134. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  4135. } else {
  4136. $qty = $line->qty ? $line->qty : 0;
  4137. }
  4138. $weight = !empty($line->weight) ? $line->weight : 0;
  4139. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  4140. $volume = !empty($line->volume) ? $line->volume : 0;
  4141. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  4142. $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
  4143. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  4144. $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
  4145. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  4146. $weightUnit = 0;
  4147. $volumeUnit = 0;
  4148. if (!empty($weight_units)) {
  4149. $weightUnit = $weight_units;
  4150. }
  4151. if (!empty($volume_units)) {
  4152. $volumeUnit = $volume_units;
  4153. }
  4154. if (empty($totalWeight)) {
  4155. $totalWeight = 0; // Avoid warning because $totalWeight is ''
  4156. }
  4157. if (empty($totalVolume)) {
  4158. $totalVolume = 0; // Avoid warning because $totalVolume is ''
  4159. }
  4160. //var_dump($line->volume_units);
  4161. if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4162. $trueWeightUnit = pow(10, $weightUnit);
  4163. $totalWeight += $weight * $qty * $trueWeightUnit;
  4164. } else {
  4165. if ($weight_units == 99) {
  4166. // conversion 1 Pound = 0.45359237 KG
  4167. $trueWeightUnit = 0.45359237;
  4168. $totalWeight += $weight * $qty * $trueWeightUnit;
  4169. } elseif ($weight_units == 98) {
  4170. // conversion 1 Ounce = 0.0283495 KG
  4171. $trueWeightUnit = 0.0283495;
  4172. $totalWeight += $weight * $qty * $trueWeightUnit;
  4173. } else {
  4174. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  4175. }
  4176. }
  4177. if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4178. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  4179. $trueVolumeUnit = pow(10, $volumeUnit);
  4180. //print $line->volume;
  4181. $totalVolume += $volume * $qty * $trueVolumeUnit;
  4182. } else {
  4183. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  4184. }
  4185. }
  4186. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  4187. }
  4188. /**
  4189. * Set extra parameters
  4190. *
  4191. * @return int <0 if KO, >0 if OK
  4192. */
  4193. public function setExtraParameters()
  4194. {
  4195. $this->db->begin();
  4196. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  4197. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  4198. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  4199. $sql .= " WHERE rowid = ".((int) $this->id);
  4200. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  4201. $resql = $this->db->query($sql);
  4202. if (!$resql) {
  4203. $this->error = $this->db->lasterror();
  4204. $this->db->rollback();
  4205. return -1;
  4206. } else {
  4207. $this->db->commit();
  4208. return 1;
  4209. }
  4210. }
  4211. // --------------------
  4212. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  4213. // --------------------
  4214. /* This is to show add lines */
  4215. /**
  4216. * Show add free and predefined products/services form
  4217. *
  4218. * @param int $dateSelector 1=Show also date range input fields
  4219. * @param Societe $seller Object thirdparty who sell
  4220. * @param Societe $buyer Object thirdparty who buy
  4221. * @param string $defaulttpldir Directory where to find the template
  4222. * @return void
  4223. */
  4224. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  4225. {
  4226. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  4227. global $form;
  4228. // Line extrafield
  4229. if (!is_object($extrafields)) {
  4230. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4231. $extrafields = new ExtraFields($this->db);
  4232. }
  4233. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4234. // Output template part (modules that overwrite templates must declare this into descriptor)
  4235. // Use global variables + $dateSelector + $seller and $buyer
  4236. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  4237. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4238. foreach ($dirtpls as $module => $reldir) {
  4239. if (!empty($module)) {
  4240. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  4241. } else {
  4242. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  4243. }
  4244. if (empty($conf->file->strict_mode)) {
  4245. $res = @include $tpl;
  4246. } else {
  4247. $res = include $tpl; // for debug
  4248. }
  4249. if ($res) {
  4250. break;
  4251. }
  4252. }
  4253. }
  4254. /* This is to show array of line of details */
  4255. /**
  4256. * Return HTML table for object lines
  4257. * TODO Move this into an output class file (htmlline.class.php)
  4258. * If lines are into a template, title must also be into a template
  4259. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4260. *
  4261. * @param string $action Action code
  4262. * @param string $seller Object of seller third party
  4263. * @param string $buyer Object of buyer third party
  4264. * @param int $selected Object line selected
  4265. * @param int $dateSelector 1=Show also date range input fields
  4266. * @param string $defaulttpldir Directory where to find the template
  4267. * @return void
  4268. */
  4269. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  4270. {
  4271. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  4272. // TODO We should not use global var for this
  4273. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  4274. // Define usemargins
  4275. $usemargins = 0;
  4276. if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
  4277. $usemargins = 1;
  4278. }
  4279. $num = count($this->lines);
  4280. // Line extrafield
  4281. if (!is_object($extrafields)) {
  4282. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4283. $extrafields = new ExtraFields($this->db);
  4284. }
  4285. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4286. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  4287. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4288. if (empty($reshook)) {
  4289. // Output template part (modules that overwrite templates must declare this into descriptor)
  4290. // Use global variables + $dateSelector + $seller and $buyer
  4291. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  4292. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4293. foreach ($dirtpls as $module => $reldir) {
  4294. if (!empty($module)) {
  4295. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  4296. } else {
  4297. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  4298. }
  4299. if (empty($conf->file->strict_mode)) {
  4300. $res = @include $tpl;
  4301. } else {
  4302. $res = include $tpl; // for debug
  4303. }
  4304. if ($res) {
  4305. break;
  4306. }
  4307. }
  4308. }
  4309. $i = 0;
  4310. print "<!-- begin printObjectLines() --><tbody>\n";
  4311. foreach ($this->lines as $line) {
  4312. //Line extrafield
  4313. $line->fetch_optionals();
  4314. //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  4315. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4316. if (empty($line->fk_parent_line)) {
  4317. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  4318. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4319. } else {
  4320. $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);
  4321. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4322. }
  4323. }
  4324. if (empty($reshook)) {
  4325. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  4326. }
  4327. $i++;
  4328. }
  4329. print "</tbody><!-- end printObjectLines() -->\n";
  4330. }
  4331. /**
  4332. * Return HTML content of a detail line
  4333. * TODO Move this into an output class file (htmlline.class.php)
  4334. *
  4335. * @param string $action GET/POST action
  4336. * @param CommonObjectLine $line Selected object line to output
  4337. * @param string $var Is it a an odd line (true)
  4338. * @param int $num Number of line (0)
  4339. * @param int $i I
  4340. * @param int $dateSelector 1=Show also date range input fields
  4341. * @param string $seller Object of seller third party
  4342. * @param string $buyer Object of buyer third party
  4343. * @param int $selected Object line selected
  4344. * @param Extrafields $extrafields Object of extrafields
  4345. * @param string $defaulttpldir Directory where to find the template (deprecated)
  4346. * @return void
  4347. */
  4348. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  4349. {
  4350. global $conf, $langs, $user, $object, $hookmanager;
  4351. global $form;
  4352. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  4353. $object_rights = $this->getRights();
  4354. $element = $this->element;
  4355. $text = '';
  4356. $description = '';
  4357. // Line in view mode
  4358. if ($action != 'editline' || $selected != $line->id) {
  4359. // Product
  4360. if ($line->fk_product > 0) {
  4361. $product_static = new Product($this->db);
  4362. $product_static->fetch($line->fk_product);
  4363. $product_static->ref = $line->ref; //can change ref in hook
  4364. $product_static->label = $line->label; //can change label in hook
  4365. $text = $product_static->getNomUrl(1);
  4366. // Define output language and label
  4367. if (!empty($conf->global->MAIN_MULTILANGS)) {
  4368. if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
  4369. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  4370. return;
  4371. }
  4372. $prod = new Product($this->db);
  4373. $prod->fetch($line->fk_product);
  4374. $outputlangs = $langs;
  4375. $newlang = '';
  4376. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  4377. $newlang = GETPOST('lang_id', 'aZ09');
  4378. }
  4379. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
  4380. $newlang = $this->thirdparty->default_lang; // To use language of customer
  4381. }
  4382. if (!empty($newlang)) {
  4383. $outputlangs = new Translate("", $conf);
  4384. $outputlangs->setDefaultLang($newlang);
  4385. }
  4386. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  4387. } else {
  4388. $label = $line->product_label;
  4389. }
  4390. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  4391. $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.
  4392. }
  4393. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4394. // Output template part (modules that overwrite templates must declare this into descriptor)
  4395. // Use global variables + $dateSelector + $seller and $buyer
  4396. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4397. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4398. foreach ($dirtpls as $module => $reldir) {
  4399. if (!empty($module)) {
  4400. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  4401. } else {
  4402. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  4403. }
  4404. if (empty($conf->file->strict_mode)) {
  4405. $res = @include $tpl;
  4406. } else {
  4407. $res = include $tpl; // for debug
  4408. }
  4409. if ($res) {
  4410. break;
  4411. }
  4412. }
  4413. }
  4414. // Line in update mode
  4415. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
  4416. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  4417. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4418. // Output template part (modules that overwrite templates must declare this into descriptor)
  4419. // Use global variables + $dateSelector + $seller and $buyer
  4420. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4421. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4422. foreach ($dirtpls as $module => $reldir) {
  4423. if (!empty($module)) {
  4424. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  4425. } else {
  4426. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  4427. }
  4428. if (empty($conf->file->strict_mode)) {
  4429. $res = @include $tpl;
  4430. } else {
  4431. $res = include $tpl; // for debug
  4432. }
  4433. if ($res) {
  4434. break;
  4435. }
  4436. }
  4437. }
  4438. }
  4439. /* This is to show array of line of details of source object */
  4440. /**
  4441. * Return HTML table table of source object lines
  4442. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4443. * If lines are into a template, title must also be into a template
  4444. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  4445. *
  4446. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  4447. * @param array $selectedLines Array of lines id for selected lines
  4448. * @return void
  4449. */
  4450. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  4451. {
  4452. global $langs, $hookmanager, $conf, $form, $action;
  4453. print '<tr class="liste_titre">';
  4454. print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
  4455. print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
  4456. print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
  4457. print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
  4458. if (!empty($conf->multicurrency->enabled)) {
  4459. print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
  4460. }
  4461. print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
  4462. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4463. print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
  4464. }
  4465. print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
  4466. print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
  4467. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  4468. print '</tr>';
  4469. $i = 0;
  4470. if (!empty($this->lines)) {
  4471. foreach ($this->lines as $line) {
  4472. $reshook = 0;
  4473. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
  4474. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4475. $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
  4476. if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
  4477. $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4478. }
  4479. if (empty($reshook)) {
  4480. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  4481. }
  4482. $i++;
  4483. }
  4484. }
  4485. }
  4486. /**
  4487. * Return HTML with a line of table array of source object lines
  4488. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4489. * If lines are into a template, title must also be into a template
  4490. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4491. *
  4492. * @param CommonObjectLine $line Line
  4493. * @param string $var Var
  4494. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  4495. * @param string $defaulttpldir Directory where to find the template
  4496. * @param array $selectedLines Array of lines id for selected lines
  4497. * @return void
  4498. */
  4499. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  4500. {
  4501. global $langs, $conf;
  4502. //var_dump($line);
  4503. if (!empty($line->date_start)) {
  4504. $date_start = $line->date_start;
  4505. } else {
  4506. $date_start = $line->date_debut_prevue;
  4507. if ($line->date_debut_reel) {
  4508. $date_start = $line->date_debut_reel;
  4509. }
  4510. }
  4511. if (!empty($line->date_end)) {
  4512. $date_end = $line->date_end;
  4513. } else {
  4514. $date_end = $line->date_fin_prevue;
  4515. if ($line->date_fin_reel) {
  4516. $date_end = $line->date_fin_reel;
  4517. }
  4518. }
  4519. $this->tpl['id'] = $line->id;
  4520. $this->tpl['label'] = '';
  4521. if (!empty($line->fk_parent_line)) {
  4522. $this->tpl['label'] .= img_picto('', 'rightarrow');
  4523. }
  4524. if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
  4525. $discount = new DiscountAbsolute($this->db);
  4526. $discount->fk_soc = $this->socid;
  4527. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  4528. } elseif (!empty($line->fk_product)) {
  4529. $productstatic = new Product($this->db);
  4530. $productstatic->id = $line->fk_product;
  4531. $productstatic->ref = $line->ref;
  4532. $productstatic->type = $line->fk_product_type;
  4533. if (empty($productstatic->ref)) {
  4534. $line->fetch_product();
  4535. $productstatic = $line->product;
  4536. }
  4537. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  4538. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  4539. // Dates
  4540. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4541. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4542. }
  4543. } else {
  4544. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  4545. if (!empty($line->desc)) {
  4546. $this->tpl['label'] .= $line->desc;
  4547. } else {
  4548. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  4549. }
  4550. // Dates
  4551. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4552. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4553. }
  4554. }
  4555. if (!empty($line->desc)) {
  4556. if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
  4557. $discount = new DiscountAbsolute($this->db);
  4558. $discount->fetch($line->fk_remise_except);
  4559. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  4560. } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
  4561. $discount = new DiscountAbsolute($this->db);
  4562. $discount->fetch($line->fk_remise_except);
  4563. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  4564. } elseif ($line->desc == '(EXCESS RECEIVED)') {
  4565. $discount = new DiscountAbsolute($this->db);
  4566. $discount->fetch($line->fk_remise_except);
  4567. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  4568. } elseif ($line->desc == '(EXCESS PAID)') {
  4569. $discount = new DiscountAbsolute($this->db);
  4570. $discount->fetch($line->fk_remise_except);
  4571. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  4572. } else {
  4573. $this->tpl['description'] = dol_trunc($line->desc, 60);
  4574. }
  4575. } else {
  4576. $this->tpl['description'] = '&nbsp;';
  4577. }
  4578. // VAT Rate
  4579. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  4580. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  4581. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
  4582. $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  4583. }
  4584. $this->tpl['price'] = price($line->subprice);
  4585. $this->tpl['total_ht'] = price($line->total_ht);
  4586. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  4587. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  4588. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4589. $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  4590. }
  4591. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  4592. // Is the line strike or not
  4593. $this->tpl['strike'] = 0;
  4594. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
  4595. $this->tpl['strike'] = 1;
  4596. }
  4597. // Output template part (modules that overwrite templates must declare this into descriptor)
  4598. // Use global variables + $dateSelector + $seller and $buyer
  4599. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4600. foreach ($dirtpls as $module => $reldir) {
  4601. if (!empty($module)) {
  4602. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  4603. } else {
  4604. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  4605. }
  4606. if (empty($conf->file->strict_mode)) {
  4607. $res = @include $tpl;
  4608. } else {
  4609. $res = include $tpl; // for debug
  4610. }
  4611. if ($res) {
  4612. break;
  4613. }
  4614. }
  4615. }
  4616. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4617. /**
  4618. * Add resources to the current object : add entry into llx_element_resources
  4619. * Need $this->element & $this->id
  4620. *
  4621. * @param int $resource_id Resource id
  4622. * @param string $resource_type 'resource'
  4623. * @param int $busy Busy or not
  4624. * @param int $mandatory Mandatory or not
  4625. * @return int <=0 if KO, >0 if OK
  4626. */
  4627. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  4628. {
  4629. // phpcs:enable
  4630. $this->db->begin();
  4631. $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
  4632. $sql .= "resource_id";
  4633. $sql .= ", resource_type";
  4634. $sql .= ", element_id";
  4635. $sql .= ", element_type";
  4636. $sql .= ", busy";
  4637. $sql .= ", mandatory";
  4638. $sql .= ") VALUES (";
  4639. $sql .= $resource_id;
  4640. $sql .= ", '".$this->db->escape($resource_type)."'";
  4641. $sql .= ", '".$this->db->escape($this->id)."'";
  4642. $sql .= ", '".$this->db->escape($this->element)."'";
  4643. $sql .= ", '".$this->db->escape($busy)."'";
  4644. $sql .= ", '".$this->db->escape($mandatory)."'";
  4645. $sql .= ")";
  4646. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  4647. if ($this->db->query($sql)) {
  4648. $this->db->commit();
  4649. return 1;
  4650. } else {
  4651. $this->error = $this->db->lasterror();
  4652. $this->db->rollback();
  4653. return 0;
  4654. }
  4655. }
  4656. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4657. /**
  4658. * Delete a link to resource line
  4659. *
  4660. * @param int $rowid Id of resource line to delete
  4661. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  4662. * @param int $notrigger Disable all triggers
  4663. * @return int >0 if OK, <0 if KO
  4664. */
  4665. public function delete_resource($rowid, $element, $notrigger = 0)
  4666. {
  4667. // phpcs:enable
  4668. global $user;
  4669. $this->db->begin();
  4670. $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
  4671. $sql .= " WHERE rowid = ".((int) $rowid);
  4672. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  4673. $resql = $this->db->query($sql);
  4674. if (!$resql) {
  4675. $this->error = $this->db->lasterror();
  4676. $this->db->rollback();
  4677. return -1;
  4678. } else {
  4679. if (!$notrigger) {
  4680. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  4681. if ($result < 0) {
  4682. $this->db->rollback();
  4683. return -1;
  4684. }
  4685. }
  4686. $this->db->commit();
  4687. return 1;
  4688. }
  4689. }
  4690. /**
  4691. * Overwrite magic function to solve problem of cloning object that are kept as references
  4692. *
  4693. * @return void
  4694. */
  4695. public function __clone()
  4696. {
  4697. // Force a copy of this->lines, otherwise it will point to same object.
  4698. if (isset($this->lines) && is_array($this->lines)) {
  4699. $nboflines = count($this->lines);
  4700. for ($i = 0; $i < $nboflines; $i++) {
  4701. $this->lines[$i] = clone $this->lines[$i];
  4702. }
  4703. }
  4704. }
  4705. /**
  4706. * Common function for all objects extending CommonObject for generating documents
  4707. *
  4708. * @param string $modelspath Relative folder where generators are placed
  4709. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4710. * @param Translate $outputlangs Output language to use
  4711. * @param int $hidedetails 1 to hide details. 0 by default
  4712. * @param int $hidedesc 1 to hide product description. 0 by default
  4713. * @param int $hideref 1 to hide product reference. 0 by default
  4714. * @param null|array $moreparams Array to provide more information
  4715. * @return int >0 if OK, <0 if KO
  4716. * @see addFileIntoDatabaseIndex()
  4717. */
  4718. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4719. {
  4720. global $conf, $langs, $user, $hookmanager, $action;
  4721. $srctemplatepath = '';
  4722. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  4723. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4724. if (empty($reshook)) {
  4725. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4726. if (empty($modele)) {
  4727. $this->error = 'BadValueForParameterModele';
  4728. return -1;
  4729. }
  4730. // Increase limit for PDF build
  4731. $err = error_reporting();
  4732. error_reporting(0);
  4733. @set_time_limit(120);
  4734. error_reporting($err);
  4735. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4736. $tmp = explode(':', $modele, 2);
  4737. if (!empty($tmp[1])) {
  4738. $modele = $tmp[0];
  4739. $srctemplatepath = $tmp[1];
  4740. }
  4741. // Search template files
  4742. $file = '';
  4743. $classname = '';
  4744. $filefound = '';
  4745. $dirmodels = array('/');
  4746. if (is_array($conf->modules_parts['models'])) {
  4747. $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4748. }
  4749. foreach ($dirmodels as $reldir) {
  4750. foreach (array('doc', 'pdf') as $prefix) {
  4751. if (in_array(get_class($this), array('Adherent'))) {
  4752. // Member module use prefix_modele.class.php
  4753. $file = $prefix."_".$modele.".class.php";
  4754. } else {
  4755. // Other module use prefix_modele.modules.php
  4756. $file = $prefix."_".$modele.".modules.php";
  4757. }
  4758. // On verifie l'emplacement du modele
  4759. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  4760. if (file_exists($file)) {
  4761. $filefound = $file;
  4762. $classname = $prefix.'_'.$modele;
  4763. break;
  4764. }
  4765. }
  4766. if ($filefound) {
  4767. break;
  4768. }
  4769. }
  4770. // If generator was found
  4771. if ($filefound) {
  4772. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4773. require_once $file;
  4774. $obj = new $classname($this->db);
  4775. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4776. if ($obj->type == 'odt' && empty($srctemplatepath)) {
  4777. $varfortemplatedir = $obj->scandir;
  4778. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
  4779. $dirtoscan = $conf->global->$varfortemplatedir;
  4780. $listoffiles = array();
  4781. // Now we add first model found in directories scanned
  4782. $listofdir = explode(',', $dirtoscan);
  4783. foreach ($listofdir as $key => $tmpdir) {
  4784. $tmpdir = trim($tmpdir);
  4785. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4786. if (!$tmpdir) {
  4787. unset($listofdir[$key]);
  4788. continue;
  4789. }
  4790. if (is_dir($tmpdir)) {
  4791. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4792. if (count($tmpfiles)) {
  4793. $listoffiles = array_merge($listoffiles, $tmpfiles);
  4794. }
  4795. }
  4796. }
  4797. if (count($listoffiles)) {
  4798. foreach ($listoffiles as $record) {
  4799. $srctemplatepath = $record['fullname'];
  4800. break;
  4801. }
  4802. }
  4803. }
  4804. if (empty($srctemplatepath)) {
  4805. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4806. return -1;
  4807. }
  4808. }
  4809. if ($obj->type == 'odt' && !empty($srctemplatepath)) {
  4810. if (!dol_is_file($srctemplatepath)) {
  4811. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  4812. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4813. return -1;
  4814. }
  4815. }
  4816. // We save charset_output to restore it because write_file can change it if needed for
  4817. // output format that does not support UTF8.
  4818. $sav_charset_output = $outputlangs->charset_output;
  4819. if (in_array(get_class($this), array('Adherent'))) {
  4820. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
  4821. } else {
  4822. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4823. }
  4824. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4825. if ($resultwritefile > 0) {
  4826. $outputlangs->charset_output = $sav_charset_output;
  4827. // We delete old preview
  4828. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4829. dol_delete_preview($this);
  4830. // Index file in database
  4831. if (!empty($obj->result['fullpath'])) {
  4832. $destfull = $obj->result['fullpath'];
  4833. // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
  4834. $update_main_doc_field = 0;
  4835. if (!empty($obj->update_main_doc_field)) {
  4836. $update_main_doc_field = 1;
  4837. }
  4838. $this->indexFile($destfull, $update_main_doc_field);
  4839. } else {
  4840. 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);
  4841. }
  4842. // Success in building document. We build meta file.
  4843. dol_meta_create($this);
  4844. return 1;
  4845. } else {
  4846. $outputlangs->charset_output = $sav_charset_output;
  4847. $this->error = $obj->error;
  4848. $this->errors = $obj->errors;
  4849. dol_syslog("Error generating document for ".__CLASS__.". Error: ".$obj->error, LOG_ERR);
  4850. return -1;
  4851. }
  4852. } else {
  4853. if (!$filefound) {
  4854. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4855. $this->errors[] = $this->error;
  4856. dol_syslog($this->error, LOG_ERR);
  4857. } else {
  4858. $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
  4859. $this->errors[] = $this->error;
  4860. dol_syslog($this->error, LOG_ERR);
  4861. }
  4862. return -1;
  4863. }
  4864. } else {
  4865. return $reshook;
  4866. }
  4867. }
  4868. /**
  4869. * Index a file into the ECM database
  4870. *
  4871. * @param string $destfull Full path of file to index
  4872. * @param int $update_main_doc_field Update field main_doc file into table of object
  4873. * @return int <0 if KO, >0 if OK
  4874. */
  4875. public function indexFile($destfull, $update_main_doc_field)
  4876. {
  4877. global $conf, $user;
  4878. $upload_dir = dirname($destfull);
  4879. $destfile = basename($destfull);
  4880. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  4881. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  4882. $filename = basename($destfile);
  4883. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4884. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4885. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4886. $ecmfile = new EcmFiles($this->db);
  4887. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  4888. // Set the public "share" key
  4889. $setsharekey = false;
  4890. if ($this->element == 'propal' || $this->element == 'proposal') {
  4891. if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
  4892. $setsharekey = true; // feature to make online signature is not set or set to on (default)
  4893. }
  4894. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4895. $setsharekey = true;
  4896. }
  4897. }
  4898. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  4899. $setsharekey = true;
  4900. }
  4901. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  4902. $setsharekey = true;
  4903. }
  4904. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4905. $setsharekey = true;
  4906. }
  4907. if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4908. $setsharekey = true;
  4909. }
  4910. if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4911. $setsharekey = true;
  4912. }
  4913. if ($setsharekey) {
  4914. if (empty($ecmfile->share)) { // Because object not found or share not set yet
  4915. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  4916. $ecmfile->share = getRandomPassword(true);
  4917. }
  4918. }
  4919. if ($result > 0) {
  4920. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4921. $ecmfile->fullpath_orig = '';
  4922. $ecmfile->gen_or_uploaded = 'generated';
  4923. $ecmfile->description = ''; // indexed content
  4924. $ecmfile->keywords = ''; // keyword content
  4925. $result = $ecmfile->update($user);
  4926. if ($result < 0) {
  4927. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4928. return -1;
  4929. }
  4930. } else {
  4931. $ecmfile->entity = $conf->entity;
  4932. $ecmfile->filepath = $rel_dir;
  4933. $ecmfile->filename = $filename;
  4934. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4935. $ecmfile->fullpath_orig = '';
  4936. $ecmfile->gen_or_uploaded = 'generated';
  4937. $ecmfile->description = ''; // indexed content
  4938. $ecmfile->keywords = ''; // keyword content
  4939. $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
  4940. $ecmfile->src_object_id = $this->id;
  4941. $result = $ecmfile->create($user);
  4942. if ($result < 0) {
  4943. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4944. return -1;
  4945. }
  4946. }
  4947. /*$this->result['fullname']=$destfull;
  4948. $this->result['filepath']=$ecmfile->filepath;
  4949. $this->result['filename']=$ecmfile->filename;*/
  4950. //var_dump($obj->update_main_doc_field);exit;
  4951. if ($update_main_doc_field && !empty($this->table_element)) {
  4952. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
  4953. $sql .= " WHERE rowid = ".((int) $this->id);
  4954. $resql = $this->db->query($sql);
  4955. if (!$resql) {
  4956. dol_print_error($this->db);
  4957. return -1;
  4958. } else {
  4959. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  4960. }
  4961. }
  4962. }
  4963. return 1;
  4964. }
  4965. /**
  4966. * Build thumb
  4967. * @todo Move this into files.lib.php
  4968. *
  4969. * @param string $file Path file in UTF8 to original file to create thumbs from.
  4970. * @return void
  4971. */
  4972. public function addThumbs($file)
  4973. {
  4974. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  4975. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  4976. $file_osencoded = dol_osencode($file);
  4977. if (file_exists($file_osencoded)) {
  4978. // Create small thumbs for company (Ratio is near 16/9)
  4979. // Used on logon for example
  4980. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  4981. // Create mini thumbs for company (Ratio is near 16/9)
  4982. // Used on menu or for setup page for example
  4983. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  4984. }
  4985. }
  4986. /* Functions common to commonobject and commonobjectline */
  4987. /* For default values */
  4988. /**
  4989. * Return the default value to use for a field when showing the create form of object.
  4990. * Return values in this order:
  4991. * 1) If parameter is available into POST, we return it first.
  4992. * 2) If not but an alternate value was provided as parameter of function, we return it.
  4993. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  4994. * 4) Return value found into database (TODO No yet implemented)
  4995. *
  4996. * @param string $fieldname Name of field
  4997. * @param string $alternatevalue Alternate value to use
  4998. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  4999. **/
  5000. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
  5001. {
  5002. global $conf, $_POST;
  5003. // If param here has been posted, we use this value first.
  5004. if (GETPOSTISSET($fieldname)) {
  5005. return GETPOST($fieldname, 'alphanohtml', 3);
  5006. }
  5007. if (isset($alternatevalue)) {
  5008. return $alternatevalue;
  5009. }
  5010. $newelement = $this->element;
  5011. if ($newelement == 'facture') {
  5012. $newelement = 'invoice';
  5013. }
  5014. if ($newelement == 'commande') {
  5015. $newelement = 'order';
  5016. }
  5017. if (empty($newelement)) {
  5018. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  5019. return '';
  5020. }
  5021. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  5022. //var_dump($keyforfieldname);
  5023. if (isset($conf->global->$keyforfieldname)) {
  5024. return $conf->global->$keyforfieldname;
  5025. }
  5026. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  5027. }
  5028. /* For triggers */
  5029. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5030. /**
  5031. * Call trigger based on this instance.
  5032. * Some context information may also be provided into array property this->context.
  5033. * NB: Error from trigger are stacked in interface->errors
  5034. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  5035. *
  5036. * @param string $triggerName trigger's name to execute
  5037. * @param User $user Object user
  5038. * @return int Result of run_triggers
  5039. */
  5040. public function call_trigger($triggerName, $user)
  5041. {
  5042. // phpcs:enable
  5043. global $langs, $conf;
  5044. if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
  5045. dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.');
  5046. exit;
  5047. }
  5048. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  5049. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  5050. $langs = new Translate('', $conf);
  5051. }
  5052. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  5053. $interface = new Interfaces($this->db);
  5054. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  5055. if ($result < 0) {
  5056. if (!empty($this->errors)) {
  5057. $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.
  5058. } else {
  5059. $this->errors = $interface->errors;
  5060. }
  5061. }
  5062. return $result;
  5063. }
  5064. /* Functions for data in other language */
  5065. /**
  5066. * Function to get alternative languages of a data into $this->array_languages
  5067. * This method is NOT called by method fetch of objects but must be called separately.
  5068. *
  5069. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  5070. * @see fetch_optionnals()
  5071. */
  5072. public function fetchValuesForExtraLanguages()
  5073. {
  5074. // To avoid SQL errors. Probably not the better solution though
  5075. if (!$this->element) {
  5076. return 0;
  5077. }
  5078. if (!($this->id > 0)) {
  5079. return 0;
  5080. }
  5081. if (is_array($this->array_languages)) {
  5082. return 1;
  5083. }
  5084. $this->array_languages = array();
  5085. $element = $this->element;
  5086. if ($element == 'categorie') {
  5087. $element = 'categories'; // For compatibility
  5088. }
  5089. // Request to get translation values for object
  5090. $sql = "SELECT rowid, property, lang , value";
  5091. $sql .= " FROM ".$this->db->prefix()."object_lang";
  5092. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  5093. $sql .= " AND fk_object = ".((int) $this->id);
  5094. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5095. $resql = $this->db->query($sql);
  5096. if ($resql) {
  5097. $numrows = $this->db->num_rows($resql);
  5098. if ($numrows) {
  5099. $i = 0;
  5100. while ($i < $numrows) {
  5101. $obj = $this->db->fetch_object($resql);
  5102. $key = $obj->property;
  5103. $value = $obj->value;
  5104. $codelang = $obj->lang;
  5105. $type = $this->fields[$key]['type'];
  5106. // we can add this attribute to object
  5107. if (preg_match('/date/', $type)) {
  5108. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  5109. } else {
  5110. $this->array_languages[$key][$codelang] = $value;
  5111. }
  5112. $i++;
  5113. }
  5114. }
  5115. $this->db->free($resql);
  5116. if ($numrows) {
  5117. return $numrows;
  5118. } else {
  5119. return 0;
  5120. }
  5121. } else {
  5122. dol_print_error($this->db);
  5123. return -1;
  5124. }
  5125. }
  5126. /**
  5127. * Fill array_options property of object by extrafields value (using for data sent by forms)
  5128. *
  5129. * @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.
  5130. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  5131. */
  5132. public function setValuesForExtraLanguages($onlykey = '')
  5133. {
  5134. global $_POST, $langs;
  5135. // Get extra fields
  5136. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  5137. $tmparray = explode('-', $postfieldkey);
  5138. if ($tmparray[0] != 'field') {
  5139. continue;
  5140. }
  5141. $element = $tmparray[1];
  5142. $key = $tmparray[2];
  5143. $codelang = $tmparray[3];
  5144. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  5145. if (!empty($onlykey) && $key != $onlykey) {
  5146. continue;
  5147. }
  5148. if ($element != $this->element) {
  5149. continue;
  5150. }
  5151. $key_type = $this->fields[$key]['type'];
  5152. $enabled = 1;
  5153. if (isset($this->fields[$key]['enabled'])) {
  5154. $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
  5155. }
  5156. /*$perms = 1;
  5157. if (isset($this->fields[$key]['perms']))
  5158. {
  5159. $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
  5160. }*/
  5161. if (empty($enabled)) {
  5162. continue;
  5163. }
  5164. //if (empty($perms)) continue;
  5165. if (in_array($key_type, array('date'))) {
  5166. // Clean parameters
  5167. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5168. $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
  5169. } elseif (in_array($key_type, array('datetime'))) {
  5170. // Clean parameters
  5171. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5172. $value_key = dol_mktime(GETPOST($postfieldkey."hour", 'int'), GETPOST($postfieldkey."min", 'int'), 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
  5173. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  5174. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  5175. if (!empty($value_arr)) {
  5176. $value_key = implode(',', $value_arr);
  5177. } else {
  5178. $value_key = '';
  5179. }
  5180. } elseif (in_array($key_type, array('price', 'double'))) {
  5181. $value_arr = GETPOST($postfieldkey, 'alpha');
  5182. $value_key = price2num($value_arr);
  5183. } else {
  5184. $value_key = GETPOST($postfieldkey);
  5185. if (in_array($key_type, array('link')) && $value_key == '-1') {
  5186. $value_key = '';
  5187. }
  5188. }
  5189. $this->array_languages[$key][$codelang] = $value_key;
  5190. /*if ($nofillrequired) {
  5191. $langs->load('errors');
  5192. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  5193. return -1;
  5194. }*/
  5195. }
  5196. return 1;
  5197. }
  5198. /* Functions for extrafields */
  5199. /**
  5200. * Function to make a fetch but set environment to avoid to load computed values before.
  5201. *
  5202. * @param int $id ID of object
  5203. * @return int >0 if OK, 0 if not found, <0 if KO
  5204. */
  5205. public function fetchNoCompute($id)
  5206. {
  5207. global $conf;
  5208. $savDisableCompute = $conf->disable_compute;
  5209. $conf->disable_compute = 1;
  5210. $ret = $this->fetch($id);
  5211. $conf->disable_compute = $savDisableCompute;
  5212. return $ret;
  5213. }
  5214. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5215. /**
  5216. * Function to get extra fields of an object into $this->array_options
  5217. * This method is in most cases called by method fetch of objects but you can call it separately.
  5218. *
  5219. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  5220. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  5221. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  5222. * @see fetchValuesForExtraLanguages()
  5223. */
  5224. public function fetch_optionals($rowid = null, $optionsArray = null)
  5225. {
  5226. // phpcs:enable
  5227. global $conf, $extrafields;
  5228. if (empty($rowid)) {
  5229. $rowid = $this->id;
  5230. }
  5231. if (empty($rowid) && isset($this->rowid)) {
  5232. $rowid = $this->rowid; // deprecated
  5233. }
  5234. // To avoid SQL errors. Probably not the better solution though
  5235. if (!$this->table_element) {
  5236. return 0;
  5237. }
  5238. $this->array_options = array();
  5239. if (!is_array($optionsArray)) {
  5240. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  5241. if (!isset($extrafields) || !is_object($extrafields)) {
  5242. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5243. $extrafields = new ExtraFields($this->db);
  5244. }
  5245. // Load array of extrafields for elementype = $this->table_element
  5246. if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
  5247. $extrafields->fetch_name_optionals_label($this->table_element);
  5248. }
  5249. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  5250. } else {
  5251. global $extrafields;
  5252. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  5253. }
  5254. $table_element = $this->table_element;
  5255. if ($table_element == 'categorie') {
  5256. $table_element = 'categories'; // For compatibility
  5257. }
  5258. // Request to get complementary values
  5259. if (is_array($optionsArray) && count($optionsArray) > 0) {
  5260. $sql = "SELECT rowid";
  5261. foreach ($optionsArray as $name => $label) {
  5262. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
  5263. $sql .= ", ".$name;
  5264. }
  5265. }
  5266. $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
  5267. $sql .= " WHERE fk_object = ".((int) $rowid);
  5268. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5269. $resql = $this->db->query($sql);
  5270. if ($resql) {
  5271. $numrows = $this->db->num_rows($resql);
  5272. if ($numrows) {
  5273. $tab = $this->db->fetch_array($resql);
  5274. foreach ($tab as $key => $value) {
  5275. // 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)
  5276. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
  5277. // we can add this attribute to object
  5278. if (!empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
  5279. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  5280. $this->array_options["options_".$key] = $this->db->jdate($value);
  5281. } else {
  5282. $this->array_options["options_".$key] = $value;
  5283. }
  5284. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  5285. }
  5286. }
  5287. // If field is a computed field, value must become result of compute
  5288. foreach ($tab as $key => $value) {
  5289. if (!empty($extrafields) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
  5290. //var_dump($conf->disable_compute);
  5291. if (empty($conf->disable_compute)) {
  5292. $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
  5293. }
  5294. }
  5295. }
  5296. }
  5297. $this->db->free($resql);
  5298. if ($numrows) {
  5299. return $numrows;
  5300. } else {
  5301. return 0;
  5302. }
  5303. } else {
  5304. $this->errors[]=$this->db->lasterror;
  5305. return -1;
  5306. }
  5307. }
  5308. return 0;
  5309. }
  5310. /**
  5311. * Delete all extra fields values for the current object.
  5312. *
  5313. * @return int <0 if KO, >0 if OK
  5314. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  5315. */
  5316. public function deleteExtraFields()
  5317. {
  5318. global $conf;
  5319. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5320. return 0;
  5321. }
  5322. $this->db->begin();
  5323. $table_element = $this->table_element;
  5324. if ($table_element == 'categorie') {
  5325. $table_element = 'categories'; // For compatibility
  5326. }
  5327. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  5328. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5329. $resql = $this->db->query($sql_del);
  5330. if (!$resql) {
  5331. $this->error = $this->db->lasterror();
  5332. $this->db->rollback();
  5333. return -1;
  5334. } else {
  5335. $this->db->commit();
  5336. return 1;
  5337. }
  5338. }
  5339. /**
  5340. * Add/Update all extra fields values for the current object.
  5341. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5342. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5343. *
  5344. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5345. * @param User $userused Object user
  5346. * @return int -1=error, O=did nothing, 1=OK
  5347. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  5348. */
  5349. public function insertExtraFields($trigger = '', $userused = null)
  5350. {
  5351. global $conf, $langs, $user;
  5352. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5353. return 0;
  5354. }
  5355. if (empty($userused)) {
  5356. $userused = $user;
  5357. }
  5358. $error = 0;
  5359. if (!empty($this->array_options)) {
  5360. // Check parameters
  5361. $langs->load('admin');
  5362. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5363. $extrafields = new ExtraFields($this->db);
  5364. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  5365. // Eliminate copied source object extra fields that do not exist in target object
  5366. $new_array_options = array();
  5367. foreach ($this->array_options as $key => $value) {
  5368. if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
  5369. $new_array_options[$key] = $value;
  5370. } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
  5371. $new_array_options['options_'.$key] = $value;
  5372. }
  5373. }
  5374. foreach ($new_array_options as $key => $value) {
  5375. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5376. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  5377. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  5378. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  5379. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  5380. $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
  5381. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  5382. // If we clone, we have to clean unique extrafields to prevent duplicates.
  5383. // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
  5384. if (! empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && ! empty($attributeUnique)) {
  5385. $new_array_options[$key] = null;
  5386. }
  5387. // Similar code than into insertExtraFields
  5388. if ($attributeRequired) {
  5389. $mandatorypb = false;
  5390. if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
  5391. $mandatorypb = true;
  5392. }
  5393. if ($this->array_options[$key] === '') {
  5394. $mandatorypb = true;
  5395. }
  5396. if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
  5397. $mandatorypb = true;
  5398. }
  5399. if ($mandatorypb) {
  5400. $langs->load("errors");
  5401. dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
  5402. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5403. return -1;
  5404. }
  5405. }
  5406. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5407. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5408. if (!empty($attrfieldcomputed)) {
  5409. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5410. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5411. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5412. $new_array_options[$key] = $value;
  5413. } else {
  5414. $new_array_options[$key] = null;
  5415. }
  5416. }
  5417. switch ($attributeType) {
  5418. case 'int':
  5419. if (!is_numeric($value) && $value != '') {
  5420. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5421. return -1;
  5422. } elseif ($value == '') {
  5423. $new_array_options[$key] = null;
  5424. }
  5425. break;
  5426. case 'price':
  5427. case 'double':
  5428. $value = price2num($value);
  5429. if (!is_numeric($value) && $value != '') {
  5430. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5431. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5432. return -1;
  5433. } elseif ($value == '') {
  5434. $value = null;
  5435. }
  5436. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5437. $new_array_options[$key] = $value;
  5438. break;
  5439. /*case 'select': // Not required, we chosed value='0' for undefined values
  5440. if ($value=='-1')
  5441. {
  5442. $this->array_options[$key] = null;
  5443. }
  5444. break;*/
  5445. case 'password':
  5446. $algo = '';
  5447. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
  5448. // If there is an encryption choice, we use it to crypt data before insert
  5449. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  5450. $algo = reset($tmparrays);
  5451. if ($algo != '') {
  5452. //global $action; // $action may be 'create', 'update', 'update_extras'...
  5453. //var_dump($action);
  5454. //var_dump($this->oldcopy);exit;
  5455. 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
  5456. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  5457. 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.
  5458. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5459. } else {
  5460. // var_dump($algo);
  5461. $newvalue = dol_hash($this->array_options[$key], $algo);
  5462. $new_array_options[$key] = $newvalue;
  5463. }
  5464. } else {
  5465. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5466. }
  5467. }
  5468. } else // Common usage
  5469. {
  5470. $new_array_options[$key] = $this->array_options[$key];
  5471. }
  5472. break;
  5473. case 'date':
  5474. case 'datetime':
  5475. // If data is a string instead of a timestamp, we convert it
  5476. if (!is_int($this->array_options[$key])) {
  5477. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5478. }
  5479. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  5480. break;
  5481. case 'link':
  5482. $param_list = array_keys($attributeParam['options']);
  5483. // 0 : ObjectName
  5484. // 1 : classPath
  5485. $InfoFieldList = explode(":", $param_list[0]);
  5486. dol_include_once($InfoFieldList[1]);
  5487. if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
  5488. if ($value == '-1') { // -1 is key for no defined in combo list of objects
  5489. $new_array_options[$key] = '';
  5490. } elseif ($value) {
  5491. $object = new $InfoFieldList[0]($this->db);
  5492. if (is_numeric($value)) {
  5493. $res = $object->fetch($value); // Common case
  5494. } else {
  5495. $res = $object->fetch('', $value); // For compatibility
  5496. }
  5497. if ($res > 0) {
  5498. $new_array_options[$key] = $object->id;
  5499. } else {
  5500. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5501. $this->db->rollback();
  5502. return -1;
  5503. }
  5504. }
  5505. } else {
  5506. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5507. }
  5508. break;
  5509. }
  5510. }
  5511. $this->db->begin();
  5512. $table_element = $this->table_element;
  5513. if ($table_element == 'categorie') {
  5514. $table_element = 'categories'; // For compatibility
  5515. }
  5516. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  5517. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5518. $this->db->query($sql_del);
  5519. $sql = "INSERT INTO ".$this->db->prefix().$table_element."_extrafields (fk_object";
  5520. foreach ($new_array_options as $key => $value) {
  5521. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5522. // Add field of attribut
  5523. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
  5524. $sql .= ",".$attributeKey;
  5525. }
  5526. }
  5527. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5528. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5529. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5530. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5531. $sql .= ",".$tmpkey;
  5532. }
  5533. }
  5534. }
  5535. $sql .= ") VALUES (".$this->id;
  5536. foreach ($new_array_options as $key => $value) {
  5537. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5538. // Add field of attribute
  5539. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
  5540. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
  5541. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  5542. } else {
  5543. $sql .= ",null";
  5544. }
  5545. }
  5546. }
  5547. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5548. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5549. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5550. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5551. if (in_array($tmpval, array('int', 'double', 'price'))) {
  5552. $sql .= ", 0";
  5553. } else {
  5554. $sql .= ", ''";
  5555. }
  5556. }
  5557. }
  5558. }
  5559. $sql .= ")";
  5560. $resql = $this->db->query($sql);
  5561. if (!$resql) {
  5562. $this->error = $this->db->lasterror();
  5563. $error++;
  5564. }
  5565. if (!$error && $trigger) {
  5566. // Call trigger
  5567. $this->context = array('extrafieldaddupdate'=>1);
  5568. $result = $this->call_trigger($trigger, $userused);
  5569. if ($result < 0) {
  5570. $error++;
  5571. }
  5572. // End call trigger
  5573. }
  5574. if ($error) {
  5575. $this->db->rollback();
  5576. return -1;
  5577. } else {
  5578. $this->db->commit();
  5579. return 1;
  5580. }
  5581. } else {
  5582. return 0;
  5583. }
  5584. }
  5585. /**
  5586. * Add/Update all extra fields values for the current object.
  5587. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5588. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5589. *
  5590. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5591. * @param User $userused Object user
  5592. * @return int -1=error, O=did nothing, 1=OK
  5593. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  5594. */
  5595. public function insertExtraLanguages($trigger = '', $userused = null)
  5596. {
  5597. global $conf, $langs, $user;
  5598. if (empty($userused)) {
  5599. $userused = $user;
  5600. }
  5601. $error = 0;
  5602. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5603. return 0; // For avoid conflicts if trigger used
  5604. }
  5605. if (is_array($this->array_languages)) {
  5606. $new_array_languages = $this->array_languages;
  5607. foreach ($new_array_languages as $key => $value) {
  5608. $attributeKey = $key;
  5609. $attributeType = $this->fields[$attributeKey]['type'];
  5610. $attributeLabel = $this->fields[$attributeKey]['label'];
  5611. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5612. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5613. switch ($attributeType) {
  5614. case 'int':
  5615. if (!is_numeric($value) && $value != '') {
  5616. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5617. return -1;
  5618. } elseif ($value == '') {
  5619. $new_array_languages[$key] = null;
  5620. }
  5621. break;
  5622. case 'double':
  5623. $value = price2num($value);
  5624. if (!is_numeric($value) && $value != '') {
  5625. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5626. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5627. return -1;
  5628. } elseif ($value == '') {
  5629. $new_array_languages[$key] = null;
  5630. }
  5631. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5632. $new_array_languages[$key] = $value;
  5633. break;
  5634. /*case 'select': // Not required, we chosed value='0' for undefined values
  5635. if ($value=='-1')
  5636. {
  5637. $this->array_options[$key] = null;
  5638. }
  5639. break;*/
  5640. }
  5641. }
  5642. $this->db->begin();
  5643. $table_element = $this->table_element;
  5644. if ($table_element == 'categorie') {
  5645. $table_element = 'categories'; // For compatibility
  5646. }
  5647. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  5648. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  5649. foreach ($langcodearray as $langcode => $value) {
  5650. $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
  5651. $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  5652. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  5653. $this->db->query($sql_del);
  5654. if ($value !== '') {
  5655. $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
  5656. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  5657. $sql .= ")";
  5658. $resql = $this->db->query($sql);
  5659. if (!$resql) {
  5660. $this->error = $this->db->lasterror();
  5661. $error++;
  5662. break;
  5663. }
  5664. }
  5665. }
  5666. }
  5667. if (!$error && $trigger) {
  5668. // Call trigger
  5669. $this->context = array('extralanguagesaddupdate'=>1);
  5670. $result = $this->call_trigger($trigger, $userused);
  5671. if ($result < 0) {
  5672. $error++;
  5673. }
  5674. // End call trigger
  5675. }
  5676. if ($error) {
  5677. $this->db->rollback();
  5678. return -1;
  5679. } else {
  5680. $this->db->commit();
  5681. return 1;
  5682. }
  5683. } else {
  5684. return 0;
  5685. }
  5686. }
  5687. /**
  5688. * Update 1 extra field value for the current object. Keep other fields unchanged.
  5689. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5690. *
  5691. * @param string $key Key of the extrafield to update (without starting 'options_')
  5692. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5693. * @param User $userused Object user
  5694. * @return int -1=error, O=did nothing, 1=OK
  5695. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  5696. */
  5697. public function updateExtraField($key, $trigger = null, $userused = null)
  5698. {
  5699. global $conf, $langs, $user;
  5700. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5701. return 0;
  5702. }
  5703. if (empty($userused)) {
  5704. $userused = $user;
  5705. }
  5706. $error = 0;
  5707. if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
  5708. // Check parameters
  5709. $langs->load('admin');
  5710. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5711. $extrafields = new ExtraFields($this->db);
  5712. $extrafields->fetch_name_optionals_label($this->table_element);
  5713. $value = $this->array_options["options_".$key];
  5714. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  5715. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  5716. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  5717. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  5718. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  5719. // Similar code than into insertExtraFields
  5720. if ($attributeRequired) {
  5721. $mandatorypb = false;
  5722. if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
  5723. $mandatorypb = true;
  5724. }
  5725. if ($this->array_options["options_".$key] === '') {
  5726. $mandatorypb = true;
  5727. }
  5728. if ($mandatorypb) {
  5729. $langs->load("errors");
  5730. dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
  5731. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5732. return -1;
  5733. }
  5734. }
  5735. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5736. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5737. if (!empty($attrfieldcomputed)) {
  5738. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5739. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5740. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5741. $this->array_options["options_".$key] = $value;
  5742. } else {
  5743. $this->array_options["options_".$key] = null;
  5744. }
  5745. }
  5746. switch ($attributeType) {
  5747. case 'int':
  5748. if (!is_numeric($value) && $value != '') {
  5749. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5750. return -1;
  5751. } elseif ($value === '') {
  5752. $this->array_options["options_".$key] = null;
  5753. }
  5754. break;
  5755. case 'double':
  5756. $value = price2num($value);
  5757. if (!is_numeric($value) && $value != '') {
  5758. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5759. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5760. return -1;
  5761. } elseif ($value === '') {
  5762. $value = null;
  5763. }
  5764. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5765. $this->array_options["options_".$key] = $value;
  5766. break;
  5767. /*case 'select': // Not required, we chosed value='0' for undefined values
  5768. if ($value=='-1')
  5769. {
  5770. $this->array_options[$key] = null;
  5771. }
  5772. break;*/
  5773. case 'price':
  5774. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  5775. break;
  5776. case 'date':
  5777. case 'datetime':
  5778. if (empty($this->array_options["options_".$key])) {
  5779. $this->array_options["options_".$key] = null;
  5780. } else {
  5781. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5782. }
  5783. break;
  5784. case 'boolean':
  5785. if (empty($this->array_options["options_".$key])) {
  5786. $this->array_options["options_".$key] = null;
  5787. }
  5788. break;
  5789. /*
  5790. case 'link':
  5791. $param_list = array_keys($attributeParam['options']);
  5792. // 0 : ObjectName
  5793. // 1 : classPath
  5794. $InfoFieldList = explode(":", $param_list[0]);
  5795. dol_include_once($InfoFieldList[1]);
  5796. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  5797. {
  5798. if ($value == '-1') // -1 is key for no defined in combo list of objects
  5799. {
  5800. $new_array_options[$key] = '';
  5801. } elseif ($value) {
  5802. $object = new $InfoFieldList[0]($this->db);
  5803. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  5804. else $res = $object->fetch('', $value); // For compatibility
  5805. if ($res > 0) $new_array_options[$key] = $object->id;
  5806. else {
  5807. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5808. $this->db->rollback();
  5809. return -1;
  5810. }
  5811. }
  5812. } else {
  5813. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5814. }
  5815. break;
  5816. */
  5817. }
  5818. $this->db->begin();
  5819. $linealreadyfound = 0;
  5820. // 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)
  5821. $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5822. $resql = $this->db->query($sql);
  5823. if ($resql) {
  5824. $tmpobj = $this->db->fetch_object($resql);
  5825. if ($tmpobj) {
  5826. $linealreadyfound = $tmpobj->nb;
  5827. }
  5828. }
  5829. if ($linealreadyfound) {
  5830. if ($this->array_options["options_".$key] === null) {
  5831. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = null";
  5832. } else {
  5833. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
  5834. }
  5835. $sql .= " WHERE fk_object = ".((int) $this->id);
  5836. } else {
  5837. $result = $this->insertExtraFields('', $user);
  5838. if ($result < 0) {
  5839. $error++;
  5840. }
  5841. }
  5842. $resql = $this->db->query($sql);
  5843. if (!$resql) {
  5844. $error++;
  5845. $this->error = $this->db->lasterror();
  5846. }
  5847. if (!$error && $trigger) {
  5848. // Call trigger
  5849. $this->context = array('extrafieldupdate'=>1);
  5850. $result = $this->call_trigger($trigger, $userused);
  5851. if ($result < 0) {
  5852. $error++;
  5853. }
  5854. // End call trigger
  5855. }
  5856. if ($error) {
  5857. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  5858. $this->db->rollback();
  5859. return -1;
  5860. } else {
  5861. $this->db->commit();
  5862. return 1;
  5863. }
  5864. } else {
  5865. return 0;
  5866. }
  5867. }
  5868. /**
  5869. * Update an extra language value for the current object.
  5870. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5871. *
  5872. * @param string $key Key of the extrafield (without starting 'options_')
  5873. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5874. * @param User $userused Object user
  5875. * @return int -1=error, O=did nothing, 1=OK
  5876. * @see updateExtraFields(), insertExtraLanguages()
  5877. */
  5878. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  5879. {
  5880. global $conf, $langs, $user;
  5881. if (empty($userused)) {
  5882. $userused = $user;
  5883. }
  5884. $error = 0;
  5885. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5886. return 0; // For avoid conflicts if trigger used
  5887. }
  5888. return 0;
  5889. }
  5890. /**
  5891. * Return HTML string to put an input field into a page
  5892. * Code very similar with showInputField of extra fields
  5893. *
  5894. * @param array $val Array of properties for field to show (used only if ->fields not defined)
  5895. * @param string $key Key of attribute
  5896. * @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)
  5897. * @param string $moreparam To add more parameters on html input tag
  5898. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5899. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5900. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  5901. * @param int $nonewbutton Force to not show the new button on field that are links to object
  5902. * @return string
  5903. */
  5904. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  5905. {
  5906. global $conf, $langs, $form;
  5907. if (!is_object($form)) {
  5908. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  5909. $form = new Form($this->db);
  5910. }
  5911. if (!empty($this->fields)) {
  5912. $val = $this->fields[$key];
  5913. }
  5914. // Validation tests and output
  5915. $fieldValidationErrorMsg = '';
  5916. $validationClass = '';
  5917. $fieldValidationErrorMsg = $this->getFieldError($key);
  5918. if (!empty($fieldValidationErrorMsg)) {
  5919. $validationClass = ' --error'; // the -- is use as class state in css : .--error can't be be defined alone it must be define with another class like .my-class.--error or input.--error
  5920. } else {
  5921. $validationClass = ' --success'; // the -- is use as class state in css : .--success can't be be defined alone it must be define with another class like .my-class.--success or input.--success
  5922. }
  5923. $out = '';
  5924. $type = '';
  5925. $isDependList = 0;
  5926. $param = array();
  5927. $param['options'] = array();
  5928. $reg = array();
  5929. $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
  5930. // Because we work on extrafields
  5931. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5932. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5933. $type = 'link';
  5934. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5935. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5936. $type = 'link';
  5937. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  5938. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5939. $type = 'link';
  5940. } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5941. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5942. $type = 'sellist';
  5943. } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5944. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5945. $type = 'sellist';
  5946. } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
  5947. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5948. $type = 'sellist';
  5949. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  5950. $param['options'] = array();
  5951. $type = 'varchar';
  5952. $size = $reg[1];
  5953. } elseif (preg_match('/varchar/', $val['type'])) {
  5954. $param['options'] = array();
  5955. $type = 'varchar';
  5956. } else {
  5957. $param['options'] = array();
  5958. $type = $this->fields[$key]['type'];
  5959. }
  5960. // Special case that force options and type ($type can be integer, varchar, ...)
  5961. if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
  5962. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  5963. $type = 'select';
  5964. }
  5965. $label = $this->fields[$key]['label'];
  5966. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  5967. $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
  5968. $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
  5969. $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
  5970. $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
  5971. $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
  5972. $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
  5973. $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
  5974. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  5975. $objectid = $this->id;
  5976. if ($computed) {
  5977. if (!preg_match('/^search_/', $keyprefix)) {
  5978. return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  5979. } else {
  5980. return '';
  5981. }
  5982. }
  5983. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  5984. if (empty($morecss) && !empty($val['css'])) {
  5985. $morecss = $val['css'];
  5986. } elseif (empty($morecss)) {
  5987. if ($type == 'date') {
  5988. $morecss = 'minwidth100imp';
  5989. } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
  5990. $morecss = 'minwidth200imp';
  5991. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  5992. $morecss = 'maxwidth75';
  5993. } elseif ($type == 'url') {
  5994. $morecss = 'minwidth400';
  5995. } elseif ($type == 'boolean') {
  5996. $morecss = '';
  5997. } else {
  5998. if (round($size) < 12) {
  5999. $morecss = 'minwidth100';
  6000. } elseif (round($size) <= 48) {
  6001. $morecss = 'minwidth200';
  6002. } else {
  6003. $morecss = 'minwidth400';
  6004. }
  6005. }
  6006. }
  6007. // Add validation state class
  6008. if (!empty($validationClass)) {
  6009. $morecss.= $validationClass;
  6010. }
  6011. if (in_array($type, array('date'))) {
  6012. $tmp = explode(',', $size);
  6013. $newsize = $tmp[0];
  6014. $showtime = 0;
  6015. // Do not show current date when field not required (see selectDate() method)
  6016. if (!$required && $value == '') {
  6017. $value = '-1';
  6018. }
  6019. // TODO Must also support $moreparam
  6020. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  6021. } elseif (in_array($type, array('datetime'))) {
  6022. $tmp = explode(',', $size);
  6023. $newsize = $tmp[0];
  6024. $showtime = 1;
  6025. // Do not show current date when field not required (see selectDate() method)
  6026. if (!$required && $value == '') $value = '-1';
  6027. // TODO Must also support $moreparam
  6028. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
  6029. } elseif (in_array($type, array('duration'))) {
  6030. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  6031. } elseif (in_array($type, array('int', 'integer'))) {
  6032. $tmp = explode(',', $size);
  6033. $newsize = $tmp[0];
  6034. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"'.($newsize > 0 ? ' maxlength="'.$newsize.'"' : '').' value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6035. } elseif (in_array($type, array('real'))) {
  6036. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6037. } elseif (preg_match('/varchar/', $type)) {
  6038. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"'.($size > 0 ? ' maxlength="'.$size.'"' : '').' value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6039. } elseif (in_array($type, array('mail', 'phone', 'url'))) {
  6040. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6041. } elseif (preg_match('/^text/', $type)) {
  6042. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6043. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  6044. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  6045. $out = $doleditor->Create(1);
  6046. } else {
  6047. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  6048. }
  6049. } elseif (preg_match('/^html/', $type)) {
  6050. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6051. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  6052. $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%');
  6053. $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
  6054. } else {
  6055. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  6056. }
  6057. } elseif ($type == 'boolean') {
  6058. $checked = '';
  6059. if (!empty($value)) {
  6060. $checked = ' checked value="1" ';
  6061. } else {
  6062. $checked = ' value="1" ';
  6063. }
  6064. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  6065. } elseif ($type == 'price') {
  6066. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6067. $value = price($value);
  6068. }
  6069. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  6070. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  6071. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6072. $value = price($value);
  6073. }
  6074. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  6075. } elseif ($type == 'select') {
  6076. $out = '';
  6077. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6078. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6079. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6080. }
  6081. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6082. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
  6083. $out .= '<option value="0">&nbsp;</option>';
  6084. }
  6085. foreach ($param['options'] as $key => $val) {
  6086. if ((string) $key == '') {
  6087. continue;
  6088. }
  6089. list($val, $parent) = explode('|', $val);
  6090. $out .= '<option value="'.$key.'"';
  6091. $out .= (((string) $value == (string) $key) ? ' selected' : '');
  6092. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6093. $out .= '>'.$val.'</option>';
  6094. }
  6095. $out .= '</select>';
  6096. } elseif ($type == 'sellist') {
  6097. $out = '';
  6098. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6099. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6100. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6101. }
  6102. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6103. if (is_array($param['options'])) {
  6104. $param_list = array_keys($param['options']);
  6105. $InfoFieldList = explode(":", $param_list[0]);
  6106. $parentName = '';
  6107. $parentField = '';
  6108. // 0 : tableName
  6109. // 1 : label field name
  6110. // 2 : key fields name (if differ of rowid)
  6111. // 3 : key field parent (for dependent lists)
  6112. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6113. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6114. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6115. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6116. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6117. } else {
  6118. $keyList = $InfoFieldList[2].' as rowid';
  6119. }
  6120. }
  6121. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6122. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6123. $keyList .= ', '.$parentField;
  6124. }
  6125. $fields_label = explode('|', $InfoFieldList[1]);
  6126. if (is_array($fields_label)) {
  6127. $keyList .= ', ';
  6128. $keyList .= implode(', ', $fields_label);
  6129. }
  6130. $sqlwhere = '';
  6131. $sql = "SELECT ".$keyList;
  6132. $sql .= " FROM ".$this->db->prefix().$InfoFieldList[0];
  6133. if (!empty($InfoFieldList[4])) {
  6134. // can use SELECT request
  6135. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6136. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6137. }
  6138. // current object id can be use into filter
  6139. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6140. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6141. } else {
  6142. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6143. }
  6144. //We have to join on extrafield table
  6145. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6146. $sql .= " as main, ".$this->db->prefix().$InfoFieldList[0]."_extrafields as extra";
  6147. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  6148. } else {
  6149. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  6150. }
  6151. } else {
  6152. $sqlwhere .= ' WHERE 1=1';
  6153. }
  6154. // Some tables may have field, some other not. For the moment we disable it.
  6155. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6156. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  6157. }
  6158. $sql .= $sqlwhere;
  6159. //print $sql;
  6160. $sql .= ' ORDER BY '.implode(', ', $fields_label);
  6161. dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
  6162. $resql = $this->db->query($sql);
  6163. if ($resql) {
  6164. $out .= '<option value="0">&nbsp;</option>';
  6165. $num = $this->db->num_rows($resql);
  6166. $i = 0;
  6167. while ($i < $num) {
  6168. $labeltoshow = '';
  6169. $obj = $this->db->fetch_object($resql);
  6170. // Several field into label (eq table:code|libelle:rowid)
  6171. $notrans = false;
  6172. $fields_label = explode('|', $InfoFieldList[1]);
  6173. if (count($fields_label) > 1) {
  6174. $notrans = true;
  6175. foreach ($fields_label as $field_toshow) {
  6176. $labeltoshow .= $obj->$field_toshow.' ';
  6177. }
  6178. } else {
  6179. $labeltoshow = $obj->{$InfoFieldList[1]};
  6180. }
  6181. $labeltoshow = dol_trunc($labeltoshow, 45);
  6182. if ($value == $obj->rowid) {
  6183. foreach ($fields_label as $field_toshow) {
  6184. $translabel = $langs->trans($obj->$field_toshow);
  6185. if ($translabel != $obj->$field_toshow) {
  6186. $labeltoshow = dol_trunc($translabel).' ';
  6187. } else {
  6188. $labeltoshow = dol_trunc($obj->$field_toshow).' ';
  6189. }
  6190. }
  6191. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6192. } else {
  6193. if (!$notrans) {
  6194. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6195. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6196. $labeltoshow = dol_trunc($translabel, 18);
  6197. } else {
  6198. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
  6199. }
  6200. }
  6201. if (empty($labeltoshow)) {
  6202. $labeltoshow = '(not defined)';
  6203. }
  6204. if ($value == $obj->rowid) {
  6205. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6206. }
  6207. if (!empty($InfoFieldList[3]) && $parentField) {
  6208. $parent = $parentName.':'.$obj->{$parentField};
  6209. $isDependList = 1;
  6210. }
  6211. $out .= '<option value="'.$obj->rowid.'"';
  6212. $out .= ($value == $obj->rowid ? ' selected' : '');
  6213. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6214. $out .= '>'.$labeltoshow.'</option>';
  6215. }
  6216. $i++;
  6217. }
  6218. $this->db->free($resql);
  6219. } else {
  6220. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6221. }
  6222. }
  6223. $out .= '</select>';
  6224. } elseif ($type == 'checkbox') {
  6225. $value_arr = explode(',', $value);
  6226. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
  6227. } elseif ($type == 'radio') {
  6228. $out = '';
  6229. foreach ($param['options'] as $keyopt => $val) {
  6230. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  6231. $out .= ' value="'.$keyopt.'"';
  6232. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  6233. $out .= ($value == $keyopt ? 'checked' : '');
  6234. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
  6235. }
  6236. } elseif ($type == 'chkbxlst') {
  6237. if (is_array($value)) {
  6238. $value_arr = $value;
  6239. } else {
  6240. $value_arr = explode(',', $value);
  6241. }
  6242. if (is_array($param['options'])) {
  6243. $param_list = array_keys($param['options']);
  6244. $InfoFieldList = explode(":", $param_list[0]);
  6245. $parentName = '';
  6246. $parentField = '';
  6247. // 0 : tableName
  6248. // 1 : label field name
  6249. // 2 : key fields name (if differ of rowid)
  6250. // 3 : key field parent (for dependent lists)
  6251. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6252. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6253. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6254. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6255. $keyList .= ', '.$parentField;
  6256. }
  6257. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6258. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6259. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6260. } else {
  6261. $keyList = $InfoFieldList[2].' as rowid';
  6262. }
  6263. }
  6264. $fields_label = explode('|', $InfoFieldList[1]);
  6265. if (is_array($fields_label)) {
  6266. $keyList .= ', ';
  6267. $keyList .= implode(', ', $fields_label);
  6268. }
  6269. $sqlwhere = '';
  6270. $sql = "SELECT ".$keyList;
  6271. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6272. if (!empty($InfoFieldList[4])) {
  6273. // can use SELECT request
  6274. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6275. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6276. }
  6277. // current object id can be use into filter
  6278. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6279. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6280. } else {
  6281. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6282. }
  6283. // We have to join on extrafield table
  6284. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6285. $sql .= ' as main, '.$this->db->prefix().$InfoFieldList[0].'_extrafields as extra';
  6286. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  6287. } else {
  6288. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  6289. }
  6290. } else {
  6291. $sqlwhere .= ' WHERE 1=1';
  6292. }
  6293. // Some tables may have field, some other not. For the moment we disable it.
  6294. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6295. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  6296. }
  6297. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  6298. // print $sql;
  6299. $sql .= $sqlwhere;
  6300. dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
  6301. $resql = $this->db->query($sql);
  6302. if ($resql) {
  6303. $num = $this->db->num_rows($resql);
  6304. $i = 0;
  6305. $data = array();
  6306. while ($i < $num) {
  6307. $labeltoshow = '';
  6308. $obj = $this->db->fetch_object($resql);
  6309. $notrans = false;
  6310. // Several field into label (eq table:code|libelle:rowid)
  6311. $fields_label = explode('|', $InfoFieldList[1]);
  6312. if (count($fields_label) > 1) {
  6313. $notrans = true;
  6314. foreach ($fields_label as $field_toshow) {
  6315. $labeltoshow .= $obj->$field_toshow.' ';
  6316. }
  6317. } else {
  6318. $labeltoshow = $obj->{$InfoFieldList[1]};
  6319. }
  6320. $labeltoshow = dol_trunc($labeltoshow, 45);
  6321. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6322. foreach ($fields_label as $field_toshow) {
  6323. $translabel = $langs->trans($obj->$field_toshow);
  6324. if ($translabel != $obj->$field_toshow) {
  6325. $labeltoshow = dol_trunc($translabel, 18).' ';
  6326. } else {
  6327. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  6328. }
  6329. }
  6330. $data[$obj->rowid] = $labeltoshow;
  6331. } else {
  6332. if (!$notrans) {
  6333. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6334. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6335. $labeltoshow = dol_trunc($translabel, 18);
  6336. } else {
  6337. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  6338. }
  6339. }
  6340. if (empty($labeltoshow)) {
  6341. $labeltoshow = '(not defined)';
  6342. }
  6343. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6344. $data[$obj->rowid] = $labeltoshow;
  6345. }
  6346. if (!empty($InfoFieldList[3]) && $parentField) {
  6347. $parent = $parentName.':'.$obj->{$parentField};
  6348. $isDependList = 1;
  6349. }
  6350. $data[$obj->rowid] = $labeltoshow;
  6351. }
  6352. $i++;
  6353. }
  6354. $this->db->free($resql);
  6355. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
  6356. } else {
  6357. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6358. }
  6359. }
  6360. } elseif ($type == 'link') {
  6361. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
  6362. $param_list_array = explode(':', $param_list[0]);
  6363. $showempty = (($required && $default != '') ? 0 : 1);
  6364. if (!preg_match('/search_/', $keyprefix)) {
  6365. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6366. if (!empty($this->fields[$key]['picto'])) {
  6367. $morecss .= ' widthcentpercentminusxx';
  6368. } else {
  6369. $morecss .= ' widthcentpercentminusx';
  6370. }
  6371. } else {
  6372. if (!empty($this->fields[$key]['picto'])) {
  6373. $morecss .= ' widthcentpercentminusx';
  6374. }
  6375. }
  6376. }
  6377. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  6378. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6379. 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".
  6380. list($class, $classfile) = explode(':', $param_list[0]);
  6381. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
  6382. $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  6383. } else {
  6384. $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  6385. }
  6386. $paramforthenewlink = '';
  6387. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  6388. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  6389. $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin='.GETPOST('origin', 'aZ09') : '');
  6390. $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid='.GETPOST('originid', 'int') : '');
  6391. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  6392. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  6393. $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>';
  6394. }
  6395. }
  6396. } elseif ($type == 'password') {
  6397. // If prefix is 'search_', field is used as a filter, we use a common text field.
  6398. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  6399. } elseif ($type == 'array') {
  6400. $newval = $val;
  6401. $newval['type'] = 'varchar(256)';
  6402. $out = '';
  6403. if (!empty($value)) {
  6404. foreach ($value as $option) {
  6405. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6406. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  6407. }
  6408. }
  6409. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6410. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6411. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  6412. if (!empty($conf->use_javascript_ajax)) {
  6413. $out .= '
  6414. <script>
  6415. $(document).ready(function() {
  6416. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  6417. $("'.dol_escape_js($newInput).'").insertBefore(this);
  6418. });
  6419. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  6420. $(this).parent().remove();
  6421. });
  6422. });
  6423. </script>';
  6424. }
  6425. }
  6426. if (!empty($hidden)) {
  6427. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  6428. }
  6429. if ($isDependList==1) {
  6430. $out .= $this->getJSListDependancies('_common');
  6431. }
  6432. /* Add comments
  6433. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  6434. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  6435. */
  6436. // Display error message for field
  6437. if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
  6438. $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
  6439. }
  6440. return $out;
  6441. }
  6442. /**
  6443. * Return HTML string to show a field into a page
  6444. * Code very similar with showOutputField of extra fields
  6445. *
  6446. * @param array $val Array of properties of field to show
  6447. * @param string $key Key of attribute
  6448. * @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)
  6449. * @param string $moreparam To add more parametes on html input tag
  6450. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6451. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6452. * @param mixed $morecss Value for css to define size. May also be a numeric.
  6453. * @return string
  6454. */
  6455. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  6456. {
  6457. global $conf, $langs, $form;
  6458. if (!is_object($form)) {
  6459. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6460. $form = new Form($this->db);
  6461. }
  6462. $objectid = $this->id; // Not used ???
  6463. $label = empty($val['label']) ? '' : $val['label'];
  6464. $type = empty($val['type']) ? '' : $val['type'];
  6465. $size = empty($val['css']) ? '' : $val['css'];
  6466. $reg = array();
  6467. // Convert var to be able to share same code than showOutputField of extrafields
  6468. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6469. $type = 'varchar'; // convert varchar(xx) int varchar
  6470. $size = $reg[1];
  6471. } elseif (preg_match('/varchar/', $type)) {
  6472. $type = 'varchar'; // convert varchar(xx) int varchar
  6473. }
  6474. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6475. $type = 'select';
  6476. }
  6477. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6478. $type = 'link';
  6479. }
  6480. $default = empty($val['default']) ? '' : $val['default'];
  6481. $computed = empty($val['computed']) ? '' : $val['computed'];
  6482. $unique = empty($val['unique']) ? '' : $val['unique'];
  6483. $required = empty($val['required']) ? '' : $val['required'];
  6484. $param = array();
  6485. $param['options'] = array();
  6486. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6487. $param['options'] = $val['arrayofkeyval'];
  6488. }
  6489. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6490. $type = 'link';
  6491. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6492. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6493. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6494. $type = 'sellist';
  6495. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6496. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6497. $type = 'sellist';
  6498. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6499. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6500. $type = 'sellist';
  6501. }
  6502. $langfile = empty($val['langfile']) ? '' : $val['langfile'];
  6503. $list = (empty($val['list']) ? '' : $val['list']);
  6504. $help = (empty($val['help']) ? '' : $val['help']);
  6505. $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)
  6506. if ($hidden) {
  6507. return '';
  6508. }
  6509. // If field is a computed field, value must become result of compute
  6510. if ($computed) {
  6511. // Make the eval of compute string
  6512. //var_dump($computed);
  6513. $value = dol_eval($computed, 1, 0, '');
  6514. }
  6515. if (empty($morecss)) {
  6516. if ($type == 'date') {
  6517. $morecss = 'minwidth100imp';
  6518. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6519. $morecss = 'minwidth200imp';
  6520. } elseif (in_array($type, array('int', 'double', 'price'))) {
  6521. $morecss = 'maxwidth75';
  6522. } elseif ($type == 'url') {
  6523. $morecss = 'minwidth400';
  6524. } elseif ($type == 'boolean') {
  6525. $morecss = '';
  6526. } else {
  6527. if (is_numeric($size) && round($size) < 12) {
  6528. $morecss = 'minwidth100';
  6529. } elseif (is_numeric($size) && round($size) <= 48) {
  6530. $morecss = 'minwidth200';
  6531. } else {
  6532. $morecss = 'minwidth400';
  6533. }
  6534. }
  6535. }
  6536. // Format output value differently according to properties of field
  6537. if ($key == 'ref' && method_exists($this, 'getNomUrl')) {
  6538. $value = $this->getNomUrl(1, '', 0, '', 1);
  6539. } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
  6540. $value = $this->getLibStatut(3);
  6541. } elseif ($type == 'date') {
  6542. if (!empty($value)) {
  6543. $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
  6544. } else {
  6545. $value = '';
  6546. }
  6547. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6548. if (!empty($value)) {
  6549. $value = dol_print_date($value, 'dayhour', 'tzuserrel');
  6550. } else {
  6551. $value = '';
  6552. }
  6553. } elseif ($type == 'duration') {
  6554. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6555. if (!is_null($value) && $value !== '') {
  6556. $value = convertSecondToTime($value, 'allhourmin');
  6557. }
  6558. } elseif ($type == 'double' || $type == 'real') {
  6559. if (!is_null($value) && $value !== '') {
  6560. $value = price($value);
  6561. }
  6562. } elseif ($type == 'boolean') {
  6563. $checked = '';
  6564. if (!empty($value)) {
  6565. $checked = ' checked ';
  6566. }
  6567. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  6568. } elseif ($type == 'mail') {
  6569. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  6570. } elseif ($type == 'url') {
  6571. $value = dol_print_url($value, '_blank', 32, 1);
  6572. } elseif ($type == 'phone') {
  6573. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
  6574. } elseif ($type == 'price') {
  6575. if (!is_null($value) && $value !== '') {
  6576. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  6577. }
  6578. } elseif ($type == 'select') {
  6579. $value = $param['options'][$value];
  6580. } elseif ($type == 'sellist') {
  6581. $param_list = array_keys($param['options']);
  6582. $InfoFieldList = explode(":", $param_list[0]);
  6583. $selectkey = "rowid";
  6584. $keyList = 'rowid';
  6585. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6586. $selectkey = $InfoFieldList[2];
  6587. $keyList = $InfoFieldList[2].' as rowid';
  6588. }
  6589. $fields_label = explode('|', $InfoFieldList[1]);
  6590. if (is_array($fields_label)) {
  6591. $keyList .= ', ';
  6592. $keyList .= implode(', ', $fields_label);
  6593. }
  6594. $sql = "SELECT ".$keyList;
  6595. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6596. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6597. $sql .= ' as main';
  6598. }
  6599. if ($selectkey == 'rowid' && empty($value)) {
  6600. $sql .= " WHERE ".$selectkey." = 0";
  6601. } elseif ($selectkey == 'rowid') {
  6602. $sql .= " WHERE ".$selectkey." = ".((int) $value);
  6603. } else {
  6604. $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
  6605. }
  6606. //$sql.= ' AND entity = '.$conf->entity;
  6607. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  6608. $resql = $this->db->query($sql);
  6609. if ($resql) {
  6610. $value = ''; // value was used, so now we reste it to use it to build final output
  6611. $obj = $this->db->fetch_object($resql);
  6612. // Several field into label (eq table:code|libelle:rowid)
  6613. $fields_label = explode('|', $InfoFieldList[1]);
  6614. if (is_array($fields_label) && count($fields_label) > 1) {
  6615. foreach ($fields_label as $field_toshow) {
  6616. $translabel = '';
  6617. if (!empty($obj->$field_toshow)) {
  6618. $translabel = $langs->trans($obj->$field_toshow);
  6619. }
  6620. if ($translabel != $field_toshow) {
  6621. $value .= dol_trunc($translabel, 18).' ';
  6622. } else {
  6623. $value .= $obj->$field_toshow.' ';
  6624. }
  6625. }
  6626. } else {
  6627. $translabel = '';
  6628. if (!empty($obj->{$InfoFieldList[1]})) {
  6629. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6630. }
  6631. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6632. $value = dol_trunc($translabel, 18);
  6633. } else {
  6634. $value = $obj->{$InfoFieldList[1]};
  6635. }
  6636. }
  6637. } else {
  6638. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6639. }
  6640. } elseif ($type == 'radio') {
  6641. $value = $param['options'][$value];
  6642. } elseif ($type == 'checkbox') {
  6643. $value_arr = explode(',', $value);
  6644. $value = '';
  6645. if (is_array($value_arr) && count($value_arr) > 0) {
  6646. $toprint = array();
  6647. foreach ($value_arr as $keyval => $valueval) {
  6648. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  6649. }
  6650. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6651. }
  6652. } elseif ($type == 'chkbxlst') {
  6653. $value_arr = explode(',', $value);
  6654. $param_list = array_keys($param['options']);
  6655. $InfoFieldList = explode(":", $param_list[0]);
  6656. $selectkey = "rowid";
  6657. $keyList = 'rowid';
  6658. if (count($InfoFieldList) >= 3) {
  6659. $selectkey = $InfoFieldList[2];
  6660. $keyList = $InfoFieldList[2].' as rowid';
  6661. }
  6662. $fields_label = explode('|', $InfoFieldList[1]);
  6663. if (is_array($fields_label)) {
  6664. $keyList .= ', ';
  6665. $keyList .= implode(', ', $fields_label);
  6666. }
  6667. $sql = "SELECT ".$keyList;
  6668. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6669. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6670. $sql .= ' as main';
  6671. }
  6672. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  6673. // $sql.= ' AND entity = '.$conf->entity;
  6674. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  6675. $resql = $this->db->query($sql);
  6676. if ($resql) {
  6677. $value = ''; // value was used, so now we reste it to use it to build final output
  6678. $toprint = array();
  6679. while ($obj = $this->db->fetch_object($resql)) {
  6680. // Several field into label (eq table:code|libelle:rowid)
  6681. $fields_label = explode('|', $InfoFieldList[1]);
  6682. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6683. if (is_array($fields_label) && count($fields_label) > 1) {
  6684. foreach ($fields_label as $field_toshow) {
  6685. $translabel = '';
  6686. if (!empty($obj->$field_toshow)) {
  6687. $translabel = $langs->trans($obj->$field_toshow);
  6688. }
  6689. if ($translabel != $field_toshow) {
  6690. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6691. } else {
  6692. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->$field_toshow.'</li>';
  6693. }
  6694. }
  6695. } else {
  6696. $translabel = '';
  6697. if (!empty($obj->{$InfoFieldList[1]})) {
  6698. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6699. }
  6700. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6701. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6702. } else {
  6703. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->{$InfoFieldList[1]}.'</li>';
  6704. }
  6705. }
  6706. }
  6707. }
  6708. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6709. } else {
  6710. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6711. }
  6712. } elseif ($type == 'link') {
  6713. $out = '';
  6714. // only if something to display (perf)
  6715. if ($value) {
  6716. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6717. $InfoFieldList = explode(":", $param_list[0]);
  6718. $classname = $InfoFieldList[0];
  6719. $classpath = $InfoFieldList[1];
  6720. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  6721. $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
  6722. if (!empty($classpath)) {
  6723. dol_include_once($InfoFieldList[1]);
  6724. if ($classname && class_exists($classname)) {
  6725. $object = new $classname($this->db);
  6726. if ($object->element === 'product') { // Special cas for product because default valut of fetch are wrong
  6727. $object->fetch($value, '', '', '', 0, 1, 1);
  6728. } else {
  6729. $object->fetch($value);
  6730. }
  6731. $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
  6732. }
  6733. } else {
  6734. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  6735. return 'Error bad setup of extrafield';
  6736. }
  6737. } else {
  6738. $value = '';
  6739. }
  6740. } elseif (preg_match('/^(text|html)/', $type)) {
  6741. $value = dol_htmlentitiesbr($value);
  6742. } elseif ($type == 'password') {
  6743. $value = preg_replace('/./i', '*', $value);
  6744. } elseif ($type == 'array') {
  6745. $value = implode('<br>', $value);
  6746. }
  6747. //print $type.'-'.$size.'-'.$value;
  6748. $out = $value;
  6749. return $out;
  6750. }
  6751. /**
  6752. * clear validation message result for a field
  6753. *
  6754. * @param string $fieldKey Key of attribute to clear
  6755. * @return null
  6756. */
  6757. public function clearFieldError($fieldKey)
  6758. {
  6759. $this->error = '';
  6760. unset($this->validateFieldsErrors[$fieldKey]);
  6761. }
  6762. /**
  6763. * set validation error message a field
  6764. *
  6765. * @param string $fieldKey Key of attribute
  6766. * @param string $msg the field error message
  6767. * @return null
  6768. */
  6769. public function setFieldError($fieldKey, $msg = '')
  6770. {
  6771. global $langs;
  6772. if (empty($msg)) { $msg = $langs->trans("UnknowError"); }
  6773. $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
  6774. }
  6775. /**
  6776. * get field error message
  6777. *
  6778. * @param string $fieldKey Key of attribute
  6779. * @return string
  6780. */
  6781. public function getFieldError($fieldKey)
  6782. {
  6783. if (!empty($this->validateFieldsErrors[$fieldKey])) {
  6784. return $this->validateFieldsErrors[$fieldKey];
  6785. }
  6786. return '';
  6787. }
  6788. /**
  6789. * Return validation test result for a field
  6790. *
  6791. * @param array $val Array of properties of field to show
  6792. * @param string $fieldKey Key of attribute
  6793. * @param string $fieldValue value of attribute
  6794. * @return bool return false if fail true on success, see $this->error for error message
  6795. */
  6796. public function validateField($val, $fieldKey, $fieldValue)
  6797. {
  6798. global $langs;
  6799. if (!class_exists('Validate')) { require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php'; }
  6800. $this->clearFieldError($fieldKey);
  6801. if (!isset($val[$fieldKey])) {
  6802. $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
  6803. return false;
  6804. }
  6805. $param = array();
  6806. $param['options'] = array();
  6807. $type = $val[$fieldKey]['type'];
  6808. $required = false;
  6809. if (isset($val[$fieldKey]['notnull']) && $val[$fieldKey]['notnull'] === 1) {
  6810. // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  6811. $required = true;
  6812. }
  6813. $maxSize = 0;
  6814. $minSize = 0;
  6815. //
  6816. // PREPARE Elements
  6817. //
  6818. // Convert var to be able to share same code than showOutputField of extrafields
  6819. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6820. $type = 'varchar'; // convert varchar(xx) int varchar
  6821. $maxSize = $reg[1];
  6822. } elseif (preg_match('/varchar/', $type)) {
  6823. $type = 'varchar'; // convert varchar(xx) int varchar
  6824. }
  6825. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6826. $type = 'select';
  6827. }
  6828. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6829. $type = 'link';
  6830. }
  6831. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6832. $param['options'] = $val['arrayofkeyval'];
  6833. }
  6834. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6835. $type = 'link';
  6836. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6837. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6838. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6839. $type = 'sellist';
  6840. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6841. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6842. $type = 'sellist';
  6843. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6844. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6845. $type = 'sellist';
  6846. }
  6847. //
  6848. // TEST Value
  6849. //
  6850. // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
  6851. $validate = new Validate($this->db, $langs);
  6852. // little trick : to perform tests with good performances sort tests by quick to low
  6853. //
  6854. // COMMON TESTS
  6855. //
  6856. // Required test and empty value
  6857. if ($required && !$validate->isNotEmptyString($fieldValue)) {
  6858. $this->setFieldError($fieldKey, $validate->error);
  6859. return false;
  6860. } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
  6861. // if no value sent and the field is not mandatory, no need to perform tests
  6862. return true;
  6863. }
  6864. // MAX Size test
  6865. if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
  6866. $this->setFieldError($fieldKey, $validate->error);
  6867. return false;
  6868. }
  6869. // MIN Size test
  6870. if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
  6871. $this->setFieldError($fieldKey, $validate->error);
  6872. return false;
  6873. }
  6874. //
  6875. // TESTS for TYPE
  6876. //
  6877. if (in_array($type, array('date', 'datetime', 'timestamp'))) {
  6878. if (!$validate->isTimestamp($fieldValue)) {
  6879. $this->setFieldError($fieldKey, $validate->error);
  6880. return false;
  6881. } else { return true; }
  6882. } elseif ($type == 'duration') {
  6883. if (!$validate->isDuration($fieldValue)) {
  6884. $this->setFieldError($fieldKey, $validate->error);
  6885. return false;
  6886. } else { return true; }
  6887. } elseif (in_array($type, array('double', 'real', 'price'))) {
  6888. // is numeric
  6889. if (!$validate->isNumeric($fieldValue)) {
  6890. $this->setFieldError($fieldKey, $validate->error);
  6891. return false;
  6892. } else { return true; }
  6893. } elseif ($type == 'boolean') {
  6894. if (!$validate->isBool($fieldValue)) {
  6895. $this->setFieldError($fieldKey, $validate->error);
  6896. return false;
  6897. } else { return true; }
  6898. } elseif ($type == 'mail') {
  6899. if (!$validate->isEmail($fieldValue)) {
  6900. $this->setFieldError($fieldKey, $validate->error);
  6901. return false;
  6902. }
  6903. } elseif ($type == 'url') {
  6904. if (!$validate->isUrl($fieldValue)) {
  6905. $this->setFieldError($fieldKey, $validate->error);
  6906. return false;
  6907. } else { return true; }
  6908. } elseif ($type == 'phone') {
  6909. if (!$validate->isPhone($fieldValue)) {
  6910. $this->setFieldError($fieldKey, $validate->error);
  6911. return false;
  6912. } else { return true; }
  6913. } elseif ($type == 'select' || $type == 'radio') {
  6914. if (!isset($param['options'][$fieldValue])) {
  6915. $this->error = $langs->trans('RequireValidValue');
  6916. return false;
  6917. } else { return true; }
  6918. } elseif ($type == 'sellist' || $type == 'chkbxlst') {
  6919. $param_list = array_keys($param['options']);
  6920. $InfoFieldList = explode(":", $param_list[0]);
  6921. $value_arr = explode(',', $fieldValue);
  6922. $value_arr = array_map(array($this->db, 'escape'), $value_arr);
  6923. $selectkey = "rowid";
  6924. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6925. $selectkey = $InfoFieldList[2];
  6926. }
  6927. if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
  6928. $this->setFieldError($fieldKey, $validate->error);
  6929. return false;
  6930. } else { return true; }
  6931. } elseif ($type == 'link') {
  6932. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6933. $InfoFieldList = explode(":", $param_list[0]);
  6934. $classname = $InfoFieldList[0];
  6935. $classpath = $InfoFieldList[1];
  6936. if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
  6937. $this->setFieldError($fieldKey, $validate->error);
  6938. return false;
  6939. } else { return true; }
  6940. }
  6941. // if no test failled all is ok
  6942. return true;
  6943. }
  6944. /**
  6945. * Function to show lines of extrafields with output datas.
  6946. * 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
  6947. *
  6948. * @param Extrafields $extrafields Extrafield Object
  6949. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  6950. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  6951. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  6952. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  6953. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  6954. * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...)
  6955. * @return string String with html content to show
  6956. */
  6957. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
  6958. {
  6959. global $db, $conf, $langs, $action, $form, $hookmanager;
  6960. if (!is_object($form)) {
  6961. $form = new Form($db);
  6962. }
  6963. if (!is_object($extrafields)) {
  6964. dol_syslog('Bad parameter extrafields for showOptionals', LOG_ERR);
  6965. return 'Bad parameter extrafields for showOptionals';
  6966. }
  6967. if (!is_array($extrafields->attributes[$this->table_element])) {
  6968. dol_syslog("extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
  6969. }
  6970. $out = '';
  6971. $parameters = array();
  6972. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  6973. if (empty($reshook)) {
  6974. if (is_array($extrafields->attributes[$this->table_element]) && key_exists('label', $extrafields->attributes[$this->table_element]) && is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0) {
  6975. $out .= "\n";
  6976. $out .= '<!-- commonobject:showOptionals --> ';
  6977. $out .= "\n";
  6978. $extrafields_collapse_num = '';
  6979. $e = 0;
  6980. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
  6981. // Show only the key field in params
  6982. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
  6983. continue;
  6984. }
  6985. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  6986. $enabled = 1;
  6987. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  6988. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '1');
  6989. }
  6990. if (empty($enabled)) {
  6991. continue;
  6992. }
  6993. $visibility = 1;
  6994. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  6995. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '1');
  6996. }
  6997. $perms = 1;
  6998. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  6999. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '1');
  7000. }
  7001. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
  7002. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  7003. } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
  7004. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  7005. } elseif ($mode == 'view' && empty($visibility)) {
  7006. continue;
  7007. }
  7008. if (empty($perms)) {
  7009. continue;
  7010. }
  7011. // Load language if required
  7012. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  7013. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  7014. }
  7015. $colspan = 0;
  7016. if (is_array($params) && count($params) > 0 && $display_type=='card') {
  7017. if (array_key_exists('cols', $params)) {
  7018. $colspan = $params['cols'];
  7019. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  7020. $reg = array();
  7021. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  7022. $colspan = $reg[1];
  7023. } else {
  7024. $colspan = $params['colspan'];
  7025. }
  7026. }
  7027. }
  7028. $colspan = intval($colspan);
  7029. switch ($mode) {
  7030. case "view":
  7031. $value = $this->array_options["options_".$key.$keysuffix]; // Value may be clean or formated later
  7032. break;
  7033. case "create":
  7034. case "edit":
  7035. // We get the value of property found with GETPOST so it takes into account:
  7036. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  7037. $check = 'alphanohtml';
  7038. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  7039. $check = 'restricthtml';
  7040. }
  7041. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  7042. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  7043. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
  7044. if (is_array($getposttemp)) {
  7045. // $getposttemp is an array but following code expects a comma separated string
  7046. $value = implode(",", $getposttemp);
  7047. } else {
  7048. $value = $getposttemp;
  7049. }
  7050. } else {
  7051. $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.
  7052. }
  7053. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  7054. break;
  7055. }
  7056. // Output value of the current field
  7057. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  7058. $extrafields_collapse_num = '';
  7059. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  7060. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  7061. $extrafield_param_list = array_keys($extrafield_param['options']);
  7062. if (count($extrafield_param_list) > 0) {
  7063. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  7064. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  7065. $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  7066. }
  7067. }
  7068. }
  7069. // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
  7070. $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
  7071. } else {
  7072. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  7073. $csstyle = '';
  7074. if (is_array($params) && count($params) > 0) {
  7075. if (array_key_exists('class', $params)) {
  7076. $class .= $params['class'].' ';
  7077. }
  7078. if (array_key_exists('style', $params)) {
  7079. $csstyle = $params['style'];
  7080. }
  7081. }
  7082. // add html5 elements
  7083. $domData = ' data-element="extrafield"';
  7084. $domData .= ' data-targetelement="'.$this->element.'"';
  7085. $domData .= ' data-targetid="'.$this->id.'"';
  7086. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  7087. if ($display_type=='card') {
  7088. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
  7089. $colspan = 0;
  7090. }
  7091. if ($action == 'selectlines') {
  7092. $colspan++;
  7093. }
  7094. }
  7095. // Convert date into timestamp format (value in memory must be a timestamp)
  7096. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
  7097. $datenotinstring = null;
  7098. if (array_key_exists('options_'.$key, $this->array_options)) {
  7099. $datenotinstring = $this->array_options['options_'.$key];
  7100. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7101. $datenotinstring = $this->db->jdate($datenotinstring);
  7102. }
  7103. }
  7104. $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;
  7105. }
  7106. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
  7107. $datenotinstring = null;
  7108. if (array_key_exists('options_'.$key, $this->array_options)) {
  7109. $datenotinstring = $this->array_options['options_'.$key];
  7110. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7111. $datenotinstring = $this->db->jdate($datenotinstring);
  7112. }
  7113. }
  7114. $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;
  7115. }
  7116. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  7117. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
  7118. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? price2num($value) : $this->array_options['options_'.$key];
  7119. }
  7120. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  7121. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int'))) {
  7122. if ($action == 'create') {
  7123. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  7124. }
  7125. }
  7126. $labeltoshow = $langs->trans($label);
  7127. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  7128. if ($display_type == 'card') {
  7129. $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="field_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >';
  7130. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action == 'view' || $action == 'valid' || $action == 'editline')) {
  7131. $out .= '<td></td>';
  7132. }
  7133. $out .= '<td class="titlefieldcreate wordbreak';
  7134. } elseif ($display_type == 'line') {
  7135. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="fieldline_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >';
  7136. $out .= '<div style="display: inline-block; padding-right:4px" class="titlefieldcreate wordbreak';
  7137. }
  7138. //$out .= "titlefield";
  7139. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  7140. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  7141. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  7142. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  7143. $out .= '">';
  7144. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7145. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7146. } else {
  7147. $out .= $labeltoshow;
  7148. }
  7149. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7150. $out .= '&nbsp;<span style="color: red">*</span>';
  7151. }
  7152. } else {
  7153. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7154. $out .= ' fieldrequired';
  7155. }
  7156. $out .= '">';
  7157. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7158. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7159. } else {
  7160. $out .= $labeltoshow;
  7161. }
  7162. }
  7163. $out .= ($display_type == 'card' ? '</td>' : '</div>');
  7164. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  7165. if ($display_type == 'card') {
  7166. // a first td column was already output (and may be another on before if MAIN_VIEW_LINE_NUMBER set), so this td is the next one
  7167. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="valuefieldcreate '.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  7168. } elseif ($display_type == 'line') {
  7169. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').' style="display: inline-block" class="valuefieldcreate '.$this->element.'_extras_'.$key.'">';
  7170. }
  7171. switch ($mode) {
  7172. case "view":
  7173. $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
  7174. break;
  7175. case "create":
  7176. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7177. break;
  7178. case "edit":
  7179. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7180. break;
  7181. }
  7182. $out .= ($display_type=='card' ? '</td>' : '</div>');
  7183. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
  7184. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7185. } else {
  7186. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7187. }
  7188. $e++;
  7189. }
  7190. }
  7191. $out .= "\n";
  7192. // Add code to manage list depending on others
  7193. if (!empty($conf->use_javascript_ajax)) {
  7194. $out .= $this->getJSListDependancies();
  7195. }
  7196. $out .= '<!-- commonobject:showOptionals end --> '."\n";
  7197. }
  7198. }
  7199. $out .= $hookmanager->resPrint;
  7200. return $out;
  7201. }
  7202. /**
  7203. * @param string $type Type for prefix
  7204. * @return string Javacript code to manage dependency
  7205. */
  7206. public function getJSListDependancies($type = '_extra')
  7207. {
  7208. $out = '
  7209. <script>
  7210. jQuery(document).ready(function() {
  7211. function showOptions'.$type.'(child_list, parent_list, orig_select)
  7212. {
  7213. var val = $("select[name=\""+parent_list+"\"]").val();
  7214. var parentVal = parent_list + ":" + val;
  7215. if(typeof val == "string"){
  7216. if(val != "") {
  7217. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7218. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7219. $("select[name=\""+child_list+"\"]").append(options);
  7220. } else {
  7221. var options = orig_select.find("option[parent]").clone();
  7222. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7223. $("select[name=\""+child_list+"\"]").append(options);
  7224. }
  7225. } else if(val > 0) {
  7226. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7227. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7228. $("select[name=\""+child_list+"\"]").append(options);
  7229. } else {
  7230. var options = orig_select.find("option[parent]").clone();
  7231. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7232. $("select[name=\""+child_list+"\"]").append(options);
  7233. }
  7234. }
  7235. function setListDependencies'.$type.'() {
  7236. jQuery("select option[parent]").parent().each(function() {
  7237. var orig_select = {};
  7238. var child_list = $(this).attr("name");
  7239. orig_select[child_list] = $(this).clone();
  7240. var parent = $(this).find("option[parent]:first").attr("parent");
  7241. var infos = parent.split(":");
  7242. var parent_list = infos[0];
  7243. //Hide daughters lists
  7244. if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
  7245. $("#"+child_list).hide();
  7246. //Show mother lists
  7247. } else if ($("#"+parent_list).val() != 0){
  7248. $("#"+parent_list).show();
  7249. }
  7250. //Show the child list if the parent list value is selected
  7251. $("select[name=\""+parent_list+"\"]").click(function() {
  7252. if ($(this).val() != 0){
  7253. $("#"+child_list).show()
  7254. }
  7255. });
  7256. //When we change parent list
  7257. $("select[name=\""+parent_list+"\"]").change(function() {
  7258. showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
  7259. //Select the value 0 on child list after a change on the parent list
  7260. $("#"+child_list).val(0).trigger("change");
  7261. //Hide child lists if the parent value is set to 0
  7262. if ($(this).val() == 0){
  7263. $("#"+child_list).hide();
  7264. }
  7265. });
  7266. });
  7267. }
  7268. setListDependencies'.$type.'();
  7269. });
  7270. </script>'."\n";
  7271. return $out;
  7272. }
  7273. /**
  7274. * Returns the rights used for this class
  7275. * @return stdClass
  7276. */
  7277. public function getRights()
  7278. {
  7279. global $user;
  7280. $element = $this->element;
  7281. if ($element == 'facturerec') {
  7282. $element = 'facture';
  7283. } elseif ($element == 'invoice_supplier_rec') {
  7284. return $user->rights->fournisseur->facture;
  7285. }
  7286. return $user->rights->{$element};
  7287. }
  7288. /**
  7289. * Function used to replace a thirdparty id with another one.
  7290. * This function is meant to be called from replaceThirdparty with the appropriate tables
  7291. * Column name fk_soc MUST be used to identify thirdparties
  7292. *
  7293. * @param DoliDB $db Database handler
  7294. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  7295. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  7296. * @param string[] $tables Tables that need to be changed
  7297. * @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)
  7298. * @return bool True if success, False if error
  7299. */
  7300. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7301. {
  7302. foreach ($tables as $table) {
  7303. $sql = 'UPDATE '.$db->prefix().$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
  7304. if (!$db->query($sql)) {
  7305. if ($ignoreerrors) {
  7306. return true; // TODO Not enough. If there is A-B on kept thirdparty and B-C on old one, we must get A-B-C after merge. Not A-B.
  7307. }
  7308. //$this->errors = $db->lasterror();
  7309. return false;
  7310. }
  7311. }
  7312. return true;
  7313. }
  7314. /**
  7315. * Function used to replace a product id with another one.
  7316. * This function is meant to be called from replaceProduct with the appropriate tables
  7317. * Column name fk_product MUST be used to identify products
  7318. *
  7319. * @param DoliDB $db Database handler
  7320. * @param int $origin_id Old product id (the product to delete)
  7321. * @param int $dest_id New product id (the product that will received element of the other)
  7322. * @param string[] $tables Tables that need to be changed
  7323. * @param int $ignoreerrors Ignore errors. Return true even if errors. We need this when replacement can fails like for categories (categorie of old product may already exists on new one)
  7324. * @return bool True if success, False if error
  7325. */
  7326. public static function commonReplaceProduct(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7327. {
  7328. foreach ($tables as $table) {
  7329. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_product = '.((int) $dest_id).' WHERE fk_product = '.((int) $origin_id);
  7330. if (!$db->query($sql)) {
  7331. if ($ignoreerrors) {
  7332. return true; // TODO Not enough. If there is A-B on kept product and B-C on old one, we must get A-B-C after merge. Not A-B.
  7333. }
  7334. //$this->errors = $db->lasterror();
  7335. return false;
  7336. }
  7337. }
  7338. return true;
  7339. }
  7340. /**
  7341. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  7342. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  7343. * else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  7344. * else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  7345. * else set min buy price as buy price
  7346. *
  7347. * @param float $unitPrice Product unit price
  7348. * @param float $discountPercent Line discount percent
  7349. * @param int $fk_product Product id
  7350. * @return float <0 if KO, buyprice if OK
  7351. */
  7352. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  7353. {
  7354. global $conf;
  7355. $buyPrice = 0;
  7356. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
  7357. // When ForceBuyingPriceIfNull is set
  7358. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  7359. } else {
  7360. // Get cost price for margin calculation
  7361. if (!empty($fk_product) && $fk_product > 0) {
  7362. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
  7363. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7364. $product = new Product($this->db);
  7365. $result = $product->fetch($fk_product);
  7366. if ($result <= 0) {
  7367. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7368. return -1;
  7369. }
  7370. if ($product->cost_price > 0) {
  7371. $buyPrice = $product->cost_price;
  7372. } elseif ($product->pmp > 0) {
  7373. $buyPrice = $product->pmp;
  7374. }
  7375. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
  7376. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7377. $product = new Product($this->db);
  7378. $result = $product->fetch($fk_product);
  7379. if ($result <= 0) {
  7380. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7381. return -1;
  7382. }
  7383. if ($product->pmp > 0) {
  7384. $buyPrice = $product->pmp;
  7385. }
  7386. }
  7387. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
  7388. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  7389. $productFournisseur = new ProductFournisseur($this->db);
  7390. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
  7391. $buyPrice = $productFournisseur->fourn_unitprice;
  7392. } elseif ($result < 0) {
  7393. $this->errors[] = $productFournisseur->error;
  7394. return -2;
  7395. }
  7396. }
  7397. }
  7398. }
  7399. return $buyPrice;
  7400. }
  7401. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7402. /**
  7403. * Show photos of an object (nbmax maximum), into several columns
  7404. *
  7405. * @param string $modulepart 'product', 'ticket', ...
  7406. * @param string $sdir Directory to scan (full absolute path)
  7407. * @param int $size 0=original size, 1='small' use thumbnail if possible
  7408. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  7409. * @param int $nbbyrow Number of image per line or -1 to use div separator or 0 to use no separator. Used only if size=1 or 'small'.
  7410. * @param int $showfilename 1=Show filename
  7411. * @param int $showaction 1=Show icon with action links (resize, delete)
  7412. * @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.
  7413. * @param int $maxWidth Max width of original image when size='small'
  7414. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  7415. * @param int $notitle Do not add title tag on image
  7416. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  7417. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  7418. */
  7419. 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)
  7420. {
  7421. // phpcs:enable
  7422. global $conf, $user, $langs;
  7423. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7424. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  7425. $sortfield = 'position_name';
  7426. $sortorder = 'asc';
  7427. $dir = $sdir.'/';
  7428. $pdir = '/';
  7429. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7430. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7431. // For backward compatibility
  7432. if ($modulepart == 'product') {
  7433. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  7434. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7435. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7436. }
  7437. }
  7438. // Defined relative dir to DOL_DATA_ROOT
  7439. $relativedir = '';
  7440. if ($dir) {
  7441. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  7442. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  7443. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  7444. }
  7445. $dirthumb = $dir.'thumbs/';
  7446. $pdirthumb = $pdir.'thumbs/';
  7447. $return = '<!-- Photo -->'."\n";
  7448. $nbphoto = 0;
  7449. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  7450. /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
  7451. {
  7452. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  7453. $filearray=array_merge($filearray, $filearrayold);
  7454. }*/
  7455. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  7456. if (count($filearray)) {
  7457. if ($sortfield && $sortorder) {
  7458. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  7459. }
  7460. foreach ($filearray as $key => $val) {
  7461. $photo = '';
  7462. $file = $val['name'];
  7463. //if (! utf8_check($file)) $file=utf8_encode($file); // To be sure file is stored in UTF8 in memory
  7464. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  7465. if (image_format_supported($file) >= 0) {
  7466. $nbphoto++;
  7467. $photo = $file;
  7468. $viewfilename = $file;
  7469. if ($size == 1 || $size == 'small') { // Format vignette
  7470. // Find name of thumb file
  7471. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  7472. if (!dol_is_file($dirthumb.$photo_vignette)) {
  7473. $photo_vignette = '';
  7474. }
  7475. // Get filesize of original file
  7476. $imgarray = dol_getImageSize($dir.$photo);
  7477. if ($nbbyrow > 0) {
  7478. if ($nbphoto == 1) {
  7479. $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  7480. }
  7481. if ($nbphoto % $nbbyrow == 1) {
  7482. $return .= '<tr class="center valignmiddle" style="border: 1px">';
  7483. }
  7484. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
  7485. } elseif ($nbbyrow < 0) {
  7486. $return .= '<div class="inline-block">';
  7487. }
  7488. $return .= "\n";
  7489. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  7490. if (empty($nolink)) {
  7491. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  7492. if ($urladvanced) {
  7493. $return .= '<a href="'.$urladvanced.'">';
  7494. } else {
  7495. $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
  7496. }
  7497. }
  7498. // Show image (width height=$maxHeight)
  7499. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  7500. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  7501. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  7502. if ($notitle) {
  7503. $alt = '';
  7504. }
  7505. $addphotorefcss = 1;
  7506. if ($usesharelink) {
  7507. if ($val['share']) {
  7508. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7509. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  7510. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7511. } else {
  7512. $return .= '<!-- Show original file -->';
  7513. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7514. }
  7515. } else {
  7516. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  7517. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  7518. }
  7519. } else {
  7520. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7521. $return .= '<!-- Show thumb -->';
  7522. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').' maxwidth150onsmartphone maxwidth200" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdirthumb.$photo_vignette).'" title="'.dol_escape_htmltag($alt).'">';
  7523. } else {
  7524. $return .= '<!-- Show original file -->';
  7525. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" title="'.dol_escape_htmltag($alt).'">';
  7526. }
  7527. }
  7528. if (empty($nolink)) {
  7529. $return .= '</a>';
  7530. }
  7531. $return .= "\n";
  7532. if ($showfilename) {
  7533. $return .= '<br>'.$viewfilename;
  7534. }
  7535. if ($showaction) {
  7536. $return .= '<br>';
  7537. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  7538. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
  7539. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=addthumb&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'), 'refresh').'&nbsp;&nbsp;</a>';
  7540. }
  7541. // Special cas for product
  7542. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7543. // Link to resize
  7544. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  7545. // Link to delete
  7546. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7547. $return .= img_delete().'</a>';
  7548. }
  7549. }
  7550. $return .= "\n";
  7551. if ($nbbyrow > 0) {
  7552. $return .= '</td>';
  7553. if (($nbphoto % $nbbyrow) == 0) {
  7554. $return .= '</tr>';
  7555. }
  7556. } elseif ($nbbyrow < 0) {
  7557. $return .= '</div>';
  7558. }
  7559. }
  7560. if (empty($size)) { // Format origine
  7561. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  7562. if ($showfilename) {
  7563. $return .= '<br>'.$viewfilename;
  7564. }
  7565. if ($showaction) {
  7566. // Special case for product
  7567. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7568. // Link to resize
  7569. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  7570. // Link to delete
  7571. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7572. $return .= img_delete().'</a>';
  7573. }
  7574. }
  7575. }
  7576. // On continue ou on arrete de boucler ?
  7577. if ($nbmax && $nbphoto >= $nbmax) {
  7578. break;
  7579. }
  7580. }
  7581. }
  7582. if ($size == 1 || $size == 'small') {
  7583. if ($nbbyrow > 0) {
  7584. // Ferme tableau
  7585. while ($nbphoto % $nbbyrow) {
  7586. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  7587. $nbphoto++;
  7588. }
  7589. if ($nbphoto) {
  7590. $return .= '</table>';
  7591. }
  7592. }
  7593. }
  7594. }
  7595. $this->nbphoto = $nbphoto;
  7596. return $return;
  7597. }
  7598. /**
  7599. * Function test if type is array
  7600. *
  7601. * @param array $info content informations of field
  7602. * @return bool true if array
  7603. */
  7604. protected function isArray($info)
  7605. {
  7606. if (is_array($info)) {
  7607. if (isset($info['type']) && $info['type'] == 'array') {
  7608. return true;
  7609. } else {
  7610. return false;
  7611. }
  7612. }
  7613. return false;
  7614. }
  7615. /**
  7616. * Function test if type is date
  7617. *
  7618. * @param array $info content informations of field
  7619. * @return bool true if date
  7620. */
  7621. public function isDate($info)
  7622. {
  7623. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
  7624. return true;
  7625. }
  7626. return false;
  7627. }
  7628. /**
  7629. * Function test if type is duration
  7630. *
  7631. * @param array $info content informations of field
  7632. * @return bool true if field of type duration
  7633. */
  7634. public function isDuration($info)
  7635. {
  7636. if (is_array($info)) {
  7637. if (isset($info['type']) && ($info['type'] == 'duration')) {
  7638. return true;
  7639. } else {
  7640. return false;
  7641. }
  7642. } else {
  7643. return false;
  7644. }
  7645. }
  7646. /**
  7647. * Function test if type is integer
  7648. *
  7649. * @param array $info content informations of field
  7650. * @return bool true if integer
  7651. */
  7652. public function isInt($info)
  7653. {
  7654. if (is_array($info)) {
  7655. if (isset($info['type']) && ($info['type'] == 'int' || preg_match('/^integer/i', $info['type']))) {
  7656. return true;
  7657. } else {
  7658. return false;
  7659. }
  7660. } else {
  7661. return false;
  7662. }
  7663. }
  7664. /**
  7665. * Function test if type is float
  7666. *
  7667. * @param array $info content informations of field
  7668. * @return bool true if float
  7669. */
  7670. public function isFloat($info)
  7671. {
  7672. if (is_array($info)) {
  7673. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
  7674. return true;
  7675. } else {
  7676. return false;
  7677. }
  7678. }
  7679. return false;
  7680. }
  7681. /**
  7682. * Function test if type is text
  7683. *
  7684. * @param array $info content informations of field
  7685. * @return bool true if type text
  7686. */
  7687. public function isText($info)
  7688. {
  7689. if (is_array($info)) {
  7690. if (isset($info['type']) && $info['type'] == 'text') {
  7691. return true;
  7692. } else {
  7693. return false;
  7694. }
  7695. }
  7696. return false;
  7697. }
  7698. /**
  7699. * Function test if field can be null
  7700. *
  7701. * @param array $info content informations of field
  7702. * @return bool true if it can be null
  7703. */
  7704. protected function canBeNull($info)
  7705. {
  7706. if (is_array($info)) {
  7707. if (isset($info['notnull']) && $info['notnull'] != '1') {
  7708. return true;
  7709. } else {
  7710. return false;
  7711. }
  7712. }
  7713. return true;
  7714. }
  7715. /**
  7716. * Function test if field is forced to null if zero or empty
  7717. *
  7718. * @param array $info content informations of field
  7719. * @return bool true if forced to null
  7720. */
  7721. protected function isForcedToNullIfZero($info)
  7722. {
  7723. if (is_array($info)) {
  7724. if (isset($info['notnull']) && $info['notnull'] == '-1') {
  7725. return true;
  7726. } else {
  7727. return false;
  7728. }
  7729. }
  7730. return false;
  7731. }
  7732. /**
  7733. * Function test if is indexed
  7734. *
  7735. * @param array $info content informations of field
  7736. * @return bool
  7737. */
  7738. protected function isIndex($info)
  7739. {
  7740. if (is_array($info)) {
  7741. if (isset($info['index']) && $info['index'] == true) {
  7742. return true;
  7743. } else {
  7744. return false;
  7745. }
  7746. }
  7747. return false;
  7748. }
  7749. /**
  7750. * Function to prepare a part of the query for insert.
  7751. * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
  7752. * $this->${field} should be a clean value. The page can run
  7753. *
  7754. * @return array
  7755. */
  7756. protected function setSaveQuery()
  7757. {
  7758. global $conf;
  7759. $queryarray = array();
  7760. foreach ($this->fields as $field => $info) { // Loop on definition of fields
  7761. // Depending on field type ('datetime', ...)
  7762. if ($this->isDate($info)) {
  7763. if (empty($this->{$field})) {
  7764. $queryarray[$field] = null;
  7765. } else {
  7766. $queryarray[$field] = $this->db->idate($this->{$field});
  7767. }
  7768. } elseif ($this->isDuration($info)) {
  7769. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7770. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7771. if (!isset($this->{$field})) {
  7772. $queryarray[$field] = 0;
  7773. } else {
  7774. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7775. }
  7776. } else {
  7777. $queryarray[$field] = null;
  7778. }
  7779. } elseif ($this->isInt($info) || $this->isFloat($info)) {
  7780. if ($field == 'entity' && is_null($this->{$field})) {
  7781. $queryarray[$field] = $conf->entity;
  7782. } else {
  7783. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7784. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7785. if (!isset($this->{$field})) {
  7786. $queryarray[$field] = 0;
  7787. } elseif ($this->isInt($info)) {
  7788. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7789. } elseif ($this->isFloat($info)) {
  7790. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7791. }
  7792. } else {
  7793. $queryarray[$field] = null;
  7794. }
  7795. }
  7796. } else {
  7797. // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
  7798. // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
  7799. $queryarray[$field] = $this->{$field};
  7800. }
  7801. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
  7802. unset($queryarray[$field]);
  7803. }
  7804. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
  7805. $queryarray[$field] = null; // May force 0 to null
  7806. }
  7807. }
  7808. return $queryarray;
  7809. }
  7810. /**
  7811. * Function to load data from a SQL pointer into properties of current object $this
  7812. *
  7813. * @param stdClass $obj Contain data of object from database
  7814. * @return void
  7815. */
  7816. public function setVarsFromFetchObj(&$obj)
  7817. {
  7818. global $db;
  7819. foreach ($this->fields as $field => $info) {
  7820. if ($this->isDate($info)) {
  7821. if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
  7822. $this->{$field} = '';
  7823. } else {
  7824. $this->{$field} = $db->jdate($obj->{$field});
  7825. }
  7826. } elseif ($this->isInt($info)) {
  7827. if ($field == 'rowid') {
  7828. $this->id = (int) $obj->{$field};
  7829. } else {
  7830. if ($this->isForcedToNullIfZero($info)) {
  7831. if (empty($obj->{$field})) {
  7832. $this->{$field} = null;
  7833. } else {
  7834. $this->{$field} = (double) $obj->{$field};
  7835. }
  7836. } else {
  7837. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7838. $this->{$field} = (int) $obj->{$field};
  7839. } else {
  7840. $this->{$field} = null;
  7841. }
  7842. }
  7843. }
  7844. } elseif ($this->isFloat($info)) {
  7845. if ($this->isForcedToNullIfZero($info)) {
  7846. if (empty($obj->{$field})) {
  7847. $this->{$field} = null;
  7848. } else {
  7849. $this->{$field} = (double) $obj->{$field};
  7850. }
  7851. } else {
  7852. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7853. $this->{$field} = (double) $obj->{$field};
  7854. } else {
  7855. $this->{$field} = null;
  7856. }
  7857. }
  7858. } else {
  7859. $this->{$field} = $obj->{$field};
  7860. }
  7861. }
  7862. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  7863. if (!isset($this->fields['ref']) && isset($this->id)) {
  7864. $this->ref = $this->id;
  7865. }
  7866. }
  7867. /**
  7868. * Function to concat keys of fields
  7869. *
  7870. * @param string $alias String of alias of table for fields. For example 't'.
  7871. * @return string list of alias fields
  7872. */
  7873. public function getFieldList($alias = '')
  7874. {
  7875. $keys = array_keys($this->fields);
  7876. if (!empty($alias)) {
  7877. $keys_with_alias = array();
  7878. foreach ($keys as $fieldname) {
  7879. $keys_with_alias[] = $alias . '.' . $fieldname;
  7880. }
  7881. return implode(',', $keys_with_alias);
  7882. } else {
  7883. return implode(',', $keys);
  7884. }
  7885. }
  7886. /**
  7887. * Add quote to field value if necessary
  7888. *
  7889. * @param string|int $value Value to protect
  7890. * @param array $fieldsentry Properties of field
  7891. * @return string
  7892. */
  7893. protected function quote($value, $fieldsentry)
  7894. {
  7895. if (is_null($value)) {
  7896. return 'NULL';
  7897. } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
  7898. return price2num("$value");
  7899. } elseif ($fieldsentry['type'] == 'boolean') {
  7900. if ($value) {
  7901. return 'true';
  7902. } else {
  7903. return 'false';
  7904. }
  7905. } else {
  7906. return "'".$this->db->escape($value)."'";
  7907. }
  7908. }
  7909. /**
  7910. * Create object into database
  7911. *
  7912. * @param User $user User that creates
  7913. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7914. * @return int <0 if KO, Id of created object if OK
  7915. */
  7916. public function createCommon(User $user, $notrigger = false)
  7917. {
  7918. global $langs;
  7919. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  7920. $error = 0;
  7921. $now = dol_now();
  7922. $fieldvalues = $this->setSaveQuery();
  7923. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
  7924. $fieldvalues['date_creation'] = $this->db->idate($now);
  7925. }
  7926. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
  7927. $fieldvalues['fk_user_creat'] = $user->id;
  7928. }
  7929. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  7930. if (array_key_exists('ref', $fieldvalues)) {
  7931. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  7932. }
  7933. $keys = array();
  7934. $values = array(); // Array to store string forged for SQL syntax
  7935. foreach ($fieldvalues as $k => $v) {
  7936. $keys[$k] = $k;
  7937. $value = $this->fields[$k];
  7938. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  7939. }
  7940. // Clean and check mandatory
  7941. foreach ($keys as $key) {
  7942. // If field is an implicit foreign key field
  7943. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  7944. $values[$key] = '';
  7945. }
  7946. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  7947. $values[$key] = '';
  7948. }
  7949. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
  7950. $error++;
  7951. $langs->load("errors");
  7952. dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
  7953. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  7954. }
  7955. // If value is null and there is a default value for field
  7956. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
  7957. $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
  7958. }
  7959. // If field is an implicit foreign key field
  7960. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  7961. if (isset($this->fields[$key]['default'])) {
  7962. $values[$key] = ((int) $this->fields[$key]['default']);
  7963. } else {
  7964. $values[$key] = 'null';
  7965. }
  7966. }
  7967. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
  7968. $values[$key] = 'null';
  7969. }
  7970. }
  7971. if ($error) {
  7972. return -1;
  7973. }
  7974. $this->db->begin();
  7975. if (!$error) {
  7976. $sql = "INSERT INTO ".$this->db->prefix().$this->table_element;
  7977. $sql .= " (".implode(", ", $keys).')';
  7978. $sql .= " VALUES (".implode(", ", $values).")"; // $values can contains 'abc' or 123
  7979. $res = $this->db->query($sql);
  7980. if (!$res) {
  7981. $error++;
  7982. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  7983. $this->errors[] = "ErrorRefAlreadyExists";
  7984. } else {
  7985. $this->errors[] = $this->db->lasterror();
  7986. }
  7987. }
  7988. }
  7989. if (!$error) {
  7990. $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
  7991. }
  7992. // If we have a field ref with a default value of (PROV)
  7993. if (!$error) {
  7994. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
  7995. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
  7996. $resqlupdate = $this->db->query($sql);
  7997. if ($resqlupdate === false) {
  7998. $error++;
  7999. $this->errors[] = $this->db->lasterror();
  8000. } else {
  8001. $this->ref = '(PROV'.$this->id.')';
  8002. }
  8003. }
  8004. }
  8005. // Create extrafields
  8006. if (!$error) {
  8007. $result = $this->insertExtraFields();
  8008. if ($result < 0) {
  8009. $error++;
  8010. }
  8011. }
  8012. // Create lines
  8013. if (!empty($this->table_element_line) && !empty($this->fk_element)) {
  8014. $num = (is_array($this->lines) ? count($this->lines) : 0);
  8015. for ($i = 0; $i < $num; $i++) {
  8016. $line = $this->lines[$i];
  8017. $keyforparent = $this->fk_element;
  8018. $line->$keyforparent = $this->id;
  8019. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  8020. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  8021. if (!is_object($line)) {
  8022. $line = (object) $line;
  8023. }
  8024. $result = $line->create($user, 1);
  8025. if ($result < 0) {
  8026. $this->error = $line->error;
  8027. $this->db->rollback();
  8028. return -1;
  8029. }
  8030. }
  8031. }
  8032. // Triggers
  8033. if (!$error && !$notrigger) {
  8034. // Call triggers
  8035. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  8036. if ($result < 0) {
  8037. $error++;
  8038. }
  8039. // End call triggers
  8040. }
  8041. // Commit or rollback
  8042. if ($error) {
  8043. $this->db->rollback();
  8044. return -1;
  8045. } else {
  8046. $this->db->commit();
  8047. return $this->id;
  8048. }
  8049. }
  8050. /**
  8051. * Load object in memory from the database
  8052. *
  8053. * @param int $id Id object
  8054. * @param string $ref Ref
  8055. * @param string $morewhere More SQL filters (' AND ...')
  8056. * @return int <0 if KO, 0 if not found, >0 if OK
  8057. */
  8058. public function fetchCommon($id, $ref = null, $morewhere = '')
  8059. {
  8060. if (empty($id) && empty($ref) && empty($morewhere)) {
  8061. return -1;
  8062. }
  8063. $fieldlist = $this->getFieldList('t');
  8064. if (empty($fieldlist)) {
  8065. return 0;
  8066. }
  8067. $sql = "SELECT ".$fieldlist;
  8068. $sql .= " FROM ".$this->db->prefix().$this->table_element.' as t';
  8069. if (!empty($id)) {
  8070. $sql .= ' WHERE t.rowid = '.((int) $id);
  8071. } elseif (!empty($ref)) {
  8072. $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
  8073. } else {
  8074. $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  8075. }
  8076. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  8077. $sql .= ' AND t.entity IN ('.getEntity($this->table_element).')';
  8078. }
  8079. if ($morewhere) {
  8080. $sql .= $morewhere;
  8081. }
  8082. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  8083. $res = $this->db->query($sql);
  8084. if ($res) {
  8085. $obj = $this->db->fetch_object($res);
  8086. if ($obj) {
  8087. $this->setVarsFromFetchObj($obj);
  8088. // Retrieve all extrafield
  8089. // fetch optionals attributes and labels
  8090. $this->fetch_optionals();
  8091. return $this->id;
  8092. } else {
  8093. return 0;
  8094. }
  8095. } else {
  8096. $this->error = $this->db->lasterror();
  8097. $this->errors[] = $this->error;
  8098. return -1;
  8099. }
  8100. }
  8101. /**
  8102. * Load object in memory from the database
  8103. *
  8104. * @param string $morewhere More SQL filters (' AND ...')
  8105. * @return int <0 if KO, 0 if not found, >0 if OK
  8106. */
  8107. public function fetchLinesCommon($morewhere = '')
  8108. {
  8109. $objectlineclassname = get_class($this).'Line';
  8110. if (!class_exists($objectlineclassname)) {
  8111. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  8112. return -1;
  8113. }
  8114. $objectline = new $objectlineclassname($this->db);
  8115. $sql = "SELECT ".$objectline->getFieldList('l');
  8116. $sql .= " FROM ".$this->db->prefix().$objectline->table_element." as l";
  8117. $sql .= " WHERE l.fk_".$this->db->escape($this->element)." = ".((int) $this->id);
  8118. if ($morewhere) {
  8119. $sql .= $morewhere;
  8120. }
  8121. if (isset($objectline->fields['position'])) {
  8122. $sql .= $this->db->order('position', 'ASC');
  8123. }
  8124. $resql = $this->db->query($sql);
  8125. if ($resql) {
  8126. $num_rows = $this->db->num_rows($resql);
  8127. $i = 0;
  8128. while ($i < $num_rows) {
  8129. $obj = $this->db->fetch_object($resql);
  8130. if ($obj) {
  8131. $newline = new $objectlineclassname($this->db);
  8132. $newline->setVarsFromFetchObj($obj);
  8133. $this->lines[] = $newline;
  8134. }
  8135. $i++;
  8136. }
  8137. return 1;
  8138. } else {
  8139. $this->error = $this->db->lasterror();
  8140. $this->errors[] = $this->error;
  8141. return -1;
  8142. }
  8143. }
  8144. /**
  8145. * Update object into database
  8146. *
  8147. * @param User $user User that modifies
  8148. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8149. * @return int <0 if KO, >0 if OK
  8150. */
  8151. public function updateCommon(User $user, $notrigger = false)
  8152. {
  8153. global $conf, $langs;
  8154. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  8155. $error = 0;
  8156. $now = dol_now();
  8157. $fieldvalues = $this->setSaveQuery();
  8158. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
  8159. $fieldvalues['date_modification'] = $this->db->idate($now);
  8160. }
  8161. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
  8162. $fieldvalues['fk_user_modif'] = $user->id;
  8163. }
  8164. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  8165. if (array_key_exists('ref', $fieldvalues)) {
  8166. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8167. }
  8168. // Add quotes and escape on fields with type string
  8169. $keys = array();
  8170. $values = array();
  8171. $tmp = array();
  8172. foreach ($fieldvalues as $k => $v) {
  8173. $keys[$k] = $k;
  8174. $value = $this->fields[$k];
  8175. $values[$k] = $this->quote($v, $value);
  8176. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  8177. }
  8178. // Clean and check mandatory fields
  8179. foreach ($keys as $key) {
  8180. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8181. $values[$key] = ''; // This is an implicit foreign key field
  8182. }
  8183. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8184. $values[$key] = ''; // This is an explicit foreign key field
  8185. }
  8186. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  8187. /*
  8188. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  8189. {
  8190. $error++;
  8191. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8192. }*/
  8193. }
  8194. $sql = 'UPDATE '.$this->db->prefix().$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
  8195. $this->db->begin();
  8196. if (!$error) {
  8197. $res = $this->db->query($sql);
  8198. if (!$res) {
  8199. $error++;
  8200. $this->errors[] = $this->db->lasterror();
  8201. }
  8202. }
  8203. // Update extrafield
  8204. if (!$error) {
  8205. $result = $this->insertExtraFields();
  8206. if ($result < 0) {
  8207. $error++;
  8208. }
  8209. }
  8210. // Triggers
  8211. if (!$error && !$notrigger) {
  8212. // Call triggers
  8213. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  8214. if ($result < 0) {
  8215. $error++;
  8216. } //Do also here what you must do to rollback action if trigger fail
  8217. // End call triggers
  8218. }
  8219. // Commit or rollback
  8220. if ($error) {
  8221. $this->db->rollback();
  8222. return -1;
  8223. } else {
  8224. $this->db->commit();
  8225. return $this->id;
  8226. }
  8227. }
  8228. /**
  8229. * Delete object in database
  8230. *
  8231. * @param User $user User that deletes
  8232. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8233. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  8234. * @return int <=0 if KO, 0=Nothing done because object has child, >0 if OK
  8235. */
  8236. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  8237. {
  8238. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  8239. $error = 0;
  8240. $this->db->begin();
  8241. if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
  8242. foreach ($this->childtables as $table) {
  8243. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8244. $resql = $this->db->query($sql);
  8245. if (!$resql) {
  8246. $this->error = $this->db->lasterror();
  8247. $this->errors[] = $this->error;
  8248. $this->db->rollback();
  8249. return -1;
  8250. }
  8251. }
  8252. } elseif (!empty($this->fk_element) && !empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
  8253. $objectisused = $this->isObjectUsed($this->id);
  8254. if (!empty($objectisused)) {
  8255. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  8256. $this->error = 'ErrorRecordHasChildren';
  8257. $this->errors[] = $this->error;
  8258. $this->db->rollback();
  8259. return 0;
  8260. }
  8261. }
  8262. // Delete cascade first
  8263. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  8264. foreach ($this->childtablesoncascade as $table) {
  8265. $deleteFromObject = explode(':', $table);
  8266. if (count($deleteFromObject) >= 2) {
  8267. $className = str_replace('@', '', $deleteFromObject[0]);
  8268. $filePath = $deleteFromObject[1];
  8269. $columnName = $deleteFromObject[2];
  8270. $TMoreSQL = array();
  8271. $more_sql = $deleteFromObject[3];
  8272. if (!empty($more_sql)) {
  8273. $TMoreSQL['customsql'] = $more_sql;
  8274. }
  8275. if (dol_include_once($filePath)) {
  8276. $childObject = new $className($this->db);
  8277. if (method_exists($childObject, 'deleteByParentField')) {
  8278. $result = $childObject->deleteByParentField($this->id, $columnName, $TMoreSQL);
  8279. if ($result < 0) {
  8280. $error++;
  8281. $this->errors[] = $childObject->error;
  8282. break;
  8283. }
  8284. } else {
  8285. $error++;
  8286. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  8287. break;
  8288. }
  8289. } else {
  8290. $error++;
  8291. $this->errors[] = 'Cannot include child class file '.$filePath;
  8292. break;
  8293. }
  8294. } else {
  8295. // Delete record in child table
  8296. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8297. $resql = $this->db->query($sql);
  8298. if (!$resql) {
  8299. $error++;
  8300. $this->error = $this->db->lasterror();
  8301. $this->errors[] = $this->error;
  8302. break;
  8303. }
  8304. }
  8305. }
  8306. }
  8307. if (!$error) {
  8308. if (!$notrigger) {
  8309. // Call triggers
  8310. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  8311. if ($result < 0) {
  8312. $error++;
  8313. } // Do also here what you must do to rollback action if trigger fail
  8314. // End call triggers
  8315. }
  8316. }
  8317. // Delete llx_ecm_files
  8318. if (!$error) {
  8319. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  8320. if (!$res) {
  8321. $error++;
  8322. }
  8323. }
  8324. if (!$error && !empty($this->isextrafieldmanaged)) {
  8325. $result = $this->deleteExtraFields();
  8326. if ($result < 0) {
  8327. $error++;
  8328. }
  8329. }
  8330. if (!$error) {
  8331. $sql = 'DELETE FROM '.$this->db->prefix().$this->table_element.' WHERE rowid='.((int) $this->id);
  8332. $resql = $this->db->query($sql);
  8333. if (!$resql) {
  8334. $error++;
  8335. $this->errors[] = $this->db->lasterror();
  8336. }
  8337. }
  8338. // Commit or rollback
  8339. if ($error) {
  8340. $this->db->rollback();
  8341. return -1;
  8342. } else {
  8343. $this->db->commit();
  8344. return 1;
  8345. }
  8346. }
  8347. /**
  8348. * Delete all child object from a parent ID
  8349. *
  8350. * @param int $parentId Parent Id
  8351. * @param string $parentField Name of Foreign key parent column
  8352. * @param array $filter an array filter
  8353. * @param string $filtermode AND or OR
  8354. * @return int <0 if KO, >0 if OK
  8355. * @throws Exception
  8356. */
  8357. public function deleteByParentField($parentId = 0, $parentField = '', $filter = array(), $filtermode = "AND")
  8358. {
  8359. global $user;
  8360. $error = 0;
  8361. $deleted = 0;
  8362. if (!empty($parentId) && !empty($parentField)) {
  8363. $this->db->begin();
  8364. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
  8365. $sql .= " WHERE ".$parentField." = ".(int) $parentId;
  8366. // Manage filters
  8367. $sqlwhere = array();
  8368. if (count($filter) > 0) {
  8369. foreach ($filter as $key => $value) {
  8370. if ($key == 'customsql') {
  8371. $sqlwhere[] = $value;
  8372. } elseif (strpos($value, '%') === false) {
  8373. $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
  8374. } else {
  8375. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  8376. }
  8377. }
  8378. }
  8379. if (count($sqlwhere) > 0) {
  8380. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  8381. }
  8382. $resql = $this->db->query($sql);
  8383. if (!$resql) {
  8384. $this->errors[] = $this->db->lasterror();
  8385. $error++;
  8386. } else {
  8387. while ($obj = $this->db->fetch_object($resql)) {
  8388. $result = $this->fetch($obj->rowid);
  8389. if ($result < 0) {
  8390. $error++;
  8391. $this->errors[] = $this->error;
  8392. } else {
  8393. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  8394. $result = $this->delete();
  8395. } else {
  8396. $result = $this->delete($user);
  8397. }
  8398. if ($result < 0) {
  8399. $error++;
  8400. $this->errors[] = $this->error;
  8401. } else {
  8402. $deleted++;
  8403. }
  8404. }
  8405. }
  8406. }
  8407. if (empty($error)) {
  8408. $this->db->commit();
  8409. return $deleted;
  8410. } else {
  8411. $this->error = implode(', ', $this->errors);
  8412. $this->db->rollback();
  8413. return $error * -1;
  8414. }
  8415. }
  8416. return $deleted;
  8417. }
  8418. /**
  8419. * Delete a line of object in database
  8420. *
  8421. * @param User $user User that delete
  8422. * @param int $idline Id of line to delete
  8423. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8424. * @return int >0 if OK, <0 if KO
  8425. */
  8426. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  8427. {
  8428. global $conf;
  8429. $error = 0;
  8430. $tmpforobjectclass = get_class($this);
  8431. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  8432. // Call trigger
  8433. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  8434. if ($result < 0) {
  8435. return -1;
  8436. }
  8437. // End call triggers
  8438. $this->db->begin();
  8439. $sql = "DELETE FROM ".$this->db->prefix().$this->table_element_line;
  8440. $sql .= " WHERE rowid = ".((int) $idline);
  8441. dol_syslog(get_class($this)."::deleteLineCommon", LOG_DEBUG);
  8442. $resql = $this->db->query($sql);
  8443. if (!$resql) {
  8444. $this->error = "Error ".$this->db->lasterror();
  8445. $error++;
  8446. }
  8447. if (empty($error)) {
  8448. // Remove extrafields
  8449. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  8450. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  8451. $tmpobjectline->id = $idline;
  8452. $result = $tmpobjectline->deleteExtraFields();
  8453. if ($result < 0) {
  8454. $error++;
  8455. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  8456. }
  8457. }
  8458. }
  8459. if (empty($error)) {
  8460. $this->db->commit();
  8461. return 1;
  8462. } else {
  8463. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  8464. $this->db->rollback();
  8465. return -1;
  8466. }
  8467. }
  8468. /**
  8469. * Set to a status
  8470. *
  8471. * @param User $user Object user that modify
  8472. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  8473. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  8474. * @param string $triggercode Trigger code to use
  8475. * @return int <0 if KO, >0 if OK
  8476. */
  8477. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  8478. {
  8479. $error = 0;
  8480. $this->db->begin();
  8481. $statusfield = 'status';
  8482. if ($this->element == 'don' || $this->element == 'donation') {
  8483. $statusfield = 'fk_statut';
  8484. }
  8485. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  8486. $sql .= " SET ".$statusfield." = ".((int) $status);
  8487. $sql .= " WHERE rowid = ".((int) $this->id);
  8488. if ($this->db->query($sql)) {
  8489. if (!$error) {
  8490. $this->oldcopy = clone $this;
  8491. }
  8492. if (!$error && !$notrigger) {
  8493. // Call trigger
  8494. $result = $this->call_trigger($triggercode, $user);
  8495. if ($result < 0) {
  8496. $error++;
  8497. }
  8498. }
  8499. if (!$error) {
  8500. $this->status = $status;
  8501. $this->db->commit();
  8502. return 1;
  8503. } else {
  8504. $this->db->rollback();
  8505. return -1;
  8506. }
  8507. } else {
  8508. $this->error = $this->db->error();
  8509. $this->db->rollback();
  8510. return -1;
  8511. }
  8512. }
  8513. /**
  8514. * Initialise object with example values
  8515. * Id must be 0 if object instance is a specimen
  8516. *
  8517. * @return int
  8518. */
  8519. public function initAsSpecimenCommon()
  8520. {
  8521. global $user;
  8522. $this->id = 0;
  8523. $this->specimen = 1;
  8524. $fields = array(
  8525. 'label' => 'This is label',
  8526. 'ref' => 'ABCD1234',
  8527. 'description' => 'This is a description',
  8528. 'qty' => 123.12,
  8529. 'note_public' => 'Public note',
  8530. 'note_private' => 'Private note',
  8531. 'date_creation' => (dol_now() - 3600 * 48),
  8532. 'date_modification' => (dol_now() - 3600 * 24),
  8533. 'fk_user_creat' => $user->id,
  8534. 'fk_user_modif' => $user->id,
  8535. 'date' => dol_now(),
  8536. );
  8537. foreach ($fields as $key => $value) {
  8538. if (array_key_exists($key, $this->fields)) {
  8539. $this->{$key} = $value;
  8540. }
  8541. }
  8542. return 1;
  8543. }
  8544. /* Part for comments */
  8545. /**
  8546. * Load comments linked with current task
  8547. * @return boolean 1 if ok
  8548. */
  8549. public function fetchComments()
  8550. {
  8551. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  8552. $comment = new Comment($this->db);
  8553. $result = $comment->fetchAllFor($this->element, $this->id);
  8554. if ($result < 0) {
  8555. $this->errors = array_merge($this->errors, $comment->errors);
  8556. return -1;
  8557. } else {
  8558. $this->comments = $comment->comments;
  8559. }
  8560. return count($this->comments);
  8561. }
  8562. /**
  8563. * Return nb comments already posted
  8564. *
  8565. * @return int
  8566. */
  8567. public function getNbComments()
  8568. {
  8569. return count($this->comments);
  8570. }
  8571. /**
  8572. * Trim object parameters
  8573. *
  8574. * @param string[] $parameters array of parameters to trim
  8575. * @return void
  8576. */
  8577. public function trimParameters($parameters)
  8578. {
  8579. if (!is_array($parameters)) {
  8580. return;
  8581. }
  8582. foreach ($parameters as $parameter) {
  8583. if (isset($this->$parameter)) {
  8584. $this->$parameter = trim($this->$parameter);
  8585. }
  8586. }
  8587. }
  8588. /* Part for categories/tags */
  8589. /**
  8590. * Sets object to given categories.
  8591. *
  8592. * Deletes object from existing categories not supplied.
  8593. * Adds it to non existing supplied categories.
  8594. * Existing categories are left untouch.
  8595. *
  8596. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  8597. * @return int Array of category objects or < 0 if KO
  8598. */
  8599. public function getCategoriesCommon($type_categ)
  8600. {
  8601. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8602. // Get current categories
  8603. $c = new Categorie($this->db);
  8604. $existing = $c->containing($this->id, $type_categ, 'id');
  8605. return $existing;
  8606. }
  8607. /**
  8608. * Sets object to given categories.
  8609. *
  8610. * Adds it to non existing supplied categories.
  8611. * Deletes object from existing categories not supplied (if remove_existing==true).
  8612. * Existing categories are left untouch.
  8613. *
  8614. * @param int[]|int $categories Category ID or array of Categories IDs
  8615. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) definied into const class Categorie type
  8616. * @param boolean $remove_existing True: Remove existings categories from Object if not supplies by $categories, False: let them
  8617. * @return int <0 if KO, >0 if OK
  8618. */
  8619. public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
  8620. {
  8621. // Handle single category
  8622. if (!is_array($categories)) {
  8623. $categories = array($categories);
  8624. }
  8625. dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
  8626. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8627. if (empty($type_categ)) {
  8628. dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
  8629. return -1;
  8630. }
  8631. // Get current categories
  8632. $c = new Categorie($this->db);
  8633. $existing = $c->containing($this->id, $type_categ, 'id');
  8634. if ($remove_existing) {
  8635. // Diff
  8636. if (is_array($existing)) {
  8637. $to_del = array_diff($existing, $categories);
  8638. $to_add = array_diff($categories, $existing);
  8639. } else {
  8640. $to_del = array(); // Nothing to delete
  8641. $to_add = $categories;
  8642. }
  8643. } else {
  8644. $to_del = array(); // Nothing to delete
  8645. $to_add = array_diff($categories, $existing);
  8646. }
  8647. $error = 0;
  8648. $ok = 0;
  8649. // Process
  8650. foreach ($to_del as $del) {
  8651. if ($c->fetch($del) > 0) {
  8652. $result=$c->del_type($this, $type_categ);
  8653. if ($result < 0) {
  8654. $error++;
  8655. $this->error = $c->error;
  8656. $this->errors = $c->errors;
  8657. break;
  8658. } else {
  8659. $ok += $result;
  8660. }
  8661. }
  8662. }
  8663. foreach ($to_add as $add) {
  8664. if ($c->fetch($add) > 0) {
  8665. $result = $c->add_type($this, $type_categ);
  8666. if ($result < 0) {
  8667. $error++;
  8668. $this->error = $c->error;
  8669. $this->errors = $c->errors;
  8670. break;
  8671. } else {
  8672. $ok += $result;
  8673. }
  8674. }
  8675. }
  8676. return $error ? -1 * $error : $ok;
  8677. }
  8678. /**
  8679. * Copy related categories to another object
  8680. *
  8681. * @param int $fromId Id object source
  8682. * @param int $toId Id object cible
  8683. * @param string $type Type of category ('product', ...)
  8684. * @return int < 0 if error, > 0 if ok
  8685. */
  8686. public function cloneCategories($fromId, $toId, $type = '')
  8687. {
  8688. $this->db->begin();
  8689. if (empty($type)) {
  8690. $type = $this->table_element;
  8691. }
  8692. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8693. $categorystatic = new Categorie($this->db);
  8694. $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  8695. $sql .= " SELECT fk_categorie, $toId FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  8696. $sql .= " WHERE fk_product = ".((int) $fromId);
  8697. if (!$this->db->query($sql)) {
  8698. $this->error = $this->db->lasterror();
  8699. $this->db->rollback();
  8700. return -1;
  8701. }
  8702. $this->db->commit();
  8703. return 1;
  8704. }
  8705. /**
  8706. * Delete related files of object in database
  8707. *
  8708. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  8709. * @return bool True if OK, False if KO
  8710. */
  8711. public function deleteEcmFiles($mode = 0)
  8712. {
  8713. global $conf;
  8714. $this->db->begin();
  8715. // Delete in database with mode 0
  8716. if ($mode == 0) {
  8717. switch ($this->element) {
  8718. case 'propal':
  8719. $element = 'propale';
  8720. break;
  8721. case 'product':
  8722. $element = 'produit';
  8723. break;
  8724. case 'order_supplier':
  8725. $element = 'fournisseur/commande';
  8726. break;
  8727. case 'invoice_supplier':
  8728. $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  8729. break;
  8730. case 'shipping':
  8731. $element = 'expedition/sending';
  8732. break;
  8733. default:
  8734. $element = $this->element;
  8735. }
  8736. // Delete ecm_files extrafields
  8737. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files_extrafields WHERE fk_object IN (";
  8738. $sql .= " SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8739. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  8740. $sql .= ")";
  8741. if (!$this->db->query($sql)) {
  8742. $this->error = $this->db->lasterror();
  8743. $this->db->rollback();
  8744. return false;
  8745. }
  8746. // Delete ecm_files
  8747. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files";
  8748. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8749. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  8750. if (!$this->db->query($sql)) {
  8751. $this->error = $this->db->lasterror();
  8752. $this->db->rollback();
  8753. return false;
  8754. }
  8755. }
  8756. // Delete in database with mode 1
  8757. if ($mode == 1) {
  8758. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files_extrafields";
  8759. $sql .= " WHERE fk_object IN (SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id).")";
  8760. $resql = $this->db->query($sql);
  8761. if (!$resql) {
  8762. $this->error = $this->db->lasterror();
  8763. $this->db->rollback();
  8764. return false;
  8765. }
  8766. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files";
  8767. $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
  8768. $resql = $this->db->query($sql);
  8769. if (!$resql) {
  8770. $this->error = $this->db->lasterror();
  8771. $this->db->rollback();
  8772. return false;
  8773. }
  8774. }
  8775. $this->db->commit();
  8776. return true;
  8777. }
  8778. }