commonobject.class.php 297 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540
  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 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-2020 Frédéric France <frederic.france@netlogic.fr>
  16. * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
  17. *
  18. * This program is free software; you can redistribute it and/or modify
  19. * it under the terms of the GNU General Public License as published by
  20. * the Free Software Foundation; either version 3 of the License, or
  21. * (at your option) any later version.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU General Public License
  29. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  30. */
  31. /**
  32. * \file htdocs/core/class/commonobject.class.php
  33. * \ingroup core
  34. * \brief File of parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  35. */
  36. /**
  37. * Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  38. */
  39. abstract class CommonObject
  40. {
  41. /**
  42. * @var DoliDb Database handler (result of a new DoliDB)
  43. */
  44. public $db;
  45. /**
  46. * @var int The object identifier
  47. */
  48. public $id;
  49. /**
  50. * @var int The environment ID when using a multicompany module
  51. */
  52. public $entity;
  53. /**
  54. * @var string Error string
  55. * @see $errors
  56. */
  57. public $error;
  58. /**
  59. * @var string Error string that is hidden but can be used to store complementatry technical code.
  60. */
  61. public $errorhidden;
  62. /**
  63. * @var string[] Array of error strings
  64. */
  65. public $errors = array();
  66. /**
  67. * @var string ID to identify managed object
  68. */
  69. public $element;
  70. /**
  71. * @var string Name of table without prefix where object is stored
  72. */
  73. public $table_element;
  74. /**
  75. * @var string Name of subtable line
  76. */
  77. public $table_element_line = '';
  78. /**
  79. * @var string Key value used to track if data is coming from import wizard
  80. */
  81. public $import_key;
  82. /**
  83. * @var mixed Contains data to manage extrafields
  84. */
  85. public $array_options = array();
  86. /**
  87. * @var mixed Array to store alternative languages values of object
  88. */
  89. public $array_languages = null; // Value is array() when load already tried
  90. /**
  91. * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked
  92. */
  93. public $linkedObjectsIds;
  94. /**
  95. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  96. */
  97. public $linkedObjects;
  98. /**
  99. * @var Object To store a cloned copy of object before to edit it and keep track of old properties
  100. */
  101. public $oldcopy;
  102. /**
  103. * @var string Column name of the ref field.
  104. */
  105. protected $table_ref_field = '';
  106. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  107. /**
  108. * @var array<string,mixed> Can be used to pass information when only object is provided to method
  109. */
  110. public $context = array();
  111. /**
  112. * @var string Contains canvas name if record is an alternative canvas record
  113. */
  114. public $canvas;
  115. /**
  116. * @var Project The related project
  117. * @see fetch_projet()
  118. */
  119. public $project;
  120. /**
  121. * @var int The related project ID
  122. * @see setProject(), project
  123. */
  124. public $fk_project;
  125. /**
  126. * @deprecated
  127. * @see project
  128. */
  129. public $projet;
  130. /**
  131. * @var Contact a related contact
  132. * @see fetch_contact()
  133. */
  134. public $contact;
  135. /**
  136. * @var int The related contact ID
  137. * @see fetch_contact()
  138. */
  139. public $contact_id;
  140. /**
  141. * @var Societe A related thirdparty
  142. * @see fetch_thirdparty()
  143. */
  144. public $thirdparty;
  145. /**
  146. * @var User A related user
  147. * @see fetch_user()
  148. */
  149. public $user;
  150. /**
  151. * @var string The type of originating object ('commande', 'facture', ...)
  152. * @see fetch_origin()
  153. */
  154. public $origin;
  155. /**
  156. * @var int The id of originating object
  157. * @see fetch_origin()
  158. */
  159. public $origin_id;
  160. /**
  161. * @var string The object's reference
  162. */
  163. public $ref;
  164. /**
  165. * @var string The object's previous reference
  166. */
  167. public $ref_previous;
  168. /**
  169. * @var string The object's next reference
  170. */
  171. public $ref_next;
  172. /**
  173. * @var string An external reference for the object
  174. */
  175. public $ref_ext;
  176. /**
  177. * @var int The object's status
  178. * @see setStatut()
  179. */
  180. public $statut;
  181. /**
  182. * @var string
  183. * @see getFullAddress()
  184. */
  185. public $country;
  186. /**
  187. * @var int
  188. * @see getFullAddress(), country
  189. */
  190. public $country_id;
  191. /**
  192. * @var string
  193. * @see getFullAddress(), isInEEC(), country
  194. */
  195. public $country_code;
  196. /**
  197. * @var string
  198. * @see getFullAddress()
  199. */
  200. public $state;
  201. /**
  202. * @var int
  203. * @see getFullAddress(), state
  204. */
  205. public $state_id;
  206. /**
  207. * @var string
  208. * @see getFullAddress(), $state
  209. */
  210. public $state_code;
  211. /**
  212. * @var int
  213. * @see getFullAddress(), $region_code, $region
  214. */
  215. public $region_id;
  216. /**
  217. * @var string
  218. * @see getFullAddress(), $region_id, $region
  219. */
  220. public $region_code;
  221. /**
  222. * @var string
  223. * @see getFullAddress(), $region_id, $region_code
  224. */
  225. public $region;
  226. /**
  227. * @var int
  228. * @see fetch_barcode()
  229. */
  230. public $barcode_type;
  231. /**
  232. * @var string
  233. * @see fetch_barcode(), barcode_type
  234. */
  235. public $barcode_type_code;
  236. /**
  237. * @var string
  238. * @see fetch_barcode(), barcode_type
  239. */
  240. public $barcode_type_label;
  241. /**
  242. * @var string
  243. * @see fetch_barcode(), barcode_type
  244. */
  245. public $barcode_type_coder;
  246. /**
  247. * @var int Payment method ID (cheque, cash, ...)
  248. * @see setPaymentMethods()
  249. */
  250. public $mode_reglement_id;
  251. /**
  252. * @var int Payment terms ID
  253. * @see setPaymentTerms()
  254. */
  255. public $cond_reglement_id;
  256. /**
  257. * @var int Demand reason ID
  258. */
  259. public $demand_reason_id;
  260. /**
  261. * @var int Transport mode ID (For module intracomm report)
  262. * @see setTransportMode()
  263. */
  264. public $transport_mode_id;
  265. /**
  266. * @var int Payment terms ID
  267. * @deprecated Kept for compatibility
  268. * @see cond_reglement_id;
  269. */
  270. public $cond_reglement;
  271. /**
  272. * @var int Delivery address ID
  273. * @see setDeliveryAddress()
  274. * @deprecated
  275. */
  276. public $fk_delivery_address;
  277. /**
  278. * @var int Shipping method ID
  279. * @see setShippingMethod()
  280. */
  281. public $shipping_method_id;
  282. /**
  283. * @var string
  284. * @see SetDocModel()
  285. */
  286. public $model_pdf;
  287. /**
  288. * @var string
  289. * Contains relative path of last generated main file
  290. */
  291. public $last_main_doc;
  292. /**
  293. * @var int Bank account ID
  294. * @deprecated
  295. * @see $fk_account
  296. */
  297. public $fk_bank;
  298. /**
  299. * @var int Bank account ID
  300. * @see SetBankAccount()
  301. */
  302. public $fk_account;
  303. /**
  304. * @var string Open ID
  305. */
  306. public $openid;
  307. /**
  308. * @var string Public note
  309. * @see update_note()
  310. */
  311. public $note_public;
  312. /**
  313. * @var string Private note
  314. * @see update_note()
  315. */
  316. public $note_private;
  317. /**
  318. * @deprecated
  319. * @see $note_private
  320. */
  321. public $note;
  322. /**
  323. * @var float Total amount before taxes
  324. * @see update_price()
  325. */
  326. public $total_ht;
  327. /**
  328. * @var float Total VAT amount
  329. * @see update_price()
  330. */
  331. public $total_tva;
  332. /**
  333. * @var float Total local tax 1 amount
  334. * @see update_price()
  335. */
  336. public $total_localtax1;
  337. /**
  338. * @var float Total local tax 2 amount
  339. * @see update_price()
  340. */
  341. public $total_localtax2;
  342. /**
  343. * @var float Total amount with taxes
  344. * @see update_price()
  345. */
  346. public $total_ttc;
  347. /**
  348. * @var CommonObjectLine[]
  349. */
  350. public $lines;
  351. /**
  352. * @var mixed Contains comments
  353. * @see fetchComments()
  354. */
  355. public $comments = array();
  356. /**
  357. * @var string The name
  358. */
  359. public $name;
  360. /**
  361. * @var string The lastname
  362. */
  363. public $lastname;
  364. /**
  365. * @var string The firstname
  366. */
  367. public $firstname;
  368. /**
  369. * @var string The civility code, not an integer
  370. */
  371. public $civility_id;
  372. // Dates
  373. /**
  374. * @var integer|string date_creation
  375. */
  376. public $date_creation;
  377. /**
  378. * @var integer|string $date_validation;
  379. */
  380. public $date_validation; // Date validation
  381. /**
  382. * @var integer|string $date_modification;
  383. */
  384. public $date_modification; // Date last change (tms field)
  385. public $next_prev_filter;
  386. /**
  387. * @var int 1 if object is specimen
  388. */
  389. public $specimen = 0;
  390. /**
  391. * @var array List of child tables. To test if we can delete object.
  392. */
  393. protected $childtables = array();
  394. /**
  395. * @var array List of child tables. To know object to delete on cascade.
  396. * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
  397. * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
  398. */
  399. protected $childtablesoncascade = array();
  400. // No constructor as it is an abstract class
  401. /**
  402. * Check an object id/ref exists
  403. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  404. *
  405. * @param string $element String of element ('product', 'facture', ...)
  406. * @param int $id Id of object
  407. * @param string $ref Ref of object to check
  408. * @param string $ref_ext Ref ext of object to check
  409. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  410. */
  411. public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
  412. {
  413. global $db, $conf;
  414. $sql = "SELECT rowid, ref, ref_ext";
  415. $sql .= " FROM ".MAIN_DB_PREFIX.$element;
  416. $sql .= " WHERE entity IN (".getEntity($element).")";
  417. if ($id > 0) $sql .= " AND rowid = ".$db->escape($id);
  418. elseif ($ref) $sql .= " AND ref = '".$db->escape($ref)."'";
  419. elseif ($ref_ext) $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
  420. else {
  421. $error = 'ErrorWrongParameters';
  422. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  423. return -1;
  424. }
  425. if ($ref || $ref_ext) $sql .= " AND entity = ".$conf->entity;
  426. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  427. $resql = $db->query($sql);
  428. if ($resql)
  429. {
  430. $num = $db->num_rows($resql);
  431. if ($num > 0) return 1;
  432. else return 0;
  433. }
  434. return -1;
  435. }
  436. /**
  437. * Method to output saved errors
  438. *
  439. * @return string String with errors
  440. */
  441. public function errorsToString()
  442. {
  443. return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
  444. }
  445. /**
  446. * Return customer ref for screen output.
  447. *
  448. * @param string $objref Customer ref
  449. * @return string Customer ref formated
  450. */
  451. public function getFormatedCustomerRef($objref)
  452. {
  453. global $hookmanager;
  454. $parameters = array('objref'=>$objref);
  455. $action = '';
  456. $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  457. if ($reshook > 0)
  458. {
  459. return $hookmanager->resArray['objref'];
  460. }
  461. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  462. }
  463. /**
  464. * Return supplier ref for screen output.
  465. *
  466. * @param string $objref Supplier ref
  467. * @return string Supplier ref formated
  468. */
  469. public function getFormatedSupplierRef($objref)
  470. {
  471. global $hookmanager;
  472. $parameters = array('objref'=>$objref);
  473. $action = '';
  474. $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  475. if ($reshook > 0)
  476. {
  477. return $hookmanager->resArray['objref'];
  478. }
  479. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  480. }
  481. /**
  482. * Return full name (civility+' '+name+' '+lastname)
  483. *
  484. * @param Translate $langs Language object for translation of civility (used only if option is 1)
  485. * @param int $option 0=No option, 1=Add civility
  486. * @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
  487. * @param int $maxlen Maximum length
  488. * @return string String with full name
  489. */
  490. public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
  491. {
  492. //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
  493. $lastname = $this->lastname;
  494. $firstname = $this->firstname;
  495. if (empty($lastname)) $lastname = (isset($this->lastname) ? $this->lastname : (isset($this->name) ? $this->name : (isset($this->nom) ? $this->nom : (isset($this->societe) ? $this->societe : (isset($this->company) ? $this->company : '')))));
  496. $ret = '';
  497. if ($option && $this->civility_code)
  498. {
  499. if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
  500. else $ret .= $this->civility_code.' ';
  501. }
  502. $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
  503. return dol_trunc($ret, $maxlen);
  504. }
  505. /**
  506. * Set to upper or ucwords/lower if needed
  507. *
  508. * @return void;
  509. */
  510. public function setUpperOrLowerCase()
  511. {
  512. global $conf;
  513. if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
  514. $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
  515. $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
  516. $this->name = dol_ucwords(dol_strtolower($this->name));
  517. }
  518. if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
  519. $this->lastname = dol_strtoupper($this->lastname);
  520. $this->name = dol_strtoupper($this->name);
  521. }
  522. if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
  523. $this->town = dol_strtoupper($this->town);
  524. }
  525. }
  526. /**
  527. * Return clicable link of object (with eventually picto)
  528. *
  529. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  530. * @return string HTML Code for Kanban thumb.
  531. */
  532. public function getKanbanView($option = '')
  533. {
  534. $return = '<div class="box-flex-item">';
  535. $return .= '<div class="info-box info-box-sm">';
  536. $return .= '<span class="info-box-icon bg-infobox-action">';
  537. $return .= '<i class="fa fa-dol-action"></i>'; // Can be image
  538. $return .= '</span>';
  539. $return .= '<div class="info-box-content">';
  540. $return .= '<span class="info-box-title">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  541. $return .= '</div>';
  542. $return .= '</div>';
  543. $return .= '</div>';
  544. return $return;
  545. }
  546. /**
  547. * Return full address of contact
  548. *
  549. * @param int $withcountry 1=Add country into address string
  550. * @param string $sep Separator to use to build string
  551. * @param int $withregion 1=Add region into address string
  552. * @param string $extralangcode User extralanguages as value
  553. * @return string Full address string
  554. */
  555. public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
  556. {
  557. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country)))
  558. {
  559. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  560. $tmparray = getCountry($this->country_id, 'all');
  561. $this->country_code = $tmparray['code'];
  562. $this->country = $tmparray['label'];
  563. }
  564. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code)))
  565. {
  566. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  567. $tmparray = getState($this->state_id, 'all', 0, 1);
  568. $this->state_code = $tmparray['code'];
  569. $this->state = $tmparray['label'];
  570. $this->region_code = $tmparray['region_code'];
  571. $this->region = $tmparray['region'];
  572. }
  573. return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
  574. }
  575. /**
  576. * Return full address for banner
  577. *
  578. * @param string $htmlkey HTML id to make banner content unique
  579. * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member)
  580. * @return string Full address string
  581. */
  582. public function getBannerAddress($htmlkey, $object)
  583. {
  584. global $conf, $langs, $form, $extralanguages;
  585. $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
  586. $contactid = 0;
  587. $thirdpartyid = 0;
  588. $elementforaltlanguage = $this->element;
  589. if ($this->element == 'societe')
  590. {
  591. $thirdpartyid = $this->id;
  592. }
  593. if ($this->element == 'contact')
  594. {
  595. $contactid = $this->id;
  596. $thirdpartyid = $object->fk_soc;
  597. }
  598. if ($this->element == 'user')
  599. {
  600. $contactid = $this->contact_id;
  601. $thirdpartyid = $object->fk_soc;
  602. }
  603. $out = '';
  604. $outdone = 0;
  605. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT);
  606. if ($coords)
  607. {
  608. if (!empty($conf->use_javascript_ajax))
  609. {
  610. // Add picto with tooltip on map
  611. $namecoords = '';
  612. if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS))
  613. {
  614. $namecoords .= $object->name.'<br>';
  615. }
  616. $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
  617. // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
  618. $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
  619. $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
  620. $out .= '</a> ';
  621. }
  622. $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', '); $outdone++;
  623. $outdone++;
  624. // List of extra languages
  625. $arrayoflangcode = array();
  626. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  627. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  628. if (!is_object($extralanguages)) {
  629. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  630. $extralanguages = new ExtraLanguages($this->db);
  631. }
  632. $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
  633. if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town']))
  634. {
  635. $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
  636. $this->fetchValuesForExtraLanguages();
  637. if (!is_object($form)) $form = new Form($this->db);
  638. $htmltext = '';
  639. // If there is extra languages
  640. foreach ($arrayoflangcode as $extralangcode) {
  641. $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  642. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
  643. $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  644. }
  645. $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  646. }
  647. }
  648. }
  649. 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
  650. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state)
  651. {
  652. if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
  653. $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
  654. } else {
  655. $out .= ($outdone ? ' - ' : '').$this->state;
  656. }
  657. $outdone++;
  658. }
  659. if (!empty($this->phone) || !empty($this->phone_pro) || !empty($this->phone_mobile) || !empty($this->phone_perso) || !empty($this->fax) || !empty($this->office_phone) || !empty($this->user_mobile) || !empty($this->office_fax)) $out .= ($outdone ? '<br>' : '');
  660. if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  661. $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro")); $outdone++;
  662. }
  663. if (!empty($this->phone_pro)) {
  664. $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro")); $outdone++;
  665. }
  666. if (!empty($this->phone_mobile)) {
  667. $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile")); $outdone++;
  668. }
  669. if (!empty($this->phone_perso)) {
  670. $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso")); $outdone++;
  671. }
  672. if (!empty($this->office_phone)) {
  673. $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro")); $outdone++;
  674. }
  675. if (!empty($this->user_mobile)) {
  676. $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile")); $outdone++;
  677. }
  678. if (!empty($this->fax)) {
  679. $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax")); $outdone++;
  680. }
  681. if (!empty($this->office_fax)) {
  682. $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax")); $outdone++;
  683. }
  684. if ($out) $out .= '<div style="clear: both;"></div>';
  685. $outdone = 0;
  686. if (!empty($this->email))
  687. {
  688. $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
  689. $outdone++;
  690. }
  691. if (!empty($this->url))
  692. {
  693. //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
  694. $out .= dol_print_url($this->url, '_blank', 0, 1);
  695. $outdone++;
  696. }
  697. if (!empty($conf->socialnetworks->enabled))
  698. {
  699. $outsocialnetwork = '';
  700. if (is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
  701. foreach ($this->socialnetworks as $key => $value) {
  702. $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key);
  703. $outdone++;
  704. }
  705. } else {
  706. if ($this->skype) $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
  707. $outdone++;
  708. if ($this->jabberid) $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
  709. $outdone++;
  710. if ($this->twitter) $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
  711. $outdone++;
  712. if ($this->facebook) $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
  713. $outdone++;
  714. if ($this->linkedin) $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
  715. $outdone++;
  716. }
  717. if ($outsocialnetwork) {
  718. $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
  719. }
  720. }
  721. if ($out) return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
  722. else return '';
  723. }
  724. /**
  725. * Return the link of last main doc file for direct public download.
  726. *
  727. * @param string $modulepart Module related to document
  728. * @param int $initsharekey Init the share key if it was not yet defined
  729. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  730. * @return string Link or empty string if there is no download link
  731. */
  732. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  733. {
  734. global $user, $dolibarr_main_url_root;
  735. if (empty($this->last_main_doc))
  736. {
  737. return ''; // No way to known which document name to use
  738. }
  739. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  740. $ecmfile = new EcmFiles($this->db);
  741. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  742. if ($result < 0)
  743. {
  744. $this->error = $ecmfile->error;
  745. $this->errors = $ecmfile->errors;
  746. return -1;
  747. }
  748. if (empty($ecmfile->id))
  749. {
  750. // Add entry into index
  751. if ($initsharekey)
  752. {
  753. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  754. // TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first
  755. /*
  756. $ecmfile->filepath = $rel_dir;
  757. $ecmfile->filename = $filename;
  758. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  759. $ecmfile->fullpath_orig = '';
  760. $ecmfile->gen_or_uploaded = 'generated';
  761. $ecmfile->description = ''; // indexed content
  762. $ecmfile->keyword = ''; // keyword content
  763. $ecmfile->share = getRandomPassword(true);
  764. $result = $ecmfile->create($user);
  765. if ($result < 0)
  766. {
  767. $this->error = $ecmfile->error;
  768. $this->errors = $ecmfile->errors;
  769. }
  770. */
  771. } else return '';
  772. } elseif (empty($ecmfile->share))
  773. {
  774. // Add entry into index
  775. if ($initsharekey)
  776. {
  777. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  778. $ecmfile->share = getRandomPassword(true);
  779. $ecmfile->update($user);
  780. } else return '';
  781. }
  782. // Define $urlwithroot
  783. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  784. // This is to use external domain name found into config file
  785. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  786. //else
  787. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  788. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  789. $forcedownload = 0;
  790. $paramlink = '';
  791. //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  792. //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  793. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  794. if (!empty($ecmfile->share)) $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
  795. if ($forcedownload) $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  796. if ($relativelink)
  797. {
  798. $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
  799. } else {
  800. $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  801. }
  802. // Here $ecmfile->share is defined
  803. return $linktoreturn;
  804. }
  805. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  806. /**
  807. * Add a link between element $this->element and a contact
  808. *
  809. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  810. * @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
  811. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  812. * @param int $notrigger Disable all triggers
  813. * @return int <0 if KO, >0 if OK
  814. */
  815. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  816. {
  817. // phpcs:enable
  818. global $user, $langs;
  819. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  820. // Check parameters
  821. if ($fk_socpeople <= 0)
  822. {
  823. $langs->load("errors");
  824. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  825. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  826. return -1;
  827. }
  828. if (!$type_contact)
  829. {
  830. $langs->load("errors");
  831. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  832. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  833. return -2;
  834. }
  835. $id_type_contact = 0;
  836. if (is_numeric($type_contact))
  837. {
  838. $id_type_contact = $type_contact;
  839. } else {
  840. // We look for id type_contact
  841. $sql = "SELECT tc.rowid";
  842. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  843. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  844. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  845. $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  846. //print $sql;
  847. $resql = $this->db->query($sql);
  848. if ($resql)
  849. {
  850. $obj = $this->db->fetch_object($resql);
  851. if ($obj) $id_type_contact = $obj->rowid;
  852. }
  853. }
  854. if ($id_type_contact == 0)
  855. {
  856. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  857. 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");
  858. return -3;
  859. }
  860. $datecreate = dol_now();
  861. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  862. $TListeContacts = $this->liste_contact(-1, $source);
  863. $already_added = false;
  864. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  865. foreach ($TListeContacts as $array_contact) {
  866. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  867. $already_added = true;
  868. break;
  869. }
  870. }
  871. }
  872. if (!$already_added) {
  873. $this->db->begin();
  874. // Insert into database
  875. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact";
  876. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  877. $sql .= " VALUES (".$this->id.", ".$fk_socpeople." , ";
  878. $sql .= "'".$this->db->idate($datecreate)."'";
  879. $sql .= ", 4, ".$id_type_contact;
  880. $sql .= ")";
  881. $resql = $this->db->query($sql);
  882. if ($resql)
  883. {
  884. if (!$notrigger)
  885. {
  886. $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  887. if ($result < 0)
  888. {
  889. $this->db->rollback();
  890. return -1;
  891. }
  892. }
  893. $this->db->commit();
  894. return 1;
  895. } else {
  896. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
  897. {
  898. $this->error = $this->db->errno();
  899. $this->db->rollback();
  900. echo 'err rollback';
  901. return -2;
  902. } else {
  903. $this->error = $this->db->error();
  904. $this->db->rollback();
  905. return -1;
  906. }
  907. }
  908. } else return 0;
  909. }
  910. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  911. /**
  912. * Copy contact from one element to current
  913. *
  914. * @param CommonObject $objFrom Source element
  915. * @param string $source Nature of contact ('internal' or 'external')
  916. * @return int >0 if OK, <0 if KO
  917. */
  918. public function copy_linked_contact($objFrom, $source = 'internal')
  919. {
  920. // phpcs:enable
  921. $contacts = $objFrom->liste_contact(-1, $source);
  922. foreach ($contacts as $contact)
  923. {
  924. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0)
  925. {
  926. $this->error = $this->db->lasterror();
  927. return -1;
  928. }
  929. }
  930. return 1;
  931. }
  932. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  933. /**
  934. * Update a link to contact line
  935. *
  936. * @param int $rowid Id of line contact-element
  937. * @param int $statut New status of link
  938. * @param int $type_contact_id Id of contact type (not modified if 0)
  939. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  940. * @return int <0 if KO, >= 0 if OK
  941. */
  942. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  943. {
  944. // phpcs:enable
  945. // Insert into database
  946. $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set";
  947. $sql .= " statut = ".$statut;
  948. if ($type_contact_id) $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
  949. if ($fk_socpeople) $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
  950. $sql .= " where rowid = ".$rowid;
  951. $resql = $this->db->query($sql);
  952. if ($resql)
  953. {
  954. return 0;
  955. } else {
  956. $this->error = $this->db->lasterror();
  957. return -1;
  958. }
  959. }
  960. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  961. /**
  962. * Delete a link to contact line
  963. *
  964. * @param int $rowid Id of contact link line to delete
  965. * @param int $notrigger Disable all triggers
  966. * @return int >0 if OK, <0 if KO
  967. */
  968. public function delete_contact($rowid, $notrigger = 0)
  969. {
  970. // phpcs:enable
  971. global $user;
  972. $this->db->begin();
  973. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  974. $sql .= " WHERE rowid =".$rowid;
  975. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  976. if ($this->db->query($sql))
  977. {
  978. if (!$notrigger)
  979. {
  980. $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  981. if ($result < 0) { $this->db->rollback(); return -1; }
  982. }
  983. $this->db->commit();
  984. return 1;
  985. } else {
  986. $this->error = $this->db->lasterror();
  987. $this->db->rollback();
  988. return -1;
  989. }
  990. }
  991. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  992. /**
  993. * Delete all links between an object $this and all its contacts
  994. *
  995. * @param string $source '' or 'internal' or 'external'
  996. * @param string $code Type of contact (code or id)
  997. * @return int >0 if OK, <0 if KO
  998. */
  999. public function delete_linked_contact($source = '', $code = '')
  1000. {
  1001. // phpcs:enable
  1002. $temp = array();
  1003. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  1004. foreach ($typeContact as $key => $value)
  1005. {
  1006. array_push($temp, $key);
  1007. }
  1008. $listId = implode(",", $temp);
  1009. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  1010. $sql .= " WHERE element_id = ".$this->id;
  1011. if ($listId)
  1012. $sql .= " AND fk_c_type_contact IN (".$listId.")";
  1013. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  1014. if ($this->db->query($sql))
  1015. {
  1016. return 1;
  1017. } else {
  1018. $this->error = $this->db->lasterror();
  1019. return -1;
  1020. }
  1021. }
  1022. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1023. /**
  1024. * Get array of all contacts for an object
  1025. *
  1026. * @param int $status Status of links to get (-1=all)
  1027. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  1028. * @param int $list 0:Return array contains all properties, 1:Return array contains just id
  1029. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1030. * @return array|int Array of contacts, -1 if error
  1031. */
  1032. public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
  1033. {
  1034. // phpcs:enable
  1035. global $langs;
  1036. $tab = array();
  1037. $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
  1038. if ($source == 'internal') $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  1039. if ($source == 'external' || $source == 'thirdparty') $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1040. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  1041. $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
  1042. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
  1043. $sql .= ", ".MAIN_DB_PREFIX."element_contact ec";
  1044. if ($source == 'internal') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
  1045. if ($source == 'external' || $source == 'thirdparty') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
  1046. $sql .= " WHERE ec.element_id =".$this->id;
  1047. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1048. $sql .= " AND tc.element='".$this->db->escape($this->element)."'";
  1049. if ($code) $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1050. if ($source == 'internal') $sql .= " AND tc.source = 'internal'";
  1051. if ($source == 'external' || $source == 'thirdparty') $sql .= " AND tc.source = 'external'";
  1052. $sql .= " AND tc.active=1";
  1053. if ($status >= 0) $sql .= " AND ec.statut = ".$status;
  1054. $sql .= " ORDER BY t.lastname ASC";
  1055. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  1056. $resql = $this->db->query($sql);
  1057. if ($resql)
  1058. {
  1059. $num = $this->db->num_rows($resql);
  1060. $i = 0;
  1061. while ($i < $num)
  1062. {
  1063. $obj = $this->db->fetch_object($resql);
  1064. if (!$list)
  1065. {
  1066. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1067. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1068. $tab[$i] = array('source'=>$obj->source, 'socid'=>$obj->socid, 'id'=>$obj->id,
  1069. 'nom'=>$obj->lastname, // For backward compatibility
  1070. 'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'login'=>$obj->login, 'photo'=>$obj->photo, 'statuscontact'=>$obj->statuscontact,
  1071. 'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact);
  1072. } else {
  1073. $tab[$i] = $obj->id;
  1074. }
  1075. $i++;
  1076. }
  1077. return $tab;
  1078. } else {
  1079. $this->error = $this->db->lasterror();
  1080. dol_print_error($this->db);
  1081. return -1;
  1082. }
  1083. }
  1084. /**
  1085. * Update status of a contact linked to object
  1086. *
  1087. * @param int $rowid Id of link between object and contact
  1088. * @return int <0 if KO, >=0 if OK
  1089. */
  1090. public function swapContactStatus($rowid)
  1091. {
  1092. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1093. $sql .= " tc.code, tc.libelle";
  1094. $sql .= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)";
  1095. $sql .= " WHERE ec.rowid =".$rowid;
  1096. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1097. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1098. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  1099. $resql = $this->db->query($sql);
  1100. if ($resql)
  1101. {
  1102. $obj = $this->db->fetch_object($resql);
  1103. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1104. $result = $this->update_contact($rowid, $newstatut);
  1105. $this->db->free($resql);
  1106. return $result;
  1107. } else {
  1108. $this->error = $this->db->error();
  1109. dol_print_error($this->db);
  1110. return -1;
  1111. }
  1112. }
  1113. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1114. /**
  1115. * Return array with list of possible values for type of contacts
  1116. *
  1117. * @param string $source 'internal', 'external' or 'all'
  1118. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  1119. * @param int $option 0=Return array id->label, 1=Return array code->label
  1120. * @param int $activeonly 0=all status of contact, 1=only the active
  1121. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1122. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1123. */
  1124. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1125. {
  1126. // phpcs:enable
  1127. global $langs;
  1128. if (empty($order)) $order = 'position';
  1129. if ($order == 'position') $order .= ',code';
  1130. $tab = array();
  1131. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  1132. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  1133. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1134. if ($activeonly == 1) $sql .= " AND tc.active=1"; // only the active types
  1135. if (!empty($source) && $source != 'all') $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1136. if (!empty($code)) $sql .= " AND tc.code='".$this->db->escape($code)."'";
  1137. $sql .= $this->db->order($order, 'ASC');
  1138. //print "sql=".$sql;
  1139. $resql = $this->db->query($sql);
  1140. if ($resql)
  1141. {
  1142. $num = $this->db->num_rows($resql);
  1143. $i = 0;
  1144. while ($i < $num)
  1145. {
  1146. $obj = $this->db->fetch_object($resql);
  1147. $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
  1148. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1149. if (empty($option)) $tab[$obj->rowid] = $libelle_type;
  1150. else $tab[$obj->code] = $libelle_type;
  1151. $i++;
  1152. }
  1153. return $tab;
  1154. } else {
  1155. $this->error = $this->db->lasterror();
  1156. //dol_print_error($this->db);
  1157. return null;
  1158. }
  1159. }
  1160. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1161. /**
  1162. * Return array with list of possible values for type of contacts
  1163. *
  1164. * @param string $source 'internal', 'external' or 'all'
  1165. * @param int $option 0=Return array id->label, 1=Return array code->label
  1166. * @param int $activeonly 0=all status of contact, 1=only the active
  1167. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1168. * @param string $element Filter on 1 element type
  1169. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1170. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1171. */
  1172. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1173. {
  1174. // phpcs:enable
  1175. global $langs, $conf;
  1176. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1177. $tab = array();
  1178. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
  1179. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  1180. $sqlWhere = array();
  1181. if (!empty($element)) {
  1182. $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
  1183. }
  1184. if (!empty($excludeelement)) {
  1185. $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
  1186. }
  1187. if ($activeonly == 1)
  1188. $sqlWhere[] = " tc.active=1"; // only the active types
  1189. if (!empty($source) && $source != 'all')
  1190. $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
  1191. if (!empty($code))
  1192. $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
  1193. if (count($sqlWhere) > 0) {
  1194. $sql .= " WHERE ".implode(' AND ', $sqlWhere);
  1195. }
  1196. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1197. dol_syslog(__METHOD__, LOG_DEBUG);
  1198. $resql = $this->db->query($sql);
  1199. if ($resql) {
  1200. $num = $this->db->num_rows($resql);
  1201. if ($num > 0) {
  1202. while ($obj = $this->db->fetch_object($resql)) {
  1203. $modulename = $obj->element;
  1204. if (strpos($obj->element, 'project') !== false) {
  1205. $modulename = 'projet';
  1206. } elseif ($obj->element == 'contrat') {
  1207. $element = 'contract';
  1208. } elseif ($obj->element == 'action') {
  1209. $modulename = 'agenda';
  1210. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1211. $modulename = 'fournisseur';
  1212. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1213. $modulename = 'fournisseur';
  1214. }
  1215. if ($conf->{$modulename}->enabled) {
  1216. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1217. $transkey = "TypeContact_".$obj->element."_".$source."_".$obj->code;
  1218. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1219. if (empty($option))
  1220. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1221. else $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1222. }
  1223. }
  1224. }
  1225. return $tab;
  1226. } else {
  1227. $this->error = $this->db->lasterror();
  1228. return null;
  1229. }
  1230. }
  1231. /**
  1232. * Return id of contacts for a source and a contact code.
  1233. * Example: contact client de facturation ('external', 'BILLING')
  1234. * Example: contact client de livraison ('external', 'SHIPPING')
  1235. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1236. *
  1237. * @param string $source 'external' or 'internal'
  1238. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1239. * @param int $status limited to a certain status
  1240. * @return array List of id for such contacts
  1241. */
  1242. public function getIdContact($source, $code, $status = 0)
  1243. {
  1244. global $conf;
  1245. $result = array();
  1246. $i = 0;
  1247. //cas particulier pour les expeditions
  1248. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1249. $id = $this->origin_id;
  1250. $element = 'commande';
  1251. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1252. $id = $this->origin_id;
  1253. $element = 'order_supplier';
  1254. } else {
  1255. $id = $this->id;
  1256. $element = $this->element;
  1257. }
  1258. $sql = "SELECT ec.fk_socpeople";
  1259. $sql .= " FROM ".MAIN_DB_PREFIX."element_contact as ec,";
  1260. if ($source == 'internal') $sql .= " ".MAIN_DB_PREFIX."user as c,";
  1261. if ($source == 'external') $sql .= " ".MAIN_DB_PREFIX."socpeople as c,";
  1262. $sql .= " ".MAIN_DB_PREFIX."c_type_contact as tc";
  1263. $sql .= " WHERE ec.element_id = ".$id;
  1264. $sql .= " AND ec.fk_socpeople = c.rowid";
  1265. if ($source == 'internal') $sql .= " AND c.entity IN (".getEntity('user').")";
  1266. if ($source == 'external') $sql .= " AND c.entity IN (".getEntity('societe').")";
  1267. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1268. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1269. $sql .= " AND tc.source = '".$this->db->escape($source)."'";
  1270. if ($code) $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1271. $sql .= " AND tc.active = 1";
  1272. if ($status) $sql .= " AND ec.statut = ".$status;
  1273. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1274. $resql = $this->db->query($sql);
  1275. if ($resql)
  1276. {
  1277. while ($obj = $this->db->fetch_object($resql))
  1278. {
  1279. $result[$i] = $obj->fk_socpeople;
  1280. $i++;
  1281. }
  1282. } else {
  1283. $this->error = $this->db->error();
  1284. return null;
  1285. }
  1286. return $result;
  1287. }
  1288. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1289. /**
  1290. * Load object contact with id=$this->contact_id into $this->contact
  1291. *
  1292. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1293. * @return int <0 if KO, >0 if OK
  1294. */
  1295. public function fetch_contact($contactid = null)
  1296. {
  1297. // phpcs:enable
  1298. if (empty($contactid)) $contactid = $this->contact_id;
  1299. if (empty($contactid)) return 0;
  1300. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1301. $contact = new Contact($this->db);
  1302. $result = $contact->fetch($contactid);
  1303. $this->contact = $contact;
  1304. return $result;
  1305. }
  1306. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1307. /**
  1308. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1309. *
  1310. * @param int $force_thirdparty_id Force thirdparty id
  1311. * @return int <0 if KO, >0 if OK
  1312. */
  1313. public function fetch_thirdparty($force_thirdparty_id = 0)
  1314. {
  1315. // phpcs:enable
  1316. global $conf;
  1317. if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id))
  1318. return 0;
  1319. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1320. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
  1321. if ($force_thirdparty_id)
  1322. $idtofetch = $force_thirdparty_id;
  1323. if ($idtofetch) {
  1324. $thirdparty = new Societe($this->db);
  1325. $result = $thirdparty->fetch($idtofetch);
  1326. $this->thirdparty = $thirdparty;
  1327. // Use first price level if level not defined for third party
  1328. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1329. $this->thirdparty->price_level = 1;
  1330. }
  1331. return $result;
  1332. } else return -1;
  1333. }
  1334. /**
  1335. * Looks for an object with ref matching the wildcard provided
  1336. * It does only work when $this->table_ref_field is set
  1337. *
  1338. * @param string $ref Wildcard
  1339. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1340. */
  1341. public function fetchOneLike($ref)
  1342. {
  1343. if (!$this->table_ref_field) {
  1344. return 0;
  1345. }
  1346. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE '.$this->table_ref_field.' LIKE "'.$this->db->escape($ref).'" LIMIT 1';
  1347. $query = $this->db->query($sql);
  1348. if (!$this->db->num_rows($query)) {
  1349. return 0;
  1350. }
  1351. $result = $this->db->fetch_object($query);
  1352. return $this->fetch($result->rowid);
  1353. }
  1354. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1355. /**
  1356. * Load data for barcode into properties ->barcode_type*
  1357. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1358. * if it is not defined, ->element must be defined to know default barcode type.
  1359. *
  1360. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1361. */
  1362. public function fetch_barcode()
  1363. {
  1364. // phpcs:enable
  1365. global $conf;
  1366. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1367. $idtype = $this->barcode_type;
  1368. 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
  1369. {
  1370. if ($this->element == 'product') $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1371. elseif ($this->element == 'societe') $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1372. else dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1373. }
  1374. if ($idtype > 0)
  1375. {
  1376. 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
  1377. {
  1378. $sql = "SELECT rowid, code, libelle as label, coder";
  1379. $sql .= " FROM ".MAIN_DB_PREFIX."c_barcode_type";
  1380. $sql .= " WHERE rowid = ".$idtype;
  1381. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1382. $resql = $this->db->query($sql);
  1383. if ($resql)
  1384. {
  1385. $obj = $this->db->fetch_object($resql);
  1386. $this->barcode_type = $obj->rowid;
  1387. $this->barcode_type_code = $obj->code;
  1388. $this->barcode_type_label = $obj->label;
  1389. $this->barcode_type_coder = $obj->coder;
  1390. return 1;
  1391. } else {
  1392. dol_print_error($this->db);
  1393. return -1;
  1394. }
  1395. }
  1396. }
  1397. return 0;
  1398. }
  1399. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1400. /**
  1401. * Load the project with id $this->fk_project into this->project
  1402. *
  1403. * @return int <0 if KO, >=0 if OK
  1404. */
  1405. public function fetch_projet()
  1406. {
  1407. // phpcs:enable
  1408. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1409. if (empty($this->fk_project) && !empty($this->fk_projet)) $this->fk_project = $this->fk_projet; // For backward compatibility
  1410. if (empty($this->fk_project)) return 0;
  1411. $project = new Project($this->db);
  1412. $result = $project->fetch($this->fk_project);
  1413. $this->projet = $project; // deprecated
  1414. $this->project = $project;
  1415. return $result;
  1416. }
  1417. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1418. /**
  1419. * Load the product with id $this->fk_product into this->product
  1420. *
  1421. * @return int <0 if KO, >=0 if OK
  1422. */
  1423. public function fetch_product()
  1424. {
  1425. // phpcs:enable
  1426. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1427. if (empty($this->fk_product)) return 0;
  1428. $product = new Product($this->db);
  1429. $result = $product->fetch($this->fk_product);
  1430. $this->product = $product;
  1431. return $result;
  1432. }
  1433. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1434. /**
  1435. * Load the user with id $userid into this->user
  1436. *
  1437. * @param int $userid Id du contact
  1438. * @return int <0 if KO, >0 if OK
  1439. */
  1440. public function fetch_user($userid)
  1441. {
  1442. // phpcs:enable
  1443. $user = new User($this->db);
  1444. $result = $user->fetch($userid);
  1445. $this->user = $user;
  1446. return $result;
  1447. }
  1448. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1449. /**
  1450. * Read linked origin object
  1451. *
  1452. * @return void
  1453. */
  1454. public function fetch_origin()
  1455. {
  1456. // phpcs:enable
  1457. if ($this->origin == 'shipping') $this->origin = 'expedition';
  1458. if ($this->origin == 'delivery') $this->origin = 'livraison';
  1459. if ($this->origin == 'order_supplier') $this->origin = 'commandeFournisseur';
  1460. $origin = $this->origin;
  1461. $classname = ucfirst($origin);
  1462. $this->$origin = new $classname($this->db);
  1463. $this->$origin->fetch($this->origin_id);
  1464. }
  1465. /**
  1466. * Load object from specific field
  1467. *
  1468. * @param string $table Table element or element line
  1469. * @param string $field Field selected
  1470. * @param string $key Import key
  1471. * @param string $element Element name
  1472. * @return int <0 if KO, >0 if OK
  1473. */
  1474. public function fetchObjectFrom($table, $field, $key, $element = null)
  1475. {
  1476. global $conf;
  1477. $result = false;
  1478. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$table;
  1479. $sql .= " WHERE ".$field." = '".$key."'";
  1480. if (!empty($element)) {
  1481. $sql .= " AND entity IN (".getEntity($element).")";
  1482. } else {
  1483. $sql .= " AND entity = ".$conf->entity;
  1484. }
  1485. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1486. $resql = $this->db->query($sql);
  1487. if ($resql)
  1488. {
  1489. $row = $this->db->fetch_row($resql);
  1490. // Test for avoid error -1
  1491. if ($row[0] > 0) {
  1492. $result = $this->fetch($row[0]);
  1493. }
  1494. }
  1495. return $result;
  1496. }
  1497. /**
  1498. * Getter generic. Load value from a specific field
  1499. *
  1500. * @param string $table Table of element or element line
  1501. * @param int $id Element id
  1502. * @param string $field Field selected
  1503. * @return int <0 if KO, >0 if OK
  1504. */
  1505. public function getValueFrom($table, $id, $field)
  1506. {
  1507. $result = false;
  1508. if (!empty($id) && !empty($field) && !empty($table)) {
  1509. $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table;
  1510. $sql .= " WHERE rowid = ".$id;
  1511. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1512. $resql = $this->db->query($sql);
  1513. if ($resql)
  1514. {
  1515. $row = $this->db->fetch_row($resql);
  1516. $result = $row[0];
  1517. }
  1518. }
  1519. return $result;
  1520. }
  1521. /**
  1522. * Setter generic. Update a specific field into database.
  1523. * Warning: Trigger is run only if param trigkey is provided.
  1524. *
  1525. * @param string $field Field to update
  1526. * @param mixed $value New value
  1527. * @param string $table To force other table element or element line (should not be used)
  1528. * @param int $id To force other object id (should not be used)
  1529. * @param string $format Data format ('text', 'date'). 'text' is used if not defined
  1530. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1531. * @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'
  1532. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1533. * @param string $fk_user_field Name of field to save user id making change
  1534. * @return int <0 if KO, >0 if OK
  1535. * @see updateExtraField()
  1536. */
  1537. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1538. {
  1539. global $user, $langs, $conf;
  1540. if (empty($table)) $table = $this->table_element;
  1541. if (empty($id)) $id = $this->id;
  1542. if (empty($format)) $format = 'text';
  1543. if (empty($id_field)) $id_field = 'rowid';
  1544. $error = 0;
  1545. $this->db->begin();
  1546. // Special case
  1547. if ($table == 'product' && $field == 'note_private') $field = 'note';
  1548. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) $fk_user_field = 'fk_user_mod';
  1549. $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
  1550. if ($format == 'text') $sql .= $field." = '".$this->db->escape($value)."'";
  1551. elseif ($format == 'int') $sql .= $field." = ".$this->db->escape($value);
  1552. elseif ($format == 'date') $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1553. if ($fk_user_field)
  1554. {
  1555. if (!empty($fuser) && is_object($fuser)) $sql .= ", ".$fk_user_field." = ".$fuser->id;
  1556. elseif (empty($fuser) || $fuser != 'none') $sql .= ", ".$fk_user_field." = ".$user->id;
  1557. }
  1558. $sql .= " WHERE ".$id_field." = ".$id;
  1559. dol_syslog(__METHOD__."", LOG_DEBUG);
  1560. $resql = $this->db->query($sql);
  1561. if ($resql)
  1562. {
  1563. if ($trigkey)
  1564. {
  1565. // call trigger with updated object values
  1566. if (empty($this->fields) && method_exists($this, 'fetch'))
  1567. {
  1568. $result = $this->fetch($id);
  1569. } else {
  1570. $result = $this->fetchCommon($id);
  1571. }
  1572. if ($result >= 0) $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1573. if ($result < 0) $error++;
  1574. }
  1575. if (!$error)
  1576. {
  1577. if (property_exists($this, $field)) $this->$field = $value;
  1578. $this->db->commit();
  1579. return 1;
  1580. } else {
  1581. $this->db->rollback();
  1582. return -2;
  1583. }
  1584. } else {
  1585. $this->error = $this->db->lasterror();
  1586. $this->db->rollback();
  1587. return -1;
  1588. }
  1589. }
  1590. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1591. /**
  1592. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1593. *
  1594. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')"
  1595. * @param string $fieldid Name of field to use for the select MAX and MIN
  1596. * @param int $nodbprefix Do not include DB prefix to forge table name
  1597. * @return int <0 if KO, >0 if OK
  1598. */
  1599. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1600. {
  1601. // phpcs:enable
  1602. global $conf, $user;
  1603. if (!$this->table_element)
  1604. {
  1605. dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1606. return -1;
  1607. }
  1608. if ($fieldid == 'none') return 1;
  1609. // Security on socid
  1610. $socid = 0;
  1611. if ($user->socid > 0) $socid = $user->socid;
  1612. // this->ismultientitymanaged contains
  1613. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1614. $aliastablesociete = 's';
  1615. if ($this->element == 'societe') $aliastablesociete = 'te'; // te as table_element
  1616. $sql = "SELECT MAX(te.".$fieldid.")";
  1617. $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1618. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1619. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  1620. }
  1621. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1622. $tmparray = explode('@', $this->ismultientitymanaged);
  1623. $sql .= ", ".MAIN_DB_PREFIX.$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1624. } elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid
  1625. elseif ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1626. if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1627. $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)
  1628. if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id;
  1629. if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)';
  1630. if (!empty($filter))
  1631. {
  1632. if (!preg_match('/^\s*AND/i', $filter)) $sql .= " AND "; // For backward compatibility
  1633. $sql .= $filter;
  1634. }
  1635. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1636. $tmparray = explode('@', $this->ismultientitymanaged);
  1637. $sql .= ' AND te.'.$tmparray[0].' = '.($tmparray[1] == 'societe' ? 's' : 'parenttable').'.rowid'; // If we need to link to this table to limit select to entity
  1638. } elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1639. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1640. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1641. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1642. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1643. } else {
  1644. $sql .= " AND ug.fk_user = te.rowid";
  1645. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1646. }
  1647. } else {
  1648. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1649. }
  1650. }
  1651. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1652. $tmparray = explode('@', $this->ismultientitymanaged);
  1653. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1654. }
  1655. if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql .= ' AND te.fk_soc = '.$socid;
  1656. if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql .= ' AND (te.fk_soc = '.$socid.' OR te.fk_soc IS NULL)';
  1657. if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql .= ' AND te.rowid = '.$socid;
  1658. //print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1659. $result = $this->db->query($sql);
  1660. if (!$result)
  1661. {
  1662. $this->error = $this->db->lasterror();
  1663. return -1;
  1664. }
  1665. $row = $this->db->fetch_row($result);
  1666. $this->ref_previous = $row[0];
  1667. $sql = "SELECT MIN(te.".$fieldid.")";
  1668. $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1669. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1670. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  1671. }
  1672. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1673. $tmparray = explode('@', $this->ismultientitymanaged);
  1674. $sql .= ", ".MAIN_DB_PREFIX.$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1675. } elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid
  1676. elseif ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1677. if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1678. $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)
  1679. if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id;
  1680. if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)';
  1681. if (!empty($filter))
  1682. {
  1683. if (!preg_match('/^\s*AND/i', $filter)) $sql .= " AND "; // For backward compatibility
  1684. $sql .= $filter;
  1685. }
  1686. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1687. $tmparray = explode('@', $this->ismultientitymanaged);
  1688. $sql .= ' AND te.'.$tmparray[0].' = '.($tmparray[1] == 'societe' ? 's' : 'parenttable').'.rowid'; // If we need to link to this table to limit select to entity
  1689. } elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1690. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1691. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1692. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1693. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1694. } else {
  1695. $sql .= " AND ug.fk_user = te.rowid";
  1696. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1697. }
  1698. } else {
  1699. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1700. }
  1701. }
  1702. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1703. $tmparray = explode('@', $this->ismultientitymanaged);
  1704. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1705. }
  1706. if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql .= ' AND te.fk_soc = '.$socid;
  1707. if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql .= ' AND (te.fk_soc = '.$socid.' OR te.fk_soc IS NULL)';
  1708. if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql .= ' AND te.rowid = '.$socid;
  1709. //print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1710. // 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
  1711. $result = $this->db->query($sql);
  1712. if (!$result)
  1713. {
  1714. $this->error = $this->db->lasterror();
  1715. return -2;
  1716. }
  1717. $row = $this->db->fetch_row($result);
  1718. $this->ref_next = $row[0];
  1719. return 1;
  1720. }
  1721. /**
  1722. * Return list of id of contacts of object
  1723. *
  1724. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  1725. * @return array Array of id of contacts (if source=external or internal)
  1726. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  1727. */
  1728. public function getListContactId($source = 'external')
  1729. {
  1730. $contactAlreadySelected = array();
  1731. $tab = $this->liste_contact(-1, $source);
  1732. $num = count($tab);
  1733. $i = 0;
  1734. while ($i < $num)
  1735. {
  1736. if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid'];
  1737. else $contactAlreadySelected[$i] = $tab[$i]['id'];
  1738. $i++;
  1739. }
  1740. return $contactAlreadySelected;
  1741. }
  1742. /**
  1743. * Link element with a project
  1744. *
  1745. * @param int $projectid Project id to link element to
  1746. * @return int <0 if KO, >0 if OK
  1747. */
  1748. public function setProject($projectid)
  1749. {
  1750. if (!$this->table_element)
  1751. {
  1752. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  1753. return -1;
  1754. }
  1755. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1756. if (!empty($this->fields['fk_project'])) // Common case
  1757. {
  1758. if ($projectid) $sql .= ' SET fk_project = '.$projectid;
  1759. else $sql .= ' SET fk_project = NULL';
  1760. $sql .= ' WHERE rowid = '.$this->id;
  1761. } elseif ($this->table_element == 'actioncomm') // Special case for actioncomm
  1762. {
  1763. if ($projectid) $sql .= ' SET fk_project = '.$projectid;
  1764. else $sql .= ' SET fk_project = NULL';
  1765. $sql .= ' WHERE id = '.$this->id;
  1766. } else // Special case for old architecture objects
  1767. {
  1768. if ($projectid) $sql .= ' SET fk_projet = '.$projectid;
  1769. else $sql .= ' SET fk_projet = NULL';
  1770. $sql .= ' WHERE rowid = '.$this->id;
  1771. }
  1772. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  1773. if ($this->db->query($sql))
  1774. {
  1775. $this->fk_project = $projectid;
  1776. return 1;
  1777. } else {
  1778. dol_print_error($this->db);
  1779. return -1;
  1780. }
  1781. }
  1782. /**
  1783. * Change the payments methods
  1784. *
  1785. * @param int $id Id of new payment method
  1786. * @return int >0 if OK, <0 if KO
  1787. */
  1788. public function setPaymentMethods($id)
  1789. {
  1790. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  1791. if ($this->statut >= 0 || $this->element == 'societe')
  1792. {
  1793. // TODO uniformize field name
  1794. $fieldname = 'fk_mode_reglement';
  1795. if ($this->element == 'societe') $fieldname = 'mode_reglement';
  1796. if (get_class($this) == 'Fournisseur') $fieldname = 'mode_reglement_supplier';
  1797. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1798. $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL');
  1799. $sql .= ' WHERE rowid='.$this->id;
  1800. if ($this->db->query($sql))
  1801. {
  1802. $this->mode_reglement_id = $id;
  1803. // for supplier
  1804. if (get_class($this) == 'Fournisseur') $this->mode_reglement_supplier_id = $id;
  1805. return 1;
  1806. } else {
  1807. dol_syslog(get_class($this).'::setPaymentMethods Error '.$sql.' - '.$this->db->error());
  1808. $this->error = $this->db->error();
  1809. return -1;
  1810. }
  1811. } else {
  1812. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  1813. $this->error = 'Status of the object is incompatible '.$this->statut;
  1814. return -2;
  1815. }
  1816. }
  1817. /**
  1818. * Change the multicurrency code
  1819. *
  1820. * @param string $code multicurrency code
  1821. * @return int >0 if OK, <0 if KO
  1822. */
  1823. public function setMulticurrencyCode($code)
  1824. {
  1825. dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
  1826. if ($this->statut >= 0 || $this->element == 'societe')
  1827. {
  1828. $fieldname = 'multicurrency_code';
  1829. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1830. $sql .= ' SET '.$fieldname." = '".$this->db->escape($code)."'";
  1831. $sql .= ' WHERE rowid='.$this->id;
  1832. if ($this->db->query($sql))
  1833. {
  1834. $this->multicurrency_code = $code;
  1835. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  1836. if ($rate) $this->setMulticurrencyRate($rate, 2);
  1837. return 1;
  1838. } else {
  1839. dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
  1840. $this->error = $this->db->error();
  1841. return -1;
  1842. }
  1843. } else {
  1844. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  1845. $this->error = 'Status of the object is incompatible '.$this->statut;
  1846. return -2;
  1847. }
  1848. }
  1849. /**
  1850. * Change the multicurrency rate
  1851. *
  1852. * @param double $rate multicurrency rate
  1853. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  1854. * @return int >0 if OK, <0 if KO
  1855. */
  1856. public function setMulticurrencyRate($rate, $mode = 1)
  1857. {
  1858. dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
  1859. if ($this->statut >= 0 || $this->element == 'societe')
  1860. {
  1861. $fieldname = 'multicurrency_tx';
  1862. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1863. $sql .= ' SET '.$fieldname.' = '.$rate;
  1864. $sql .= ' WHERE rowid='.$this->id;
  1865. if ($this->db->query($sql))
  1866. {
  1867. $this->multicurrency_tx = $rate;
  1868. // Update line price
  1869. if (!empty($this->lines))
  1870. {
  1871. foreach ($this->lines as &$line)
  1872. {
  1873. // Amounts in company currency will be recalculated
  1874. if ($mode == 1) {
  1875. $line->subprice = 0;
  1876. }
  1877. // Amounts in foreign currency will be recalculated
  1878. if ($mode == 2) {
  1879. $line->multicurrency_subprice = 0;
  1880. }
  1881. switch ($this->element) {
  1882. case 'propal':
  1883. $this->updateline(
  1884. $line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx,
  1885. ($line->description ? $line->description : $line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line,
  1886. $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->date_start,
  1887. $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
  1888. );
  1889. break;
  1890. case 'commande':
  1891. $this->updateline(
  1892. $line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->qty, $line->remise_percent,
  1893. $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->date_start, $line->date_end,
  1894. $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label,
  1895. $line->special_code, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
  1896. );
  1897. break;
  1898. case 'facture':
  1899. $this->updateline(
  1900. $line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->qty, $line->remise_percent,
  1901. $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits,
  1902. $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label,
  1903. $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice
  1904. );
  1905. break;
  1906. case 'supplier_proposal':
  1907. $this->updateline(
  1908. $line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx,
  1909. ($line->description ? $line->description : $line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line,
  1910. $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->array_options,
  1911. $line->ref_fourn, $line->multicurrency_subprice
  1912. );
  1913. break;
  1914. case 'order_supplier':
  1915. $this->updateline(
  1916. $line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->qty, $line->remise_percent,
  1917. $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, false,
  1918. $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
  1919. );
  1920. break;
  1921. case 'invoice_supplier':
  1922. $this->updateline(
  1923. $line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->tva_tx, $line->localtax1_tx,
  1924. $line->localtax2_tx, $line->qty, 0, 'HT', $line->info_bits, $line->product_type, $line->remise_percent, false,
  1925. $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
  1926. );
  1927. break;
  1928. default:
  1929. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  1930. break;
  1931. }
  1932. }
  1933. }
  1934. return 1;
  1935. } else {
  1936. dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
  1937. $this->error = $this->db->error();
  1938. return -1;
  1939. }
  1940. } else {
  1941. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  1942. $this->error = 'Status of the object is incompatible '.$this->statut;
  1943. return -2;
  1944. }
  1945. }
  1946. /**
  1947. * Change the payments terms
  1948. *
  1949. * @param int $id Id of new payment terms
  1950. * @return int >0 if OK, <0 if KO
  1951. */
  1952. public function setPaymentTerms($id)
  1953. {
  1954. dol_syslog(get_class($this).'::setPaymentTerms('.$id.')');
  1955. if ($this->statut >= 0 || $this->element == 'societe')
  1956. {
  1957. // TODO uniformize field name
  1958. $fieldname = 'fk_cond_reglement';
  1959. if ($this->element == 'societe') $fieldname = 'cond_reglement';
  1960. if (get_class($this) == 'Fournisseur') $fieldname = 'cond_reglement_supplier';
  1961. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1962. $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL');
  1963. $sql .= ' WHERE rowid='.$this->id;
  1964. if ($this->db->query($sql))
  1965. {
  1966. $this->cond_reglement_id = $id;
  1967. // for supplier
  1968. if (get_class($this) == 'Fournisseur') $this->cond_reglement_supplier_id = $id;
  1969. $this->cond_reglement = $id; // for compatibility
  1970. return 1;
  1971. } else {
  1972. dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
  1973. $this->error = $this->db->error();
  1974. return -1;
  1975. }
  1976. } else {
  1977. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  1978. $this->error = 'Status of the object is incompatible '.$this->statut;
  1979. return -2;
  1980. }
  1981. }
  1982. /**
  1983. * Change the transport mode methods
  1984. *
  1985. * @param int $id Id of new payment method
  1986. * @return int >0 if OK, <0 if KO
  1987. */
  1988. public function setTransportMode($id)
  1989. {
  1990. dol_syslog(get_class($this).'::setTransportMode('.$id.')');
  1991. if ($this->statut >= 0 || $this->element == 'societe')
  1992. {
  1993. $fieldname = 'fk_transport_mode';
  1994. if ($this->element == 'societe') $fieldname = 'transport_mode';
  1995. if (get_class($this) == 'Fournisseur') $fieldname = 'transport_mode_supplier';
  1996. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1997. $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL');
  1998. $sql .= ' WHERE rowid='.$this->id;
  1999. if ($this->db->query($sql))
  2000. {
  2001. $this->transport_mode_id = $id;
  2002. // for supplier
  2003. if (get_class($this) == 'Fournisseur') $this->transport_mode_supplier_id = $id;
  2004. return 1;
  2005. } else {
  2006. dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
  2007. $this->error = $this->db->error();
  2008. return -1;
  2009. }
  2010. } else {
  2011. dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
  2012. $this->error = 'Status of the object is incompatible '.$this->statut;
  2013. return -2;
  2014. }
  2015. }
  2016. /**
  2017. * Change the retained warranty payments terms
  2018. *
  2019. * @param int $id Id of new payment terms
  2020. * @return int >0 if OK, <0 if KO
  2021. */
  2022. public function setRetainedWarrantyPaymentTerms($id)
  2023. {
  2024. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
  2025. if ($this->statut >= 0 || $this->element == 'societe')
  2026. {
  2027. $fieldname = 'retained_warranty_fk_cond_reglement';
  2028. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2029. $sql .= ' SET '.$fieldname.' = '.$id;
  2030. $sql .= ' WHERE rowid='.$this->id;
  2031. if ($this->db->query($sql))
  2032. {
  2033. $this->retained_warranty_fk_cond_reglement = $id;
  2034. return 1;
  2035. } else {
  2036. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
  2037. $this->error = $this->db->error();
  2038. return -1;
  2039. }
  2040. } else {
  2041. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  2042. $this->error = 'Status of the object is incompatible '.$this->statut;
  2043. return -2;
  2044. }
  2045. }
  2046. /**
  2047. * Define delivery address
  2048. * @deprecated
  2049. *
  2050. * @param int $id Address id
  2051. * @return int <0 si ko, >0 si ok
  2052. */
  2053. public function setDeliveryAddress($id)
  2054. {
  2055. $fieldname = 'fk_delivery_address';
  2056. if ($this->element == 'delivery' || $this->element == 'shipping') $fieldname = 'fk_address';
  2057. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".$id;
  2058. $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0";
  2059. if ($this->db->query($sql))
  2060. {
  2061. $this->fk_delivery_address = $id;
  2062. return 1;
  2063. } else {
  2064. $this->error = $this->db->error();
  2065. dol_syslog(get_class($this).'::setDeliveryAddress Error '.$sql.' - '.$this->error);
  2066. return -1;
  2067. }
  2068. }
  2069. /**
  2070. * Change the shipping method
  2071. *
  2072. * @param int $shipping_method_id Id of shipping method
  2073. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2074. * @param User $userused Object user
  2075. *
  2076. * @return int 1 if OK, 0 if KO
  2077. */
  2078. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  2079. {
  2080. global $user;
  2081. if (empty($userused)) $userused = $user;
  2082. $error = 0;
  2083. if (!$this->table_element) {
  2084. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2085. return -1;
  2086. }
  2087. $this->db->begin();
  2088. if ($shipping_method_id < 0) $shipping_method_id = 'NULL';
  2089. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  2090. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2091. $sql .= " SET fk_shipping_method = ".$shipping_method_id;
  2092. $sql .= " WHERE rowid=".$this->id;
  2093. $resql = $this->db->query($sql);
  2094. if (!$resql) {
  2095. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  2096. $this->error = $this->db->lasterror();
  2097. $error++;
  2098. } else {
  2099. if (!$notrigger)
  2100. {
  2101. // Call trigger
  2102. $this->context = array('shippingmethodupdate'=>1);
  2103. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2104. if ($result < 0) $error++;
  2105. // End call trigger
  2106. }
  2107. }
  2108. if ($error)
  2109. {
  2110. $this->db->rollback();
  2111. return -1;
  2112. } else {
  2113. $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
  2114. $this->db->commit();
  2115. return 1;
  2116. }
  2117. }
  2118. /**
  2119. * Change the warehouse
  2120. *
  2121. * @param int $warehouse_id Id of warehouse
  2122. * @return int 1 if OK, 0 if KO
  2123. */
  2124. public function setWarehouse($warehouse_id)
  2125. {
  2126. if (!$this->table_element) {
  2127. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2128. return -1;
  2129. }
  2130. if ($warehouse_id < 0) $warehouse_id = 'NULL';
  2131. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  2132. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2133. $sql .= " SET fk_warehouse = ".$warehouse_id;
  2134. $sql .= " WHERE rowid=".$this->id;
  2135. if ($this->db->query($sql)) {
  2136. $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
  2137. return 1;
  2138. } else {
  2139. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  2140. $this->error = $this->db->error();
  2141. return 0;
  2142. }
  2143. }
  2144. /**
  2145. * Set last model used by doc generator
  2146. *
  2147. * @param User $user User object that make change
  2148. * @param string $modelpdf Modele name
  2149. * @return int <0 if KO, >0 if OK
  2150. */
  2151. public function setDocModel($user, $modelpdf)
  2152. {
  2153. if (!$this->table_element)
  2154. {
  2155. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2156. return -1;
  2157. }
  2158. $newmodelpdf = dol_trunc($modelpdf, 255);
  2159. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2160. $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  2161. $sql .= " WHERE rowid = ".$this->id;
  2162. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  2163. $resql = $this->db->query($sql);
  2164. if ($resql)
  2165. {
  2166. $this->model_pdf = $modelpdf;
  2167. $this->modelpdf = $modelpdf; // For bakward compatibility
  2168. return 1;
  2169. } else {
  2170. dol_print_error($this->db);
  2171. return 0;
  2172. }
  2173. }
  2174. /**
  2175. * Change the bank account
  2176. *
  2177. * @param int $fk_account Id of bank account
  2178. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2179. * @param User $userused Object user
  2180. * @return int 1 if OK, 0 if KO
  2181. */
  2182. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2183. {
  2184. global $user;
  2185. if (empty($userused)) $userused = $user;
  2186. $error = 0;
  2187. if (!$this->table_element) {
  2188. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2189. return -1;
  2190. }
  2191. $this->db->begin();
  2192. if ($fk_account < 0) $fk_account = 'NULL';
  2193. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  2194. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2195. $sql .= " SET fk_account = ".$fk_account;
  2196. $sql .= " WHERE rowid=".$this->id;
  2197. $resql = $this->db->query($sql);
  2198. if (!$resql)
  2199. {
  2200. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  2201. $this->error = $this->db->lasterror();
  2202. $error++;
  2203. } else {
  2204. if (!$notrigger)
  2205. {
  2206. // Call trigger
  2207. $this->context = array('bankaccountupdate'=>1);
  2208. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2209. if ($result < 0) $error++;
  2210. // End call trigger
  2211. }
  2212. }
  2213. if ($error)
  2214. {
  2215. $this->db->rollback();
  2216. return -1;
  2217. } else {
  2218. $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
  2219. $this->db->commit();
  2220. return 1;
  2221. }
  2222. }
  2223. // TODO: Move line related operations to CommonObjectLine?
  2224. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2225. /**
  2226. * Save a new position (field rang) for details lines.
  2227. * You can choose to set position for lines with already a position or lines without any position defined.
  2228. *
  2229. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2230. * @param string $rowidorder ASC or DESC
  2231. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2232. * @return int <0 if KO, >0 if OK
  2233. */
  2234. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2235. {
  2236. // phpcs:enable
  2237. if (!$this->table_element_line)
  2238. {
  2239. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2240. return -1;
  2241. }
  2242. if (!$this->fk_element)
  2243. {
  2244. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2245. return -1;
  2246. }
  2247. // Count number of lines to reorder (according to choice $renum)
  2248. $nl = 0;
  2249. $sql = 'SELECT count(rowid) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2250. $sql .= ' WHERE '.$this->fk_element.'='.$this->id;
  2251. if (!$renum) $sql .= ' AND rang = 0';
  2252. if ($renum) $sql .= ' AND rang <> 0';
  2253. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  2254. $resql = $this->db->query($sql);
  2255. if ($resql)
  2256. {
  2257. $row = $this->db->fetch_row($resql);
  2258. $nl = $row[0];
  2259. } else dol_print_error($this->db);
  2260. if ($nl > 0)
  2261. {
  2262. // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
  2263. $rows = array();
  2264. // We first search all lines that are parent lines (for multilevel details lines)
  2265. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2266. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2267. if ($fk_parent_line) $sql .= ' AND fk_parent_line IS NULL';
  2268. $sql .= ' ORDER BY rang ASC, rowid '.$rowidorder;
  2269. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  2270. $resql = $this->db->query($sql);
  2271. if ($resql)
  2272. {
  2273. $i = 0;
  2274. $num = $this->db->num_rows($resql);
  2275. while ($i < $num)
  2276. {
  2277. $row = $this->db->fetch_row($resql);
  2278. $rows[] = $row[0]; // Add parent line into array rows
  2279. $childrens = $this->getChildrenOfLine($row[0]);
  2280. if (!empty($childrens))
  2281. {
  2282. foreach ($childrens as $child)
  2283. {
  2284. array_push($rows, $child);
  2285. }
  2286. }
  2287. $i++;
  2288. }
  2289. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2290. if (!empty($rows))
  2291. {
  2292. foreach ($rows as $key => $row)
  2293. {
  2294. $this->updateRangOfLine($row, ($key + 1));
  2295. }
  2296. }
  2297. } else {
  2298. dol_print_error($this->db);
  2299. }
  2300. }
  2301. return 1;
  2302. }
  2303. /**
  2304. * Get children of line
  2305. *
  2306. * @param int $id Id of parent line
  2307. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2308. * @return array Array with list of children lines id
  2309. */
  2310. public function getChildrenOfLine($id, $includealltree = 0)
  2311. {
  2312. $rows = array();
  2313. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2314. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2315. $sql .= ' AND fk_parent_line = '.$id;
  2316. $sql .= ' ORDER BY rang ASC';
  2317. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id."", LOG_DEBUG);
  2318. $resql = $this->db->query($sql);
  2319. if ($resql)
  2320. {
  2321. if ($this->db->num_rows($resql) > 0) {
  2322. while ($row = $this->db->fetch_row($resql)) {
  2323. $rows[] = $row[0];
  2324. if (!empty($includealltree)) $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2325. }
  2326. }
  2327. }
  2328. return $rows;
  2329. }
  2330. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2331. /**
  2332. * Update a line to have a lower rank
  2333. *
  2334. * @param int $rowid Id of line
  2335. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2336. * @return void
  2337. */
  2338. public function line_up($rowid, $fk_parent_line = true)
  2339. {
  2340. // phpcs:enable
  2341. $this->line_order(false, 'ASC', $fk_parent_line);
  2342. // Get rang of line
  2343. $rang = $this->getRangOfLine($rowid);
  2344. // Update position of line
  2345. $this->updateLineUp($rowid, $rang);
  2346. }
  2347. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2348. /**
  2349. * Update a line to have a higher rank
  2350. *
  2351. * @param int $rowid Id of line
  2352. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2353. * @return void
  2354. */
  2355. public function line_down($rowid, $fk_parent_line = true)
  2356. {
  2357. // phpcs:enable
  2358. $this->line_order(false, 'ASC', $fk_parent_line);
  2359. // Get rang of line
  2360. $rang = $this->getRangOfLine($rowid);
  2361. // Get max value for rang
  2362. $max = $this->line_max();
  2363. // Update position of line
  2364. $this->updateLineDown($rowid, $rang, $max);
  2365. }
  2366. /**
  2367. * Update position of line (rang)
  2368. *
  2369. * @param int $rowid Id of line
  2370. * @param int $rang Position
  2371. * @return void
  2372. */
  2373. public function updateRangOfLine($rowid, $rang)
  2374. {
  2375. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2376. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
  2377. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang;
  2378. $sql .= ' WHERE rowid = '.$rowid;
  2379. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2380. if (!$this->db->query($sql))
  2381. {
  2382. dol_print_error($this->db);
  2383. }
  2384. }
  2385. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2386. /**
  2387. * Update position of line with ajax (rang)
  2388. *
  2389. * @param array $rows Array of rows
  2390. * @return void
  2391. */
  2392. public function line_ajaxorder($rows)
  2393. {
  2394. // phpcs:enable
  2395. $num = count($rows);
  2396. for ($i = 0; $i < $num; $i++)
  2397. {
  2398. $this->updateRangOfLine($rows[$i], ($i + 1));
  2399. }
  2400. }
  2401. /**
  2402. * Update position of line up (rang)
  2403. *
  2404. * @param int $rowid Id of line
  2405. * @param int $rang Position
  2406. * @return void
  2407. */
  2408. public function updateLineUp($rowid, $rang)
  2409. {
  2410. if ($rang > 1)
  2411. {
  2412. $fieldposition = 'rang';
  2413. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
  2414. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang;
  2415. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2416. $sql .= ' AND rang = '.($rang - 1);
  2417. if ($this->db->query($sql))
  2418. {
  2419. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.($rang - 1);
  2420. $sql .= ' WHERE rowid = '.$rowid;
  2421. if (!$this->db->query($sql))
  2422. {
  2423. dol_print_error($this->db);
  2424. }
  2425. } else {
  2426. dol_print_error($this->db);
  2427. }
  2428. }
  2429. }
  2430. /**
  2431. * Update position of line down (rang)
  2432. *
  2433. * @param int $rowid Id of line
  2434. * @param int $rang Position
  2435. * @param int $max Max
  2436. * @return void
  2437. */
  2438. public function updateLineDown($rowid, $rang, $max)
  2439. {
  2440. if ($rang < $max)
  2441. {
  2442. $fieldposition = 'rang';
  2443. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
  2444. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang;
  2445. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2446. $sql .= ' AND rang = '.($rang + 1);
  2447. if ($this->db->query($sql))
  2448. {
  2449. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.($rang + 1);
  2450. $sql .= ' WHERE rowid = '.$rowid;
  2451. if (!$this->db->query($sql))
  2452. {
  2453. dol_print_error($this->db);
  2454. }
  2455. } else {
  2456. dol_print_error($this->db);
  2457. }
  2458. }
  2459. }
  2460. /**
  2461. * Get position of line (rang)
  2462. *
  2463. * @param int $rowid Id of line
  2464. * @return int Value of rang in table of lines
  2465. */
  2466. public function getRangOfLine($rowid)
  2467. {
  2468. $sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2469. $sql .= ' WHERE rowid ='.$rowid;
  2470. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  2471. $resql = $this->db->query($sql);
  2472. if ($resql)
  2473. {
  2474. $row = $this->db->fetch_row($resql);
  2475. return $row[0];
  2476. }
  2477. }
  2478. /**
  2479. * Get rowid of the line relative to its position
  2480. *
  2481. * @param int $rang Rang value
  2482. * @return int Rowid of the line
  2483. */
  2484. public function getIdOfLine($rang)
  2485. {
  2486. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2487. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2488. $sql .= ' AND rang = '.$rang;
  2489. $resql = $this->db->query($sql);
  2490. if ($resql)
  2491. {
  2492. $row = $this->db->fetch_row($resql);
  2493. return $row[0];
  2494. }
  2495. }
  2496. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2497. /**
  2498. * Get max value used for position of line (rang)
  2499. *
  2500. * @param int $fk_parent_line Parent line id
  2501. * @return int Max value of rang in table of lines
  2502. */
  2503. public function line_max($fk_parent_line = 0)
  2504. {
  2505. // phpcs:enable
  2506. $positionfield = 'rang';
  2507. if ($this->table_element == 'bom_bom') $positionfield = 'position';
  2508. // Search the last rang with fk_parent_line
  2509. if ($fk_parent_line)
  2510. {
  2511. $sql = 'SELECT max('.$positionfield.') FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2512. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2513. $sql .= ' AND fk_parent_line = '.$fk_parent_line;
  2514. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2515. $resql = $this->db->query($sql);
  2516. if ($resql)
  2517. {
  2518. $row = $this->db->fetch_row($resql);
  2519. if (!empty($row[0]))
  2520. {
  2521. return $row[0];
  2522. } else {
  2523. return $this->getRangOfLine($fk_parent_line);
  2524. }
  2525. }
  2526. }
  2527. // If not, search the last rang of element
  2528. else {
  2529. $sql = 'SELECT max('.$positionfield.') FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2530. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2531. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2532. $resql = $this->db->query($sql);
  2533. if ($resql)
  2534. {
  2535. $row = $this->db->fetch_row($resql);
  2536. return $row[0];
  2537. }
  2538. }
  2539. }
  2540. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2541. /**
  2542. * Update external ref of element
  2543. *
  2544. * @param string $ref_ext Update field ref_ext
  2545. * @return int <0 if KO, >0 if OK
  2546. */
  2547. public function update_ref_ext($ref_ext)
  2548. {
  2549. // phpcs:enable
  2550. if (!$this->table_element)
  2551. {
  2552. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  2553. return -1;
  2554. }
  2555. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2556. $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  2557. $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".$this->id;
  2558. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  2559. if ($this->db->query($sql))
  2560. {
  2561. $this->ref_ext = $ref_ext;
  2562. return 1;
  2563. } else {
  2564. $this->error = $this->db->error();
  2565. return -1;
  2566. }
  2567. }
  2568. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2569. /**
  2570. * Update note of element
  2571. *
  2572. * @param string $note New value for note
  2573. * @param string $suffix '', '_public' or '_private'
  2574. * @return int <0 if KO, >0 if OK
  2575. */
  2576. public function update_note($note, $suffix = '')
  2577. {
  2578. // phpcs:enable
  2579. global $user;
  2580. if (!$this->table_element)
  2581. {
  2582. $this->error = 'update_note was called on objet with property table_element not defined';
  2583. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  2584. return -1;
  2585. }
  2586. if (!in_array($suffix, array('', '_public', '_private')))
  2587. {
  2588. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  2589. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  2590. return -2;
  2591. }
  2592. $newsuffix = $suffix;
  2593. // Special cas
  2594. if ($this->table_element == 'product' && $newsuffix == '_private') $newsuffix = '';
  2595. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2596. $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
  2597. $sql .= " ,".(in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment')) ? "fk_user_mod" : "fk_user_modif")." = ".$user->id;
  2598. $sql .= " WHERE rowid =".$this->id;
  2599. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  2600. if ($this->db->query($sql))
  2601. {
  2602. if ($suffix == '_public') $this->note_public = $note;
  2603. elseif ($suffix == '_private') $this->note_private = $note;
  2604. else {
  2605. $this->note = $note; // deprecated
  2606. $this->note_private = $note;
  2607. }
  2608. return 1;
  2609. } else {
  2610. $this->error = $this->db->lasterror();
  2611. return -1;
  2612. }
  2613. }
  2614. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2615. /**
  2616. * Update public note (kept for backward compatibility)
  2617. *
  2618. * @param string $note New value for note
  2619. * @return int <0 if KO, >0 if OK
  2620. * @deprecated
  2621. * @see update_note()
  2622. */
  2623. public function update_note_public($note)
  2624. {
  2625. // phpcs:enable
  2626. return $this->update_note($note, '_public');
  2627. }
  2628. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2629. /**
  2630. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  2631. * Must be called at end of methods addline or updateline.
  2632. *
  2633. * @param int $exclspec >0 = Exclude special product (product_type=9)
  2634. * @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
  2635. * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object.
  2636. * @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.
  2637. * @return int <0 if KO, >0 if OK
  2638. */
  2639. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  2640. {
  2641. // phpcs:enable
  2642. global $conf, $hookmanager, $action;
  2643. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  2644. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  2645. if ($reshook > 0) {
  2646. return 1; // replacement code
  2647. } elseif ($reshook < 0) {
  2648. return -1; // failure
  2649. } // reshook = 0 => execute normal code
  2650. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  2651. $MODULE = "";
  2652. if ($this->element == 'propal')
  2653. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  2654. elseif ($this->element == 'commande' || $this->element == 'order')
  2655. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  2656. elseif ($this->element == 'facture' || $this->element == 'invoice')
  2657. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  2658. elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier')
  2659. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  2660. elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order')
  2661. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  2662. elseif ($this->element == 'supplier_proposal')
  2663. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  2664. if (!empty($MODULE)) {
  2665. if (!empty($conf->global->$MODULE)) {
  2666. $modsactivated = explode(',', $conf->global->$MODULE);
  2667. foreach ($modsactivated as $mod) {
  2668. if ($conf->$mod->enabled)
  2669. return 1; // update was disabled by specific setup
  2670. }
  2671. }
  2672. }
  2673. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  2674. if ($roundingadjust == '-1') $roundingadjust = 'auto'; // For backward compatibility
  2675. $forcedroundingmode = $roundingadjust;
  2676. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) $forcedroundingmode = $conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
  2677. elseif ($forcedroundingmode == 'auto') $forcedroundingmode = '0';
  2678. $error = 0;
  2679. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  2680. // Define constants to find lines to sum
  2681. $fieldtva = 'total_tva';
  2682. $fieldlocaltax1 = 'total_localtax1';
  2683. $fieldlocaltax2 = 'total_localtax2';
  2684. $fieldup = 'subprice';
  2685. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
  2686. {
  2687. $fieldtva = 'tva';
  2688. $fieldup = 'pu_ht';
  2689. }
  2690. if ($this->element == 'expensereport')
  2691. {
  2692. $fieldup = 'value_unit';
  2693. }
  2694. $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,';
  2695. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  2696. if ($this->table_element_line == 'facturedet') $sql .= ', situation_percent';
  2697. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  2698. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2699. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2700. if ($exclspec)
  2701. {
  2702. $product_field = 'product_type';
  2703. if ($this->table_element_line == 'contratdet') $product_field = ''; // contratdet table has no product_type field
  2704. if ($product_field) $sql .= ' AND '.$product_field.' <> 9';
  2705. }
  2706. $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
  2707. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  2708. $resql = $this->db->query($sql);
  2709. if ($resql)
  2710. {
  2711. $this->total_ht = 0;
  2712. $this->total_tva = 0;
  2713. $this->total_localtax1 = 0;
  2714. $this->total_localtax2 = 0;
  2715. $this->total_ttc = 0;
  2716. $total_ht_by_vats = array();
  2717. $total_tva_by_vats = array();
  2718. $total_ttc_by_vats = array();
  2719. $this->multicurrency_total_ht = 0;
  2720. $this->multicurrency_total_tva = 0;
  2721. $this->multicurrency_total_ttc = 0;
  2722. $num = $this->db->num_rows($resql);
  2723. $i = 0;
  2724. while ($i < $num)
  2725. {
  2726. $obj = $this->db->fetch_object($resql);
  2727. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  2728. $parameters = array('fk_element' => $obj->rowid);
  2729. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  2730. 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'
  2731. {
  2732. // This part of code is to fix data. We should not call it too often.
  2733. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  2734. $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);
  2735. $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.
  2736. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  2737. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
  2738. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  2739. if ($diff_when_using_price_ht && $diff_on_current_total)
  2740. {
  2741. $sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
  2742. 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);
  2743. $resqlfix = $this->db->query($sqlfix);
  2744. if (!$resqlfix) dol_print_error($this->db, 'Failed to update line');
  2745. $obj->total_tva = $tmpcal[1];
  2746. $obj->total_ttc = $tmpcal[2];
  2747. }
  2748. }
  2749. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  2750. $this->total_tva += $obj->total_tva;
  2751. $this->total_localtax1 += $obj->total_localtax1;
  2752. $this->total_localtax2 += $obj->total_localtax2;
  2753. $this->total_ttc += $obj->total_ttc;
  2754. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  2755. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  2756. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  2757. if (!isset($total_ht_by_vats[$obj->vatrate])) $total_ht_by_vats[$obj->vatrate] = 0;
  2758. if (!isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate] = 0;
  2759. if (!isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate] = 0;
  2760. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  2761. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  2762. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  2763. if ($forcedroundingmode == '1') // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  2764. {
  2765. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  2766. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  2767. //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";
  2768. if ($diff)
  2769. {
  2770. if (abs($diff) > 0.1) {
  2771. $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.';
  2772. dol_syslog($errmsg, LOG_WARNING);
  2773. dol_print_error('', $errmsg);
  2774. exit;
  2775. }
  2776. $sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".($obj->total_tva - $diff).", total_ttc = ".($obj->total_ttc - $diff)." WHERE rowid = ".$obj->rowid;
  2777. 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);
  2778. $resqlfix = $this->db->query($sqlfix);
  2779. if (!$resqlfix) dol_print_error($this->db, 'Failed to update line');
  2780. $this->total_tva -= $diff;
  2781. $this->total_ttc -= $diff;
  2782. $total_tva_by_vats[$obj->vatrate] -= $diff;
  2783. $total_ttc_by_vats[$obj->vatrate] -= $diff;
  2784. }
  2785. }
  2786. $i++;
  2787. }
  2788. // Add revenue stamp to total
  2789. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  2790. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  2791. // Situations totals
  2792. if ($this->situation_cycle_ref && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE)
  2793. {
  2794. $prev_sits = $this->get_prev_sits();
  2795. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  2796. $this->total_ht -= $sit->total_ht;
  2797. $this->total_tva -= $sit->total_tva;
  2798. $this->total_localtax1 -= $sit->total_localtax1;
  2799. $this->total_localtax2 -= $sit->total_localtax2;
  2800. $this->total_ttc -= $sit->total_ttc;
  2801. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  2802. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  2803. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  2804. }
  2805. }
  2806. $this->db->free($resql);
  2807. // Now update global field total_ht, total_ttc and tva
  2808. $fieldht = 'total_ht';
  2809. $fieldtva = 'tva';
  2810. $fieldlocaltax1 = 'localtax1';
  2811. $fieldlocaltax2 = 'localtax2';
  2812. $fieldttc = 'total_ttc';
  2813. // Specific code for backward compatibility with old field names
  2814. if ($this->element == 'facture' || $this->element == 'facturerec') $fieldht = 'total';
  2815. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva = 'total_tva';
  2816. if ($this->element == 'propal') $fieldttc = 'total';
  2817. if ($this->element == 'expensereport') $fieldtva = 'total_tva';
  2818. if ($this->element == 'supplier_proposal') $fieldttc = 'total';
  2819. if (empty($nodatabaseupdate))
  2820. {
  2821. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
  2822. $sql .= " ".$fieldht."='".price2num($this->total_ht)."',";
  2823. $sql .= " ".$fieldtva."='".price2num($this->total_tva)."',";
  2824. $sql .= " ".$fieldlocaltax1."='".price2num($this->total_localtax1)."',";
  2825. $sql .= " ".$fieldlocaltax2."='".price2num($this->total_localtax2)."',";
  2826. $sql .= " ".$fieldttc."='".price2num($this->total_ttc)."'";
  2827. $sql .= ", multicurrency_total_ht='".price2num($this->multicurrency_total_ht, 'MT', 1)."'";
  2828. $sql .= ", multicurrency_total_tva='".price2num($this->multicurrency_total_tva, 'MT', 1)."'";
  2829. $sql .= ", multicurrency_total_ttc='".price2num($this->multicurrency_total_ttc, 'MT', 1)."'";
  2830. $sql .= ' WHERE rowid = '.$this->id;
  2831. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  2832. $resql = $this->db->query($sql);
  2833. if (!$resql)
  2834. {
  2835. $error++;
  2836. $this->error = $this->db->lasterror();
  2837. $this->errors[] = $this->db->lasterror();
  2838. }
  2839. }
  2840. if (!$error)
  2841. {
  2842. return 1;
  2843. } else {
  2844. return -1;
  2845. }
  2846. } else {
  2847. dol_print_error($this->db, 'Bad request in update_price');
  2848. return -1;
  2849. }
  2850. }
  2851. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2852. /**
  2853. * Add objects linked in llx_element_element.
  2854. *
  2855. * @param string $origin Linked element type
  2856. * @param int $origin_id Linked element id
  2857. * @return int <=0 if KO, >0 if OK
  2858. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  2859. */
  2860. public function add_object_linked($origin = null, $origin_id = null)
  2861. {
  2862. // phpcs:enable
  2863. $origin = (!empty($origin) ? $origin : $this->origin);
  2864. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  2865. // Special case
  2866. if ($origin == 'order') $origin = 'commande';
  2867. if ($origin == 'invoice') $origin = 'facture';
  2868. if ($origin == 'invoice_template') $origin = 'facturerec';
  2869. if ($origin == 'supplierorder') $origin = 'order_supplier';
  2870. $this->db->begin();
  2871. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
  2872. $sql .= "fk_source";
  2873. $sql .= ", sourcetype";
  2874. $sql .= ", fk_target";
  2875. $sql .= ", targettype";
  2876. $sql .= ") VALUES (";
  2877. $sql .= $origin_id;
  2878. $sql .= ", '".$this->db->escape($origin)."'";
  2879. $sql .= ", ".$this->id;
  2880. $sql .= ", '".$this->db->escape($this->element)."'";
  2881. $sql .= ")";
  2882. dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG);
  2883. if ($this->db->query($sql))
  2884. {
  2885. $this->db->commit();
  2886. return 1;
  2887. } else {
  2888. $this->error = $this->db->lasterror();
  2889. $this->db->rollback();
  2890. return 0;
  2891. }
  2892. }
  2893. /**
  2894. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  2895. * this->linkedObjectsIds array and
  2896. * this->linkedObjects array if $loadalsoobjects = 1
  2897. * Possible usage for parameters:
  2898. * - all parameters empty -> we look all link to current object (current object can be source or target)
  2899. * - source id+type -> will get target list linked to source
  2900. * - target id+type -> will get source list linked to target
  2901. * - source id+type + target type -> will get target list of the type
  2902. * - target id+type + target source -> will get source list of the type
  2903. *
  2904. * @param int $sourceid Object source id (if not defined, id of object)
  2905. * @param string $sourcetype Object source type (if not defined, element name of object)
  2906. * @param int $targetid Object target id (if not defined, id of object)
  2907. * @param string $targettype Object target type (if not defined, elemennt name of object)
  2908. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  2909. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  2910. * @param string $orderby SQL 'ORDER BY' clause
  2911. * @param int $loadalsoobjects Load also array this->linkedObjects (Use 0 to increase performances)
  2912. * @return int <0 if KO, >0 if OK
  2913. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  2914. */
  2915. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  2916. {
  2917. global $conf;
  2918. $this->linkedObjectsIds = array();
  2919. $this->linkedObjects = array();
  2920. $justsource = false;
  2921. $justtarget = false;
  2922. $withtargettype = false;
  2923. $withsourcetype = false;
  2924. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid))
  2925. {
  2926. $justsource = true; // the source (id and type) is a search criteria
  2927. if (!empty($targettype)) $withtargettype = true;
  2928. }
  2929. if (!empty($targetid) && !empty($targettype) && empty($sourceid))
  2930. {
  2931. $justtarget = true; // the target (id and type) is a search criteria
  2932. if (!empty($sourcetype)) $withsourcetype = true;
  2933. }
  2934. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  2935. $targetid = (!empty($targetid) ? $targetid : $this->id);
  2936. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  2937. $targettype = (!empty($targettype) ? $targettype : $this->element);
  2938. /*if (empty($sourceid) && empty($targetid))
  2939. {
  2940. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  2941. return -1;
  2942. }*/
  2943. // Links between objects are stored in table element_element
  2944. $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype';
  2945. $sql .= ' FROM '.MAIN_DB_PREFIX.'element_element';
  2946. $sql .= " WHERE ";
  2947. if ($justsource || $justtarget)
  2948. {
  2949. if ($justsource)
  2950. {
  2951. $sql .= "fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  2952. if ($withtargettype) $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
  2953. } elseif ($justtarget)
  2954. {
  2955. $sql .= "fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."'";
  2956. if ($withsourcetype) $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
  2957. }
  2958. } else {
  2959. $sql .= "(fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."')";
  2960. $sql .= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."')";
  2961. }
  2962. $sql .= ' ORDER BY '.$orderby;
  2963. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  2964. $resql = $this->db->query($sql);
  2965. if ($resql)
  2966. {
  2967. $num = $this->db->num_rows($resql);
  2968. $i = 0;
  2969. while ($i < $num)
  2970. {
  2971. $obj = $this->db->fetch_object($resql);
  2972. if ($justsource || $justtarget)
  2973. {
  2974. if ($justsource)
  2975. {
  2976. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  2977. } elseif ($justtarget)
  2978. {
  2979. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  2980. }
  2981. } else {
  2982. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype)
  2983. {
  2984. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  2985. }
  2986. if ($obj->fk_target == $targetid && $obj->targettype == $targettype)
  2987. {
  2988. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  2989. }
  2990. }
  2991. $i++;
  2992. }
  2993. if (!empty($this->linkedObjectsIds))
  2994. {
  2995. $tmparray = $this->linkedObjectsIds;
  2996. foreach ($tmparray as $objecttype => $objectids) // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  2997. {
  2998. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  2999. $module = $element = $subelement = $objecttype;
  3000. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  3001. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs))
  3002. {
  3003. $module = $element = $regs[1];
  3004. $subelement = $regs[2];
  3005. }
  3006. $classpath = $element.'/class';
  3007. // To work with non standard classpath or module name
  3008. if ($objecttype == 'facture') {
  3009. $classpath = 'compta/facture/class';
  3010. } elseif ($objecttype == 'facturerec') {
  3011. $classpath = 'compta/facture/class'; $module = 'facture';
  3012. } elseif ($objecttype == 'propal') {
  3013. $classpath = 'comm/propal/class';
  3014. } elseif ($objecttype == 'supplier_proposal') {
  3015. $classpath = 'supplier_proposal/class';
  3016. } elseif ($objecttype == 'shipping') {
  3017. $classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon';
  3018. } elseif ($objecttype == 'delivery') {
  3019. $classpath = 'delivery/class'; $subelement = 'delivery'; $module = 'delivery_note';
  3020. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  3021. $classpath = 'fourn/class'; $module = 'fournisseur';
  3022. } elseif ($objecttype == 'fichinter') {
  3023. $classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter';
  3024. } elseif ($objecttype == 'subscription') {
  3025. $classpath = 'adherents/class'; $module = 'adherent';
  3026. } elseif ($objecttype == 'contact') {
  3027. $module = 'societe';
  3028. }
  3029. // Set classfile
  3030. $classfile = strtolower($subelement); $classname = ucfirst($subelement);
  3031. if ($objecttype == 'order') {
  3032. $classfile = 'commande'; $classname = 'Commande';
  3033. } elseif ($objecttype == 'invoice_supplier') {
  3034. $classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur';
  3035. } elseif ($objecttype == 'order_supplier') {
  3036. $classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur';
  3037. } elseif ($objecttype == 'supplier_proposal') {
  3038. $classfile = 'supplier_proposal'; $classname = 'SupplierProposal';
  3039. } elseif ($objecttype == 'facturerec') {
  3040. $classfile = 'facture-rec'; $classname = 'FactureRec';
  3041. } elseif ($objecttype == 'subscription') {
  3042. $classfile = 'subscription'; $classname = 'Subscription';
  3043. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  3044. $classpath = 'projet/class'; $classfile = 'project'; $classname = 'Project';
  3045. }
  3046. // Here $module, $classfile and $classname are set
  3047. if ($conf->$module->enabled && (($element != $this->element) || $alsosametype))
  3048. {
  3049. if ($loadalsoobjects)
  3050. {
  3051. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  3052. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  3053. if (class_exists($classname))
  3054. {
  3055. foreach ($objectids as $i => $objectid) // $i is rowid into llx_element_element
  3056. {
  3057. $object = new $classname($this->db);
  3058. $ret = $object->fetch($objectid);
  3059. if ($ret >= 0)
  3060. {
  3061. $this->linkedObjects[$objecttype][$i] = $object;
  3062. }
  3063. }
  3064. }
  3065. }
  3066. } else {
  3067. unset($this->linkedObjectsIds[$objecttype]);
  3068. }
  3069. }
  3070. }
  3071. return 1;
  3072. } else {
  3073. dol_print_error($this->db);
  3074. return -1;
  3075. }
  3076. }
  3077. /**
  3078. * Update object linked of a current object
  3079. *
  3080. * @param int $sourceid Object source id
  3081. * @param string $sourcetype Object source type
  3082. * @param int $targetid Object target id
  3083. * @param string $targettype Object target type
  3084. * @return int >0 if OK, <0 if KO
  3085. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3086. */
  3087. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '')
  3088. {
  3089. $updatesource = false;
  3090. $updatetarget = false;
  3091. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) $updatesource = true;
  3092. elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) $updatetarget = true;
  3093. $sql = "UPDATE ".MAIN_DB_PREFIX."element_element SET ";
  3094. if ($updatesource)
  3095. {
  3096. $sql .= "fk_source = ".$sourceid;
  3097. $sql .= ", sourcetype = '".$this->db->escape($sourcetype)."'";
  3098. $sql .= " WHERE fk_target = ".$this->id;
  3099. $sql .= " AND targettype = '".$this->db->escape($this->element)."'";
  3100. } elseif ($updatetarget)
  3101. {
  3102. $sql .= "fk_target = ".$targetid;
  3103. $sql .= ", targettype = '".$this->db->escape($targettype)."'";
  3104. $sql .= " WHERE fk_source = ".$this->id;
  3105. $sql .= " AND sourcetype = '".$this->db->escape($this->element)."'";
  3106. }
  3107. dol_syslog(get_class($this)."::updateObjectLinked", LOG_DEBUG);
  3108. if ($this->db->query($sql))
  3109. {
  3110. return 1;
  3111. } else {
  3112. $this->error = $this->db->lasterror();
  3113. return -1;
  3114. }
  3115. }
  3116. /**
  3117. * Delete all links between an object $this
  3118. *
  3119. * @param int $sourceid Object source id
  3120. * @param string $sourcetype Object source type
  3121. * @param int $targetid Object target id
  3122. * @param string $targettype Object target type
  3123. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3124. * @return int >0 if OK, <0 if KO
  3125. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3126. */
  3127. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '')
  3128. {
  3129. $deletesource = false;
  3130. $deletetarget = false;
  3131. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) $deletesource = true;
  3132. elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) $deletetarget = true;
  3133. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3134. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3135. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3136. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3137. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_element";
  3138. $sql .= " WHERE";
  3139. if ($rowid > 0)
  3140. {
  3141. $sql .= " rowid = ".$rowid;
  3142. } else {
  3143. if ($deletesource)
  3144. {
  3145. $sql .= " fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3146. $sql .= " AND fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."'";
  3147. } elseif ($deletetarget)
  3148. {
  3149. $sql .= " fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."'";
  3150. $sql .= " AND fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."'";
  3151. } else {
  3152. $sql .= " (fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."')";
  3153. $sql .= " OR";
  3154. $sql .= " (fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."')";
  3155. }
  3156. }
  3157. dol_syslog(get_class($this)."::deleteObjectLinked", LOG_DEBUG);
  3158. if ($this->db->query($sql))
  3159. {
  3160. return 1;
  3161. } else {
  3162. $this->error = $this->db->lasterror();
  3163. $this->errors[] = $this->error;
  3164. return -1;
  3165. }
  3166. }
  3167. /**
  3168. * Set status of an object
  3169. *
  3170. * @param int $status Status to set
  3171. * @param int $elementId Id of element to force (use this->id by default)
  3172. * @param string $elementType Type of element to force (use this->table_element by default)
  3173. * @param string $trigkey Trigger key to use for trigger
  3174. * @return int <0 if KO, >0 if OK
  3175. */
  3176. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '')
  3177. {
  3178. global $user, $langs, $conf;
  3179. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3180. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3181. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3182. $this->db->begin();
  3183. $fieldstatus = "fk_statut";
  3184. if ($elementTable == 'facture_rec') $fieldstatus = "suspended";
  3185. if ($elementTable == 'mailing') $fieldstatus = "statut";
  3186. if ($elementTable == 'cronjob') $fieldstatus = "status";
  3187. if ($elementTable == 'user') $fieldstatus = "statut";
  3188. if ($elementTable == 'expensereport') $fieldstatus = "fk_statut";
  3189. if ($elementTable == 'commande_fournisseur_dispatch') $fieldstatus = "status";
  3190. if (is_array($this->fields) && array_key_exists('status', $this->fields)) $fieldstatus = 'status';
  3191. $sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable;
  3192. $sql .= " SET ".$fieldstatus." = ".$status;
  3193. // If status = 1 = validated, update also fk_user_valid
  3194. if ($status == 1 && $elementTable == 'expensereport') $sql .= ", fk_user_valid = ".$user->id;
  3195. $sql .= " WHERE rowid=".$elementId;
  3196. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  3197. if ($this->db->query($sql))
  3198. {
  3199. $error = 0;
  3200. // Try autoset of trigkey
  3201. if (empty($trigkey))
  3202. {
  3203. if ($this->element == 'supplier_proposal' && $status == 2) $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3204. if ($this->element == 'supplier_proposal' && $status == 3) $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3205. if ($this->element == 'supplier_proposal' && $status == 4) $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3206. if ($this->element == 'fichinter' && $status == 3) $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3207. if ($this->element == 'fichinter' && $status == 2) $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3208. if ($this->element == 'fichinter' && $status == 1) $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3209. }
  3210. if ($trigkey)
  3211. {
  3212. // Call trigger
  3213. $result = $this->call_trigger($trigkey, $user);
  3214. if ($result < 0) $error++;
  3215. // End call triggers
  3216. }
  3217. if (!$error)
  3218. {
  3219. $this->db->commit();
  3220. if (empty($savElementId)) // If the element we update was $this (so $elementId is null)
  3221. {
  3222. $this->statut = $status;
  3223. $this->status = $status;
  3224. }
  3225. return 1;
  3226. } else {
  3227. $this->db->rollback();
  3228. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  3229. return -1;
  3230. }
  3231. } else {
  3232. $this->error = $this->db->lasterror();
  3233. $this->db->rollback();
  3234. return -1;
  3235. }
  3236. }
  3237. /**
  3238. * Load type of canvas of an object if it exists
  3239. *
  3240. * @param int $id Record id
  3241. * @param string $ref Record ref
  3242. * @return int <0 if KO, 0 if nothing done, >0 if OK
  3243. */
  3244. public function getCanvas($id = 0, $ref = '')
  3245. {
  3246. global $conf;
  3247. if (empty($id) && empty($ref)) return 0;
  3248. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) return 0; // To increase speed. Not enabled by default.
  3249. // Clean parameters
  3250. $ref = trim($ref);
  3251. $sql = "SELECT rowid, canvas";
  3252. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
  3253. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  3254. if (!empty($id)) $sql .= " AND rowid = ".$id;
  3255. if (!empty($ref)) $sql .= " AND ref = '".$this->db->escape($ref)."'";
  3256. $resql = $this->db->query($sql);
  3257. if ($resql)
  3258. {
  3259. $obj = $this->db->fetch_object($resql);
  3260. if ($obj)
  3261. {
  3262. $this->canvas = $obj->canvas;
  3263. return 1;
  3264. } else return 0;
  3265. } else {
  3266. dol_print_error($this->db);
  3267. return -1;
  3268. }
  3269. }
  3270. /**
  3271. * Get special code of a line
  3272. *
  3273. * @param int $lineid Id of line
  3274. * @return int Special code
  3275. */
  3276. public function getSpecialCode($lineid)
  3277. {
  3278. $sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  3279. $sql .= ' WHERE rowid = '.$lineid;
  3280. $resql = $this->db->query($sql);
  3281. if ($resql)
  3282. {
  3283. $row = $this->db->fetch_row($resql);
  3284. return $row[0];
  3285. }
  3286. }
  3287. /**
  3288. * Function to check if an object is used by others.
  3289. * Check is done into this->childtables. There is no check into llx_element_element.
  3290. *
  3291. * @param int $id Force id of object
  3292. * @return int <0 if KO, 0 if not used, >0 if already used
  3293. */
  3294. public function isObjectUsed($id = 0)
  3295. {
  3296. global $langs;
  3297. if (empty($id)) $id = $this->id;
  3298. // Check parameters
  3299. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0)
  3300. {
  3301. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  3302. return -1;
  3303. }
  3304. $arraytoscan = $this->childtables;
  3305. // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
  3306. $tmparray = array_keys($this->childtables);
  3307. if (is_numeric($tmparray[0]))
  3308. {
  3309. $arraytoscan = array_flip($this->childtables);
  3310. }
  3311. // Test if child exists
  3312. $haschild = 0;
  3313. foreach ($arraytoscan as $table => $elementname)
  3314. {
  3315. //print $id.'-'.$table.'-'.$elementname.'<br>';
  3316. // Check if third party can be deleted
  3317. $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table;
  3318. $sql .= " WHERE ".$this->fk_element." = ".$id;
  3319. $resql = $this->db->query($sql);
  3320. if ($resql)
  3321. {
  3322. $obj = $this->db->fetch_object($resql);
  3323. if ($obj->nb > 0)
  3324. {
  3325. $langs->load("errors");
  3326. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  3327. $haschild += $obj->nb;
  3328. if (is_numeric($elementname)) // old usage
  3329. {
  3330. $this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table);
  3331. } else // new usage: $elementname=Translation key
  3332. {
  3333. $this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname));
  3334. }
  3335. break; // We found at least one, we stop here
  3336. }
  3337. } else {
  3338. $this->errors[] = $this->db->lasterror();
  3339. return -1;
  3340. }
  3341. }
  3342. if ($haschild > 0)
  3343. {
  3344. $this->errors[] = "ErrorRecordHasChildren";
  3345. return $haschild;
  3346. } else return 0;
  3347. }
  3348. /**
  3349. * Function to say how many lines object contains
  3350. *
  3351. * @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
  3352. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  3353. */
  3354. public function hasProductsOrServices($predefined = -1)
  3355. {
  3356. $nb = 0;
  3357. foreach ($this->lines as $key => $val)
  3358. {
  3359. $qualified = 0;
  3360. if ($predefined == -1) $qualified = 1;
  3361. if ($predefined == 1 && $val->fk_product > 0) $qualified = 1;
  3362. if ($predefined == 0 && $val->fk_product <= 0) $qualified = 1;
  3363. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) $qualified = 1;
  3364. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) $qualified = 1;
  3365. if ($qualified) $nb++;
  3366. }
  3367. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  3368. return $nb;
  3369. }
  3370. /**
  3371. * Function that returns the total amount HT of discounts applied for all lines.
  3372. *
  3373. * @return float
  3374. */
  3375. public function getTotalDiscount()
  3376. {
  3377. $total_discount = 0.00;
  3378. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  3379. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element."det";
  3380. $sql .= " WHERE ".$this->fk_element." = ".$this->id;
  3381. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  3382. $resql = $this->db->query($sql);
  3383. if ($resql)
  3384. {
  3385. $num = $this->db->num_rows($resql);
  3386. $i = 0;
  3387. while ($i < $num)
  3388. {
  3389. $obj = $this->db->fetch_object($resql);
  3390. $pu_ht = $obj->pu_ht;
  3391. $qty = $obj->qty;
  3392. $total_ht = $obj->total_ht;
  3393. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  3394. $total_discount += $total_discount_line;
  3395. $i++;
  3396. }
  3397. }
  3398. //print $total_discount; exit;
  3399. return price2num($total_discount);
  3400. }
  3401. /**
  3402. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  3403. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  3404. *
  3405. * @return array array('weight'=>...,'volume'=>...)
  3406. */
  3407. public function getTotalWeightVolume()
  3408. {
  3409. $totalWeight = 0;
  3410. $totalVolume = 0;
  3411. // defined for shipment only
  3412. $totalOrdered = '';
  3413. // defined for shipment only
  3414. $totalToShip = '';
  3415. foreach ($this->lines as $line)
  3416. {
  3417. if (isset($line->qty_asked))
  3418. {
  3419. if (empty($totalOrdered)) $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  3420. $totalOrdered += $line->qty_asked; // defined for shipment only
  3421. }
  3422. if (isset($line->qty_shipped))
  3423. {
  3424. if (empty($totalToShip)) $totalToShip = 0; // Avoid warning because $totalToShip is ''
  3425. $totalToShip += $line->qty_shipped; // defined for shipment only
  3426. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty))
  3427. {
  3428. if (empty($totalToShip)) $totalToShip = 0;
  3429. $totalToShip += $line->qty; // defined for reception only
  3430. }
  3431. // Define qty, weight, volume, weight_units, volume_units
  3432. if ($this->element == 'shipping') {
  3433. // for shipments
  3434. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  3435. } else {
  3436. $qty = $line->qty ? $line->qty : 0;
  3437. }
  3438. $weight = $line->weight ? $line->weight : 0;
  3439. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  3440. $volume = $line->volume ? $line->volume : 0;
  3441. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  3442. $weight_units = $line->weight_units;
  3443. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  3444. $volume_units = $line->volume_units;
  3445. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  3446. $weightUnit = 0;
  3447. $volumeUnit = 0;
  3448. if (!empty($weight_units)) $weightUnit = $weight_units;
  3449. if (!empty($volume_units)) $volumeUnit = $volume_units;
  3450. if (empty($totalWeight)) $totalWeight = 0; // Avoid warning because $totalWeight is ''
  3451. if (empty($totalVolume)) $totalVolume = 0; // Avoid warning because $totalVolume is ''
  3452. //var_dump($line->volume_units);
  3453. if ($weight_units < 50) // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  3454. {
  3455. $trueWeightUnit = pow(10, $weightUnit);
  3456. $totalWeight += $weight * $qty * $trueWeightUnit;
  3457. } else {
  3458. if ($weight_units == 99) {
  3459. // conversion 1 Pound = 0.45359237 KG
  3460. $trueWeightUnit = 0.45359237;
  3461. $totalWeight += $weight * $qty * $trueWeightUnit;
  3462. } elseif ($weight_units == 98) {
  3463. // conversion 1 Ounce = 0.0283495 KG
  3464. $trueWeightUnit = 0.0283495;
  3465. $totalWeight += $weight * $qty * $trueWeightUnit;
  3466. } else {
  3467. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  3468. }
  3469. }
  3470. if ($volume_units < 50) // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  3471. {
  3472. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  3473. $trueVolumeUnit = pow(10, $volumeUnit);
  3474. //print $line->volume;
  3475. $totalVolume += $volume * $qty * $trueVolumeUnit;
  3476. } else {
  3477. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  3478. }
  3479. }
  3480. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  3481. }
  3482. /**
  3483. * Set extra parameters
  3484. *
  3485. * @return int <0 if KO, >0 if OK
  3486. */
  3487. public function setExtraParameters()
  3488. {
  3489. $this->db->begin();
  3490. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  3491. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  3492. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  3493. $sql .= " WHERE rowid = ".$this->id;
  3494. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  3495. $resql = $this->db->query($sql);
  3496. if (!$resql)
  3497. {
  3498. $this->error = $this->db->lasterror();
  3499. $this->db->rollback();
  3500. return -1;
  3501. } else {
  3502. $this->db->commit();
  3503. return 1;
  3504. }
  3505. }
  3506. // --------------------
  3507. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  3508. // --------------------
  3509. /* This is to show add lines */
  3510. /**
  3511. * Show add free and predefined products/services form
  3512. *
  3513. * @param int $dateSelector 1=Show also date range input fields
  3514. * @param Societe $seller Object thirdparty who sell
  3515. * @param Societe $buyer Object thirdparty who buy
  3516. * @param string $defaulttpldir Directory where to find the template
  3517. * @return void
  3518. */
  3519. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  3520. {
  3521. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  3522. global $form;
  3523. // Line extrafield
  3524. if (!is_object($extrafields))
  3525. {
  3526. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  3527. $extrafields = new ExtraFields($this->db);
  3528. }
  3529. $extrafields->fetch_name_optionals_label($this->table_element_line);
  3530. // Output template part (modules that overwrite templates must declare this into descriptor)
  3531. // Use global variables + $dateSelector + $seller and $buyer
  3532. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  3533. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  3534. foreach ($dirtpls as $module => $reldir)
  3535. {
  3536. if (!empty($module))
  3537. {
  3538. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  3539. } else {
  3540. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  3541. }
  3542. if (empty($conf->file->strict_mode)) {
  3543. $res = @include $tpl;
  3544. } else {
  3545. $res = include $tpl; // for debug
  3546. }
  3547. if ($res) break;
  3548. }
  3549. }
  3550. /* This is to show array of line of details */
  3551. /**
  3552. * Return HTML table for object lines
  3553. * TODO Move this into an output class file (htmlline.class.php)
  3554. * If lines are into a template, title must also be into a template
  3555. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  3556. *
  3557. * @param string $action Action code
  3558. * @param string $seller Object of seller third party
  3559. * @param string $buyer Object of buyer third party
  3560. * @param int $selected Object line selected
  3561. * @param int $dateSelector 1=Show also date range input fields
  3562. * @param string $defaulttpldir Directory where to find the template
  3563. * @return void
  3564. */
  3565. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  3566. {
  3567. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  3568. // TODO We should not use global var for this
  3569. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  3570. // Define usemargins
  3571. $usemargins = 0;
  3572. if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) $usemargins = 1;
  3573. $num = count($this->lines);
  3574. // Line extrafield
  3575. if (!is_object($extrafields))
  3576. {
  3577. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  3578. $extrafields = new ExtraFields($this->db);
  3579. }
  3580. $extrafields->fetch_name_optionals_label($this->table_element_line);
  3581. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  3582. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3583. if (empty($reshook))
  3584. {
  3585. // Output template part (modules that overwrite templates must declare this into descriptor)
  3586. // Use global variables + $dateSelector + $seller and $buyer
  3587. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  3588. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  3589. foreach ($dirtpls as $module => $reldir)
  3590. {
  3591. if (!empty($module))
  3592. {
  3593. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  3594. } else {
  3595. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  3596. }
  3597. if (empty($conf->file->strict_mode)) {
  3598. $res = @include $tpl;
  3599. } else {
  3600. $res = include $tpl; // for debug
  3601. }
  3602. if ($res) break;
  3603. }
  3604. }
  3605. $i = 0;
  3606. print "<!-- begin printObjectLines() --><tbody>\n";
  3607. foreach ($this->lines as $line)
  3608. {
  3609. //Line extrafield
  3610. $line->fetch_optionals();
  3611. //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  3612. if (is_object($hookmanager)) // Old code is commented on preceding line.
  3613. {
  3614. if (empty($line->fk_parent_line))
  3615. {
  3616. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  3617. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3618. } else {
  3619. $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);
  3620. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3621. }
  3622. }
  3623. if (empty($reshook))
  3624. {
  3625. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  3626. }
  3627. $i++;
  3628. }
  3629. print "</tbody><!-- end printObjectLines() -->\n";
  3630. }
  3631. /**
  3632. * Return HTML content of a detail line
  3633. * TODO Move this into an output class file (htmlline.class.php)
  3634. *
  3635. * @param string $action GET/POST action
  3636. * @param CommonObjectLine $line Selected object line to output
  3637. * @param string $var Is it a an odd line (true)
  3638. * @param int $num Number of line (0)
  3639. * @param int $i I
  3640. * @param int $dateSelector 1=Show also date range input fields
  3641. * @param string $seller Object of seller third party
  3642. * @param string $buyer Object of buyer third party
  3643. * @param int $selected Object line selected
  3644. * @param Extrafields $extrafields Object of extrafields
  3645. * @param string $defaulttpldir Directory where to find the template (deprecated)
  3646. * @return void
  3647. */
  3648. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  3649. {
  3650. global $conf, $langs, $user, $object, $hookmanager;
  3651. global $form;
  3652. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  3653. $object_rights = $this->getRights();
  3654. $element = $this->element;
  3655. $text = ''; $description = '';
  3656. // Line in view mode
  3657. if ($action != 'editline' || $selected != $line->id)
  3658. {
  3659. // Product
  3660. if ($line->fk_product > 0)
  3661. {
  3662. $product_static = new Product($this->db);
  3663. $product_static->fetch($line->fk_product);
  3664. $product_static->ref = $line->ref; //can change ref in hook
  3665. $product_static->label = $line->label; //can change label in hook
  3666. $text = $product_static->getNomUrl(1);
  3667. // Define output language and label
  3668. if (!empty($conf->global->MAIN_MULTILANGS))
  3669. {
  3670. if (property_exists($this, 'socid') && !is_object($this->thirdparty))
  3671. {
  3672. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  3673. return;
  3674. }
  3675. $prod = new Product($this->db);
  3676. $prod->fetch($line->fk_product);
  3677. $outputlangs = $langs;
  3678. $newlang = '';
  3679. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
  3680. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) $newlang = $this->thirdparty->default_lang; // To use language of customer
  3681. if (!empty($newlang))
  3682. {
  3683. $outputlangs = new Translate("", $conf);
  3684. $outputlangs->setDefaultLang($newlang);
  3685. }
  3686. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  3687. } else {
  3688. $label = $line->product_label;
  3689. }
  3690. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  3691. $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.
  3692. }
  3693. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  3694. // Output template part (modules that overwrite templates must declare this into descriptor)
  3695. // Use global variables + $dateSelector + $seller and $buyer
  3696. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  3697. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  3698. foreach ($dirtpls as $module => $reldir)
  3699. {
  3700. if (!empty($module))
  3701. {
  3702. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  3703. } else {
  3704. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  3705. }
  3706. if (empty($conf->file->strict_mode)) {
  3707. $res = @include $tpl;
  3708. } else {
  3709. $res = include $tpl; // for debug
  3710. }
  3711. if ($res) break;
  3712. }
  3713. }
  3714. // Line in update mode
  3715. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id)
  3716. {
  3717. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  3718. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  3719. // Output template part (modules that overwrite templates must declare this into descriptor)
  3720. // Use global variables + $dateSelector + $seller and $buyer
  3721. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  3722. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  3723. foreach ($dirtpls as $module => $reldir)
  3724. {
  3725. if (!empty($module))
  3726. {
  3727. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  3728. } else {
  3729. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  3730. }
  3731. if (empty($conf->file->strict_mode)) {
  3732. $res = @include $tpl;
  3733. } else {
  3734. $res = include $tpl; // for debug
  3735. }
  3736. if ($res) break;
  3737. }
  3738. }
  3739. }
  3740. /* This is to show array of line of details of source object */
  3741. /**
  3742. * Return HTML table table of source object lines
  3743. * TODO Move this and previous function into output html class file (htmlline.class.php).
  3744. * If lines are into a template, title must also be into a template
  3745. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  3746. *
  3747. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  3748. * @param array $selectedLines Array of lines id for selected lines
  3749. * @return void
  3750. */
  3751. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  3752. {
  3753. global $langs, $hookmanager, $conf, $form;
  3754. print '<tr class="liste_titre">';
  3755. print '<td>'.$langs->trans('Ref').'</td>';
  3756. print '<td>'.$langs->trans('Description').'</td>';
  3757. print '<td class="right">'.$langs->trans('VATRate').'</td>';
  3758. print '<td class="right">'.$langs->trans('PriceUHT').'</td>';
  3759. if (!empty($conf->multicurrency->enabled)) print '<td class="right">'.$langs->trans('PriceUHTCurrency').'</td>';
  3760. print '<td class="right">'.$langs->trans('Qty').'</td>';
  3761. if (!empty($conf->global->PRODUCT_USE_UNITS))
  3762. {
  3763. print '<td class="left">'.$langs->trans('Unit').'</td>';
  3764. }
  3765. print '<td class="right">'.$langs->trans('ReductionShort').'</td>';
  3766. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  3767. print '</tr>';
  3768. $i = 0;
  3769. if (!empty($this->lines))
  3770. {
  3771. foreach ($this->lines as $line)
  3772. {
  3773. if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line)))
  3774. {
  3775. if (empty($line->fk_parent_line))
  3776. {
  3777. $parameters = array('line'=>$line, 'i'=>$i);
  3778. $action = '';
  3779. $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3780. }
  3781. } else {
  3782. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  3783. }
  3784. $i++;
  3785. }
  3786. }
  3787. }
  3788. /**
  3789. * Return HTML with a line of table array of source object lines
  3790. * TODO Move this and previous function into output html class file (htmlline.class.php).
  3791. * If lines are into a template, title must also be into a template
  3792. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  3793. *
  3794. * @param CommonObjectLine $line Line
  3795. * @param string $var Var
  3796. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  3797. * @param string $defaulttpldir Directory where to find the template
  3798. * @param array $selectedLines Array of lines id for selected lines
  3799. * @return void
  3800. */
  3801. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  3802. {
  3803. global $langs, $conf;
  3804. //var_dump($line);
  3805. if (!empty($line->date_start))
  3806. {
  3807. $date_start = $line->date_start;
  3808. } else {
  3809. $date_start = $line->date_debut_prevue;
  3810. if ($line->date_debut_reel) $date_start = $line->date_debut_reel;
  3811. }
  3812. if (!empty($line->date_end))
  3813. {
  3814. $date_end = $line->date_end;
  3815. } else {
  3816. $date_end = $line->date_fin_prevue;
  3817. if ($line->date_fin_reel) $date_end = $line->date_fin_reel;
  3818. }
  3819. $this->tpl['id'] = $line->id;
  3820. $this->tpl['label'] = '';
  3821. if (!empty($line->fk_parent_line)) $this->tpl['label'] .= img_picto('', 'rightarrow');
  3822. if (($line->info_bits & 2) == 2) // TODO Not sure this is used for source object
  3823. {
  3824. $discount = new DiscountAbsolute($this->db);
  3825. $discount->fk_soc = $this->socid;
  3826. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  3827. } elseif (!empty($line->fk_product))
  3828. {
  3829. $productstatic = new Product($this->db);
  3830. $productstatic->id = $line->fk_product;
  3831. $productstatic->ref = $line->ref;
  3832. $productstatic->type = $line->fk_product_type;
  3833. if (empty($productstatic->ref)) {
  3834. $line->fetch_product();
  3835. $productstatic = $line->product;
  3836. }
  3837. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  3838. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  3839. // Dates
  3840. if ($line->product_type == 1 && ($date_start || $date_end))
  3841. {
  3842. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  3843. }
  3844. } else {
  3845. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  3846. if (!empty($line->desc)) {
  3847. $this->tpl['label'] .= $line->desc;
  3848. } else {
  3849. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  3850. }
  3851. // Dates
  3852. if ($line->product_type == 1 && ($date_start || $date_end))
  3853. {
  3854. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  3855. }
  3856. }
  3857. if (!empty($line->desc))
  3858. {
  3859. if ($line->desc == '(CREDIT_NOTE)') // TODO Not sure this is used for source object
  3860. {
  3861. $discount = new DiscountAbsolute($this->db);
  3862. $discount->fetch($line->fk_remise_except);
  3863. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  3864. } elseif ($line->desc == '(DEPOSIT)') // TODO Not sure this is used for source object
  3865. {
  3866. $discount = new DiscountAbsolute($this->db);
  3867. $discount->fetch($line->fk_remise_except);
  3868. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  3869. } elseif ($line->desc == '(EXCESS RECEIVED)')
  3870. {
  3871. $discount = new DiscountAbsolute($this->db);
  3872. $discount->fetch($line->fk_remise_except);
  3873. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  3874. } elseif ($line->desc == '(EXCESS PAID)')
  3875. {
  3876. $discount = new DiscountAbsolute($this->db);
  3877. $discount->fetch($line->fk_remise_except);
  3878. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  3879. } else {
  3880. $this->tpl['description'] = dol_trunc($line->desc, 60);
  3881. }
  3882. } else {
  3883. $this->tpl['description'] = '&nbsp;';
  3884. }
  3885. // VAT Rate
  3886. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  3887. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  3888. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  3889. $this->tpl['price'] = price($line->subprice);
  3890. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  3891. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  3892. if (!empty($conf->global->PRODUCT_USE_UNITS)) $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  3893. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  3894. // Is the line strike or not
  3895. $this->tpl['strike'] = 0;
  3896. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) $this->tpl['strike'] = 1;
  3897. // Output template part (modules that overwrite templates must declare this into descriptor)
  3898. // Use global variables + $dateSelector + $seller and $buyer
  3899. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  3900. foreach ($dirtpls as $module => $reldir)
  3901. {
  3902. if (!empty($module))
  3903. {
  3904. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  3905. } else {
  3906. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  3907. }
  3908. if (empty($conf->file->strict_mode)) {
  3909. $res = @include $tpl;
  3910. } else {
  3911. $res = include $tpl; // for debug
  3912. }
  3913. if ($res) break;
  3914. }
  3915. }
  3916. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3917. /**
  3918. * Add resources to the current object : add entry into llx_element_resources
  3919. * Need $this->element & $this->id
  3920. *
  3921. * @param int $resource_id Resource id
  3922. * @param string $resource_type 'resource'
  3923. * @param int $busy Busy or not
  3924. * @param int $mandatory Mandatory or not
  3925. * @return int <=0 if KO, >0 if OK
  3926. */
  3927. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  3928. {
  3929. // phpcs:enable
  3930. $this->db->begin();
  3931. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources (";
  3932. $sql .= "resource_id";
  3933. $sql .= ", resource_type";
  3934. $sql .= ", element_id";
  3935. $sql .= ", element_type";
  3936. $sql .= ", busy";
  3937. $sql .= ", mandatory";
  3938. $sql .= ") VALUES (";
  3939. $sql .= $resource_id;
  3940. $sql .= ", '".$this->db->escape($resource_type)."'";
  3941. $sql .= ", '".$this->db->escape($this->id)."'";
  3942. $sql .= ", '".$this->db->escape($this->element)."'";
  3943. $sql .= ", '".$this->db->escape($busy)."'";
  3944. $sql .= ", '".$this->db->escape($mandatory)."'";
  3945. $sql .= ")";
  3946. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  3947. if ($this->db->query($sql))
  3948. {
  3949. $this->db->commit();
  3950. return 1;
  3951. } else {
  3952. $this->error = $this->db->lasterror();
  3953. $this->db->rollback();
  3954. return 0;
  3955. }
  3956. }
  3957. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3958. /**
  3959. * Delete a link to resource line
  3960. *
  3961. * @param int $rowid Id of resource line to delete
  3962. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  3963. * @param int $notrigger Disable all triggers
  3964. * @return int >0 if OK, <0 if KO
  3965. */
  3966. public function delete_resource($rowid, $element, $notrigger = 0)
  3967. {
  3968. // phpcs:enable
  3969. global $user;
  3970. $this->db->begin();
  3971. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
  3972. $sql .= " WHERE rowid=".$rowid;
  3973. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  3974. $resql = $this->db->query($sql);
  3975. if (!$resql)
  3976. {
  3977. $this->error = $this->db->lasterror();
  3978. $this->db->rollback();
  3979. return -1;
  3980. } else {
  3981. if (!$notrigger)
  3982. {
  3983. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  3984. if ($result < 0) { $this->db->rollback(); return -1; }
  3985. }
  3986. $this->db->commit();
  3987. return 1;
  3988. }
  3989. }
  3990. /**
  3991. * Overwrite magic function to solve problem of cloning object that are kept as references
  3992. *
  3993. * @return void
  3994. */
  3995. public function __clone()
  3996. {
  3997. // Force a copy of this->lines, otherwise it will point to same object.
  3998. if (isset($this->lines) && is_array($this->lines))
  3999. {
  4000. $nboflines = count($this->lines);
  4001. for ($i = 0; $i < $nboflines; $i++)
  4002. {
  4003. $this->lines[$i] = clone $this->lines[$i];
  4004. }
  4005. }
  4006. }
  4007. /**
  4008. * Common function for all objects extending CommonObject for generating documents
  4009. *
  4010. * @param string $modelspath Relative folder where generators are placed
  4011. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4012. * @param Translate $outputlangs Output language to use
  4013. * @param int $hidedetails 1 to hide details. 0 by default
  4014. * @param int $hidedesc 1 to hide product description. 0 by default
  4015. * @param int $hideref 1 to hide product reference. 0 by default
  4016. * @param null|array $moreparams Array to provide more information
  4017. * @return int >0 if OK, <0 if KO
  4018. * @see addFileIntoDatabaseIndex()
  4019. */
  4020. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4021. {
  4022. global $conf, $langs, $user, $hookmanager, $action;
  4023. $srctemplatepath = '';
  4024. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  4025. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4026. if (empty($reshook))
  4027. {
  4028. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4029. // Increase limit for PDF build
  4030. $err = error_reporting();
  4031. error_reporting(0);
  4032. @set_time_limit(120);
  4033. error_reporting($err);
  4034. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4035. $tmp = explode(':', $modele, 2);
  4036. if (!empty($tmp[1]))
  4037. {
  4038. $modele = $tmp[0];
  4039. $srctemplatepath = $tmp[1];
  4040. }
  4041. // Search template files
  4042. $file = '';
  4043. $classname = '';
  4044. $filefound = '';
  4045. $dirmodels = array('/');
  4046. if (is_array($conf->modules_parts['models'])) $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4047. foreach ($dirmodels as $reldir)
  4048. {
  4049. foreach (array('doc', 'pdf') as $prefix)
  4050. {
  4051. if (in_array(get_class($this), array('Adherent'))) {
  4052. // Member module use prefix_modele.class.php
  4053. $file = $prefix."_".$modele.".class.php";
  4054. } else {
  4055. // Other module use prefix_modele.modules.php
  4056. $file = $prefix."_".$modele.".modules.php";
  4057. }
  4058. // On verifie l'emplacement du modele
  4059. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  4060. if (file_exists($file)) {
  4061. $filefound = $file;
  4062. $classname = $prefix.'_'.$modele;
  4063. break;
  4064. }
  4065. }
  4066. if ($filefound) break;
  4067. }
  4068. // If generator was found
  4069. if ($filefound)
  4070. {
  4071. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4072. require_once $file;
  4073. $obj = new $classname($this->db);
  4074. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4075. if ($obj->type == 'odt' && empty($srctemplatepath))
  4076. {
  4077. $varfortemplatedir = $obj->scandir;
  4078. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir))
  4079. {
  4080. $dirtoscan = $conf->global->$varfortemplatedir;
  4081. $listoffiles = array();
  4082. // Now we add first model found in directories scanned
  4083. $listofdir = explode(',', $dirtoscan);
  4084. foreach ($listofdir as $key => $tmpdir)
  4085. {
  4086. $tmpdir = trim($tmpdir);
  4087. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4088. if (!$tmpdir) { unset($listofdir[$key]); continue; }
  4089. if (is_dir($tmpdir))
  4090. {
  4091. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4092. if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles);
  4093. }
  4094. }
  4095. if (count($listoffiles))
  4096. {
  4097. foreach ($listoffiles as $record)
  4098. {
  4099. $srctemplatepath = $record['fullname'];
  4100. break;
  4101. }
  4102. }
  4103. }
  4104. if (empty($srctemplatepath))
  4105. {
  4106. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4107. return -1;
  4108. }
  4109. }
  4110. if ($obj->type == 'odt' && !empty($srctemplatepath))
  4111. {
  4112. if (!dol_is_file($srctemplatepath))
  4113. {
  4114. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  4115. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4116. return -1;
  4117. }
  4118. }
  4119. // We save charset_output to restore it because write_file can change it if needed for
  4120. // output format that does not support UTF8.
  4121. $sav_charset_output = $outputlangs->charset_output;
  4122. if (in_array(get_class($this), array('Adherent')))
  4123. {
  4124. $arrayofrecords = array(); // The write_file of templates of adherent class need this var
  4125. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams);
  4126. } else {
  4127. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4128. }
  4129. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4130. if ($resultwritefile > 0)
  4131. {
  4132. $outputlangs->charset_output = $sav_charset_output;
  4133. // We delete old preview
  4134. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4135. dol_delete_preview($this);
  4136. // Index file in database
  4137. if (!empty($obj->result['fullpath']))
  4138. {
  4139. $destfull = $obj->result['fullpath'];
  4140. $upload_dir = dirname($destfull);
  4141. $destfile = basename($destfull);
  4142. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  4143. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) // If not a tmp dir
  4144. {
  4145. $filename = basename($destfile);
  4146. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4147. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4148. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4149. $ecmfile = new EcmFiles($this->db);
  4150. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  4151. // Set the public "share" key
  4152. $setsharekey = false;
  4153. if ($this->element == 'propal')
  4154. {
  4155. $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok
  4156. if ($useonlinesignature) $setsharekey = true;
  4157. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey = true;
  4158. }
  4159. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  4160. $setsharekey = true;
  4161. }
  4162. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  4163. $setsharekey = true;
  4164. }
  4165. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4166. $setsharekey = true;
  4167. }
  4168. if ($setsharekey) {
  4169. if (empty($ecmfile->share)) // Because object not found or share not set yet
  4170. {
  4171. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  4172. $ecmfile->share = getRandomPassword(true);
  4173. }
  4174. }
  4175. if ($result > 0)
  4176. {
  4177. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4178. $ecmfile->fullpath_orig = '';
  4179. $ecmfile->gen_or_uploaded = 'generated';
  4180. $ecmfile->description = ''; // indexed content
  4181. $ecmfile->keyword = ''; // keyword content
  4182. $result = $ecmfile->update($user);
  4183. if ($result < 0) {
  4184. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4185. }
  4186. } else {
  4187. $ecmfile->entity = $conf->entity;
  4188. $ecmfile->filepath = $rel_dir;
  4189. $ecmfile->filename = $filename;
  4190. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4191. $ecmfile->fullpath_orig = '';
  4192. $ecmfile->gen_or_uploaded = 'generated';
  4193. $ecmfile->description = ''; // indexed content
  4194. $ecmfile->keyword = ''; // keyword content
  4195. $ecmfile->src_object_type = $this->table_element;
  4196. $ecmfile->src_object_id = $this->id;
  4197. $result = $ecmfile->create($user);
  4198. if ($result < 0) {
  4199. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4200. }
  4201. }
  4202. /*$this->result['fullname']=$destfull;
  4203. $this->result['filepath']=$ecmfile->filepath;
  4204. $this->result['filename']=$ecmfile->filename;*/
  4205. //var_dump($obj->update_main_doc_field);exit;
  4206. // Update the last_main_doc field into main object (if documenent generator has property ->update_main_doc_field set)
  4207. $update_main_doc_field = 0;
  4208. if (!empty($obj->update_main_doc_field)) $update_main_doc_field = 1;
  4209. if ($update_main_doc_field && !empty($this->table_element))
  4210. {
  4211. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath.'/'.$ecmfile->filename)."'";
  4212. $sql .= ' WHERE rowid = '.$this->id;
  4213. $resql = $this->db->query($sql);
  4214. if (!$resql) {
  4215. dol_print_error($this->db);
  4216. } else {
  4217. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  4218. }
  4219. }
  4220. }
  4221. } else {
  4222. 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);
  4223. }
  4224. // Success in building document. We build meta file.
  4225. dol_meta_create($this);
  4226. return 1;
  4227. } else {
  4228. $outputlangs->charset_output = $sav_charset_output;
  4229. dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
  4230. return -1;
  4231. }
  4232. } else {
  4233. if (!$filefound) {
  4234. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4235. dol_print_error('', $this->error);
  4236. } else {
  4237. $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
  4238. dol_print_error('', $this->error);
  4239. }
  4240. return -1;
  4241. }
  4242. } else return $reshook;
  4243. }
  4244. /**
  4245. * Build thumb
  4246. * @todo Move this into files.lib.php
  4247. *
  4248. * @param string $file Path file in UTF8 to original file to create thumbs from.
  4249. * @return void
  4250. */
  4251. public function addThumbs($file)
  4252. {
  4253. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  4254. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  4255. $file_osencoded = dol_osencode($file);
  4256. if (file_exists($file_osencoded))
  4257. {
  4258. // Create small thumbs for company (Ratio is near 16/9)
  4259. // Used on logon for example
  4260. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  4261. // Create mini thumbs for company (Ratio is near 16/9)
  4262. // Used on menu or for setup page for example
  4263. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  4264. }
  4265. }
  4266. /* Functions common to commonobject and commonobjectline */
  4267. /* For default values */
  4268. /**
  4269. * Return the default value to use for a field when showing the create form of object.
  4270. * Return values in this order:
  4271. * 1) If parameter is available into POST, we return it first.
  4272. * 2) If not but an alternate value was provided as parameter of function, we return it.
  4273. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  4274. * 4) Return value found into database (TODO No yet implemented)
  4275. *
  4276. * @param string $fieldname Name of field
  4277. * @param string $alternatevalue Alternate value to use
  4278. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  4279. **/
  4280. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
  4281. {
  4282. global $conf, $_POST;
  4283. // If param here has been posted, we use this value first.
  4284. if (GETPOSTISSET($fieldname)) return GETPOST($fieldname, 'alphanohtml', 3);
  4285. if (isset($alternatevalue)) return $alternatevalue;
  4286. $newelement = $this->element;
  4287. if ($newelement == 'facture') $newelement = 'invoice';
  4288. if ($newelement == 'commande') $newelement = 'order';
  4289. if (empty($newelement))
  4290. {
  4291. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  4292. return '';
  4293. }
  4294. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  4295. //var_dump($keyforfieldname);
  4296. if (isset($conf->global->$keyforfieldname)) return $conf->global->$keyforfieldname;
  4297. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  4298. }
  4299. /* For triggers */
  4300. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4301. /**
  4302. * Call trigger based on this instance.
  4303. * Some context information may also be provided into array property this->context.
  4304. * NB: Error from trigger are stacked in interface->errors
  4305. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  4306. *
  4307. * @param string $triggerName trigger's name to execute
  4308. * @param User $user Object user
  4309. * @return int Result of run_triggers
  4310. */
  4311. public function call_trigger($triggerName, $user)
  4312. {
  4313. // phpcs:enable
  4314. global $langs, $conf;
  4315. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  4316. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4317. $langs = new Translate('', $conf);
  4318. }
  4319. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  4320. $interface = new Interfaces($this->db);
  4321. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  4322. if ($result < 0)
  4323. {
  4324. if (!empty($this->errors))
  4325. {
  4326. $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.
  4327. } else {
  4328. $this->errors = $interface->errors;
  4329. }
  4330. }
  4331. return $result;
  4332. }
  4333. /* Functions for data in other language */
  4334. /**
  4335. * Function to get alternative languages of a data into $this->array_languages
  4336. * This method is NOT called by method fetch of objects but must be called separately.
  4337. *
  4338. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  4339. * @see fetch_optionnals()
  4340. */
  4341. public function fetchValuesForExtraLanguages()
  4342. {
  4343. // To avoid SQL errors. Probably not the better solution though
  4344. if (!$this->element) {
  4345. return 0;
  4346. }
  4347. if (!($this->id > 0)) {
  4348. return 0;
  4349. }
  4350. if (is_array($this->array_languages)) {
  4351. return 1;
  4352. }
  4353. $this->array_languages = array();
  4354. $element = $this->element;
  4355. if ($element == 'categorie') $element = 'categories'; // For compatibility
  4356. // Request to get translation values for object
  4357. $sql = "SELECT rowid, property, lang , value";
  4358. $sql .= " FROM ".MAIN_DB_PREFIX."object_lang";
  4359. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  4360. $sql .= " AND fk_object = ".$this->id;
  4361. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  4362. $resql = $this->db->query($sql);
  4363. if ($resql)
  4364. {
  4365. $numrows = $this->db->num_rows($resql);
  4366. if ($numrows)
  4367. {
  4368. $i = 0;
  4369. while ($i < $numrows) {
  4370. $obj = $this->db->fetch_object($resql);
  4371. $key = $obj->property;
  4372. $value = $obj->value;
  4373. $codelang = $obj->lang;
  4374. $type = $this->fields[$key]['type'];
  4375. // we can add this attribute to object
  4376. if (preg_match('/date/', $type))
  4377. {
  4378. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  4379. } else {
  4380. $this->array_languages[$key][$codelang] = $value;
  4381. }
  4382. $i++;
  4383. }
  4384. }
  4385. $this->db->free($resql);
  4386. if ($numrows) return $numrows;
  4387. else return 0;
  4388. } else {
  4389. dol_print_error($this->db);
  4390. return -1;
  4391. }
  4392. }
  4393. /**
  4394. * Fill array_options property of object by extrafields value (using for data sent by forms)
  4395. *
  4396. * @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.
  4397. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  4398. */
  4399. public function setValuesForExtraLanguages($onlykey = '')
  4400. {
  4401. global $_POST, $langs;
  4402. // Get extra fields
  4403. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  4404. $tmparray = explode('-', $postfieldkey);
  4405. if ($tmparray[0] != 'field') continue;
  4406. $element = $tmparray[1];
  4407. $key = $tmparray[2];
  4408. $codelang = $tmparray[3];
  4409. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  4410. if (!empty($onlykey) && $key != $onlykey) continue;
  4411. if ($element != $this->element) continue;
  4412. $key_type = $this->fields[$key]['type'];
  4413. $enabled = 1;
  4414. if (isset($this->fields[$key]['enabled']))
  4415. {
  4416. $enabled = dol_eval($this->fields[$key]['enabled'], 1);
  4417. }
  4418. /*$perms = 1;
  4419. if (isset($this->fields[$key]['perms']))
  4420. {
  4421. $perms = dol_eval($this->fields[$key]['perms'], 1);
  4422. }*/
  4423. if (empty($enabled)) continue;
  4424. //if (empty($perms)) continue;
  4425. if (in_array($key_type, array('date')))
  4426. {
  4427. // Clean parameters
  4428. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  4429. $value_key = dol_mktime(0, 0, 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]);
  4430. } elseif (in_array($key_type, array('datetime')))
  4431. {
  4432. // Clean parameters
  4433. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  4434. $value_key = dol_mktime($_POST[$postfieldkey."hour"], $_POST[$postfieldkey."min"], 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]);
  4435. } elseif (in_array($key_type, array('checkbox', 'chkbxlst')))
  4436. {
  4437. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  4438. if (!empty($value_arr)) {
  4439. $value_key = implode(',', $value_arr);
  4440. } else {
  4441. $value_key = '';
  4442. }
  4443. } elseif (in_array($key_type, array('price', 'double')))
  4444. {
  4445. $value_arr = GETPOST($postfieldkey, 'alpha');
  4446. $value_key = price2num($value_arr);
  4447. } else {
  4448. $value_key = GETPOST($postfieldkey);
  4449. if (in_array($key_type, array('link')) && $value_key == '-1') $value_key = '';
  4450. }
  4451. $this->array_languages[$key][$codelang] = $value_key;
  4452. /*if ($nofillrequired) {
  4453. $langs->load('errors');
  4454. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  4455. return -1;
  4456. }*/
  4457. }
  4458. return 1;
  4459. }
  4460. /* Functions for extrafields */
  4461. /**
  4462. * Function to make a fetch but set environment to avoid to load computed values before.
  4463. *
  4464. * @param int $id ID of object
  4465. * @return int >0 if OK, 0 if not found, <0 if KO
  4466. */
  4467. public function fetchNoCompute($id)
  4468. {
  4469. global $conf;
  4470. $savDisableCompute = $conf->disable_compute;
  4471. $conf->disable_compute = 1;
  4472. $ret = $this->fetch($id);
  4473. $conf->disable_compute = $savDisableCompute;
  4474. return $ret;
  4475. }
  4476. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4477. /**
  4478. * Function to get extra fields of an object into $this->array_options
  4479. * This method is in most cases called by method fetch of objects but you can call it separately.
  4480. *
  4481. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  4482. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  4483. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  4484. * @see fetchValuesForExtraLanguages()
  4485. */
  4486. public function fetch_optionals($rowid = null, $optionsArray = null)
  4487. {
  4488. // phpcs:enable
  4489. global $conf, $extrafields;
  4490. if (empty($rowid)) $rowid = $this->id;
  4491. if (empty($rowid) && isset($this->rowid)) $rowid = $this->rowid; // deprecated
  4492. // To avoid SQL errors. Probably not the better solution though
  4493. if (!$this->table_element) {
  4494. return 0;
  4495. }
  4496. $this->array_options = array();
  4497. if (!is_array($optionsArray))
  4498. {
  4499. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  4500. if (!isset($extrafields) || !is_object($extrafields))
  4501. {
  4502. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4503. $extrafields = new ExtraFields($this->db);
  4504. }
  4505. // Load array of extrafields for elementype = $this->table_element
  4506. if (empty($extrafields->attributes[$this->table_element]['loaded']))
  4507. {
  4508. $extrafields->fetch_name_optionals_label($this->table_element);
  4509. }
  4510. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  4511. } else {
  4512. global $extrafields;
  4513. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  4514. }
  4515. $table_element = $this->table_element;
  4516. if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
  4517. // Request to get complementary values
  4518. if (is_array($optionsArray) && count($optionsArray) > 0)
  4519. {
  4520. $sql = "SELECT rowid";
  4521. foreach ($optionsArray as $name => $label)
  4522. {
  4523. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate')
  4524. {
  4525. $sql .= ", ".$name;
  4526. }
  4527. }
  4528. $sql .= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
  4529. $sql .= " WHERE fk_object = ".((int) $rowid);
  4530. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  4531. $resql = $this->db->query($sql);
  4532. if ($resql)
  4533. {
  4534. $numrows = $this->db->num_rows($resql);
  4535. if ($numrows)
  4536. {
  4537. $tab = $this->db->fetch_array($resql);
  4538. foreach ($tab as $key => $value)
  4539. {
  4540. // 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)
  4541. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key))
  4542. {
  4543. // we can add this attribute to object
  4544. if (!empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime')))
  4545. {
  4546. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  4547. $this->array_options["options_".$key] = $this->db->jdate($value);
  4548. } else {
  4549. $this->array_options["options_".$key] = $value;
  4550. }
  4551. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  4552. }
  4553. }
  4554. // If field is a computed field, value must become result of compute
  4555. foreach ($tab as $key => $value) {
  4556. if (!empty($extrafields) && !empty($extrafields->attributes[$this->table_element]['computed'][$key]))
  4557. {
  4558. //var_dump($conf->disable_compute);
  4559. if (empty($conf->disable_compute)) {
  4560. $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0);
  4561. }
  4562. }
  4563. }
  4564. }
  4565. $this->db->free($resql);
  4566. if ($numrows) return $numrows;
  4567. else return 0;
  4568. } else {
  4569. dol_print_error($this->db);
  4570. return -1;
  4571. }
  4572. }
  4573. return 0;
  4574. }
  4575. /**
  4576. * Delete all extra fields values for the current object.
  4577. *
  4578. * @return int <0 if KO, >0 if OK
  4579. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  4580. */
  4581. public function deleteExtraFields()
  4582. {
  4583. global $conf;
  4584. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0;
  4585. $this->db->begin();
  4586. $table_element = $this->table_element;
  4587. if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
  4588. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
  4589. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  4590. $resql = $this->db->query($sql_del);
  4591. if (!$resql)
  4592. {
  4593. $this->error = $this->db->lasterror();
  4594. $this->db->rollback();
  4595. return -1;
  4596. } else {
  4597. $this->db->commit();
  4598. return 1;
  4599. }
  4600. }
  4601. /**
  4602. * Add/Update all extra fields values for the current object.
  4603. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  4604. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  4605. *
  4606. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  4607. * @param User $userused Object user
  4608. * @return int -1=error, O=did nothing, 1=OK
  4609. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  4610. */
  4611. public function insertExtraFields($trigger = '', $userused = null)
  4612. {
  4613. global $conf, $langs, $user;
  4614. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0;
  4615. if (empty($userused)) $userused = $user;
  4616. $error = 0;
  4617. if (!empty($this->array_options))
  4618. {
  4619. // Check parameters
  4620. $langs->load('admin');
  4621. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4622. $extrafields = new ExtraFields($this->db);
  4623. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  4624. // Eliminate copied source object extra fields that do not exist in target object
  4625. $new_array_options = array();
  4626. foreach ($this->array_options as $key => $value) {
  4627. if (in_array(substr($key, 8), array_keys($target_extrafields))) // We remove the 'options_' from $key for test
  4628. $new_array_options[$key] = $value;
  4629. elseif (in_array($key, array_keys($target_extrafields))) // We test on $key that does not contains the 'options_' prefix
  4630. $new_array_options['options_'.$key] = $value;
  4631. }
  4632. foreach ($new_array_options as $key => $value)
  4633. {
  4634. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  4635. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  4636. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  4637. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  4638. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  4639. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  4640. // Similar code than into insertExtraFields
  4641. if ($attributeRequired)
  4642. {
  4643. $mandatorypb = false;
  4644. if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb = true;
  4645. if ($this->array_options[$key] === '') $mandatorypb = true;
  4646. if ($mandatorypb)
  4647. {
  4648. dol_syslog("Mandatory extra field ".$key." is empty");
  4649. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  4650. return -1;
  4651. }
  4652. }
  4653. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  4654. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  4655. if (!empty($attrfieldcomputed))
  4656. {
  4657. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS))
  4658. {
  4659. $value = dol_eval($attrfieldcomputed, 1, 0);
  4660. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  4661. $new_array_options[$key] = $value;
  4662. } else {
  4663. $new_array_options[$key] = null;
  4664. }
  4665. }
  4666. switch ($attributeType)
  4667. {
  4668. case 'int':
  4669. if (!is_numeric($value) && $value != '')
  4670. {
  4671. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  4672. return -1;
  4673. } elseif ($value == '')
  4674. {
  4675. $new_array_options[$key] = null;
  4676. }
  4677. break;
  4678. case 'price':
  4679. case 'double':
  4680. $value = price2num($value);
  4681. if (!is_numeric($value) && $value != '')
  4682. {
  4683. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  4684. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  4685. return -1;
  4686. } elseif ($value == '')
  4687. {
  4688. $new_array_options[$key] = null;
  4689. }
  4690. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  4691. $new_array_options[$key] = $value;
  4692. break;
  4693. /*case 'select': // Not required, we chosed value='0' for undefined values
  4694. if ($value=='-1')
  4695. {
  4696. $this->array_options[$key] = null;
  4697. }
  4698. break;*/
  4699. case 'password':
  4700. $algo = '';
  4701. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']))
  4702. {
  4703. // If there is an encryption choice, we use it to crypt data before insert
  4704. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  4705. $algo = reset($tmparrays);
  4706. if ($algo != '')
  4707. {
  4708. //global $action; // $action may be 'create', 'update', 'update_extras'...
  4709. //var_dump($action);
  4710. //var_dump($this->oldcopy);exit;
  4711. 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
  4712. {
  4713. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  4714. 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.
  4715. {
  4716. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  4717. } else {
  4718. // var_dump($algo);
  4719. $newvalue = dol_hash($this->array_options[$key], $algo);
  4720. $new_array_options[$key] = $newvalue;
  4721. }
  4722. } else {
  4723. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  4724. }
  4725. }
  4726. } else // Common usage
  4727. {
  4728. $new_array_options[$key] = $this->array_options[$key];
  4729. }
  4730. break;
  4731. case 'date':
  4732. case 'datetime':
  4733. // If data is a string instead of a timestamp, we convert it
  4734. if (!is_int($this->array_options[$key])) {
  4735. $this->array_options[$key] = strtotime($this->array_options[$key]);
  4736. }
  4737. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  4738. break;
  4739. case 'link':
  4740. $param_list = array_keys($attributeParam['options']);
  4741. // 0 : ObjectName
  4742. // 1 : classPath
  4743. $InfoFieldList = explode(":", $param_list[0]);
  4744. dol_include_once($InfoFieldList[1]);
  4745. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  4746. {
  4747. if ($value == '-1') // -1 is key for no defined in combo list of objects
  4748. {
  4749. $new_array_options[$key] = '';
  4750. } elseif ($value) {
  4751. $object = new $InfoFieldList[0]($this->db);
  4752. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  4753. else $res = $object->fetch('', $value); // For compatibility
  4754. if ($res > 0) $new_array_options[$key] = $object->id;
  4755. else {
  4756. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  4757. $this->db->rollback();
  4758. return -1;
  4759. }
  4760. }
  4761. } else {
  4762. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  4763. }
  4764. break;
  4765. }
  4766. }
  4767. $this->db->begin();
  4768. $table_element = $this->table_element;
  4769. if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
  4770. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  4771. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
  4772. $this->db->query($sql_del);
  4773. $sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object";
  4774. foreach ($new_array_options as $key => $value)
  4775. {
  4776. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  4777. // Add field of attribut
  4778. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator
  4779. $sql .= ",".$attributeKey;
  4780. }
  4781. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  4782. if (is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']))
  4783. {
  4784. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval)
  4785. {
  4786. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) // If field not already added previously
  4787. {
  4788. $sql .= ",".$tmpkey;
  4789. }
  4790. }
  4791. }
  4792. $sql .= ") VALUES (".$this->id;
  4793. foreach ($new_array_options as $key => $value)
  4794. {
  4795. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  4796. // Add field of attribute
  4797. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator)
  4798. {
  4799. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0')
  4800. {
  4801. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  4802. } else {
  4803. $sql .= ",null";
  4804. }
  4805. }
  4806. }
  4807. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  4808. if (is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']))
  4809. {
  4810. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval)
  4811. {
  4812. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) // If field not already added previously
  4813. {
  4814. if (in_array($tmpval, array('int', 'double', 'price'))) $sql .= ", 0";
  4815. else $sql .= ", ''";
  4816. }
  4817. }
  4818. }
  4819. $sql .= ")";
  4820. $resql = $this->db->query($sql);
  4821. if (!$resql)
  4822. {
  4823. $this->error = $this->db->lasterror();
  4824. $error++;
  4825. }
  4826. if (!$error && $trigger)
  4827. {
  4828. // Call trigger
  4829. $this->context = array('extrafieldaddupdate'=>1);
  4830. $result = $this->call_trigger($trigger, $userused);
  4831. if ($result < 0) $error++;
  4832. // End call trigger
  4833. }
  4834. if ($error)
  4835. {
  4836. $this->db->rollback();
  4837. return -1;
  4838. } else {
  4839. $this->db->commit();
  4840. return 1;
  4841. }
  4842. } else return 0;
  4843. }
  4844. /**
  4845. * Add/Update all extra fields values for the current object.
  4846. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  4847. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  4848. *
  4849. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  4850. * @param User $userused Object user
  4851. * @return int -1=error, O=did nothing, 1=OK
  4852. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  4853. */
  4854. public function insertExtraLanguages($trigger = '', $userused = null)
  4855. {
  4856. global $conf, $langs, $user;
  4857. if (empty($userused)) $userused = $user;
  4858. $error = 0;
  4859. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) return 0; // For avoid conflicts if trigger used
  4860. if (is_array($this->array_languages))
  4861. {
  4862. $new_array_languages = $this->array_languages;
  4863. foreach ($new_array_languages as $key => $value)
  4864. {
  4865. $attributeKey = $key;
  4866. $attributeType = $this->fields[$attributeKey]['type'];
  4867. $attributeLabel = $this->fields[$attributeKey]['label'];
  4868. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  4869. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  4870. switch ($attributeType)
  4871. {
  4872. case 'int':
  4873. if (!is_numeric($value) && $value != '')
  4874. {
  4875. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  4876. return -1;
  4877. } elseif ($value == '')
  4878. {
  4879. $new_array_languages[$key] = null;
  4880. }
  4881. break;
  4882. case 'double':
  4883. $value = price2num($value);
  4884. if (!is_numeric($value) && $value != '')
  4885. {
  4886. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  4887. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  4888. return -1;
  4889. } elseif ($value == '')
  4890. {
  4891. $new_array_languages[$key] = null;
  4892. }
  4893. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  4894. $new_array_languages[$key] = $value;
  4895. break;
  4896. /*case 'select': // Not required, we chosed value='0' for undefined values
  4897. if ($value=='-1')
  4898. {
  4899. $this->array_options[$key] = null;
  4900. }
  4901. break;*/
  4902. }
  4903. }
  4904. $this->db->begin();
  4905. $table_element = $this->table_element;
  4906. if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
  4907. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  4908. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  4909. foreach ($langcodearray as $langcode => $value) {
  4910. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX."object_lang";
  4911. $sql_del .= " WHERE fk_object = ".$this->id." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  4912. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  4913. $this->db->query($sql_del);
  4914. if ($value !== '') {
  4915. $sql = "INSERT INTO ".MAIN_DB_PREFIX."object_lang (fk_object, property, type_object, lang, value";
  4916. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  4917. $sql .= ")";
  4918. $resql = $this->db->query($sql);
  4919. if (!$resql)
  4920. {
  4921. $this->error = $this->db->lasterror();
  4922. $error++;
  4923. break;
  4924. }
  4925. }
  4926. }
  4927. }
  4928. if (!$error && $trigger)
  4929. {
  4930. // Call trigger
  4931. $this->context = array('extralanguagesaddupdate'=>1);
  4932. $result = $this->call_trigger($trigger, $userused);
  4933. if ($result < 0) $error++;
  4934. // End call trigger
  4935. }
  4936. if ($error)
  4937. {
  4938. $this->db->rollback();
  4939. return -1;
  4940. } else {
  4941. $this->db->commit();
  4942. return 1;
  4943. }
  4944. } else return 0;
  4945. }
  4946. /**
  4947. * Update 1 extra field value for the current object. Keep other fields unchanged.
  4948. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  4949. *
  4950. * @param string $key Key of the extrafield to update (without starting 'options_')
  4951. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  4952. * @param User $userused Object user
  4953. * @return int -1=error, O=did nothing, 1=OK
  4954. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  4955. */
  4956. public function updateExtraField($key, $trigger = null, $userused = null)
  4957. {
  4958. global $conf, $langs, $user;
  4959. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0;
  4960. if (empty($userused)) $userused = $user;
  4961. $error = 0;
  4962. if (!empty($this->array_options) && isset($this->array_options["options_".$key]))
  4963. {
  4964. // Check parameters
  4965. $langs->load('admin');
  4966. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4967. $extrafields = new ExtraFields($this->db);
  4968. $extrafields->fetch_name_optionals_label($this->table_element);
  4969. $value = $this->array_options["options_".$key];
  4970. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  4971. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  4972. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  4973. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  4974. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  4975. // Similar code than into insertExtraFields
  4976. if ($attributeRequired)
  4977. {
  4978. $mandatorypb = false;
  4979. if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') $mandatorypb = true;
  4980. if ($this->array_options["options_".$key] === '') $mandatorypb = true;
  4981. if ($mandatorypb)
  4982. {
  4983. dol_syslog("Mandatory extra field options_".$key." is empty");
  4984. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  4985. return -1;
  4986. }
  4987. }
  4988. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  4989. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  4990. if (!empty($attrfieldcomputed))
  4991. {
  4992. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS))
  4993. {
  4994. $value = dol_eval($attrfieldcomputed, 1, 0);
  4995. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  4996. $this->array_options["options_".$key] = $value;
  4997. } else {
  4998. $this->array_options["options_".$key] = null;
  4999. }
  5000. }
  5001. switch ($attributeType)
  5002. {
  5003. case 'int':
  5004. if (!is_numeric($value) && $value != '')
  5005. {
  5006. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5007. return -1;
  5008. } elseif ($value === '')
  5009. {
  5010. $this->array_options["options_".$key] = null;
  5011. }
  5012. break;
  5013. case 'double':
  5014. $value = price2num($value);
  5015. if (!is_numeric($value) && $value != '')
  5016. {
  5017. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5018. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5019. return -1;
  5020. } elseif ($value === '')
  5021. {
  5022. $this->array_options["options_".$key] = null;
  5023. }
  5024. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5025. $this->array_options["options_".$key] = $value;
  5026. break;
  5027. /*case 'select': // Not required, we chosed value='0' for undefined values
  5028. if ($value=='-1')
  5029. {
  5030. $this->array_options[$key] = null;
  5031. }
  5032. break;*/
  5033. case 'price':
  5034. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  5035. break;
  5036. case 'date':
  5037. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5038. break;
  5039. case 'datetime':
  5040. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5041. break;
  5042. /*
  5043. case 'link':
  5044. $param_list = array_keys($attributeParam['options']);
  5045. // 0 : ObjectName
  5046. // 1 : classPath
  5047. $InfoFieldList = explode(":", $param_list[0]);
  5048. dol_include_once($InfoFieldList[1]);
  5049. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  5050. {
  5051. if ($value == '-1') // -1 is key for no defined in combo list of objects
  5052. {
  5053. $new_array_options[$key] = '';
  5054. } elseif ($value) {
  5055. $object = new $InfoFieldList[0]($this->db);
  5056. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  5057. else $res = $object->fetch('', $value); // For compatibility
  5058. if ($res > 0) $new_array_options[$key] = $object->id;
  5059. else {
  5060. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5061. $this->db->rollback();
  5062. return -1;
  5063. }
  5064. }
  5065. } else {
  5066. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5067. }
  5068. break;
  5069. */
  5070. }
  5071. $this->db->begin();
  5072. $linealreadyfound = 0;
  5073. // 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)
  5074. $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields WHERE fk_object = ".$this->id;
  5075. $resql = $this->db->query($sql);
  5076. if ($resql) {
  5077. $tmpobj = $this->db->fetch_object($resql);
  5078. if ($tmpobj) {
  5079. $linealreadyfound = $tmpobj->nb;
  5080. }
  5081. }
  5082. if ($linealreadyfound) {
  5083. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
  5084. $sql .= " WHERE fk_object = ".$this->id;
  5085. } else {
  5086. $result = $this->insertExtraFields('', $user);
  5087. if ($result < 0) $error++;
  5088. }
  5089. $resql = $this->db->query($sql);
  5090. if (!$resql)
  5091. {
  5092. $error++;
  5093. $this->error = $this->db->lasterror();
  5094. }
  5095. if (!$error && $trigger)
  5096. {
  5097. // Call trigger
  5098. $this->context = array('extrafieldupdate'=>1);
  5099. $result = $this->call_trigger($trigger, $userused);
  5100. if ($result < 0) $error++;
  5101. // End call trigger
  5102. }
  5103. if ($error)
  5104. {
  5105. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  5106. $this->db->rollback();
  5107. return -1;
  5108. } else {
  5109. $this->db->commit();
  5110. return 1;
  5111. }
  5112. } else return 0;
  5113. }
  5114. /**
  5115. * Update an extra language value for the current object.
  5116. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5117. *
  5118. * @param string $key Key of the extrafield (without starting 'options_')
  5119. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5120. * @param User $userused Object user
  5121. * @return int -1=error, O=did nothing, 1=OK
  5122. * @see updateExtraFields(), insertExtraLanguages()
  5123. */
  5124. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  5125. {
  5126. global $conf, $langs, $user;
  5127. if (empty($userused)) $userused = $user;
  5128. $error = 0;
  5129. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) return 0; // For avoid conflicts if trigger used
  5130. return 0;
  5131. }
  5132. /**
  5133. * Return HTML string to put an input field into a page
  5134. * Code very similar with showInputField of extra fields
  5135. *
  5136. * @param array $val Array of properties for field to show (used only if ->fields not defined)
  5137. * @param string $key Key of attribute
  5138. * @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)
  5139. * @param string $moreparam To add more parameters on html input tag
  5140. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5141. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5142. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  5143. * @param int $nonewbutton Force to not show the new button on field that are links to object
  5144. * @return string
  5145. */
  5146. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  5147. {
  5148. global $conf, $langs, $form;
  5149. if (!is_object($form))
  5150. {
  5151. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  5152. $form = new Form($this->db);
  5153. }
  5154. if (!empty($this->fields)) {
  5155. $val = $this->fields[$key];
  5156. }
  5157. $out = '';
  5158. $type = '';
  5159. $param = array();
  5160. $param['options'] = array();
  5161. $reg = array();
  5162. $size = $this->fields[$key]['size'];
  5163. // Because we work on extrafields
  5164. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5165. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5166. $type = 'link';
  5167. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5168. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5169. $type = 'link';
  5170. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  5171. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5172. $type = 'link';
  5173. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5174. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5175. $type = 'sellist';
  5176. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  5177. $param['options'] = array();
  5178. $type = 'varchar';
  5179. $size = $reg[1];
  5180. } elseif (preg_match('/varchar/', $val['type'])) {
  5181. $param['options'] = array();
  5182. $type = 'varchar';
  5183. } elseif (is_array($this->fields[$key]['arrayofkeyval'])) {
  5184. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  5185. $type = 'select';
  5186. } else {
  5187. $param['options'] = array();
  5188. $type = $this->fields[$key]['type'];
  5189. }
  5190. $label = $this->fields[$key]['label'];
  5191. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  5192. $default = $this->fields[$key]['default'];
  5193. $computed = $this->fields[$key]['computed'];
  5194. $unique = $this->fields[$key]['unique'];
  5195. $required = $this->fields[$key]['required'];
  5196. $autofocusoncreate = $this->fields[$key]['autofocusoncreate'];
  5197. $langfile = $this->fields[$key]['langfile'];
  5198. $list = $this->fields[$key]['list'];
  5199. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  5200. $objectid = $this->id;
  5201. if ($computed)
  5202. {
  5203. if (!preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  5204. else return '';
  5205. }
  5206. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  5207. if (empty($morecss) && !empty($val['css'])) {
  5208. $morecss = $val['css'];
  5209. } elseif (empty($morecss)) {
  5210. if ($type == 'date')
  5211. {
  5212. $morecss = 'minwidth100imp';
  5213. } elseif ($type == 'datetime' || $type == 'link') // link means an foreign key to another primary id
  5214. {
  5215. $morecss = 'minwidth200imp';
  5216. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type))
  5217. {
  5218. $morecss = 'maxwidth75';
  5219. } elseif ($type == 'url') {
  5220. $morecss = 'minwidth400';
  5221. } elseif ($type == 'boolean')
  5222. {
  5223. $morecss = '';
  5224. } else {
  5225. if (round($size) < 12)
  5226. {
  5227. $morecss = 'minwidth100';
  5228. } elseif (round($size) <= 48)
  5229. {
  5230. $morecss = 'minwidth200';
  5231. } else {
  5232. $morecss = 'minwidth400';
  5233. }
  5234. }
  5235. }
  5236. if (in_array($type, array('date', 'datetime'))) {
  5237. $tmp = explode(',', $size);
  5238. $newsize = $tmp[0];
  5239. $showtime = in_array($type, array('datetime')) ? 1 : 0;
  5240. // Do not show current date when field not required (see selectDate() method)
  5241. if (!$required && $value == '') $value = '-1';
  5242. // TODO Must also support $moreparam
  5243. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  5244. } elseif (in_array($type, array('duration'))) {
  5245. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  5246. } elseif (in_array($type, array('int', 'integer'))) {
  5247. $tmp = explode(',', $size);
  5248. $newsize = $tmp[0];
  5249. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$newsize.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5250. } elseif (in_array($type, array('real'))) {
  5251. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5252. } elseif (preg_match('/varchar/', $type)) {
  5253. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$size.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5254. } elseif (in_array($type, array('mail', 'phone', 'url'))) {
  5255. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5256. } elseif (preg_match('/^text/', $type)) {
  5257. if (!preg_match('/search_/', $keyprefix)) // If keyprefix is search_ or search_options_, we must just use a simple text field
  5258. {
  5259. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5260. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  5261. $out = $doleditor->Create(1);
  5262. } else {
  5263. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5264. }
  5265. } elseif (preg_match('/^html/', $type)) {
  5266. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  5267. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5268. $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%');
  5269. $out = $doleditor->Create(1);
  5270. } else {
  5271. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5272. }
  5273. } elseif ($type == 'boolean') {
  5274. $checked = '';
  5275. if (!empty($value)) {
  5276. $checked = ' checked value="1" ';
  5277. } else {
  5278. $checked = ' value="1" ';
  5279. }
  5280. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  5281. } elseif ($type == 'price') {
  5282. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5283. $value = price($value);
  5284. }
  5285. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  5286. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  5287. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5288. $value = price($value);
  5289. }
  5290. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  5291. } elseif ($type == 'select') {
  5292. $out = '';
  5293. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
  5294. {
  5295. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5296. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  5297. }
  5298. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  5299. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1))$out .= '<option value="0">&nbsp;</option>';
  5300. foreach ($param['options'] as $key => $val)
  5301. {
  5302. if ((string) $key == '') continue;
  5303. list($val, $parent) = explode('|', $val);
  5304. $out .= '<option value="'.$key.'"';
  5305. $out .= (((string) $value == (string) $key) ? ' selected' : '');
  5306. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  5307. $out .= '>'.$val.'</option>';
  5308. }
  5309. $out .= '</select>';
  5310. } elseif ($type == 'sellist') {
  5311. $out = '';
  5312. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) {
  5313. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5314. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  5315. }
  5316. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  5317. if (is_array($param['options'])) {
  5318. $param_list = array_keys($param['options']);
  5319. $InfoFieldList = explode(":", $param_list[0]);
  5320. $parentName = '';
  5321. $parentField = '';
  5322. // 0 : tableName
  5323. // 1 : label field name
  5324. // 2 : key fields name (if differ of rowid)
  5325. // 3 : key field parent (for dependent lists)
  5326. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  5327. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  5328. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4]))
  5329. {
  5330. if (strpos($InfoFieldList[4], 'extra.') !== false)
  5331. {
  5332. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  5333. } else {
  5334. $keyList = $InfoFieldList[2].' as rowid';
  5335. }
  5336. }
  5337. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3]))
  5338. {
  5339. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  5340. $keyList .= ', '.$parentField;
  5341. }
  5342. $fields_label = explode('|', $InfoFieldList[1]);
  5343. if (is_array($fields_label))
  5344. {
  5345. $keyList .= ', ';
  5346. $keyList .= implode(', ', $fields_label);
  5347. }
  5348. $sqlwhere = '';
  5349. $sql = 'SELECT '.$keyList;
  5350. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  5351. if (!empty($InfoFieldList[4]))
  5352. {
  5353. // can use SELECT request
  5354. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  5355. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  5356. }
  5357. // current object id can be use into filter
  5358. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  5359. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  5360. } else {
  5361. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  5362. }
  5363. //We have to join on extrafield table
  5364. if (strpos($InfoFieldList[4], 'extra') !== false)
  5365. {
  5366. $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
  5367. $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
  5368. } else {
  5369. $sqlwhere .= ' WHERE '.$InfoFieldList[4];
  5370. }
  5371. } else {
  5372. $sqlwhere .= ' WHERE 1=1';
  5373. }
  5374. // Some tables may have field, some other not. For the moment we disable it.
  5375. if (in_array($InfoFieldList[0], array('tablewithentity')))
  5376. {
  5377. $sqlwhere .= ' AND entity = '.$conf->entity;
  5378. }
  5379. $sql .= $sqlwhere;
  5380. //print $sql;
  5381. $sql .= ' ORDER BY '.implode(', ', $fields_label);
  5382. dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
  5383. $resql = $this->db->query($sql);
  5384. if ($resql)
  5385. {
  5386. $out .= '<option value="0">&nbsp;</option>';
  5387. $num = $this->db->num_rows($resql);
  5388. $i = 0;
  5389. while ($i < $num)
  5390. {
  5391. $labeltoshow = '';
  5392. $obj = $this->db->fetch_object($resql);
  5393. // Several field into label (eq table:code|libelle:rowid)
  5394. $notrans = false;
  5395. $fields_label = explode('|', $InfoFieldList[1]);
  5396. if (count($fields_label) > 1)
  5397. {
  5398. $notrans = true;
  5399. foreach ($fields_label as $field_toshow)
  5400. {
  5401. $labeltoshow .= $obj->$field_toshow.' ';
  5402. }
  5403. } else {
  5404. $labeltoshow = $obj->{$InfoFieldList[1]};
  5405. }
  5406. $labeltoshow = dol_trunc($labeltoshow, 45);
  5407. if ($value == $obj->rowid)
  5408. {
  5409. foreach ($fields_label as $field_toshow)
  5410. {
  5411. $translabel = $langs->trans($obj->$field_toshow);
  5412. if ($translabel != $obj->$field_toshow) {
  5413. $labeltoshow = dol_trunc($translabel, 18).' ';
  5414. } else {
  5415. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  5416. }
  5417. }
  5418. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  5419. } else {
  5420. if (!$notrans)
  5421. {
  5422. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  5423. if ($translabel != $obj->{$InfoFieldList[1]}) {
  5424. $labeltoshow = dol_trunc($translabel, 18);
  5425. } else {
  5426. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  5427. }
  5428. }
  5429. if (empty($labeltoshow)) $labeltoshow = '(not defined)';
  5430. if ($value == $obj->rowid)
  5431. {
  5432. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  5433. }
  5434. if (!empty($InfoFieldList[3]) && $parentField)
  5435. {
  5436. $parent = $parentName.':'.$obj->{$parentField};
  5437. }
  5438. $out .= '<option value="'.$obj->rowid.'"';
  5439. $out .= ($value == $obj->rowid ? ' selected' : '');
  5440. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  5441. $out .= '>'.$labeltoshow.'</option>';
  5442. }
  5443. $i++;
  5444. }
  5445. $this->db->free($resql);
  5446. } else {
  5447. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  5448. }
  5449. }
  5450. $out .= '</select>';
  5451. } elseif ($type == 'checkbox') {
  5452. $value_arr = explode(',', $value);
  5453. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
  5454. } elseif ($type == 'radio') {
  5455. $out = '';
  5456. foreach ($param['options'] as $keyopt => $val)
  5457. {
  5458. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  5459. $out .= ' value="'.$keyopt.'"';
  5460. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  5461. $out .= ($value == $keyopt ? 'checked' : '');
  5462. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
  5463. }
  5464. } elseif ($type == 'chkbxlst') {
  5465. if (is_array($value)) {
  5466. $value_arr = $value;
  5467. } else {
  5468. $value_arr = explode(',', $value);
  5469. }
  5470. if (is_array($param['options'])) {
  5471. $param_list = array_keys($param['options']);
  5472. $InfoFieldList = explode(":", $param_list[0]);
  5473. $parentName = '';
  5474. $parentField = '';
  5475. // 0 : tableName
  5476. // 1 : label field name
  5477. // 2 : key fields name (if differ of rowid)
  5478. // 3 : key field parent (for dependent lists)
  5479. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  5480. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  5481. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  5482. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  5483. $keyList .= ', '.$parentField;
  5484. }
  5485. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  5486. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  5487. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  5488. } else {
  5489. $keyList = $InfoFieldList[2].' as rowid';
  5490. }
  5491. }
  5492. $fields_label = explode('|', $InfoFieldList[1]);
  5493. if (is_array($fields_label)) {
  5494. $keyList .= ', ';
  5495. $keyList .= implode(', ', $fields_label);
  5496. }
  5497. $sqlwhere = '';
  5498. $sql = 'SELECT '.$keyList;
  5499. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  5500. if (!empty($InfoFieldList[4])) {
  5501. // can use SELECT request
  5502. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  5503. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  5504. }
  5505. // current object id can be use into filter
  5506. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  5507. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  5508. } else {
  5509. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  5510. }
  5511. // We have to join on extrafield table
  5512. if (strpos($InfoFieldList[4], 'extra') !== false) {
  5513. $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
  5514. $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
  5515. } else {
  5516. $sqlwhere .= ' WHERE '.$InfoFieldList[4];
  5517. }
  5518. } else {
  5519. $sqlwhere .= ' WHERE 1=1';
  5520. }
  5521. // Some tables may have field, some other not. For the moment we disable it.
  5522. if (in_array($InfoFieldList[0], array('tablewithentity')))
  5523. {
  5524. $sqlwhere .= ' AND entity = '.$conf->entity;
  5525. }
  5526. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  5527. // print $sql;
  5528. $sql .= $sqlwhere;
  5529. dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
  5530. $resql = $this->db->query($sql);
  5531. if ($resql) {
  5532. $num = $this->db->num_rows($resql);
  5533. $i = 0;
  5534. $data = array();
  5535. while ($i < $num) {
  5536. $labeltoshow = '';
  5537. $obj = $this->db->fetch_object($resql);
  5538. $notrans = false;
  5539. // Several field into label (eq table:code|libelle:rowid)
  5540. $fields_label = explode('|', $InfoFieldList[1]);
  5541. if (count($fields_label) > 1) {
  5542. $notrans = true;
  5543. foreach ($fields_label as $field_toshow) {
  5544. $labeltoshow .= $obj->$field_toshow.' ';
  5545. }
  5546. } else {
  5547. $labeltoshow = $obj->{$InfoFieldList[1]};
  5548. }
  5549. $labeltoshow = dol_trunc($labeltoshow, 45);
  5550. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  5551. foreach ($fields_label as $field_toshow) {
  5552. $translabel = $langs->trans($obj->$field_toshow);
  5553. if ($translabel != $obj->$field_toshow) {
  5554. $labeltoshow = dol_trunc($translabel, 18).' ';
  5555. } else {
  5556. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  5557. }
  5558. }
  5559. $data[$obj->rowid] = $labeltoshow;
  5560. } else {
  5561. if (!$notrans) {
  5562. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  5563. if ($translabel != $obj->{$InfoFieldList[1]}) {
  5564. $labeltoshow = dol_trunc($translabel, 18);
  5565. } else {
  5566. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  5567. }
  5568. }
  5569. if (empty($labeltoshow)) {
  5570. $labeltoshow = '(not defined)';
  5571. }
  5572. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  5573. $data[$obj->rowid] = $labeltoshow;
  5574. }
  5575. if (!empty($InfoFieldList[3]) && $parentField) {
  5576. $parent = $parentName.':'.$obj->{$parentField};
  5577. }
  5578. $data[$obj->rowid] = $labeltoshow;
  5579. }
  5580. $i++;
  5581. }
  5582. $this->db->free($resql);
  5583. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
  5584. } else {
  5585. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  5586. }
  5587. }
  5588. } elseif ($type == 'link') {
  5589. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter]]'
  5590. $param_list_array = explode(':', $param_list[0]);
  5591. $showempty = (($required && $default != '') ? 0 : 1);
  5592. if (!preg_match('/search_/', $keyprefix)) {
  5593. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  5594. if ($this->fields[$key]['picto']) {
  5595. $morecss .= ' widthcentpercentminusxx';
  5596. } else {
  5597. $morecss .= ' widthcentpercentminusx';
  5598. }
  5599. } else {
  5600. if ($this->fields[$key]['picto']) {
  5601. $morecss .= ' widthcentpercentminusx';
  5602. }
  5603. }
  5604. }
  5605. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  5606. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  5607. 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".
  5608. {
  5609. list($class, $classfile) = explode(':', $param_list[0]);
  5610. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  5611. else $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  5612. $paramforthenewlink = '';
  5613. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  5614. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  5615. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  5616. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  5617. $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>';
  5618. }
  5619. }
  5620. } elseif ($type == 'password') {
  5621. // If prefix is 'search_', field is used as a filter, we use a common text field.
  5622. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  5623. } elseif ($type == 'array') {
  5624. $newval = $val;
  5625. $newval['type'] = 'varchar(256)';
  5626. $out = '';
  5627. if (!empty($value)) {
  5628. foreach ($value as $option) {
  5629. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  5630. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  5631. }
  5632. }
  5633. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  5634. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  5635. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  5636. if (!empty($conf->use_javascript_ajax)) {
  5637. $out .= '
  5638. <script>
  5639. $(document).ready(function() {
  5640. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  5641. $("'.dol_escape_js($newInput).'").insertBefore(this);
  5642. });
  5643. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  5644. $(this).parent().remove();
  5645. });
  5646. });
  5647. </script>';
  5648. }
  5649. }
  5650. if (!empty($hidden)) {
  5651. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  5652. }
  5653. /* Add comments
  5654. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  5655. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  5656. */
  5657. return $out;
  5658. }
  5659. /**
  5660. * Return HTML string to show a field into a page
  5661. * Code very similar with showOutputField of extra fields
  5662. *
  5663. * @param array $val Array of properties of field to show
  5664. * @param string $key Key of attribute
  5665. * @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)
  5666. * @param string $moreparam To add more parametes on html input tag
  5667. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5668. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5669. * @param mixed $morecss Value for css to define size. May also be a numeric.
  5670. * @return string
  5671. */
  5672. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  5673. {
  5674. global $conf, $langs, $form;
  5675. if (!is_object($form))
  5676. {
  5677. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  5678. $form = new Form($this->db);
  5679. }
  5680. $objectid = $this->id;
  5681. $label = $val['label'];
  5682. $type = $val['type'];
  5683. $size = $val['css'];
  5684. $reg = array();
  5685. // Convert var to be able to share same code than showOutputField of extrafields
  5686. if (preg_match('/varchar\((\d+)\)/', $type, $reg))
  5687. {
  5688. $type = 'varchar'; // convert varchar(xx) int varchar
  5689. $size = $reg[1];
  5690. } elseif (preg_match('/varchar/', $type)) $type = 'varchar'; // convert varchar(xx) int varchar
  5691. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) $type = 'select';
  5692. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type = 'link';
  5693. $default = $val['default'];
  5694. $computed = $val['computed'];
  5695. $unique = $val['unique'];
  5696. $required = $val['required'];
  5697. $param = array();
  5698. $param['options'] = array();
  5699. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval'];
  5700. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg))
  5701. {
  5702. $type = 'link';
  5703. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  5704. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5705. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5706. $type = 'sellist';
  5707. }
  5708. $langfile = $val['langfile'];
  5709. $list = $val['list'];
  5710. $help = $val['help'];
  5711. $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)
  5712. if ($hidden) return '';
  5713. // If field is a computed field, value must become result of compute
  5714. if ($computed)
  5715. {
  5716. // Make the eval of compute string
  5717. //var_dump($computed);
  5718. $value = dol_eval($computed, 1, 0);
  5719. }
  5720. if (empty($morecss))
  5721. {
  5722. if ($type == 'date') {
  5723. $morecss = 'minwidth100imp';
  5724. } elseif ($type == 'datetime' || $type == 'timestamp') {
  5725. $morecss = 'minwidth200imp';
  5726. } elseif (in_array($type, array('int', 'double', 'price'))) {
  5727. $morecss = 'maxwidth75';
  5728. } elseif ($type == 'url') {
  5729. $morecss = 'minwidth400';
  5730. } elseif ($type == 'boolean') {
  5731. $morecss = '';
  5732. } else {
  5733. if (round($size) < 12) {
  5734. $morecss = 'minwidth100';
  5735. } elseif (round($size) <= 48) {
  5736. $morecss = 'minwidth200';
  5737. } else {
  5738. $morecss = 'minwidth400';
  5739. }
  5740. }
  5741. }
  5742. // Format output value differently according to properties of field
  5743. if ($key == 'ref' && method_exists($this, 'getNomUrl')) $value = $this->getNomUrl(1, '', 0, '', 1);
  5744. elseif ($key == 'status' && method_exists($this, 'getLibStatut')) $value = $this->getLibStatut(3);
  5745. elseif ($type == 'date') {
  5746. if (!empty($value)) {
  5747. $value = dol_print_date($value, 'day');
  5748. } else {
  5749. $value = '';
  5750. }
  5751. } elseif ($type == 'datetime' || $type == 'timestamp') {
  5752. if (!empty($value)) {
  5753. $value = dol_print_date($value, 'dayhour');
  5754. } else {
  5755. $value = '';
  5756. }
  5757. } elseif ($type == 'duration') {
  5758. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5759. if (!is_null($value) && $value !== '') {
  5760. $value = convertSecondToTime($value, 'allhourmin');
  5761. }
  5762. } elseif ($type == 'double' || $type == 'real') {
  5763. if (!is_null($value) && $value !== '') {
  5764. $value = price($value);
  5765. }
  5766. } elseif ($type == 'boolean') {
  5767. $checked = '';
  5768. if (!empty($value)) {
  5769. $checked = ' checked ';
  5770. }
  5771. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  5772. } elseif ($type == 'mail') {
  5773. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  5774. } elseif ($type == 'url') {
  5775. $value = dol_print_url($value, '_blank', 32, 1);
  5776. } elseif ($type == 'phone') {
  5777. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
  5778. } elseif ($type == 'price')
  5779. {
  5780. if (!is_null($value) && $value !== '') {
  5781. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  5782. }
  5783. } elseif ($type == 'select') {
  5784. $value = $param['options'][$value];
  5785. } elseif ($type == 'sellist') {
  5786. $param_list = array_keys($param['options']);
  5787. $InfoFieldList = explode(":", $param_list[0]);
  5788. $selectkey = "rowid";
  5789. $keyList = 'rowid';
  5790. if (count($InfoFieldList) >= 3)
  5791. {
  5792. $selectkey = $InfoFieldList[2];
  5793. $keyList = $InfoFieldList[2].' as rowid';
  5794. }
  5795. $fields_label = explode('|', $InfoFieldList[1]);
  5796. if (is_array($fields_label)) {
  5797. $keyList .= ', ';
  5798. $keyList .= implode(', ', $fields_label);
  5799. }
  5800. $sql = 'SELECT '.$keyList;
  5801. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  5802. if (strpos($InfoFieldList[4], 'extra') !== false)
  5803. {
  5804. $sql .= ' as main';
  5805. }
  5806. if ($selectkey == 'rowid' && empty($value)) {
  5807. $sql .= " WHERE ".$selectkey."=0";
  5808. } elseif ($selectkey == 'rowid') {
  5809. $sql .= " WHERE ".$selectkey."=".$this->db->escape($value);
  5810. } else {
  5811. $sql .= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  5812. }
  5813. //$sql.= ' AND entity = '.$conf->entity;
  5814. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  5815. $resql = $this->db->query($sql);
  5816. if ($resql)
  5817. {
  5818. $value = ''; // value was used, so now we reste it to use it to build final output
  5819. $obj = $this->db->fetch_object($resql);
  5820. // Several field into label (eq table:code|libelle:rowid)
  5821. $fields_label = explode('|', $InfoFieldList[1]);
  5822. if (is_array($fields_label) && count($fields_label) > 1)
  5823. {
  5824. foreach ($fields_label as $field_toshow)
  5825. {
  5826. $translabel = '';
  5827. if (!empty($obj->$field_toshow)) {
  5828. $translabel = $langs->trans($obj->$field_toshow);
  5829. }
  5830. if ($translabel != $field_toshow) {
  5831. $value .= dol_trunc($translabel, 18).' ';
  5832. } else {
  5833. $value .= $obj->$field_toshow.' ';
  5834. }
  5835. }
  5836. } else {
  5837. $translabel = '';
  5838. if (!empty($obj->{$InfoFieldList[1]})) {
  5839. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  5840. }
  5841. if ($translabel != $obj->{$InfoFieldList[1]}) {
  5842. $value = dol_trunc($translabel, 18);
  5843. } else {
  5844. $value = $obj->{$InfoFieldList[1]};
  5845. }
  5846. }
  5847. } else dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  5848. } elseif ($type == 'radio') {
  5849. $value = $param['options'][$value];
  5850. } elseif ($type == 'checkbox') {
  5851. $value_arr = explode(',', $value);
  5852. $value = '';
  5853. if (is_array($value_arr) && count($value_arr) > 0)
  5854. {
  5855. $toprint = array();
  5856. foreach ($value_arr as $keyval=>$valueval) {
  5857. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  5858. }
  5859. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  5860. }
  5861. } elseif ($type == 'chkbxlst') {
  5862. $value_arr = explode(',', $value);
  5863. $param_list = array_keys($param['options']);
  5864. $InfoFieldList = explode(":", $param_list[0]);
  5865. $selectkey = "rowid";
  5866. $keyList = 'rowid';
  5867. if (count($InfoFieldList) >= 3) {
  5868. $selectkey = $InfoFieldList[2];
  5869. $keyList = $InfoFieldList[2].' as rowid';
  5870. }
  5871. $fields_label = explode('|', $InfoFieldList[1]);
  5872. if (is_array($fields_label)) {
  5873. $keyList .= ', ';
  5874. $keyList .= implode(', ', $fields_label);
  5875. }
  5876. $sql = 'SELECT '.$keyList;
  5877. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  5878. if (strpos($InfoFieldList[4], 'extra') !== false) {
  5879. $sql .= ' as main';
  5880. }
  5881. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  5882. // $sql.= ' AND entity = '.$conf->entity;
  5883. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  5884. $resql = $this->db->query($sql);
  5885. if ($resql) {
  5886. $value = ''; // value was used, so now we reste it to use it to build final output
  5887. $toprint = array();
  5888. while ($obj = $this->db->fetch_object($resql)) {
  5889. // Several field into label (eq table:code|libelle:rowid)
  5890. $fields_label = explode('|', $InfoFieldList[1]);
  5891. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  5892. if (is_array($fields_label) && count($fields_label) > 1) {
  5893. foreach ($fields_label as $field_toshow) {
  5894. $translabel = '';
  5895. if (!empty($obj->$field_toshow)) {
  5896. $translabel = $langs->trans($obj->$field_toshow);
  5897. }
  5898. if ($translabel != $field_toshow) {
  5899. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  5900. } else {
  5901. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->$field_toshow.'</li>';
  5902. }
  5903. }
  5904. } else {
  5905. $translabel = '';
  5906. if (!empty($obj->{$InfoFieldList[1]})) {
  5907. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  5908. }
  5909. if ($translabel != $obj->{$InfoFieldList[1]}) {
  5910. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  5911. } else {
  5912. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->{$InfoFieldList[1]}.'</li>';
  5913. }
  5914. }
  5915. }
  5916. }
  5917. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  5918. } else {
  5919. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  5920. }
  5921. } elseif ($type == 'link') {
  5922. $out = '';
  5923. // only if something to display (perf)
  5924. if ($value)
  5925. {
  5926. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  5927. $InfoFieldList = explode(":", $param_list[0]);
  5928. $classname = $InfoFieldList[0];
  5929. $classpath = $InfoFieldList[1];
  5930. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  5931. if (!empty($classpath))
  5932. {
  5933. dol_include_once($InfoFieldList[1]);
  5934. if ($classname && class_exists($classname))
  5935. {
  5936. $object = new $classname($this->db);
  5937. $object->fetch($value);
  5938. $value = $object->getNomUrl($getnomurlparam);
  5939. }
  5940. } else {
  5941. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5942. return 'Error bad setup of extrafield';
  5943. }
  5944. } else $value = '';
  5945. } elseif (preg_match('/^(text|html)/', $type)) {
  5946. $value = dol_htmlentitiesbr($value);
  5947. } elseif ($type == 'password') {
  5948. $value = preg_replace('/./i', '*', $value);
  5949. } elseif ($type == 'array') {
  5950. $value = implode('<br>', $value);
  5951. }
  5952. //print $type.'-'.$size.'-'.$value;
  5953. $out = $value;
  5954. return $out;
  5955. }
  5956. /**
  5957. * Function to show lines of extrafields with output datas.
  5958. * This function is responsible to output the <tr> and <td> according to correct number of columns received into $params['colspan']
  5959. *
  5960. * @param Extrafields $extrafields Extrafield Object
  5961. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  5962. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  5963. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  5964. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  5965. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  5966. * @return string
  5967. */
  5968. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0)
  5969. {
  5970. global $db, $conf, $langs, $action, $form, $hookmanager;
  5971. if (!is_object($form)) $form = new Form($db);
  5972. $out = '';
  5973. $parameters = array();
  5974. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  5975. if (empty($reshook))
  5976. {
  5977. if (is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0)
  5978. {
  5979. $out .= "\n";
  5980. $out .= '<!-- showOptionals --> ';
  5981. $out .= "\n";
  5982. $extrafields_collapse_num = '';
  5983. $e = 0;
  5984. foreach ($extrafields->attributes[$this->table_element]['label'] as $key=>$label)
  5985. {
  5986. // Show only the key field in params
  5987. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) continue;
  5988. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  5989. $enabled = 1;
  5990. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key]))
  5991. {
  5992. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1);
  5993. }
  5994. if (empty($enabled)) continue;
  5995. $visibility = 1;
  5996. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key]))
  5997. {
  5998. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1);
  5999. }
  6000. $perms = 1;
  6001. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key]))
  6002. {
  6003. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1);
  6004. }
  6005. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  6006. elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  6007. elseif ($mode == 'view' && empty($visibility)) continue;
  6008. if (empty($perms)) continue;
  6009. // Load language if required
  6010. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  6011. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  6012. }
  6013. $colspan = '';
  6014. if (is_array($params) && count($params) > 0) {
  6015. if (array_key_exists('cols', $params)) {
  6016. $colspan = $params['cols'];
  6017. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  6018. $reg = array();
  6019. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  6020. $colspan = $reg[1];
  6021. } else {
  6022. $colspan = $params['colspan'];
  6023. }
  6024. }
  6025. }
  6026. switch ($mode) {
  6027. case "view":
  6028. $value = $this->array_options["options_".$key.$keysuffix]; // Value may be clean or formated later
  6029. break;
  6030. case "create":
  6031. case "edit":
  6032. // We get the value of property found with GETPOST so it takes into account:
  6033. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  6034. $check = 'alphanohtml';
  6035. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  6036. $check = 'restricthtml';
  6037. }
  6038. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  6039. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  6040. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix))
  6041. {
  6042. if (is_array($getposttemp)) {
  6043. // $getposttemp is an array but following code expects a comma separated string
  6044. $value = implode(",", $getposttemp);
  6045. } else {
  6046. $value = $getposttemp;
  6047. }
  6048. } else {
  6049. $value = $this->array_options["options_".$key]; // No GET, no POST, no default value, so we take value of object.
  6050. }
  6051. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  6052. break;
  6053. }
  6054. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate')
  6055. {
  6056. $extrafields_collapse_num = '';
  6057. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  6058. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  6059. $extrafield_param_list = array_keys($extrafield_param['options']);
  6060. if (count($extrafield_param_list) > 0) {
  6061. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  6062. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  6063. $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  6064. }
  6065. }
  6066. }
  6067. $out .= $extrafields->showSeparator($key, $this, ($colspan + 1));
  6068. } else {
  6069. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  6070. $csstyle = '';
  6071. if (is_array($params) && count($params) > 0) {
  6072. if (array_key_exists('class', $params)) {
  6073. $class .= $params['class'].' ';
  6074. }
  6075. if (array_key_exists('style', $params)) {
  6076. $csstyle = $params['style'];
  6077. }
  6078. }
  6079. // add html5 elements
  6080. $domData = ' data-element="extrafield"';
  6081. $domData .= ' data-targetelement="'.$this->element.'"';
  6082. $domData .= ' data-targetid="'.$this->id.'"';
  6083. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  6084. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) { $colspan = '0'; }
  6085. if ($action == 'selectlines') { $colspan++; }
  6086. // Convert date into timestamp format (value in memory must be a timestamp)
  6087. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime')))
  6088. {
  6089. $datenotinstring = $this->array_options['options_'.$key];
  6090. if (!is_numeric($this->array_options['options_'.$key])) // For backward compatibility
  6091. {
  6092. $datenotinstring = $this->db->jdate($datenotinstring);
  6093. }
  6094. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) ? dol_mktime(GETPOST($keyprefix.'options_'.$key.$keysuffix."hour", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."min", 'int', 3), 0, GETPOST($keyprefix.'options_'.$key.$keysuffix."month", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."day", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."year", 'int', 3)) : $datenotinstring;
  6095. }
  6096. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  6097. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double')))
  6098. {
  6099. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? price2num($value) : $this->array_options['options_'.$key];
  6100. }
  6101. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  6102. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int')))
  6103. {
  6104. if ($action == 'create') $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  6105. }
  6106. $labeltoshow = $langs->trans($label);
  6107. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  6108. $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="'.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.'" '.$domData.' >';
  6109. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) {
  6110. $out .= '<td></td>';
  6111. }
  6112. $out .= '<td class="wordbreak';
  6113. //$out .= "titlefield";
  6114. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  6115. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  6116. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  6117. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  6118. $out .= '">';
  6119. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  6120. else $out .= $labeltoshow;
  6121. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= '&nbsp;<font color="red">*</font>';
  6122. } else {
  6123. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= ' fieldrequired';
  6124. $out .= '">';
  6125. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  6126. else $out .= $labeltoshow;
  6127. }
  6128. $out .= '</td>';
  6129. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  6130. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').'class="'.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  6131. switch ($mode) {
  6132. case "view":
  6133. $out .= $extrafields->showOutputField($key, $value);
  6134. break;
  6135. case "create":
  6136. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  6137. break;
  6138. case "edit":
  6139. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  6140. break;
  6141. }
  6142. $out .= '</td>';
  6143. /*for($ii = 0; $ii < ($colspan - 1); $ii++)
  6144. {
  6145. $out .='<td class="'.$this->element.'_extras_'.$key.'"></td>';
  6146. }*/
  6147. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) $out .= '</tr>';
  6148. else $out .= '</tr>';
  6149. $e++;
  6150. }
  6151. }
  6152. $out .= "\n";
  6153. // Add code to manage list depending on others
  6154. if (!empty($conf->use_javascript_ajax)) {
  6155. $out .= '
  6156. <script>
  6157. jQuery(document).ready(function() {
  6158. function showOptions(child_list, parent_list, orig_select)
  6159. {
  6160. var val = $("select[name=\""+parent_list+"\"]").val();
  6161. var parentVal = parent_list + ":" + val;
  6162. if(val > 0) {
  6163. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  6164. $("select[name=\""+child_list+"\"] option[parent]").remove();
  6165. $("select[name=\""+child_list+"\"]").append(options);
  6166. } else {
  6167. var options = orig_select.find("option[parent]").clone();
  6168. $("select[name=\""+child_list+"\"] option[parent]").remove();
  6169. $("select[name=\""+child_list+"\"]").append(options);
  6170. }
  6171. }
  6172. function setListDependencies() {
  6173. jQuery("select option[parent]").parent().each(function() {
  6174. var orig_select = {};
  6175. var child_list = $(this).attr("name");
  6176. orig_select[child_list] = $(this).clone();
  6177. var parent = $(this).find("option[parent]:first").attr("parent");
  6178. var infos = parent.split(":");
  6179. var parent_list = infos[0];
  6180. $("select[name=\""+parent_list+"\"]").change(function() {
  6181. showOptions(child_list, parent_list, orig_select[child_list]);
  6182. });
  6183. });
  6184. }
  6185. setListDependencies();
  6186. });
  6187. </script>'."\n";
  6188. }
  6189. $out .= '<!-- /showOptionals --> '."\n";
  6190. }
  6191. }
  6192. $out .= $hookmanager->resPrint;
  6193. return $out;
  6194. }
  6195. /**
  6196. * Returns the rights used for this class
  6197. * @return stdClass
  6198. */
  6199. public function getRights()
  6200. {
  6201. global $user;
  6202. $element = $this->element;
  6203. if ($element == 'facturerec') $element = 'facture';
  6204. return $user->rights->{$element};
  6205. }
  6206. /**
  6207. * Function used to replace a thirdparty id with another one.
  6208. * This function is meant to be called from replaceThirdparty with the appropiate tables
  6209. * Column name fk_soc MUST be used to identify thirdparties
  6210. *
  6211. * @param DoliDB $db Database handler
  6212. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  6213. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  6214. * @param string[] $tables Tables that need to be changed
  6215. * @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)
  6216. * @return bool True if success, False if error
  6217. */
  6218. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  6219. {
  6220. foreach ($tables as $table)
  6221. {
  6222. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.$dest_id.' WHERE fk_soc = '.$origin_id;
  6223. if (!$db->query($sql))
  6224. {
  6225. if ($ignoreerrors) return true; // TODO Not enough. If there is A-B on kept thirdarty and B-C on old one, we must get A-B-C after merge. Not A-B.
  6226. //$this->errors = $db->lasterror();
  6227. return false;
  6228. }
  6229. }
  6230. return true;
  6231. }
  6232. /**
  6233. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  6234. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  6235. * else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  6236. * else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  6237. * else set min buy price as buy price
  6238. *
  6239. * @param float $unitPrice Product unit price
  6240. * @param float $discountPercent Line discount percent
  6241. * @param int $fk_product Product id
  6242. * @return float <0 if KO, buyprice if OK
  6243. */
  6244. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  6245. {
  6246. global $conf;
  6247. $buyPrice = 0;
  6248. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) // In most cases, test here is false
  6249. {
  6250. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  6251. } else {
  6252. // Get cost price for margin calculation
  6253. if (!empty($fk_product))
  6254. {
  6255. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice')
  6256. {
  6257. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6258. $product = new Product($this->db);
  6259. $result = $product->fetch($fk_product);
  6260. if ($result <= 0)
  6261. {
  6262. $this->errors[] = 'ErrorProductIdDoesNotExists';
  6263. return -1;
  6264. }
  6265. if ($product->cost_price > 0)
  6266. {
  6267. $buyPrice = $product->cost_price;
  6268. } elseif ($product->pmp > 0)
  6269. {
  6270. $buyPrice = $product->pmp;
  6271. }
  6272. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp')
  6273. {
  6274. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6275. $product = new Product($this->db);
  6276. $result = $product->fetch($fk_product);
  6277. if ($result <= 0)
  6278. {
  6279. $this->errors[] = 'ErrorProductIdDoesNotExists';
  6280. return -1;
  6281. }
  6282. if ($product->pmp > 0)
  6283. {
  6284. $buyPrice = $product->pmp;
  6285. }
  6286. }
  6287. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice')))
  6288. {
  6289. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  6290. $productFournisseur = new ProductFournisseur($this->db);
  6291. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0)
  6292. {
  6293. $buyPrice = $productFournisseur->fourn_unitprice;
  6294. } elseif ($result < 0)
  6295. {
  6296. $this->errors[] = $productFournisseur->error;
  6297. return -2;
  6298. }
  6299. }
  6300. }
  6301. }
  6302. return $buyPrice;
  6303. }
  6304. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6305. /**
  6306. * Show photos of an object (nbmax maximum), into several columns
  6307. *
  6308. * @param string $modulepart 'product', 'ticket', ...
  6309. * @param string $sdir Directory to scan (full absolute path)
  6310. * @param int $size 0=original size, 1='small' use thumbnail if possible
  6311. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  6312. * @param int $nbbyrow Number of image per line or -1 to use div. Used only if size=1.
  6313. * @param int $showfilename 1=Show filename
  6314. * @param int $showaction 1=Show icon with action links (resize, delete)
  6315. * @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.
  6316. * @param int $maxWidth Max width of original image when size='small'
  6317. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  6318. * @param int $notitle Do not add title tag on image
  6319. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  6320. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  6321. */
  6322. 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)
  6323. {
  6324. // phpcs:enable
  6325. global $conf, $user, $langs;
  6326. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  6327. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  6328. $sortfield = 'position_name';
  6329. $sortorder = 'asc';
  6330. $dir = $sdir.'/';
  6331. $pdir = '/';
  6332. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/';
  6333. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/';
  6334. // For backward compatibility
  6335. if ($modulepart == 'product' && !empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
  6336. {
  6337. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  6338. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  6339. }
  6340. // Defined relative dir to DOL_DATA_ROOT
  6341. $relativedir = '';
  6342. if ($dir)
  6343. {
  6344. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  6345. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  6346. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  6347. }
  6348. $dirthumb = $dir.'thumbs/';
  6349. $pdirthumb = $pdir.'thumbs/';
  6350. $return = '<!-- Photo -->'."\n";
  6351. $nbphoto = 0;
  6352. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  6353. /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
  6354. {
  6355. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  6356. $filearray=array_merge($filearray, $filearrayold);
  6357. }*/
  6358. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  6359. if (count($filearray))
  6360. {
  6361. if ($sortfield && $sortorder)
  6362. {
  6363. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  6364. }
  6365. foreach ($filearray as $key => $val)
  6366. {
  6367. $photo = '';
  6368. $file = $val['name'];
  6369. //if (! utf8_check($file)) $file=utf8_encode($file); // To be sure file is stored in UTF8 in memory
  6370. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  6371. if (image_format_supported($file) >= 0)
  6372. {
  6373. $nbphoto++;
  6374. $photo = $file;
  6375. $viewfilename = $file;
  6376. if ($size == 1 || $size == 'small') { // Format vignette
  6377. // Find name of thumb file
  6378. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  6379. if (!dol_is_file($dirthumb.$photo_vignette)) $photo_vignette = '';
  6380. // Get filesize of original file
  6381. $imgarray = dol_getImageSize($dir.$photo);
  6382. if ($nbbyrow > 0)
  6383. {
  6384. if ($nbphoto == 1) $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  6385. if ($nbphoto % $nbbyrow == 1) $return .= '<tr class="center valignmiddle" style="border: 1px">';
  6386. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
  6387. } elseif ($nbbyrow < 0) $return .= '<div class="inline-block">';
  6388. $return .= "\n";
  6389. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  6390. if (empty($nolink))
  6391. {
  6392. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  6393. if ($urladvanced) $return .= '<a href="'.$urladvanced.'">';
  6394. else $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
  6395. }
  6396. // Show image (width height=$maxHeight)
  6397. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  6398. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  6399. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  6400. if ($notitle) $alt = '';
  6401. if ($usesharelink)
  6402. {
  6403. if ($val['share'])
  6404. {
  6405. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
  6406. {
  6407. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  6408. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  6409. } else {
  6410. $return .= '<!-- Show original file -->';
  6411. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  6412. }
  6413. } else {
  6414. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  6415. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  6416. }
  6417. } else {
  6418. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
  6419. {
  6420. $return .= '<!-- Show thumb -->';
  6421. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdirthumb.$photo_vignette).'" title="'.dol_escape_htmltag($alt).'">';
  6422. } else {
  6423. $return .= '<!-- Show original file -->';
  6424. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" title="'.dol_escape_htmltag($alt).'">';
  6425. }
  6426. }
  6427. if (empty($nolink)) $return .= '</a>';
  6428. $return .= "\n";
  6429. if ($showfilename) $return .= '<br>'.$viewfilename;
  6430. if ($showaction)
  6431. {
  6432. $return .= '<br>';
  6433. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  6434. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight))
  6435. {
  6436. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=addthumb&amp;file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'), 'refresh').'&nbsp;&nbsp;</a>';
  6437. }
  6438. // Special cas for product
  6439. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
  6440. {
  6441. // Link to resize
  6442. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&amp;file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  6443. // Link to delete
  6444. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;token='.newToken().'&amp;file='.urlencode($pdir.$viewfilename).'">';
  6445. $return .= img_delete().'</a>';
  6446. }
  6447. }
  6448. $return .= "\n";
  6449. if ($nbbyrow > 0)
  6450. {
  6451. $return .= '</td>';
  6452. if (($nbphoto % $nbbyrow) == 0) $return .= '</tr>';
  6453. } elseif ($nbbyrow < 0) $return .= '</div>';
  6454. }
  6455. if (empty($size)) { // Format origine
  6456. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  6457. if ($showfilename) $return .= '<br>'.$viewfilename;
  6458. if ($showaction)
  6459. {
  6460. // Special case for product
  6461. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
  6462. {
  6463. // Link to resize
  6464. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&amp;file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  6465. // Link to delete
  6466. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;token='.newToken().'&amp;file='.urlencode($pdir.$viewfilename).'">';
  6467. $return .= img_delete().'</a>';
  6468. }
  6469. }
  6470. }
  6471. // On continue ou on arrete de boucler ?
  6472. if ($nbmax && $nbphoto >= $nbmax) break;
  6473. }
  6474. }
  6475. if ($size == 1 || $size == 'small')
  6476. {
  6477. if ($nbbyrow > 0)
  6478. {
  6479. // Ferme tableau
  6480. while ($nbphoto % $nbbyrow)
  6481. {
  6482. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  6483. $nbphoto++;
  6484. }
  6485. if ($nbphoto) $return .= '</table>';
  6486. }
  6487. }
  6488. }
  6489. $this->nbphoto = $nbphoto;
  6490. return $return;
  6491. }
  6492. /**
  6493. * Function test if type is array
  6494. *
  6495. * @param array $info content informations of field
  6496. * @return bool true if array
  6497. */
  6498. protected function isArray($info)
  6499. {
  6500. if (is_array($info)) {
  6501. if (isset($info['type']) && $info['type'] == 'array') return true;
  6502. else return false;
  6503. }
  6504. return false;
  6505. }
  6506. /**
  6507. * Function test if type is date
  6508. *
  6509. * @param array $info content informations of field
  6510. * @return bool true if date
  6511. */
  6512. public function isDate($info)
  6513. {
  6514. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) return true;
  6515. return false;
  6516. }
  6517. /**
  6518. * Function test if type is duration
  6519. *
  6520. * @param array $info content informations of field
  6521. * @return bool true if field of type duration
  6522. */
  6523. public function isDuration($info)
  6524. {
  6525. if (is_array($info)) {
  6526. if (isset($info['type']) && ($info['type'] == 'duration')) return true;
  6527. else return false;
  6528. } else return false;
  6529. }
  6530. /**
  6531. * Function test if type is integer
  6532. *
  6533. * @param array $info content informations of field
  6534. * @return bool true if integer
  6535. */
  6536. public function isInt($info)
  6537. {
  6538. if (is_array($info)) {
  6539. if (isset($info['type']) && ($info['type'] == 'int' || preg_match('/^integer/i', $info['type']))) return true;
  6540. else return false;
  6541. } else return false;
  6542. }
  6543. /**
  6544. * Function test if type is float
  6545. *
  6546. * @param array $info content informations of field
  6547. * @return bool true if float
  6548. */
  6549. public function isFloat($info)
  6550. {
  6551. if (is_array($info)) {
  6552. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) return true;
  6553. else return false;
  6554. }
  6555. return false;
  6556. }
  6557. /**
  6558. * Function test if type is text
  6559. *
  6560. * @param array $info content informations of field
  6561. * @return bool true if type text
  6562. */
  6563. public function isText($info)
  6564. {
  6565. if (is_array($info)) {
  6566. if (isset($info['type']) && $info['type'] == 'text') return true;
  6567. else return false;
  6568. }
  6569. return false;
  6570. }
  6571. /**
  6572. * Function test if field can be null
  6573. *
  6574. * @param array $info content informations of field
  6575. * @return bool true if it can be null
  6576. */
  6577. protected function canBeNull($info)
  6578. {
  6579. if (is_array($info)) {
  6580. if (isset($info['notnull']) && $info['notnull'] != '1') return true;
  6581. else return false;
  6582. }
  6583. return true;
  6584. }
  6585. /**
  6586. * Function test if field is forced to null if zero or empty
  6587. *
  6588. * @param array $info content informations of field
  6589. * @return bool true if forced to null
  6590. */
  6591. protected function isForcedToNullIfZero($info)
  6592. {
  6593. if (is_array($info)) {
  6594. if (isset($info['notnull']) && $info['notnull'] == '-1') return true;
  6595. else return false;
  6596. }
  6597. return false;
  6598. }
  6599. /**
  6600. * Function test if is indexed
  6601. *
  6602. * @param array $info content informations of field
  6603. * @return bool
  6604. */
  6605. protected function isIndex($info)
  6606. {
  6607. if (is_array($info)) {
  6608. if (isset($info['index']) && $info['index'] == true) return true;
  6609. else return false;
  6610. }
  6611. return false;
  6612. }
  6613. /**
  6614. * Function to prepare a part of the query for insert.
  6615. * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
  6616. * $this->${field} should be a clean value. The page can run
  6617. *
  6618. * @return array
  6619. */
  6620. protected function setSaveQuery()
  6621. {
  6622. global $conf;
  6623. $queryarray = array();
  6624. foreach ($this->fields as $field => $info) // Loop on definition of fields
  6625. {
  6626. // Depending on field type ('datetime', ...)
  6627. if ($this->isDate($info))
  6628. {
  6629. if (empty($this->{$field})) {
  6630. $queryarray[$field] = null;
  6631. } else {
  6632. $queryarray[$field] = $this->db->idate($this->{$field});
  6633. }
  6634. } elseif ($this->isArray($info))
  6635. {
  6636. if (!empty($this->{$field})) {
  6637. if (!is_array($this->{$field})) {
  6638. $this->{$field} = array($this->{$field});
  6639. }
  6640. $queryarray[$field] = serialize($this->{$field});
  6641. } else {
  6642. $queryarray[$field] = null;
  6643. }
  6644. } elseif ($this->isDuration($info))
  6645. {
  6646. // $this->{$field} may be null, '', 0, '0', 123, '123'
  6647. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  6648. if (!isset($this->{$field})) {
  6649. $queryarray[$field] = 0;
  6650. } else {
  6651. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  6652. }
  6653. }
  6654. else $queryarray[$field] = null;
  6655. } elseif ($this->isInt($info) || $this->isFloat($info))
  6656. {
  6657. if ($field == 'entity' && is_null($this->{$field})) $queryarray[$field] = $conf->entity;
  6658. else {
  6659. // $this->{$field} may be null, '', 0, '0', 123, '123'
  6660. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  6661. if (!isset($this->{$field})) {
  6662. $queryarray[$field] = 0;
  6663. } elseif ($this->isInt($info)) {
  6664. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  6665. } elseif ($this->isFloat($info)) {
  6666. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  6667. }
  6668. } else $queryarray[$field] = null;
  6669. }
  6670. } else {
  6671. $queryarray[$field] = $this->{$field};
  6672. }
  6673. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) unset($queryarray[$field]);
  6674. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) $queryarray[$field] = null; // May force 0 to null
  6675. }
  6676. return $queryarray;
  6677. }
  6678. /**
  6679. * Function to load data from a SQL pointer into properties of current object $this
  6680. *
  6681. * @param stdClass $obj Contain data of object from database
  6682. * @return void
  6683. */
  6684. public function setVarsFromFetchObj(&$obj)
  6685. {
  6686. foreach ($this->fields as $field => $info)
  6687. {
  6688. if ($this->isDate($info)) {
  6689. if (empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0;
  6690. else $this->{$field} = strtotime($obj->{$field});
  6691. } elseif ($this->isArray($info))
  6692. {
  6693. if (!empty($obj->{$field})) {
  6694. $this->{$field} = @unserialize($obj->{$field});
  6695. // Hack for data not in UTF8
  6696. if ($this->{$field } === false) @unserialize(utf8_decode($obj->{$field}));
  6697. } else {
  6698. $this->{$field} = array();
  6699. }
  6700. } elseif ($this->isInt($info)) {
  6701. if ($field == 'rowid') $this->id = (int) $obj->{$field};
  6702. else {
  6703. if ($this->isForcedToNullIfZero($info)) {
  6704. if (empty($obj->{$field})) $this->{$field} = null;
  6705. else $this->{$field} = (double) $obj->{$field};
  6706. } else {
  6707. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  6708. $this->{$field} = (int) $obj->{$field};
  6709. } else {
  6710. $this->{$field} = null;
  6711. }
  6712. }
  6713. }
  6714. } elseif ($this->isFloat($info)) {
  6715. if ($this->isForcedToNullIfZero($info)) {
  6716. if (empty($obj->{$field})) $this->{$field} = null;
  6717. else $this->{$field} = (double) $obj->{$field};
  6718. } else {
  6719. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  6720. $this->{$field} = (double) $obj->{$field};
  6721. } else {
  6722. $this->{$field} = null;
  6723. }
  6724. }
  6725. } else {
  6726. $this->{$field} = $obj->{$field};
  6727. }
  6728. }
  6729. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  6730. if (!isset($this->fields['ref']) && isset($this->id)) $this->ref = $this->id;
  6731. }
  6732. /**
  6733. * Function to concat keys of fields
  6734. *
  6735. * @return string
  6736. */
  6737. protected function getFieldList()
  6738. {
  6739. $keys = array_keys($this->fields);
  6740. return implode(',', $keys);
  6741. }
  6742. /**
  6743. * Add quote to field value if necessary
  6744. *
  6745. * @param string|int $value Value to protect
  6746. * @param array $fieldsentry Properties of field
  6747. * @return string
  6748. */
  6749. protected function quote($value, $fieldsentry)
  6750. {
  6751. if (is_null($value)) return 'NULL';
  6752. elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) return $this->db->escape("$value");
  6753. elseif ($fieldsentry['type'] == 'boolean') {
  6754. if ($value) return 'true';
  6755. else return 'false';
  6756. }
  6757. else return "'".$this->db->escape($value)."'";
  6758. }
  6759. /**
  6760. * Create object into database
  6761. *
  6762. * @param User $user User that creates
  6763. * @param bool $notrigger false=launch triggers after, true=disable triggers
  6764. * @return int <0 if KO, Id of created object if OK
  6765. */
  6766. public function createCommon(User $user, $notrigger = false)
  6767. {
  6768. global $langs;
  6769. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  6770. $error = 0;
  6771. $now = dol_now();
  6772. $fieldvalues = $this->setSaveQuery();
  6773. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) $fieldvalues['date_creation'] = $this->db->idate($now);
  6774. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) $fieldvalues['fk_user_creat'] = $user->id;
  6775. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  6776. if (array_key_exists('ref', $fieldvalues)) $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  6777. $keys = array();
  6778. $values = array(); // Array to store string forged for SQL syntax
  6779. foreach ($fieldvalues as $k => $v) {
  6780. $keys[$k] = $k;
  6781. $value = $this->fields[$k];
  6782. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  6783. }
  6784. // Clean and check mandatory
  6785. foreach ($keys as $key)
  6786. {
  6787. // If field is an implicit foreign key field
  6788. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key] = '';
  6789. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key] = '';
  6790. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default']))
  6791. {
  6792. $error++;
  6793. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  6794. }
  6795. // If value is null and there is a default value for field
  6796. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default']))
  6797. {
  6798. $values[$key] = $this->fields[$key]['default'];
  6799. }
  6800. // If field is an implicit foreign key field
  6801. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  6802. if (isset($this->fields[$key]['default'])) $values[$key] = $this->fields[$key]['default'];
  6803. else $values[$key] = 'null';
  6804. }
  6805. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) $values[$key] = 'null';
  6806. }
  6807. if ($error) return -1;
  6808. $this->db->begin();
  6809. if (!$error)
  6810. {
  6811. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
  6812. $sql .= ' ('.implode(", ", $keys).')';
  6813. $sql .= ' VALUES ('.implode(", ", $values).')';
  6814. $res = $this->db->query($sql);
  6815. if ($res === false) {
  6816. $error++;
  6817. $this->errors[] = $this->db->lasterror();
  6818. }
  6819. }
  6820. if (!$error)
  6821. {
  6822. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
  6823. }
  6824. // If we have a field ref with a default value of (PROV)
  6825. if (!$error)
  6826. {
  6827. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && !is_null($this->fields['ref']['default']) && $this->fields['ref']['default'] == '(PROV)')
  6828. {
  6829. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ref = '(PROV".$this->id.")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".$this->id;
  6830. $resqlupdate = $this->db->query($sql);
  6831. if ($resqlupdate === false)
  6832. {
  6833. $error++;
  6834. $this->errors[] = $this->db->lasterror();
  6835. } else {
  6836. $this->ref = '(PROV'.$this->id.')';
  6837. }
  6838. }
  6839. }
  6840. // Create extrafields
  6841. if (!$error)
  6842. {
  6843. $result = $this->insertExtraFields();
  6844. if ($result < 0) $error++;
  6845. }
  6846. // Create lines
  6847. if (!empty($this->table_element_line) && !empty($this->fk_element))
  6848. {
  6849. $num = (is_array($this->lines) ? count($this->lines) : 0);
  6850. for ($i = 0; $i < $num; $i++)
  6851. {
  6852. $line = $this->lines[$i];
  6853. $keyforparent = $this->fk_element;
  6854. $line->$keyforparent = $this->id;
  6855. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  6856. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  6857. if (!is_object($line)) $line = (object) $line;
  6858. $result = $line->create($user, 1);
  6859. if ($result < 0)
  6860. {
  6861. $this->error = $this->db->lasterror();
  6862. $this->db->rollback();
  6863. return -1;
  6864. }
  6865. }
  6866. }
  6867. // Triggers
  6868. if (!$error && !$notrigger)
  6869. {
  6870. // Call triggers
  6871. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  6872. if ($result < 0) { $error++; }
  6873. // End call triggers
  6874. }
  6875. // Commit or rollback
  6876. if ($error) {
  6877. $this->db->rollback();
  6878. return -1;
  6879. } else {
  6880. $this->db->commit();
  6881. return $this->id;
  6882. }
  6883. }
  6884. /**
  6885. * Load object in memory from the database
  6886. *
  6887. * @param int $id Id object
  6888. * @param string $ref Ref
  6889. * @param string $morewhere More SQL filters (' AND ...')
  6890. * @return int <0 if KO, 0 if not found, >0 if OK
  6891. */
  6892. public function fetchCommon($id, $ref = null, $morewhere = '')
  6893. {
  6894. if (empty($id) && empty($ref) && empty($morewhere)) return -1;
  6895. $fieldlist = $this->getFieldList();
  6896. if (empty($fieldlist)) return 0;
  6897. $sql = 'SELECT '.$fieldlist;
  6898. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
  6899. if (!empty($id)) $sql .= ' WHERE rowid = '.$id;
  6900. elseif (!empty($ref)) $sql .= " WHERE ref = ".$this->quote($ref, $this->fields['ref']);
  6901. else $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  6902. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' AND entity IN ('.getEntity($this->table_element).')';
  6903. if ($morewhere) $sql .= $morewhere;
  6904. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  6905. $res = $this->db->query($sql);
  6906. if ($res)
  6907. {
  6908. $obj = $this->db->fetch_object($res);
  6909. if ($obj)
  6910. {
  6911. $this->setVarsFromFetchObj($obj);
  6912. // Retrieve all extrafield
  6913. // fetch optionals attributes and labels
  6914. $this->fetch_optionals();
  6915. return $this->id;
  6916. } else {
  6917. return 0;
  6918. }
  6919. } else {
  6920. $this->error = $this->db->lasterror();
  6921. $this->errors[] = $this->error;
  6922. return -1;
  6923. }
  6924. }
  6925. /**
  6926. * Load object in memory from the database
  6927. *
  6928. * @param string $morewhere More SQL filters (' AND ...')
  6929. * @return int <0 if KO, 0 if not found, >0 if OK
  6930. */
  6931. public function fetchLinesCommon($morewhere = '')
  6932. {
  6933. $objectlineclassname = get_class($this).'Line';
  6934. if (!class_exists($objectlineclassname))
  6935. {
  6936. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  6937. return -1;
  6938. }
  6939. $objectline = new $objectlineclassname($this->db);
  6940. $sql = 'SELECT '.$objectline->getFieldList();
  6941. $sql .= ' FROM '.MAIN_DB_PREFIX.$objectline->table_element;
  6942. $sql .= ' WHERE fk_'.$this->element.' = '.$this->id;
  6943. if ($morewhere) $sql .= $morewhere;
  6944. if (isset($objectline->fields['position'])) {
  6945. $sql .= $this->db->order('position', 'ASC');
  6946. }
  6947. $resql = $this->db->query($sql);
  6948. if ($resql)
  6949. {
  6950. $num_rows = $this->db->num_rows($resql);
  6951. $i = 0;
  6952. while ($i < $num_rows)
  6953. {
  6954. $obj = $this->db->fetch_object($resql);
  6955. if ($obj)
  6956. {
  6957. $newline = new $objectlineclassname($this->db);
  6958. $newline->setVarsFromFetchObj($obj);
  6959. $this->lines[] = $newline;
  6960. }
  6961. $i++;
  6962. }
  6963. return 1;
  6964. } else {
  6965. $this->error = $this->db->lasterror();
  6966. $this->errors[] = $this->error;
  6967. return -1;
  6968. }
  6969. }
  6970. /**
  6971. * Update object into database
  6972. *
  6973. * @param User $user User that modifies
  6974. * @param bool $notrigger false=launch triggers after, true=disable triggers
  6975. * @return int <0 if KO, >0 if OK
  6976. */
  6977. public function updateCommon(User $user, $notrigger = false)
  6978. {
  6979. global $conf, $langs;
  6980. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  6981. $error = 0;
  6982. $now = dol_now();
  6983. $fieldvalues = $this->setSaveQuery();
  6984. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) $fieldvalues['date_modification'] = $this->db->idate($now);
  6985. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) $fieldvalues['fk_user_modif'] = $user->id;
  6986. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  6987. if (array_key_exists('ref', $fieldvalues)) $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  6988. // Add quotes and escape on fields with type string
  6989. $keys = array();
  6990. $values = array();
  6991. $tmp = array();
  6992. foreach ($fieldvalues as $k => $v) {
  6993. $keys[$k] = $k;
  6994. $value = $this->fields[$k];
  6995. $values[$k] = $this->quote($v, $value);
  6996. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  6997. }
  6998. // Clean and check mandatory fields
  6999. foreach ($keys as $key)
  7000. {
  7001. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key] = ''; // This is an implicit foreign key field
  7002. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key] = ''; // This is an explicit foreign key field
  7003. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  7004. /*
  7005. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  7006. {
  7007. $error++;
  7008. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  7009. }*/
  7010. }
  7011. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.$this->id;
  7012. $this->db->begin();
  7013. if (!$error)
  7014. {
  7015. $res = $this->db->query($sql);
  7016. if ($res === false)
  7017. {
  7018. $error++;
  7019. $this->errors[] = $this->db->lasterror();
  7020. }
  7021. }
  7022. // Update extrafield
  7023. if (!$error)
  7024. {
  7025. $result = $this->insertExtraFields();
  7026. if ($result < 0)
  7027. {
  7028. $error++;
  7029. }
  7030. }
  7031. // Triggers
  7032. if (!$error && !$notrigger)
  7033. {
  7034. // Call triggers
  7035. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  7036. if ($result < 0) { $error++; } //Do also here what you must do to rollback action if trigger fail
  7037. // End call triggers
  7038. }
  7039. // Commit or rollback
  7040. if ($error) {
  7041. $this->db->rollback();
  7042. return -1;
  7043. } else {
  7044. $this->db->commit();
  7045. return $this->id;
  7046. }
  7047. }
  7048. /**
  7049. * Delete object in database
  7050. *
  7051. * @param User $user User that deletes
  7052. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7053. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  7054. * @return int <=0 if KO, >0 if OK
  7055. */
  7056. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  7057. {
  7058. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  7059. $error = 0;
  7060. $this->db->begin();
  7061. if ($forcechilddeletion) // Force also delete of childtables that should lock deletion in standard case when option force is off
  7062. {
  7063. foreach ($this->childtables as $table)
  7064. {
  7065. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
  7066. $resql = $this->db->query($sql);
  7067. if (!$resql)
  7068. {
  7069. $this->error = $this->db->lasterror();
  7070. $this->errors[] = $this->error;
  7071. $this->db->rollback();
  7072. return -1;
  7073. }
  7074. }
  7075. } elseif (!empty($this->fk_element) && !empty($this->childtables)) // If object has childs linked with a foreign key field, we check all child tables.
  7076. {
  7077. $objectisused = $this->isObjectUsed($this->id);
  7078. if (!empty($objectisused))
  7079. {
  7080. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  7081. $this->error = 'ErrorRecordHasChildren';
  7082. $this->errors[] = $this->error;
  7083. $this->db->rollback();
  7084. return 0;
  7085. }
  7086. }
  7087. // Delete cascade first
  7088. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  7089. foreach ($this->childtablesoncascade as $table)
  7090. {
  7091. $deleteFromObject = explode(':', $table);
  7092. if (count($deleteFromObject) >= 2) {
  7093. $className = str_replace('@', '', $deleteFromObject[0]);
  7094. $filePath = $deleteFromObject[1];
  7095. $columnName = $deleteFromObject[2];
  7096. if (dol_include_once($filePath)) {
  7097. $childObject = new $className($this->db);
  7098. if (method_exists($childObject, 'deleteByParentField')) {
  7099. $result = $childObject->deleteByParentField($this->id, $columnName);
  7100. if ($result < 0) {
  7101. $error++;
  7102. $this->errors[] = $childObject->error;
  7103. break;
  7104. }
  7105. } else {
  7106. $error++;
  7107. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  7108. break;
  7109. }
  7110. } else {
  7111. $error++;
  7112. $this->errors[] = 'Cannot include child class file '.$filePath;
  7113. break;
  7114. }
  7115. } else {
  7116. // Delete record in child table
  7117. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
  7118. $resql = $this->db->query($sql);
  7119. if (!$resql) {
  7120. $error++;
  7121. $this->error = $this->db->lasterror();
  7122. $this->errors[] = $this->error;
  7123. break;
  7124. }
  7125. }
  7126. }
  7127. }
  7128. if (!$error) {
  7129. if (!$notrigger) {
  7130. // Call triggers
  7131. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  7132. if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail
  7133. // End call triggers
  7134. }
  7135. }
  7136. // Delete llx_ecm_files
  7137. if (!$error) {
  7138. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  7139. if (! $res) {
  7140. $error++;
  7141. }
  7142. }
  7143. if (!$error && !empty($this->isextrafieldmanaged))
  7144. {
  7145. $result = $this->deleteExtraFields();
  7146. if ($result < 0) { $error++; }
  7147. }
  7148. if (!$error)
  7149. {
  7150. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id;
  7151. $res = $this->db->query($sql);
  7152. if ($res === false) {
  7153. $error++;
  7154. $this->errors[] = $this->db->lasterror();
  7155. }
  7156. }
  7157. // Commit or rollback
  7158. if ($error) {
  7159. $this->db->rollback();
  7160. return -1;
  7161. } else {
  7162. $this->db->commit();
  7163. return 1;
  7164. }
  7165. }
  7166. /**
  7167. * Delete all child object from a parent ID
  7168. *
  7169. * @param int $parentId Parent Id
  7170. * @param string $parentField Name of Foreign key parent column
  7171. * @return int <0 if KO, >0 if OK
  7172. * @throws Exception
  7173. */
  7174. public function deleteByParentField($parentId = 0, $parentField = '')
  7175. {
  7176. global $user;
  7177. $error = 0;
  7178. $deleted = 0;
  7179. if (!empty($parentId) && !empty($parentField)) {
  7180. $this->db->begin();
  7181. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$this->table_element;
  7182. $sql .= ' WHERE '.$parentField.' = '.(int) $parentId;
  7183. $resql = $this->db->query($sql);
  7184. if (!$resql) {
  7185. $this->errors[] = $this->db->lasterror();
  7186. $error++;
  7187. } else {
  7188. while ($obj = $this->db->fetch_object($resql)) {
  7189. $result = $this->fetch($obj->rowid);
  7190. if ($result < 0) {
  7191. $error++;
  7192. $this->errors[] = $this->error;
  7193. } else {
  7194. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  7195. $result = $this->delete();
  7196. } else {
  7197. $result = $this->delete($user);
  7198. }
  7199. if ($result < 0) {
  7200. $error++;
  7201. $this->errors[] = $this->error;
  7202. } else {
  7203. $deleted++;
  7204. }
  7205. }
  7206. }
  7207. }
  7208. if (empty($error)) {
  7209. $this->db->commit();
  7210. return $deleted;
  7211. } else {
  7212. $this->error = implode(', ', $this->errors);
  7213. $this->db->rollback();
  7214. return $error * -1;
  7215. }
  7216. }
  7217. return $deleted;
  7218. }
  7219. /**
  7220. * Delete a line of object in database
  7221. *
  7222. * @param User $user User that delete
  7223. * @param int $idline Id of line to delete
  7224. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7225. * @return int >0 if OK, <0 if KO
  7226. */
  7227. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  7228. {
  7229. global $conf;
  7230. $error = 0;
  7231. $tmpforobjectclass = get_class($this);
  7232. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  7233. // Call trigger
  7234. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  7235. if ($result < 0) return -1;
  7236. // End call triggers
  7237. $this->db->begin();
  7238. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  7239. $sql .= " WHERE rowid=".$idline;
  7240. dol_syslog(get_class($this)."::deleteLineCommon", LOG_DEBUG);
  7241. $resql = $this->db->query($sql);
  7242. if (!$resql)
  7243. {
  7244. $this->error = "Error ".$this->db->lasterror();
  7245. $error++;
  7246. }
  7247. if (empty($error)) {
  7248. // Remove extrafields
  7249. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  7250. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  7251. $tmpobjectline->id = $idline;
  7252. $result = $tmpobjectline->deleteExtraFields();
  7253. if ($result < 0)
  7254. {
  7255. $error++;
  7256. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  7257. }
  7258. }
  7259. }
  7260. if (empty($error)) {
  7261. $this->db->commit();
  7262. return 1;
  7263. } else {
  7264. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  7265. $this->db->rollback();
  7266. return -1;
  7267. }
  7268. }
  7269. /**
  7270. * Set to a status
  7271. *
  7272. * @param User $user Object user that modify
  7273. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  7274. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  7275. * @param string $triggercode Trigger code to use
  7276. * @return int <0 if KO, >0 if OK
  7277. */
  7278. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  7279. {
  7280. $error = 0;
  7281. $this->db->begin();
  7282. $statusfield = 'status';
  7283. if ($this->element == 'don' || $this->element == 'donation') $statusfield = 'fk_statut';
  7284. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  7285. $sql .= " SET ".$statusfield." = ".((int) $status);
  7286. $sql .= " WHERE rowid = ".$this->id;
  7287. if ($this->db->query($sql))
  7288. {
  7289. if (!$error)
  7290. {
  7291. $this->oldcopy = clone $this;
  7292. }
  7293. if (!$error && !$notrigger) {
  7294. // Call trigger
  7295. $result = $this->call_trigger($triggercode, $user);
  7296. if ($result < 0) $error++;
  7297. }
  7298. if (!$error) {
  7299. $this->status = $status;
  7300. $this->db->commit();
  7301. return 1;
  7302. } else {
  7303. $this->db->rollback();
  7304. return -1;
  7305. }
  7306. } else {
  7307. $this->error = $this->db->error();
  7308. $this->db->rollback();
  7309. return -1;
  7310. }
  7311. }
  7312. /**
  7313. * Initialise object with example values
  7314. * Id must be 0 if object instance is a specimen
  7315. *
  7316. * @return int
  7317. */
  7318. public function initAsSpecimenCommon()
  7319. {
  7320. global $user;
  7321. $this->id = 0;
  7322. $this->specimen = 1;
  7323. $fields = array(
  7324. 'label' => 'This is label',
  7325. 'ref' => 'ABCD1234',
  7326. 'description' => 'This is a description',
  7327. 'qty' => 123.12,
  7328. 'note_public' => 'Public note',
  7329. 'note_private' => 'Private note',
  7330. 'date_creation' => (dol_now() - 3600 * 48),
  7331. 'date_modification' => (dol_now() - 3600 * 24),
  7332. 'fk_user_creat' => $user->id,
  7333. 'fk_user_modif' => $user->id,
  7334. 'date' => dol_now(),
  7335. );
  7336. foreach ($fields as $key => $value) {
  7337. if (array_key_exists($key, $this->fields)) $this->{$key} = $value;
  7338. }
  7339. return 1;
  7340. }
  7341. /* Part for comments */
  7342. /**
  7343. * Load comments linked with current task
  7344. * @return boolean 1 if ok
  7345. */
  7346. public function fetchComments()
  7347. {
  7348. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  7349. $comment = new Comment($this->db);
  7350. $result = $comment->fetchAllFor($this->element, $this->id);
  7351. if ($result < 0) {
  7352. $this->errors = array_merge($this->errors, $comment->errors);
  7353. return -1;
  7354. } else {
  7355. $this->comments = $comment->comments;
  7356. }
  7357. return count($this->comments);
  7358. }
  7359. /**
  7360. * Return nb comments already posted
  7361. *
  7362. * @return int
  7363. */
  7364. public function getNbComments()
  7365. {
  7366. return count($this->comments);
  7367. }
  7368. /**
  7369. * Trim object parameters
  7370. *
  7371. * @param string[] $parameters array of parameters to trim
  7372. * @return void
  7373. */
  7374. public function trimParameters($parameters)
  7375. {
  7376. if (!is_array($parameters)) return;
  7377. foreach ($parameters as $parameter) {
  7378. if (isset($this->$parameter)) {
  7379. $this->$parameter = trim($this->$parameter);
  7380. }
  7381. }
  7382. }
  7383. /* Part for categories/tags */
  7384. /**
  7385. * Sets object to given categories.
  7386. *
  7387. * Deletes object from existing categories not supplied.
  7388. * Adds it to non existing supplied categories.
  7389. * Existing categories are left untouch.
  7390. *
  7391. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  7392. * @return int Array of category objects or < 0 if KO
  7393. */
  7394. public function getCategoriesCommon($type_categ)
  7395. {
  7396. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  7397. // Get current categories
  7398. $c = new Categorie($this->db);
  7399. $existing = $c->containing($this->id, $type_categ, 'id');
  7400. return $existing;
  7401. }
  7402. /**
  7403. * Sets object to given categories.
  7404. *
  7405. * Deletes object from existing categories not supplied.
  7406. * Adds it to non existing supplied categories.
  7407. * Existing categories are left untouch.
  7408. *
  7409. * @param int[]|int $categories Category ID or array of Categories IDs
  7410. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  7411. * @return int <0 if KO, >0 if OK
  7412. */
  7413. public function setCategoriesCommon($categories, $type_categ)
  7414. {
  7415. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  7416. // Handle single category
  7417. if (!is_array($categories)) {
  7418. $categories = array($categories);
  7419. }
  7420. // Get current categories
  7421. $c = new Categorie($this->db);
  7422. $existing = $c->containing($this->id, $type_categ, 'id');
  7423. // Diff
  7424. if (is_array($existing)) {
  7425. $to_del = array_diff($existing, $categories);
  7426. $to_add = array_diff($categories, $existing);
  7427. } else {
  7428. $to_del = array(); // Nothing to delete
  7429. $to_add = $categories;
  7430. }
  7431. $error = 0;
  7432. // Process
  7433. foreach ($to_del as $del) {
  7434. if ($c->fetch($del) > 0) {
  7435. $c->del_type($this, $type_categ);
  7436. }
  7437. }
  7438. foreach ($to_add as $add) {
  7439. if ($c->fetch($add) > 0)
  7440. {
  7441. $result = $c->add_type($this, $type_categ);
  7442. if ($result < 0)
  7443. {
  7444. $error++;
  7445. $this->error = $c->error;
  7446. $this->errors = $c->errors;
  7447. break;
  7448. }
  7449. }
  7450. }
  7451. return $error ? -1 : 1;
  7452. }
  7453. /**
  7454. * Copy related categories to another object
  7455. *
  7456. * @param int $fromId Id object source
  7457. * @param int $toId Id object cible
  7458. * @param string $type Type of category ('product', ...)
  7459. * @return int < 0 if error, > 0 if ok
  7460. */
  7461. public function cloneCategories($fromId, $toId, $type = '')
  7462. {
  7463. $this->db->begin();
  7464. if (empty($type)) $type = $this->table_element;
  7465. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  7466. $categorystatic = new Categorie($this->db);
  7467. $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  7468. $sql .= " SELECT fk_categorie, $toId FROM ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  7469. $sql .= " WHERE fk_product = ".((int) $fromId);
  7470. if (!$this->db->query($sql))
  7471. {
  7472. $this->error = $this->db->lasterror();
  7473. $this->db->rollback();
  7474. return -1;
  7475. }
  7476. $this->db->commit();
  7477. return 1;
  7478. }
  7479. /**
  7480. * Delete related files of object in database
  7481. *
  7482. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  7483. * @return bool True if OK, False if KO
  7484. */
  7485. public function deleteEcmFiles($mode = 0)
  7486. {
  7487. global $conf;
  7488. $this->db->begin();
  7489. // Delete in database with mode 0
  7490. if ($mode == 0) {
  7491. switch ($this->element) {
  7492. case 'propal':
  7493. $element = 'propale';
  7494. break;
  7495. case 'product':
  7496. $element = 'produit';
  7497. break;
  7498. case 'order_supplier':
  7499. $element = 'fournisseur/commande';
  7500. break;
  7501. case 'invoice_supplier':
  7502. $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  7503. break;
  7504. case 'shipping':
  7505. $element = 'expedition/sending';
  7506. break;
  7507. default:
  7508. $element = $this->element;
  7509. }
  7510. // Delete ecm_files extrafields
  7511. $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files_extrafields WHERE fk_object IN (";
  7512. $sql .= " SELECT rowid FROM ".MAIN_DB_PREFIX."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  7513. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".$conf->entity; // No need of getEntity here
  7514. $sql .= ")";
  7515. if (!$this->db->query($sql)) {
  7516. $this->error = $this->db->lasterror();
  7517. $this->db->rollback();
  7518. return false;
  7519. }
  7520. // Delete ecm_files
  7521. $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files";
  7522. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  7523. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".$conf->entity; // No need of getEntity here
  7524. if (!$this->db->query($sql)) {
  7525. $this->error = $this->db->lasterror();
  7526. $this->db->rollback();
  7527. return false;
  7528. }
  7529. }
  7530. // Delete in database with mode 1
  7531. if ($mode == 1) {
  7532. $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files_extrafields";
  7533. $sql .= " WHERE fk_object IN (SELECT rowid FROM ".MAIN_DB_PREFIX."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? '' : '@'.$this->module))."' AND src_object_id = ".$this->id.")";
  7534. $resql = $this->db->query($sql);
  7535. if (!$resql) {
  7536. $this->error = $this->db->lasterror();
  7537. $this->db->rollback();
  7538. return false;
  7539. }
  7540. $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files";
  7541. $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? '' : '@'.$this->module))."' AND src_object_id = ".$this->id;
  7542. $resql = $this->db->query($sql);
  7543. if (!$resql) {
  7544. $this->error = $this->db->lasterror();
  7545. $this->db->rollback();
  7546. return false;
  7547. }
  7548. }
  7549. $this->db->commit();
  7550. return true;
  7551. }
  7552. }