TableAjax.php 242 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509
  1. <?php
  2. Lib::loadClass('ViewAjax');
  3. Lib::loadClass('TableAjaxMap');
  4. Lib::loadClass('Typespecial');
  5. Lib::loadClass('UI');
  6. Lib::loadClass('FoldersConfig');
  7. Lib::loadClass('FileUploader');
  8. Lib::loadClass('UserProfile');
  9. Lib::loadClass('ProcesHelper');
  10. Lib::loadClass('Router');
  11. Lib::loadClass('Route_UrlAction');
  12. Lib::loadClass('Core_AclHelper');
  13. // TODO: change all links: MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={idZasob} to _route=ViewTableAjax&typeName=p5_default_db:{tableName}
  14. class TableAjax extends ViewAjax {
  15. private $_cnf = '';// Column
  16. private $_htmlID = '';
  17. private $_rowFunctions = array();
  18. private $_pageSize = 10;
  19. private $_pageSizes = array();
  20. private $_filterInit = null;
  21. private $_forceFilterInit = null;
  22. private $_showProcesInit = true;
  23. private $_useUserTableFilter = false;
  24. public $syncUrl = null;
  25. public function __construct($tblAcl) {
  26. $this->_tbl = $tblAcl->getName();
  27. $this->_acl = $tblAcl;
  28. $this->_zasobID = $tblAcl->getID();
  29. $this->_pageSize = 10;
  30. {
  31. UserProfile::load();
  32. $tableAjaxSettings = UserProfile::getTableAjaxSettings();
  33. $this->_pageSize = V::get('pageSize', 10, $tableAjaxSettings, 'int');
  34. }
  35. $this->_pageSizes = array(10, 20, 50, 100);// default page sizes
  36. $this->_filterInit = new stdClass();
  37. $hash = V::get('_hash', '', $_GET);
  38. if ($hash) {
  39. $this->_htmlID = $hash;
  40. $this->_readState();
  41. } else {
  42. $this->_htmlID = $this->generateHtmlID();
  43. $this->_readState();
  44. }
  45. }
  46. public function setSyncUrl($syncUrl) {
  47. $this->syncUrl = $syncUrl;
  48. }
  49. public function showProcesInit($bool = true) {
  50. $this->_showProcesInit = $bool;
  51. }
  52. public function showUserTableFilter($url = null) {
  53. $this->_useUserTableFilter = $url;
  54. }
  55. private function _hasStateFilterInit() {
  56. return array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache']) && array_key_exists('_filterInit', $_SESSION['TableAjax_Cache'][$this->_htmlID]);
  57. }
  58. // TODO: read state from cache by key $this->_htmlID
  59. // TODO: load filters and state: table, edit, add, etc.
  60. // TODO: save this data in Workspace 1, 2, 3, etc.
  61. // TODO: default filters in VIEWTABLE_AJAX
  62. // $tbl->setLabel($zasobObj->OPIS);
  63. // $tbl->setFilterInit($filterInit);
  64. // $tbl->addRowFunction('edit');
  65. // $tbl->addRowFunction('hist');
  66. // $tbl->addRowFunction('files');
  67. // $tbl->addRowFunction('cp');
  68. private function _readState() {
  69. if (!array_key_exists('TableAjax_Cache', $_SESSION)) {
  70. $_SESSION['TableAjax_Cache'] = array();
  71. }
  72. //trigger_error("F." . __FUNCTION__ . " (" . (array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) . ")", E_USER_NOTICE);
  73. //trigger_error("F." . __FUNCTION__ . " (".basename($_SERVER['SCRIPT_FILENAME'])."::_filterInit: " . json_encode($_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit']) . ")", E_USER_NOTICE);
  74. if (array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) {
  75. foreach ($_SESSION['TableAjax_Cache'][$this->_htmlID] as $k => $v) {
  76. //trigger_error("F." . __FUNCTION__ . " key: ({$k})", E_USER_NOTICE);
  77. switch ($k) {
  78. case '_label':
  79. $this->_label = $v;
  80. break;
  81. case '_filterInit':
  82. $this->_filterInit = $v;
  83. break;
  84. case '_rowFunctions':
  85. $this->_rowFunctions = $v;
  86. break;
  87. default:
  88. }
  89. }
  90. }
  91. }
  92. protected function _saveState($key = null) {
  93. if (!array_key_exists('TableAjax_Cache', $_SESSION)) {
  94. $_SESSION['TableAjax_Cache'] = array();
  95. }
  96. if (!array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) {
  97. $_SESSION['TableAjax_Cache'][$this->_htmlID] = array();
  98. }
  99. if (!$key) {
  100. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_label'] = $this->_label;
  101. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'] = $this->_filterInit;
  102. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_rowFunctions'] = $this->_rowFunctions;
  103. } else if ($key == '_label') {
  104. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_label'] = $this->_label;
  105. } else if ($key == '_filterInit') {
  106. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'] = $this->_filterInit;
  107. } else if ($key == '_rowFunctions') {
  108. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_rowFunctions'] = $this->_rowFunctions;
  109. }
  110. }
  111. public function setPageSizes($pageSizes) {
  112. $this->_pageSizes = $pageSizes;
  113. }
  114. public function setFilterInit($filterInit) {
  115. if ($this->_hasStateFilterInit()) {
  116. return;
  117. }
  118. $this->_filterInit = (object)$filterInit;
  119. $this->_saveState();
  120. }
  121. /**
  122. * @param array $forceFilterInit
  123. */
  124. public function setForceFilterInit($forceFilterInit) {
  125. $this->_forceFilterInit = (object)$forceFilterInit;
  126. }
  127. private function setFilters($filterInit) {
  128. $this->_filterInit = (object)$filterInit;
  129. $this->_saveState();
  130. }
  131. public function setRowFunctions($functions) {
  132. $this->_rowFunctions = [];
  133. $defaultRowFunction = array();
  134. $defaultRowFunction['edit'] = array('href'=>'#EDIT/{0}', 'ico'=>'glyphicon glyphicon-pencil', 'title'=>'Edytuj rekord');
  135. $defaultRowFunction['hist'] = array('href'=>'#HIST/{0}', 'ico'=>'glyphicon glyphicon-book', 'title'=>'Historia');
  136. $defaultRowFunction['files'] = array('href'=>'#FILES/{0}', 'ico'=>'glyphicon glyphicon-folder-open', 'title'=>'Pliki');
  137. $defaultRowFunction['cp'] = array('href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});');
  138. $defaultRowFunction['msgs'] = array('href'=>"index.php?_route=TableMsgs&_task=tableRow&idTable={$this->_zasobID}&idRow={0}", 'ico'=>'glyphicon glyphicon-envelope', 'title'=>'Wiadomości');
  139. foreach ($functions as $funName => $params) {
  140. if (true === $params) {
  141. if (array_key_exists($funName, $defaultRowFunction)) {
  142. $this->_rowFunctions[$funName] = $defaultRowFunction[$funName];
  143. } else {
  144. throw new Exception("Row function not defined '{$funName}'");
  145. }
  146. }
  147. if (is_array($params)) {
  148. $this->_rowFunctions[$funName] = $params;
  149. }
  150. }
  151. $this->_saveState('_rowFunctions');
  152. }
  153. public function addRowFunction($funName, $funParams = array()) {
  154. $defaultRowFunction = array();
  155. //$defaultRowFunction['edit'] = '<a href="#EDIT/{0}" class="glyphicon glyphicon-pencil" title="Edytuj rekord"></a>';
  156. //$defaultRowFunction['hist'] = '<a href="#HIST/{0}" class="glyphicon glyphicon-book" title="Historia"></a>';
  157. //$defaultRowFunction['files'] = '<a href="#FILES/{0}" class="glyphicon glyphicon-folder-open" title="Pliki"></a>';
  158. //$defaultRowFunction['cp'] = '<a href="#" class="glyphicon glyphicon-plus-sign" title="Kopiuj rekord" onclick="return tableAjaxCopy({0});"></a>';
  159. $defaultRowFunction['edit'] = array('href'=>'#EDIT/{0}', 'ico'=>'glyphicon glyphicon-pencil', 'title'=>'Edytuj rekord');
  160. $defaultRowFunction['hist'] = array('href'=>'#HIST/{0}', 'ico'=>'glyphicon glyphicon-book', 'title'=>'Historia');
  161. $defaultRowFunction['files'] = array('href'=>'#FILES/{0}', 'ico'=>'glyphicon glyphicon-folder-open', 'title'=>'Pliki');
  162. $defaultRowFunction['cp'] = array('href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});');
  163. $defaultRowFunction['msgs'] = array('href'=>"index.php?_route=TableMsgs&_task=tableRow&idTable={$this->_zasobID}&idRow={0}", 'ico'=>'glyphicon glyphicon-envelope', 'title'=>'Wiadomości');
  164. if (array_key_exists($funName, $defaultRowFunction)) {
  165. $this->_rowFunctions[$funName] = $defaultRowFunction[$funName];
  166. }
  167. else {
  168. $this->_rowFunctions[$funName] = $funParams;
  169. }
  170. $this->_saveState('_rowFunctions');
  171. }
  172. private function _parseRowFunctions($recordID = null, $pomin = array(), $showLabel = false) {
  173. $rowFunctions = array();
  174. foreach ($this->_rowFunctions as $kFunName => $vParams) {
  175. if (in_array($kFunName, $pomin)) continue;
  176. //$rowFunctionsOut .= str_replace('{0}', $recordID, $vUrl);
  177. $attrs = array();
  178. // $defaultRowFunction['cp'] = (object)array('href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});');
  179. $label = '';
  180. $ico = '';
  181. foreach ($vParams as $kParamName => $v) {
  182. if ($kParamName == 'ico') {
  183. $ico = '<span class="' . $v . '"></span>';
  184. continue;
  185. }
  186. $attr = $v;
  187. if ($recordID > 0) {
  188. $attr = str_replace('{0}', $recordID, $attr);
  189. }
  190. if ($showLabel && $kParamName == 'title') {
  191. $label = $attr;
  192. }
  193. $attr = $kParamName . '="' . $attr . '"';
  194. $attrs[] = $attr;
  195. }
  196. $rowFunctions[$kFunName] = '<a ' . implode(' ', $attrs) . '>' . "{$ico} {$label} " . '</a>';
  197. }
  198. return $rowFunctions;
  199. }
  200. private function _showRowFunctions($recordID = null, $pomin = array(), $showLabel = false) {
  201. $rowFunctionsOut = $this->_parseRowFunctions($recordID, $pomin, $showLabel);
  202. $rowFunctionsOut = implode('', $rowFunctionsOut);
  203. return $rowFunctionsOut;
  204. }
  205. private function _showRowFunctionsJson($recordID = null, $pomin = array(), $showLabel = false) {
  206. $rowFunctions = $this->_parseRowFunctions($recordID, $pomin, $showLabel);
  207. $rowFunctions = (object)$rowFunctions;
  208. return $rowFunctions;
  209. }
  210. private function getProcesInitSelected() {
  211. $userAcl = User::getAcl();
  212. return $userAcl->getPermsFiltrProcesId();
  213. }
  214. public function allowTreeView() {
  215. if ($this->_tbl == 'CRM_LISTA_ZASOBOW') return true;
  216. if ($this->_tbl == 'CRM_PROCES') return true;
  217. return false;
  218. }
  219. public function renderStatic($tblAjaxMap = null) {
  220. static $_rendered = false;
  221. if ($_rendered) return;
  222. if ($tblAjaxMap) $tblAjaxMap->printCSS();
  223. if ($tblAjaxMap) $tblAjaxMap->printJS();
  224. echo UI::h('script', ['src'=>"stuff/jquery-ui-1.10.4.custom.min.js"]);
  225. echo UI::h('script', ['src'=>"static/sweetalert2.min.js"]);
  226. echo UI::h('script', ['src'=>"static/jquery.doubleScroll.js"]);
  227. echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"stuff/jquery-ui-smoothness/jquery-ui-1.10.4.custom.min.css"]);
  228. echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"static/sweetalert2.min.css"]);
  229. echo UI::h('style', ['type'=>"text/css"], "
  230. .AjaxTable{max-width:100%;background-color:transparent;border-collapse:collapse;border-spacing:0;}
  231. .AjaxTableCont {position:relative; margin:10px 0; width:100%; overflow-x:auto; border:none;}
  232. .AjaxTable *,
  233. .AjaxTable.table {white-space:nowrap; width:auto;}
  234. .AjaxTable .popover * {white-space:normal;}
  235. .AjaxTable p {margin:0;}
  236. .AjaxTable td, .AjaxTable th {line-height:18px;}
  237. .AjaxTable i {margin: 0 0 0 2px;opacity: 0.5;}
  238. .AjaxTable span.filter {background-color:#999;}
  239. .AjaxTable .indeterminate {opacity: 0.4;-ms-filter:\"progid:DXImageTransform.Microsoft.Alpha(Opacity=40)\";filter:alpha(opacity=40);}
  240. .AjaxTable .columnpicker li, .AjaxTable .actions li {padding-left:5px;}
  241. .AjaxTableCont .btn-toolbar {margin:2px 0 0 0;}
  242. .AjaxTableCont .btn-toolbar .btn-group {vertical-align:top;}
  243. .AjaxTable input[type=checkbox] {margin:0;padding:0;height:13px;}
  244. .AjaxTable input[type=text].filter {margin:0;padding:0 5px;box-shadow:none;width:100%;background:#eee;color:#000;}
  245. .AjaxTable input[type=text].filter {border-width:2px 0;border-color:#eee;border-style:solid;}
  246. .AjaxTable input[type=text].filter-active {border-color:#00ACCC;}
  247. .AjaxTable .date-wrap {width:100%;min-width:115px;}
  248. .AjaxTable .dateWrap .add-on {margin:0;padding:0;background:none;border:none;float:right;cursor:pointer;}
  249. .AjaxTable .actions a {padding:0;margin:0;}
  250. .AjaxTableCont .text-right {text-align:right}
  251. .AjaxTableCont .breadcrumb em {color:#bbb;}
  252. .AjaxTable-loading .head-info {background:url(./icon/loading.gif) no-repeat left top; background-position:0 6px;}
  253. .AjaxTable-loading .loading-info,
  254. .AjaxTableCont .tblAjax__inlineEditBox .loading-info {display:block; padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;}
  255. .AjaxTableCont .loading-info {display:none;}
  256. .AjaxTableCont .tblAjax__inlineEditBox .loading-info {display:block;}
  257. .AjaxTableCont .table {margin-bottom:0px;}
  258. .AjaxTableCont .stickyCol1 a { color:#333; }
  259. .AjaxTableCont .stickyCol1 a:hover { color:#337AB7; text-decoration:none; }
  260. .AjaxTableTaskCnt {padding:0 10px 10px 10px;}
  261. .AjaxTable .tbl-short-txt{max-width:140px; overflow:hidden;}
  262. .AjaxTable .tbl-short-txt span{display:block; height:18px;}
  263. .AjaxTable .tooltip-inner{white-space:normal;}
  264. .AjaxTable thead .sort .ta-ordering {cursor:pointer;}
  265. .AjaxTable thead .sort .ta-ordering span {margin:0 10px 0 0; padding:0; background-repeat:no-repeat; background-position:right top;}
  266. .AjaxTable thead .sort .ta-ordering-down span:after{content:\"\\e252\";font-family:\"Glyphicons Halflings\";line-height:1;margin:0 0 0 3px;display:inline-block;color:#bbb;}
  267. .AjaxTable thead .sort .ta-ordering-up span:after{content:\"\\e253\";font-family:\"Glyphicons Halflings\";line-height:1;margin:0 0 0 3px;display:inline-block;color:#bbb;}
  268. .AjaxTable thead .sort .ta-ordering {position:relative;}
  269. .AjaxTable thead .sort th .hover-show:hover{background-color:#000; background-image:url(stuff/twitter-bootstrap/img/glyphicons-halflings-white.png);}
  270. .AjaxTable thead .sort th .hover-show{display:none;}
  271. .AjaxTable thead .sort th:hover .hover-show{display:inline;}
  272. .AjaxTable thead .sort .ta-ordering .remove-cell {position:absolute; top:6px; right:2px; display:none; color:#f00;}
  273. .AjaxTable thead .sort .ta-ordering:hover .remove-cell {display:block;}
  274. .AjaxTableCont .pagination { margin:0; }
  275. .AjaxTableCont .pagination a { line-height:16px; }
  276. .AjaxTableCont .AjaxTableEdit-label { display:block; margin:0 0 3px 0; font-size:12px !important; line-height:16px !important; }
  277. .AjaxTableCont .AjaxTableEdit-label code { padding:0; white-space:nowrap; background-color:transparent; border:none; color:#777; font-size:10px !important; line-height:14px !important; }
  278. .AjaxTableCont .AjaxTableEdit .show-last-value .button-appendBack .glyphicon,
  279. .AjaxTableCont .AjaxFrmHorizontalEdit .show-last-value .button-appendBack .glyphicon {display:none;}
  280. .AjaxTableHist em {color:silver;}
  281. .AjaxTableCont .foot * { font-size:12px !important; }
  282. .AjaxTableCont .foot { margin:10px; }
  283. .AjaxTableCont .foot .foot-info { float:left; padding:0 20px; }
  284. .AjaxTableCont .foot .foot-info p { line-height:16px; margin:5px 0; }
  285. .AjaxTable-loading .foot .foot-info {padding-left:20px; background:url(./icon/loading.gif) no-repeat left top;}
  286. .tblAjax__head__specialFilter {margin:0;padding:4px 4px 4px 127px;}
  287. .tblAjax__head__specialFilter .btn-group {margin:0 4px;padding:0;}
  288. .tblAjax__head__specialFilter .btn-group .glyphicon-remove {color:#f00;}
  289. .tblAjax__head__specialFilter .btn-group button.disabled .glyphicon-remove {color:#bbb;}
  290. /* overwrite bootstrap table border */
  291. .AjaxTable, .AjaxTableEdit,
  292. .AjaxTable td, .AjaxTableEdit td,
  293. .AjaxTable th, .AjaxTableEdit th { border-color:#999; }
  294. /* cell A_STATUS */
  295. .AjaxTable .cell-A_STATUS-NORMAL { background:#aeffae; color:#000; text-align:center; }
  296. .AjaxTable .cell-A_STATUS-WAITING { background:#ffd2ff; color:#000; text-align:center; }
  297. .AjaxTable .cell-A_STATUS-MONITOR { background:#cccaff; color:#000; text-align:center; }
  298. .AjaxTable .cell-A_STATUS-WARNING { background:#ffbaba; color:#000; text-align:center; }
  299. .AjaxTable .cell-A_STATUS-DELETED { background:#e0e0e0; color:#808080; text-align:center; }
  300. .AjaxTable .cell-A_STATUS-OFF_SOFT { background:#fce3b7; color:#808080; text-align:center; }
  301. .AjaxTable .cell-A_STATUS-OFF_HARD { background:#eee; color:#808080; text-align:center; }
  302. /* cell Status */
  303. .AjaxTable .cell-Status-U { background:rgb(0,176,80); color:#000; text-align:center; }
  304. .AjaxTable .cell-Status-NU { background:#f00; color:#000; text-align:center; }
  305. .AjaxTable .cell-Status-P { background:rgb(112,48,160); color:#000; text-align:center; }
  306. .AjaxTable .cell-Status-PT { background:rgb(127,127,127); color:#000; text-align:center; }
  307. .AjaxTable .cell-Status-O { background:rgb(0,176,240); color:#000; text-align:center; }
  308. .AjaxTable .cell-Status-DZ { background:rgb(0,112,192); color:#000; text-align:center; }
  309. .AjaxTable .cell-Status-Z {}
  310. /* map */
  311. .AjaxTable .cell-mapfld { cursor:pointer; }
  312. .AjaxTable .cell-mapfld:hover { opacity:1; }
  313. .AjaxTable .cell-mapfld-remove { display:none; }
  314. .AjaxTable .cell-mapfld-hasValue .cell-mapfld-select { color:#f00; }
  315. .AjaxTable .cell-mapfld-hasValue .cell-mapfld-remove { display:inline-block; }
  316. .AjaxTableCont .mapEditor { position:absolute; bottom:0; right:6px; width:512px; height:318px; overflow:hidden; color:#eee; border:1px solid #999; }
  317. .AjaxTableCont .mapEditor-panel { height:16px; padding:0 6px; background:#999; border-bottom:1px solid #eee; }
  318. .AjaxTableCont .mapEditor-panel a { display:block; float:right; padding:0 6px; font-weight:bold; font-size:12px; line-height:16px; color:#fff; }
  319. .AjaxTableCont .mapEditor-panel a:hover { color:#006CD7; text-decoration:none; }
  320. .AjaxTableCont .mapEditor-panel a.mapEditor-panel-close:hover { color:#f00; }
  321. .AjaxTableCont .mapEditor-map { background:#fff; height:400px; }
  322. .AjaxTableCont-mapEditorContainer .mapEditor-map { border:1px solid #999; overflow:hidden; }
  323. /* .mapEditor-btnBackToWindow \"olControlSave\",overview_replacement */
  324. .olControlEditingToolbar .mapEditor-btnBackToWindowItemInactive,
  325. .olControlEditingToolbar .mapEditor-btnBackToWindowItemActive {
  326. background-image: url(icon/map.window.png);
  327. background-position: 0 0;
  328. background-repeat: no-repeat;
  329. }
  330. /*
  331. .mapEditor-btnBackToWindowItemInactive { background-image: url(stuff/open-layers/theme/default/img/overview_replacement.gif); }
  332. .mapEditor-btnBackToWindowItemActive { background-image: url(stuff/open-layers/theme/default/img/overview_replacement.gif); }
  333. */
  334. .ui-dialog-content .mapEditor-btnBackToWindowItemInactive,
  335. .ui-dialog-content .mapEditor-btnBackToWindowItemActive { display:none; }
  336. .AjaxTableCont .valign-btns-bottom a { vertical-align:text-bottom; font-weight:normal; font-size:12px; line-height:14px; }
  337. .ui-resizable-s { bottom:0; }
  338. .ui-resizable-e { right:0; }
  339. .AjaxTableCont-mapEditorContainer .ui-resizable-s { background-color:#ddd; }
  340. .AjaxTableCont-mapEditorContainer .ui-resizable-s:hover { background-color:#888; }
  341. ");
  342. $_rendered = true;
  343. }
  344. public function render() {
  345. $acl = $this->_acl;
  346. $hasGeomFlds = Core_AclHelper::hasGeomFields($acl);
  347. $tblAjaxMap = ($hasGeomFlds) ? new TableAjaxMap($acl, 512, 400) : null;
  348. $hasPermCreate = Core_AclHelper::hasCreatePerms($acl);
  349. $jsToogleFiltrProcesuFunctionName = 'tableAjaxToggleFiltrProcesInit';
  350. ob_start();
  351. $this->renderStatic($tblAjaxMap);
  352. UI::startContainer();
  353. UI::showMessagesForTable($this->_tbl);
  354. UI::endContainer();
  355. ?>
  356. <div class="AjaxTableCont">
  357. <ul class="breadcrumb">
  358. <li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>
  359. <!-- TODO: if has perm 'C' then add btn to create new record -->
  360. <?php if ($hasPermCreate) : ?>
  361. <li><a title="Dodaj nowy rekord"
  362. class=""
  363. href="#CREATE"><span class="glyphicon glyphicon-plus"></span> Dodaj nowy rekord</a></li>
  364. <?php endif; ?>
  365. <?php if ($this->_showProcesInit) : ?>
  366. <div class="btn-group pull-right">
  367. <a class="btn btn-xs btn-info dropdown-toggle"
  368. data-toggle="dropdown"
  369. href="#"
  370. title="Uruchom filtr procesu powiązanego z tabelą <?php echo $this->getLabel(); ?>"
  371. onclick="return <?php echo $jsToogleFiltrProcesuFunctionName; ?>(this);">
  372. Filtr procesu <span class="caret"></span>
  373. </a>
  374. <ul class="dropdown-menu pull-left" style="max-height:250px;overflow:auto;">
  375. <li class="disabled"><a href="#" onclick="return false;"> loading ... </a></li>
  376. </ul>
  377. </div>
  378. <?php endif; ?>
  379. <?php if ($this->_tbl == 'IN7_MK_BAZA_DYSTRYBUCJI') : ?>
  380. <a class="pull-right" style="padding:0 20px 0 0;" href="<?php echo "index.php?MENU_INIT=TREEJS&ZASOB_ID={$this->_zasobID}"; ?>"><i class="glyphicon glyphicon-eye-open"></i> Drzewo</a>
  381. <?php elseif ($this->allowTreeView()) : ?>
  382. <a class="pull-right" style="padding:0 20px 0 0;" href="<?php echo "index.php?MENU_INIT=VIEWTREE_AJAX&ZASOB_ID={$this->_zasobID}"; ?>"><i class="glyphicon glyphicon-eye-open"></i> Drzewo</a>
  383. <?php endif; ?>
  384. </ul>
  385. <div id="<?php echo $this->_htmlID; ?>"></div>
  386. </div>
  387. <script>
  388. var p5UI_TableAjax_generateFunctionNode = function(funObj, rowPK, props) {
  389. var defaultsProps = {
  390. ico: true,
  391. label: false
  392. },
  393. props = $.extend({}, defaultsProps, props);
  394. funcNode = $('<a href="#" style="margin:0 2px;"></a>')
  395. ;
  396. if ('href' in funObj) funcNode.attr('href', funObj.href.f(rowPK));
  397. if (props.ico) {
  398. if ('ico' in funObj) funcNode.append('<span class="' + funObj.ico + '"></span>');
  399. }
  400. if ('onclick' in funObj) funcNode.attr('onclick', funObj.onclick.f(rowPK));
  401. if ('title' in funObj) funcNode.attr('title', funObj.title);
  402. if ('target' in funObj) funcNode.attr('target', funObj.target);
  403. if (props.label) {
  404. if ('label' in funObj) {
  405. funcNode.append(' ' + funObj.label);
  406. } else if ('title' in funObj) {
  407. funcNode.append(' ' + funObj.title);
  408. }
  409. }
  410. return funcNode;
  411. };
  412. (function($) {
  413. var TableAjaxGeomField = function() {
  414. var priv = {}; //private api
  415. var publ = {}; //public api
  416. priv.options = {};
  417. var defaults = {
  418. recordID: '',
  419. fieldValue: '',
  420. hasValueClassName: 'TableAjaxGeomField-hasValue',
  421. linkClassNamePrefix: 'TableAjaxGeomField',
  422. linkSelectClassName: 'select',
  423. linkSelectAddClassNames: '', // 'glyphicon glyphicon-map-marker'
  424. linkRemoveClassName: 'remove',
  425. linkRemoveAddClassNames: '', // 'glyphicon glyphicon-remove'
  426. removeUrl: '',
  427. onSelect: null,
  428. onRemove: null,
  429. debug: false
  430. };
  431. priv.init = function() {
  432. priv.render();
  433. };
  434. priv.render = function() {
  435. var state = priv.options;
  436. var cellMapSelect = jQuery('<i title="Pokaż/utwórz obiekt na mapie"></i>');
  437. cellMapSelect.addClass(state.linkClassNamePrefix + '-' + state.linkSelectClassName);
  438. if (state.linkSelectAddClassNames) {
  439. cellMapSelect.addClass(state.linkSelectAddClassNames);
  440. }
  441. cellMapSelect.on('click', {recordID: priv.options.recordID, fieldValue: priv.options.fieldValue}, function(e) {
  442. if (typeof state.onSelect == "function") {
  443. state.onSelect.call(this, e.data.recordID, e.data.fieldValue);
  444. }
  445. });
  446. var cellMapRemove = jQuery('<i title="Usuń obiekt z mapy"></i>');
  447. cellMapRemove.addClass(state.linkClassNamePrefix + '-' + state.linkRemoveClassName);
  448. if (state.linkRemoveAddClassNames) {
  449. cellMapRemove.addClass(state.linkRemoveAddClassNames);
  450. }
  451. cellMapRemove.on('click', {recordID: state.recordID, fieldValue: state.fieldValue}, function(e) {
  452. if (typeof state.onRemove == "function") {
  453. state.onRemove.call(this, publ, e.data.recordID, e.data.fieldValue);
  454. }
  455. });
  456. var node = $(state.id);
  457. node.empty();
  458. node.addClass(state.linkClassNamePrefix);
  459. node.removeClass(state.hasValueClassName);
  460. if (state.fieldValue) {
  461. node.addClass(state.hasValueClassName);
  462. }
  463. node.append(cellMapSelect);
  464. node.append(cellMapRemove);
  465. };
  466. publ.setValue = function(value) {
  467. if (priv.options.debug) console.log('TEST setValue: ', value, 'this', this);
  468. priv.options.fieldValue = value;
  469. priv.render();
  470. };
  471. publ.init = function(options) {
  472. if (priv.options.debug) console.log('TableAjaxGeomField initialization...', options);
  473. //merge supplied options with defaults
  474. $.extend(priv.options, defaults, options);
  475. priv.init();
  476. return publ;
  477. };
  478. return publ;
  479. };
  480. $.fn.TableAjaxGeomFieldSetValue = function(value) {
  481. return this.each(function() {
  482. var tblAjaxMapGeomFld = $(this).data('TableAjaxGeomField');
  483. if (tblAjaxMapGeomFld) {
  484. tblAjaxMapGeomFld.setValue(value);
  485. }
  486. });
  487. return this;
  488. };
  489. $.fn.TableAjaxGeomField = function(options) {
  490. options = options || {};
  491. return this.each(function() {
  492. options.id = this;
  493. if (!$(this).data('TableAjaxGeomField')) {
  494. $(this).data('TableAjaxGeomField', new TableAjaxGeomField().init(options));
  495. }
  496. });
  497. return this;
  498. };
  499. }(jQuery));
  500. (function($, undefined) {
  501. var TableAjax = function() {
  502. var priv = {}; //private api
  503. var publ = {}; //public api
  504. priv.options = {};
  505. var defaults = {
  506. url: '', //webservice url
  507. urlData: '', //webservice params
  508. urlPost: false, //use POST instead of GET
  509. debug: false, //prints debug info to console
  510. filter: false, //show filter row
  511. filterInit: false,// init filters data
  512. forceFilterInit: false,
  513. columnPicker: false, //show columnpicker
  514. checkboxes: false, //show body checkboxes
  515. actions: '', //holds action links
  516. pageSize: 10, //current pagesize
  517. pageSizes: [10, 20, 30, 40, 50, 'All'], //available pagesizes
  518. hidePagerOnEmpty: false, //removes pager if no rows
  519. types: { //type specific options
  520. string: {},
  521. number: {},
  522. bool: {},
  523. date: {}
  524. },
  525. rowFunctions: false,
  526. tblFunctions: false,
  527. specialFilterFunctions: false,
  528. filtersClean: false,
  529. router: false,
  530. longDesc: false,
  531. exportFields: [],
  532. mapEditor: false, // mapEditor visible or not
  533. mapEditorContainer: 'window' // 'window' or 'dock'
  534. };
  535. var _uiNodeCont; // container holding table
  536. var _uiNode$Table; // the table node
  537. var _head; // table header
  538. var _headSort; // table header sorting row
  539. var _headFilter; // table header columns filter row
  540. var _headSpecialFilter; // table header special filter row
  541. var _bodyNode; // table body
  542. var _body; // TODO: table body need render?
  543. var _foot; // table footer
  544. var _inlineEditBox; // inline edit box with form
  545. var _popoverCell; // inline popover cell
  546. var _popoverCellCurrent; // inline popover cell
  547. var _popoverCellAjaxXhr;
  548. var _mapEditor; // map editor node
  549. var _mapEditorWrap; // map editor wrapper node
  550. var _mapEditorDialog; // map editor jquery ui dialog node
  551. var _state = {};// state - to replace variables below (date, ...)
  552. var _data; //columns and rows
  553. var _totalPages; // total pages
  554. var _currDpOp; // clicked datetimepicker operator
  555. var _filterFields = {}; // array with filter DOM elements
  556. var _filterTimeout; // timer for delayed filtering
  557. var _uniqueCols = {}; // array with checked rows /// TODO: mv to _state.
  558. var _checkToggleChecked = false; // check-all toggle state
  559. var _exportFieldsSelect = {};
  560. var _tableWidth;
  561. var _fieldWidgets = {};
  562. /*
  563. initialize the plugin.
  564. */
  565. priv.init = function() {
  566. _uiNodeCont = priv.options.id;
  567. _state = {};// init state
  568. _state.page = 1;
  569. _state.specialFilters = {};
  570. _state.filters = {};
  571. _state.filters.currSortCol = '';
  572. _state.filters.currSortFlip = false;
  573. _state.filters.filterCols = {};
  574. priv.initEvents();
  575. priv.initialRender();// set up _uiNode$...
  576. priv.options.types.string = ((priv.options.types || {}).string || {});
  577. priv.options.types.number = ((priv.options.types || {}).number || {});
  578. priv.options.types.bool = ((priv.options.types || {}).bool || {});
  579. priv.options.types.date = ((priv.options.types || {}).date || {});
  580. if (priv.options.mapEditorContainer != 'dock'
  581. && priv.options.mapEditorContainer != 'window') {
  582. priv.options.mapEditorContainer = 'window';
  583. }
  584. if (priv.options.filterInit) {
  585. priv.setStateFilters(priv.options.filterInit);
  586. }
  587. if (priv.options.exportFields) {
  588. $.each(priv.options.exportFields, function(ind, col) {
  589. _exportFieldsSelect[col] = true;
  590. });
  591. }
  592. //try call webservice for data
  593. priv.update(priv.options.router);
  594. if (typeof priv.options.router == "function") {
  595. $(window).bind('hashchange', function() {
  596. priv.options.router.apply(this);
  597. });
  598. }
  599. };
  600. priv.initEvents = function() {
  601. jQuery(_uiNodeCont).on('TableAjax:render', priv.onRender);
  602. jQuery(window).on('resize', priv.onWindowResize)
  603. };
  604. priv.onRender = function(e) {
  605. if (priv.options.debug) console.log('onRender.arguments:', arguments.length, arguments, 'e:', e);
  606. if (arguments.length > 1) {
  607. for (var i=1; i<arguments.length; i++) {
  608. switch (arguments[i]) {
  609. case 'head': _head = undefined; break;
  610. case 'body': _body = undefined; break;
  611. case 'foot': _foot = undefined; break;
  612. case 'foot_pagination': {
  613. priv.renderFooterInfo();
  614. priv.renderFooterPagination();
  615. priv.renderFooterPageSizes();
  616. }
  617. break;
  618. case 'footer__toolbar__info': priv.renderFooterInfo(); break;
  619. case 'footer__toolbar__pagination': priv.renderFooterPagination(); break;
  620. case 'footer__toolbar__pagesizes': priv.renderFooterPageSizes(); break;
  621. case 'foot__columnPicker': priv.renderFooterColumnPicker(); break;
  622. case 'head__specialFilters': priv.renderHeadSpecialFilters(); break;
  623. }
  624. }
  625. priv.renderTable();
  626. priv.onWindowResize();
  627. {// activate saveBtn if some columns hidden
  628. var selectedFilter = priv.modelColFilter_getSelected();
  629. if (null === selectedFilter) {
  630. priv.modelColFilter_getSaveBtn().prop("disabled", false)
  631. } else {
  632. priv.modelColFilter_getSaveBtn().prop("disabled", true)
  633. }
  634. }
  635. }
  636. };
  637. priv.onWindowResize = function() {
  638. var stickyCol1Width = (12 + 3) * 4 + 2 * 5 + 1;
  639. var stickyCol2Width = 50 + 2 * 5 + 1;
  640. var contW = jQuery(_uiNodeCont).parent().width();
  641. var colsW = stickyCol1Width + stickyCol2Width;
  642. jQuery(_uiNodeCont).css({width:'' + (contW - colsW) + 'px'})//, marginLeft:'' + colsW + 'px', overflowX:'scroll', overflowY:'visible', paddingBottom:'1px'});
  643. var wh = jQuery(window).height(); // returns height of browser viewport
  644. var dh = jQuery(document).height(); // returns height of HTML document (same as pageHeight in screenshot)
  645. if (dh > wh) {
  646. jQuery(_uiNodeCont).doubleScroll()
  647. jQuery(_uiNodeCont).prev('.doubleScroll-scroll-wrapper').css({float: 'right', display:'block'})
  648. } else {
  649. jQuery(_uiNodeCont).prev('.doubleScroll-scroll-wrapper').css({display:'none'})
  650. }
  651. }
  652. priv.initialRender = function() {
  653. _uiNode$Table = $('<table class="AjaxTable table table-striped table-hover table-bordered table-condensed"></table>').appendTo(_uiNodeCont);
  654. _head = $('<thead></thead>').prependTo(_uiNode$Table);
  655. _headSort = $('<tr class="sort tblAjax__head__sort"></tr>').prependTo(_head);
  656. _headFilter = $('<tr class="filter tblAjax__head__filter"></tr>').appendTo(_head);
  657. _bodyNode = $('<tbody></tbody>').insertAfter(_head);
  658. $('<tfoot></tfoot>').insertAfter(_bodyNode);
  659. _foot = $('<div class="foot tblAjax__footer"></div>').insertAfter(_uiNodeCont);
  660. var footToolbar = $('<div class="btn-toolbar tblAjax__footer__toolbar"></div>').appendTo(_foot);
  661. $('<span class="tblAjax__footer__toolbar__info"></span>').appendTo(footToolbar);
  662. $('<span class="tblAjax__footer__toolbar__pagination"></span>').appendTo(footToolbar);
  663. $('<span class="tblAjax__footer__toolbar__pagesizes"></span>').appendTo(footToolbar);
  664. $('<span class="tblAjax__footer__toolbar__columnPicker"></span>').appendTo(footToolbar);
  665. $('<span class="tblAjax__footer__toolbar__functions"></span>').appendTo(footToolbar);
  666. $('<span class="tblAjax__footer__toolbar__export"></span>').appendTo(footToolbar);
  667. _mapEditorWrap = $('<div class="mapEditor" style="display:none"></div>').insertAfter(_foot);
  668. _mapEditor = $('<div class="mapEditor-map"></div>').appendTo(_mapEditorWrap);
  669. _popoverCell = $('<div class="popoverCell" style="display:none"></div>').insertAfter(_foot);
  670. $('<div class="tblAjax__inlineEditBox"></div>').insertAfter(_foot);
  671. $('<div class="btn-toolbar tblAjax__head__specialFilter"></div>').insertBefore(_uiNodeCont);
  672. priv.renderInlineEditBox();// .tblAjax__inlineEditBox
  673. _foot = _head = _body = _headSort = _headFilter = undefined;// TODO: refactor
  674. /// console.log('L.<?php echo __LINE__; ?> priv.initialRender, _uiNode$Table: ', _uiNode$Table.html())
  675. };
  676. /*
  677. creates the table with all its parts and handlers.
  678. note that only the parts we need is created.
  679. (yeah, the function is huge)
  680. */
  681. priv.renderTable = function() {
  682. //create table itself
  683. // console.log('renderTable:: _data', _data);//TODO:DBG:RMME
  684. /// console.log('renderTable:: _uiNode$Table', _uiNode$Table);//TODO:DBG:RMME
  685. //create the header which will later hold both sorting and filtering
  686. /// console.log('L.<?php echo __LINE__; ?> renderTable:: _head', _head);//TODO:DBG:RMME
  687. if (!_head) {
  688. _headSort = _headFilter = _headSpecialFilter = undefined;
  689. //_head = $('<thead></thead>');
  690. // $('<tr class="sort"></tr>').prependTo(_head);
  691. //_uiNode$Table.find('thead').replaceWith(_head);
  692. _head = _uiNode$Table.find('thead');
  693. }
  694. //create the header sorting row
  695. if (!_headSort) {
  696. /// console.log('L.<?php echo __LINE__; ?> renderTable::renderTableTheadSort...');//TODO:DBG:RMME
  697. priv.renderTableTheadSort();
  698. }
  699. //create the header filtering row
  700. if (!_headFilter && priv.options.filter) {
  701. /// console.log('L.<?php echo __LINE__; ?> renderTable::renderTableTheadFilter...');//TODO:DBG:RMME
  702. priv.renderTableTheadFilter();
  703. _headFilter = true;
  704. }
  705. //create the header special filters row
  706. if (!_headSpecialFilter && priv.options.specialFilterFunctions) {
  707. priv.renderHeadSpecialFilters();
  708. _headSpecialFilter = true;
  709. }
  710. //create the body
  711. if (!_body) {
  712. _uiNode$Table.find('tbody').remove();
  713. _bodyNode = $('<tbody></tbody>').insertAfter(_head);
  714. //_bodyNode.on('change', '.unique', priv.rowChecked);
  715. //find out what rows to show next...
  716. var rowsAdded = 0;
  717. //slice out the chunk of data we need and create rows
  718. $.each(_data.rows, function(index, props) {
  719. var rowNode = priv.renderRow(props);
  720. if (rowNode) rowNode.appendTo(_bodyNode);
  721. rowsAdded++;
  722. //enough rows created?
  723. if (rowsAdded >= priv.options.pageSize) {
  724. return false;
  725. }
  726. });
  727. if (_state.page == 1) {
  728. _totalPages = Math.ceil(_data.total / priv.options.pageSize);
  729. }
  730. //pad with empty rows if we're at last page.
  731. if (_state.page == _totalPages) {
  732. while (rowsAdded < priv.options.pageSize) {
  733. var rowNode = priv.renderRowEmptyNode();
  734. if (rowNode) rowNode.appendTo(_bodyNode);
  735. rowsAdded++;
  736. }
  737. }
  738. }
  739. //create the footer
  740. if (!_foot) {
  741. priv.renderTableTfoot();
  742. priv.renderFooter();
  743. }
  744. _foot = $(_uiNodeCont).next('.foot');
  745. var stickyCol1Width = (12 + 3) * 4 + 2 * 5 + 1;
  746. var stickyCol2Width = 50 + 2 * 5 + 1;
  747. if (undefined === _tableWidth) {
  748. _tableWidth = true;
  749. var contW = jQuery(_uiNodeCont).width();
  750. var th1 = _uiNode$Table.find('.stickyCol1:first');
  751. var th2 = th1.next();
  752. var th1W = th1.innerWidth();
  753. var th2W = 50 + 2 * 5;//th2.innerWidth();
  754. var colsW = stickyCol1Width + stickyCol2Width;
  755. jQuery(_uiNodeCont).css({width:'' + (contW - colsW) + 'px', marginLeft:'' + colsW + 'px', overflowX:'scroll', overflowY:'visible', paddingBottom:'1px'});
  756. }
  757. _uiNode$Table.find('.stickyCol1').css({position:'absolute',
  758. left:'0',
  759. top:'auto',
  760. width:'' + stickyCol1Width + 'px',
  761. });
  762. //_uiNode$Table.find('.filter').find('.stickyCol1').css({height:'34px'});
  763. var sortStickyColHeight = _uiNode$Table.find('.sort').find('th:last').outerHeight();
  764. _uiNode$Table.find('.sort').find('.stickyCol1').css({height: sortStickyColHeight + 'px'});
  765. _uiNode$Table.find('.sort').find('.stickyCol2').css({height: sortStickyColHeight + 'px'});
  766. _uiNode$Table.find('.stickyCol2').css({position:'absolute',
  767. left:'' + (stickyCol1Width) + 'px',
  768. top:'auto',
  769. width:'' + stickyCol2Width + 'px',
  770. borderRight: '1px solid silver',
  771. overflow: 'hidden'
  772. });
  773. if (_data.total == 0 && priv.options.hidePagerOnEmpty) {
  774. $('.btn-toolbar', _foot).remove();
  775. }
  776. if (priv.options.debug) console.log('table created L.<?php echo __LINE__; ?>');
  777. if (typeof priv.options.tableCreated == 'function') {
  778. priv.options.tableCreated.call(_uiNode$Table.get(0), {table: _uiNode$Table.get(0)});
  779. }
  780. };
  781. // TODO: priv.renderFieldWidget_InlineEdit = function(fldName, value) {}
  782. // TODO: priv.renderFieldWidget_FormField = function(fldName, value) {}
  783. // @usage: priv.renderFieldWidget_TableCell(fldName, val, rowPK, row)
  784. priv.renderFieldWidget_TableCell = function(fldName, value, rowPK, row) {
  785. var renderFieldAsTableCell = priv.getFieldWidget_TableCell(fldName);
  786. if (!renderFieldAsTableCell) return null;
  787. return renderFieldAsTableCell(value, rowPK, row);
  788. };
  789. priv.registerFieldWidget = function(type, fldName, fieldProps) {
  790. var fieldWidget = null;
  791. switch (type) {
  792. case "date":// @return Element - TODO: not used yet
  793. fieldWidget = (function(fldName, fieldProps) {
  794. var _fieldName = fldName,
  795. _fieldProps = fieldProps;
  796. // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
  797. return function(val, fieldPK, row) {
  798. // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
  799. return val;
  800. }
  801. }(fldName, fieldProps));
  802. break;
  803. case "bool":// @return Element - TODO: not used yet
  804. fieldWidget = (function(fldName, fieldProps) {
  805. var _fieldName = fldName,
  806. _fieldProps = fieldProps;
  807. // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
  808. return function(val, fieldPK, row) {
  809. // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
  810. fldNode = document.createElement('input');
  811. fldNode.setAttribute('type', 'checkbox');
  812. if (val) fldNode.setAttribute('checked', 'checked');
  813. fldNode.setAttribute('disabled', 'disabled');
  814. fldNode.appendChild(document.createTextNode(val));
  815. return fldNode;
  816. }
  817. }(fldName, fieldProps));
  818. break;
  819. case "number":// @return String - TODO: not used yet
  820. fieldWidget = (function(fldName, fieldProps) {
  821. var _fieldName = fldName,
  822. _fieldProps = fieldProps,
  823. _fractionDigits = _.get(_fieldProps, 'fractionDigits', 2);
  824. // console.log('FieldWidget: generate function to render field('+_fieldName+') _fractionDigits('+_fractionDigits+')', fieldProps);
  825. return function(val, fieldPK, row) {
  826. // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
  827. // enumeration
  828. // fractionDigits
  829. // maxExclusive
  830. // maxInclusive
  831. // minExclusive
  832. // minInclusive
  833. // pattern
  834. // totalDigits
  835. // whiteSpace
  836. val = Number(val);
  837. return ((val || 0) % 1 === 0)? val : val.toFixed(_fractionDigits);
  838. }
  839. }(fldName, fieldProps));
  840. break;
  841. case "string":// @return String
  842. fieldWidget = (function(fldName, fieldProps) {
  843. var _fieldName = fldName,
  844. _fieldProps = fieldProps,
  845. _format = _.get(_fieldProps, 'format', '{0}');
  846. // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
  847. return function(val, fieldPK, row) {
  848. // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
  849. return _format.f(val);
  850. }
  851. }(fldName, fieldProps));
  852. break;
  853. case "p5:price":// @return String
  854. fieldWidget = (function(fldName, fieldProps) {
  855. var _fieldName = fldName,
  856. _fieldProps = fieldProps,
  857. _format = _.get(_fieldProps, 'format', '<span style="text-align:right">{0}</span>');
  858. // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
  859. return function(val, fieldPK, row) {
  860. // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
  861. return _format.f(val);
  862. }
  863. }(fldName, fieldProps));
  864. break;
  865. case "p5:string":// @return String
  866. fieldWidget = (function(fldName, fieldProps) {
  867. var _fieldName = fldName,
  868. _fieldProps = fieldProps,
  869. _formatByValue = _.get(_fieldProps, 'formatByValue', null);
  870. return function(val, fieldPK, row) {
  871. if (_formatByValue && val in _formatByValue) {
  872. return _formatByValue[val].f(val)
  873. }
  874. return val;
  875. }
  876. }(fldName, fieldProps));
  877. break;
  878. case "p5:www_link":// @return Element
  879. fieldWidget = (function(fldName, fieldProps) {
  880. var _fieldName = fldName,
  881. _fieldProps = fieldProps;
  882. // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
  883. return function(val, fieldPK, row) {
  884. // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
  885. var link = '',
  886. a = null,
  887. dbg = false;
  888. if (!val.length) return '';
  889. if ('index.php' == val.substr(0, 9) || 'procesy5.php' == val.substr(0, 12)) {
  890. link = window.location.protocol + '//' + window.location.hostname
  891. link += window.location.pathname.split('/').slice(0, -1).join('/')
  892. link += '/' + val
  893. } else {
  894. if ('http' == val.substr(0, 4)) link = val
  895. //else if ('ftp' == val.substr(0, 3))
  896. else link = 'http://' + val
  897. }
  898. var linkErrors = validate({www_link: link}, {www_link: {url: true}});
  899. if (linkErrors) {
  900. // if(dbg)console.log('linkErrors for (' + link +')', linkErrors);
  901. return val;
  902. }
  903. fldNode = document.createElement('a');
  904. fldNode.setAttribute('href', link);
  905. fldNode.setAttribute('target', '_blank');
  906. fldNode.appendChild(document.createTextNode(val));
  907. return fldNode;
  908. }
  909. }(fldName, fieldProps));
  910. break;
  911. case "special":
  912. fieldWidget = (function(fldName, fieldProps) {
  913. var _fieldName = fldName,
  914. _fieldProps = fieldProps,
  915. _format = _.get(_fieldProps, 'format', '{0}');
  916. // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
  917. return function(val, fieldPK, row) {
  918. // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
  919. return _format.f(val);
  920. }
  921. }(fldName, fieldProps));
  922. break;
  923. case "simpleLink":
  924. fieldWidget = (function(fldName, fieldProps) {
  925. var _fieldName = fldName,
  926. _fieldProps = fieldProps,
  927. _format = _.get(_fieldProps, 'format', '{0}');
  928. // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
  929. return function(val, fieldPK, row) {
  930. // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
  931. var valLink = String(val);
  932. if (undefined !== _fieldProps._tsRetId
  933. && (0 === _fieldProps._tsRetId || '0' === _fieldProps._tsRetId)
  934. && undefined !== _fieldProps._tsSimpleLink) {
  935. valLink = _fieldProps._tsSimpleLink.format;
  936. $.each(_fieldProps._tsSimpleLink.aliasMap, function(i, v) {
  937. // console.log('simpleLink aliasMap fldName:', fldName, 'i:', i, 'v:', v, 'row['+v+']', row[v], 'val', val, 'typeof val', typeof val);
  938. if (undefined !== row[v]) {
  939. valLink = valLink.replace(new RegExp('\{' + i + '\}', 'g'), row[v]);
  940. }
  941. });
  942. }
  943. return _format.f(valLink);
  944. }
  945. }(fldName, fieldProps));
  946. break;
  947. case "gml:PolygonPropertyType":
  948. case "gml:LineStringPropertyType":
  949. case "gml:PointPropertyType":
  950. case "geom":
  951. fieldWidget = (function(fldName, fieldProps) {
  952. var _fieldName = fldName,
  953. _fieldProps = fieldProps,
  954. _format = _.get(_fieldProps, 'format', '{0}');
  955. // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
  956. return function(val, fieldPK, row) {
  957. // console.log('FieldWidget: run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
  958. // console.log('FieldWidget: test priv', priv);
  959. var node = jQuery('<span></span>');
  960. node.TableAjaxGeomField({
  961. recordID: fieldPK,
  962. fieldValue: val,
  963. hasValueClassName: 'cell-mapfld-hasValue',
  964. //removeUrl: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=THE_GEOM_REMOVE&ID=' + rowPK,
  965. linkClassNamePrefix: 'cell-mapfld',
  966. linkSelectClassName: 'select',
  967. linkSelectAddClassNames: 'glyphicon glyphicon-map-marker',
  968. linkRemoveClassName: 'remove',
  969. linkRemoveAddClassNames: 'glyphicon glyphicon-remove',
  970. onSelect: function(recordID, geomShape) {
  971. if (priv.options.debug) console.log('recordID:', recordID, 'geomShape:', geomShape);
  972. priv.mapEditorShow();
  973. _mapEditor.TableAjaxMapSelectRecord(recordID, geomShape);
  974. },
  975. onRemove: function(geomField, recordID, geomShape) {
  976. if (confirm('Czy usunąć obiekt z mapy dla rekordu ' + recordID + '?')) {
  977. if (!recordID) return;
  978. var selectedRecordId = recordID;
  979. superagent
  980. .post('<?= $this->syncUrl; ?>&_hash=<?= $this->_htmlID; ?>&_task=removeTheGeomAjax')
  981. .type('json') // header ĺapplication/x-www-form-urlencoded' requires type('form');
  982. .send({
  983. ID: recordID,
  984. namespace: '<?= $acl->getNamespace(); ?>'
  985. })
  986. .set('Accept', 'application/json')
  987. .end(function(err, res) {
  988. if(priv.options.debug)console.log('DBG: res:', res, 'res.body:', res.body);
  989. var payload;
  990. if (err || !res.ok || 'application/json' !== res.type) {
  991. payload = {type: 'warning', msg: res.body.msg || 'Wystąpiły błędy', body: res.body};
  992. } else {
  993. payload = {type: 'success', msg: res.body.msg || '', body: res.body};
  994. }
  995. p5UI__notifyAjaxCallback(payload);
  996. var data = res.body;
  997. if (data && data.record && data.record.the_geom) {
  998. if (priv.options.debug) console.log('data.record.the_geom:2:', data.record.the_geom);
  999. geomField.setValue(data.record.the_geom);
  1000. }
  1001. else if (data && data.record) {
  1002. if (priv.options.debug) console.log('data.record.the_geom:2:', data.record.the_geom);
  1003. geomField.setValue(data.record.the_geom);
  1004. }
  1005. _mapEditor.TableAjaxMapRefresh();
  1006. });
  1007. }
  1008. }
  1009. });
  1010. return node;
  1011. }
  1012. }(fldName, fieldProps));
  1013. break;
  1014. case "ref":
  1015. fieldWidget = (function(fldName, fieldProps) {
  1016. var _fieldName = fldName,
  1017. _fieldProps = fieldProps;
  1018. // console.log('FieldWidget: generate function to render field('+_fieldName+') fieldProps: ', fieldProps);
  1019. return function(val, fieldPK, row) {
  1020. // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value: ', val, ', fieldProps: ', fieldProps);
  1021. return _.map(val, function(v) {
  1022. if (!v || !v.xlink) return '';
  1023. var idRemote = v.xlink.split('.').pop()
  1024. var nsRemote = v.xlink.split(':').pop().split('.').shift()
  1025. var seLink = '<?= Request::getPathUri(); ?>index.php?_route=ViewTableAjax&namespace=' + fieldProps.xsdRefNsPrefix + '/' + nsRemote + '#EDIT/' + idRemote;
  1026. var wfsLink = fieldProps.xsdRefUri + '#' + fieldProps.xsdRefType + '.' + idRemote;
  1027. return '<a href="' + seLink + '" title="' + wfsLink + '">' + v.xlink + '</a>';
  1028. }).join(' ');
  1029. }
  1030. }(fldName, fieldProps));
  1031. break;
  1032. }
  1033. _fieldWidgets[fldName] = fieldWidget;
  1034. };
  1035. priv.getFieldWidget_TableCell = function(fieldName) {
  1036. var props = _data.cols[fieldName],
  1037. type = null,
  1038. renderFieldAsTableCell = null;
  1039. if (!props) return null;
  1040. type = _.get(props, 'type');
  1041. if (!type) type = 'string';// TODO: throw Exception? / default string
  1042. renderFieldAsTableCell = _.get(_fieldWidgets, fieldName);
  1043. if (renderFieldAsTableCell) return renderFieldAsTableCell;
  1044. priv.registerFieldWidget(type, fieldName, props);
  1045. renderFieldAsTableCell = _.get(_fieldWidgets, fieldName);
  1046. if (!renderFieldAsTableCell) throw "Field type '" + type + "' not implemented";
  1047. return renderFieldAsTableCell;
  1048. };
  1049. priv.renderRow = function(props) {
  1050. var rowNode = $('<tr></tr>'),
  1051. uniqueColName = _state.uniqueCol,
  1052. rowPK = (uniqueColName in props)? props[uniqueColName] : null,
  1053. cellNode,
  1054. columnName, columnProps, val, cellCnt, format, showTooltip, fldWidgetNode,
  1055. dbg = priv.options.debug
  1056. ;
  1057. if (priv.options.rowFunctions || priv.options.filtersClean) {
  1058. cellNode = priv.renderCellRowFunctions(priv.options.rowFunctions, rowPK, props);
  1059. cellNode.addClass('text-right stickyCol1');
  1060. cellNode.appendTo(rowNode);
  1061. }
  1062. //create checkbox
  1063. if (_state.uniqueCol && priv.options.checkboxes) {
  1064. var check = _uniqueCols[props[_state.uniqueCol]] != undefined ? 'checked' : '';
  1065. var checkable = props['checkable'] === false ? 'disabled' : '';
  1066. cellNode = $('<td></td>').appendTo(rowNode);
  1067. $('<input class="unique" {0} {1} type="checkbox" />'.f(check, checkable)).appendTo(cellNode);
  1068. }
  1069. if (uniqueColName) rowNode.data('unique', rowPK);
  1070. //create cells
  1071. for (var i = 0; i < _state.colsSorted.length; i++) {
  1072. columnName = _state.colsSorted[i];
  1073. columnProps = _data.cols[columnName];
  1074. val = '';
  1075. if (!columnProps) continue;
  1076. if (columnProps.hidden) continue;// TODO: "unique" is hidden
  1077. showTooltip = true;
  1078. val = props[columnName];
  1079. cellNode = $('<td></td>').appendTo(rowNode);
  1080. if (i === 1) cellNode.addClass('stickyCol2');// primaryKey(ID)
  1081. if (i !== 1) cellNode.on('dblclick', {id:rowPK, col:columnName}, priv.rowDblClicked);
  1082. cellCnt = (i === 1)? '<div></div>' : '<span></span>';
  1083. cellCnt = $(cellCnt).appendTo(cellNode);// fix dblclick for copy
  1084. cellNode.data('column', columnName);
  1085. if (val === undefined) continue;
  1086. format = _.get(columnProps, 'format', '{0}');
  1087. // test use field widgets
  1088. fldWidgetNode = priv.renderFieldWidget_TableCell(columnName, val, rowPK, props);
  1089. if (fldWidgetNode) {
  1090. cellCnt.empty();
  1091. // console.log('FieldWidget: row.pk('+rowPK+') col('+columnName+') typeof fldWidgetNode', typeof fldWidgetNode, fldWidgetNode);
  1092. cellCnt.append(fldWidgetNode);
  1093. } else if (fldWidgetNode === '') {
  1094. cellCnt.empty();
  1095. } else {
  1096. console.log('TODO: !FieldWidget for row.pk('+rowPK+') col('+columnName+') typeof fldWidgetNode(' + (typeof fldWidgetNode) + ')');
  1097. }// test fld widgets
  1098. if (columnProps._tsRetId) {
  1099. showTooltip = false;
  1100. if (columnProps._tsRetId > 0) {
  1101. cellCnt.on('click', {id:rowPK, col:columnName, friendly:columnProps.friendly, value:format.f(val)}, priv.popoverCellTypeSpecial);
  1102. }
  1103. }
  1104. if (i > 1 && priv.options.longDesc) {// TODO: use better check for columns: functions and pk
  1105. cellNode.addClass('tbl-short-txt');
  1106. if (showTooltip) {
  1107. cellCnt.tooltip({title: cellCnt.text(), placement: 'left'});
  1108. }
  1109. }
  1110. }
  1111. return rowNode;
  1112. };
  1113. priv.renderCellRowFunctions = function(rowFunctions, rowPK, rowProps) {
  1114. var cellNode = $('<td></td>'),
  1115. keys = Object.keys(rowFunctions),
  1116. total = keys.length,
  1117. moreFuncBtnNode,
  1118. moreFunctions = [],
  1119. idx
  1120. ;
  1121. if (priv.options.debug) console.log('TableAjax::renderCellRowFunctions: rowFunctions', rowFunctions);
  1122. idx = keys.indexOf('hist');
  1123. if (idx !== -1) {
  1124. histFunc = keys.splice(idx, 1);
  1125. keys.push('hist');
  1126. }
  1127. moreFunctions = keys.splice(3);
  1128. keys.forEach(function(key) {
  1129. var funObj = rowFunctions[key],
  1130. funcNode = p5UI_TableAjax_generateFunctionNode(funObj, rowPK, {ico: true, label: false})
  1131. ;
  1132. funcNode.appendTo(cellNode);
  1133. });
  1134. moreFuncBtnNode = $('<a href="#" style="margin:0 2px;text-decoration:none" title="Więcej funkcji dla rekordu nr '+rowPK+'" class="glyphicon glyphicon-menu-hamburger"> </a>');
  1135. moreFuncBtnNode.on('click', {rowPK: rowPK, rowFunctions: rowFunctions, more: moreFunctions}, priv.popoverCellMoreFunctions);
  1136. moreFuncBtnNode.appendTo(cellNode);
  1137. return cellNode;
  1138. };
  1139. priv.popoverCellMoreFunctions = function(e) {
  1140. e.preventDefault();
  1141. e.stopPropagation();
  1142. if (priv.options.debug) console.log('TableAjax::popoverCellMoreFunctions: rowPK', e.data.rowPK, 'moreFunctions', e.data.more, 'rowFunctions', e.data.rowFunctions);
  1143. if ('rowPK' in e.data && e.data.rowPK > 0) {
  1144. var lastId = _popoverCell.data('rowid'),
  1145. lastCol = _popoverCell.data('col'),
  1146. rowPK = e.data.rowPK,
  1147. moreFunctions = e.data.more,
  1148. rowFunctions = e.data.rowFunctions,
  1149. funcListNode
  1150. ;
  1151. if (lastId == e.data.rowPK && lastCol == 'moreFunctions') {
  1152. //_popoverCellCurrent.popover('toggle');
  1153. }
  1154. else {
  1155. if (_popoverCellCurrent) {
  1156. _popoverCellCurrent.popover('destroy');
  1157. }
  1158. _popoverCell.data('rowid', rowPK);
  1159. _popoverCell.data('col', 'rowFunctions');
  1160. _popoverCell.empty();
  1161. funcListNode = $('<ul class="list-unstyled popoverRowFunctions"></ul>').appendTo(_popoverCell);
  1162. moreFunctions.forEach(function(funcName) {
  1163. var funcItemNode = $('<li></li>').appendTo(funcListNode),
  1164. funObj = rowFunctions[funcName],
  1165. funcNode = p5UI_TableAjax_generateFunctionNode(funObj, rowPK, {ico: true, label: true})
  1166. ;
  1167. funcNode.addClass('func_name-' + funcName);
  1168. funcItemNode.append(funcNode);
  1169. });
  1170. _popoverCell.append('<div class="popoverCellContent" style="white-space:normal"></div>');
  1171. _popoverCellCurrent = jQuery(e.currentTarget);
  1172. // title : '<span class="text-info"><strong>title</strong></span> <button type="button" id="close" class="close">&times;</button>'
  1173. var opts = {
  1174. container: 'body',
  1175. placement: 'right',
  1176. trigger: 'click',
  1177. template: '',
  1178. html: true,
  1179. content: _popoverCell.html()
  1180. }
  1181. opts.template += '<div class="popover" role="tooltip" style="max-width:600px;width:400px;">';
  1182. {
  1183. opts.template += '<div class="arrow"></div>';
  1184. //opts.template += '<h3 class="popover-title"></h3>';
  1185. opts.template += '<div style="display:block;position:relative;">';
  1186. {
  1187. opts.template += '<div class="popover-title">';
  1188. opts.template += '</div>';
  1189. opts.template += '<button type="button" class="close" onclick="return hidePopover();" style="position:absolute;right:8px;top:6px;">&times;</button>';
  1190. }
  1191. opts.template += '</div>';
  1192. opts.template += '<div class="popover-content"></div>';
  1193. }
  1194. opts.template += '</div>';
  1195. _popoverCellCurrent.popover(opts);
  1196. _popoverCellCurrent.on('shown.bs.popover', function(e) {
  1197. if (!_popoverCellCurrent) return;
  1198. var popoverNodeId = _popoverCellCurrent.attr('aria-describedby');
  1199. if (!popoverNodeId) return;
  1200. var popover$Node = jQuery('#' + popoverNodeId);
  1201. if (!popover$Node.length) return;
  1202. var arrow$Node = popover$Node.children('.arrow');
  1203. if (arrow$Node.length) {
  1204. var posTop = parseFloat(arrow$Node.css('top'));
  1205. arrow$Node.css('top', '' + posTop + 'px')
  1206. }
  1207. popover$Node.find('.popoverCellContent').html('<p class="text-muted">Pobieranie funkcji...<p>');
  1208. priv.ajaxLoadMoreFunctionsCell(rowPK);
  1209. });
  1210. _popoverCellCurrent.popover('show');
  1211. }
  1212. } else {
  1213. if (priv.options.debug) console.log('NO data');
  1214. return false;
  1215. }
  1216. return;
  1217. };
  1218. priv.ajaxLoadMoreFunctionsCell = function(rowPK) {
  1219. var dbg = priv.options.debug;
  1220. if (_popoverCellAjaxXhr) {
  1221. _popoverCellAjaxXhr.abort();
  1222. }
  1223. _popoverCellAjaxXhr = $.ajax({
  1224. type: 'GET',
  1225. url: '<?= $this->syncUrl; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=moreFunctionsCellAjax&ID=' + rowPK,
  1226. dataType: 'json',
  1227. contentType: "application/json; charset=utf-8",
  1228. data: ''
  1229. })
  1230. .done(function(data, textStatus, jqXHR){
  1231. if (data && 'success' === data.type) {
  1232. var popoverCellContent,
  1233. rowFunctions = [],
  1234. funcNodesToUpdate = []
  1235. ;
  1236. if (data.rowFunctions && data.rowFunctions.length > 0) {
  1237. rowFunctions = data.rowFunctions;
  1238. }
  1239. if (rowFunctions.length > 0) {
  1240. var popoverCellContent = $('<ul class="list-unstyled"></ul>');
  1241. rowFunctions.forEach(function(funObj) {
  1242. var funcNode = p5UI_TableAjax_generateFunctionNode(funObj, rowPK, {ico: true, label: true});
  1243. if (funObj.id) {
  1244. funcNodesToUpdate.push({id: funObj.id, node: funcNode});
  1245. } else {
  1246. var funcItemNode = $('<li></li>').appendTo(popoverCellContent);
  1247. funcItemNode.append(funcNode);
  1248. }
  1249. });
  1250. } else {
  1251. popoverCellContent = '<p class="text-muted">Brak dodatkowych funkcji</p>';
  1252. }
  1253. //_popoverCell.append(popoverCellContent);// cache
  1254. if (_popoverCellCurrent) {
  1255. var popoverNodeId = _popoverCellCurrent.attr('aria-describedby');
  1256. if (popoverNodeId) {
  1257. var popoverNode = jQuery('#' + popoverNodeId),
  1258. popoverCntNode = popoverNode.find('.popoverCellContent'),
  1259. popoverRowFuncNode = popoverNode.find('.popoverRowFunctions');
  1260. ;
  1261. {// fix generated row Functions by loaded from ajax call
  1262. if(dbg) console.log('popoverRowFunctions. popoverRowFuncNode', popoverRowFuncNode);
  1263. if(dbg) console.log('popoverRowFunctions. funcNodesToUpdate', funcNodesToUpdate);
  1264. funcNodesToUpdate.forEach(function(funcNodeInfo) {
  1265. var className = 'func_name-' + funcNodeInfo.id,
  1266. foundRowFuncNode = null
  1267. ;
  1268. if(dbg) console.log('popoverRowFunctions. funcNodesToUpdate loop:', funcNodeInfo);
  1269. popoverRowFuncNode.find('li > a').each(function(ind, n) {
  1270. var n$ = $(n);
  1271. if(dbg) console.log('popoverRowFunctions loop(',ind,'):', n, 'data(func_name)', n$.data('func_name'), 'data', n$.data());
  1272. if (n$.hasClass(className)) {
  1273. foundRowFuncNode = n$;
  1274. }
  1275. });
  1276. if (foundRowFuncNode) {
  1277. foundRowFuncNode.replaceWith(funcNodeInfo.node);
  1278. } else {
  1279. var funcItemNode = $('<li></li>').appendTo(popoverCellContent);
  1280. funcItemNode.append(foundRowFuncNode);
  1281. }
  1282. });
  1283. }
  1284. popoverCntNode.empty().append(popoverCellContent);
  1285. if (rowFunctions.length <= 0) {
  1286. popoverCntNode.find('p.text-muted').delay(600).hide(300);
  1287. }
  1288. }
  1289. }
  1290. }
  1291. });
  1292. };
  1293. priv.renderRowEmptyNode = function() {
  1294. var rowNode = $('<tr></tr>');
  1295. if (priv.options.rowFunctions || priv.options.filtersClean) {
  1296. $('<td class="text-right stickyCol1">&nbsp;</td>').appendTo(rowNode);
  1297. }
  1298. if (_state.uniqueCol && priv.options.checkboxes) {
  1299. $('<td><input disabled type="checkbox" /></td>').appendTo(rowNode);
  1300. }
  1301. for (var i = 0; i < _state.colsSorted.length; i++) {
  1302. var columnName = _state.colsSorted[i],
  1303. columnProps = _data.cols[columnName]
  1304. ;
  1305. if (!columnProps) return;
  1306. if (columnProps.hidden) continue;// "unique" is hidden - TODO: rm "unique" from _state.colsSorted ?
  1307. if (i == 1) {// TODO: 1 is pk - use better check
  1308. $('<td class="stickyCol2">&nbsp;</td>').appendTo(rowNode);
  1309. } else {
  1310. $('<td>&nbsp;</td>').appendTo(rowNode);
  1311. }
  1312. }
  1313. return rowNode;
  1314. };
  1315. priv.renderTableTheadSort = function() {
  1316. var nodeClass = 'tblAjax__' + 'head__sort',
  1317. currentNode = _uiNode$Table.find('thead').find('.' + nodeClass),
  1318. node;
  1319. // currentNode.find('i').tooltip('hide');
  1320. node = $('<tr class="sort ' + nodeClass + '"></tr>');
  1321. //create the functions column
  1322. if (priv.options.tblFunctions || priv.options.filtersClean) {
  1323. var headCell = $('<th class="text-right head-info stickyCol1"></th>').appendTo(node);
  1324. $.map(priv.options.tblFunctions, function(funObj, funName){
  1325. var funHtml = $('<a></a>');
  1326. funHtml.attr('href', funObj.href || '#');
  1327. if (funObj.title) funHtml.attr('title', funObj.title);
  1328. if (funObj.icon) funHtml.html('<span class="glyphicon glyphicon-' + funObj.icon + '"></span> ');
  1329. if (funObj.method && priv[funObj.method] && typeof priv[funObj.method] == 'function') {
  1330. funHtml.on('click', priv[funObj.method]);
  1331. }
  1332. funHtml.appendTo(headCell);
  1333. });
  1334. }
  1335. //create the checkall toggle
  1336. if (_state.uniqueCol && priv.options.checkboxes) {
  1337. var checked = _checkToggleChecked ? 'checked' : '';
  1338. var headCell = $('<th></th>').appendTo(node);
  1339. var elem = $('<input {0} class="checkToggle" type="checkbox" />'.f(checked)).appendTo(headCell);
  1340. elem.on('change', priv.checkToggleChanged);
  1341. }
  1342. //create the sortable headers
  1343. for (var i = 0; i < _state.colsSorted.length; i++) {
  1344. var column = _state.colsSorted[i];
  1345. var props = _data.cols[column];
  1346. if (!props.hidden) {
  1347. var headCell = $('<th class="ta-ordering"></th>').appendTo(node);
  1348. if (i == 1) headCell.addClass('stickyCol2');
  1349. if (false) {// TODO: old way
  1350. var link = $('<a class="pull-left" href="#">{0}</a>'.f(props.friendly || column));
  1351. link.on('click', {column: column}, priv.columnClicked).appendTo(headCell);
  1352. if (props.tooltip) {
  1353. $('<i class="glyphicon glyphicon-info-sign"></i>').tooltip({
  1354. title: props.tooltip.trim(),
  1355. html: true,
  1356. container: 'body',
  1357. placement: "top",
  1358. delay: {
  1359. show: 500,
  1360. hide: 100
  1361. }
  1362. }).appendTo(link);
  1363. }
  1364. //Add sort arrow
  1365. if (column == _state.filters.currSortCol) {
  1366. if (_state.filters.currSortFlip) $('<i class="glyphicon glyphicon-chevron-down pull-right"></i>').appendTo(headCell);
  1367. else $('<i class="glyphicon glyphicon-chevron-up pull-right"></i>').appendTo(headCell);
  1368. }
  1369. //Add hide btn
  1370. if (column != 'ID') {
  1371. var hideColBtn = $('<i class="glyphicon glyphicon-remove pull-right hover-show"></i>');
  1372. hideColBtn.on('click', {column: column}, priv.columnHideClicked);
  1373. hideColBtn.appendTo(headCell);
  1374. }
  1375. }
  1376. if (props.type != 'special' && props.type != 'geom') {
  1377. headCell.on('click', {column: column}, priv.columnClicked);
  1378. }
  1379. var colTitle = column;
  1380. if (props.description && props.description.length > 0) {
  1381. colTitle = props.description;
  1382. colTitle += ' (' + column + ')';
  1383. }
  1384. else if (props._tsRetId > 0) {
  1385. colTitle = 'Kliknij na pole i przejdź do powiązanych rekordów (' + colTitle + ')';
  1386. }
  1387. if (props.friendly) {
  1388. var headCnt = $('<span class="pull-left" title="{1}">{0}</span>'.f(props.friendly, colTitle));
  1389. } else {
  1390. var headCnt = $('<span class="pull-left" title="{1}">{0}</span>'.f(column, colTitle));
  1391. }
  1392. headCnt.appendTo(headCell);
  1393. //Add sort arrow
  1394. if (column == _state.filters.currSortCol) {
  1395. if (_state.filters.currSortFlip) headCell.addClass('ta-ordering-down');
  1396. else headCell.addClass('ta-ordering-up');
  1397. }
  1398. if (column != 'ID') {
  1399. var hideColBtn = $('<i class="glyphicon glyphicon-remove remove-cell"></i>');
  1400. hideColBtn.on('click', {column: column}, priv.columnHideClicked);
  1401. hideColBtn.appendTo(headCell);
  1402. }
  1403. }
  1404. }
  1405. currentNode.replaceWith(node);
  1406. };
  1407. priv.renderHeadSpecialFilters = function() {
  1408. var nodeClass = 'tblAjax__' + 'head__specialFilter',
  1409. currentNode = $(_uiNodeCont).prev('.' + nodeClass),
  1410. node;
  1411. /// console.log('L.<?php echo __LINE__; ?> renderTable::renderHeadSpecialFilters...');//TODO:DBG:RMME
  1412. if (!priv.options.specialFilterFunctions) {
  1413. return;
  1414. }
  1415. var node = $('<div class="btn-toolbar tblAjax__head__specialFilter"></div>');
  1416. $.map(priv.options.specialFilterFunctions, function(groupObj, groupName) {
  1417. var btnHtml,
  1418. btnSelected,
  1419. groupLabel = groupObj.label || groupName,
  1420. groupHtml = $('<div class="btn-group"></div>')
  1421. ;
  1422. // _state.specialFilters[e.data.group] = e.data.value;
  1423. if (groupName in _state.specialFilters) {
  1424. btnSelected = _state.specialFilters[groupName];
  1425. }
  1426. if (groupObj.icon) {
  1427. $('<button class="btn btn-xs btn-default" title="' + groupLabel + '"><i class="' + groupObj.icon + '"></i></button>').appendTo(groupHtml);
  1428. }
  1429. $.map(groupObj.btns, function(btnObj, btnName) {
  1430. btnHtml = $('<button class="btn btn-xs btn-default' + ((btnSelected && btnSelected == btnObj.value)? ' active' : '') + '">' + btnName + '</button>').appendTo(groupHtml);
  1431. btnHtml.on('click', {group: groupName, value: btnObj.value}, priv.specialFilterChanged);
  1432. });
  1433. btnHtml = $('<button class="btn btn-xs btn-default' + ((!btnSelected)? ' disabled' : '') + '" title="Kasuj filtr"><i class="glyphicon glyphicon-remove"></i></button>').appendTo(groupHtml);
  1434. btnHtml.on('click', {group: groupName, value: ''}, priv.specialFilterChanged);
  1435. groupHtml.appendTo(node);
  1436. });
  1437. currentNode.replaceWith(node);
  1438. };
  1439. priv.renderTableTheadFilter = function() {
  1440. var nodeClass = 'tblAjax__' + 'head__filter',
  1441. currentNode = _uiNode$Table.find('thead').find('.' + nodeClass),
  1442. node;
  1443. /// console.log('L.<?php echo __LINE__; ?> renderTable::renderTableTheadFilter...');//TODO:DBG:RMME
  1444. // currentNode.find('i').tooltip('hide');
  1445. node = $('<tr class="filter ' + nodeClass + '"></tr>');
  1446. //_head.find(".filter").remove();
  1447. //_headFilter = $('<tr class="filter"></tr>').appendTo(_head);
  1448. var headCell;
  1449. var elem;
  1450. var placeHolder = '';
  1451. var tooltip = '';
  1452. //create the functions column
  1453. if (priv.options.rowFunctions || priv.options.filtersClean) {
  1454. var headCell = $('<th class="text-right stickyCol1"></th>').appendTo(node);
  1455. headCell.css({padding: '0'});
  1456. if (priv.options.filtersClean) {
  1457. var elem = $('<button title="Kasuj filtry" class="btn btn-xs btn-link glyphicon glyphicon-remove"></button>').appendTo(headCell);
  1458. elem.on('click', priv.filtersClean);
  1459. }
  1460. }
  1461. //create the filter checkbox
  1462. if (_state.uniqueCol && priv.options.checkboxes) {
  1463. tooltip = priv.options.types.bool.filterTooltip || 'Toggle between:<br/>indeterminate,<br/>checked,<br/>unchecked';
  1464. headCell = $('<th></th>').appendTo(node);
  1465. elem = $('<input class="filter indeterminate" checked type="checkbox" />').appendTo(headCell);
  1466. $.map(_state.filters.filterCols, function(colProps, col) {
  1467. if (col == "unique") {
  1468. if (colProps.filter) elem.prop('checked', true).removeClass('indeterminate');
  1469. else if (!colProps.filter) elem.prop('checked', false).removeClass('indeterminate');
  1470. else if (colProps.filter == '') elem.addClass('indeterminate');
  1471. }
  1472. });
  1473. if (tooltip) {
  1474. elem.tooltip({
  1475. title: tooltip.trim(),
  1476. html: true,
  1477. container: 'body',
  1478. trigger: 'hover',
  1479. placement: 'top',
  1480. delay: {
  1481. show: 500,
  1482. hide: 100
  1483. }
  1484. });
  1485. }
  1486. elem.on('click', {column: "unique"}, priv.filterChanged);
  1487. }
  1488. //create the column filters
  1489. for (var i = 0; i < _state.colsSorted.length; i++) {
  1490. var column = _state.colsSorted[i];
  1491. var props = _data.cols[column];
  1492. tooltip = props.filterTooltip === true ? undefined : props.filterTooltip === false ? '' : props.filterTooltip;
  1493. placeHolder = props.placeHolder === true ? undefined : props.placeHolder === false ? '' : props.placeHolder;
  1494. if (props.hidden) continue;
  1495. headCell = $('<th></th>').appendTo(node);
  1496. headCell.css({padding: '0'});
  1497. if (i == 1) headCell.addClass('stickyCol2');
  1498. // @mark MarkTableAjaxFilterColType
  1499. switch (props.type || 'string') {
  1500. case "number":
  1501. if (placeHolder == undefined) placeHolder = priv.options.types.number.placeHolder;
  1502. placeHolder = (placeHolder === true || placeHolder == undefined) ? '10..20 =50' : placeHolder === false ? '' : placeHolder;
  1503. if (tooltip == undefined) tooltip = priv.options.types.number.filterTooltip;
  1504. tooltip = (tooltip === true || tooltip == undefined) ? 'Values 10 to 20:<br/>10..20<br/>Values exactly 50:<br/>=50' : tooltip === false ? '' : tooltip;
  1505. elem = $('<input placeholder="{0}" class="filter" type="text" />'.f(placeHolder));
  1506. elem.on('keyup', {column: column}, priv.filterChanged);
  1507. break;
  1508. case "date":
  1509. if (placeHolder == undefined) placeHolder = priv.options.types.date.placeHolder;
  1510. placeHolder = (placeHolder === true || placeHolder == undefined) ? '-7..0' : placeHolder === false ? '' : placeHolder;
  1511. if (tooltip == undefined) tooltip = priv.options.types.date.filterTooltip;
  1512. tooltip = (tooltip === true || tooltip == undefined) ? 'Today:<br/>0..1<br/>A week today excluded:<br/>-7..0' : tooltip === false ? '' : tooltip;
  1513. elem = $('<div><input placeholder="{0}" class="filter" type="text" /></div>'.f(placeHolder));
  1514. if (priv.options.types.date.datePicker === true || priv.options.types.date.datePicker == undefined)
  1515. {
  1516. if ($().datepicker)
  1517. {
  1518. elem.addClass('date-wrap');
  1519. var today = 0;//new priv.ext.XDate(false).setHours(0, 0, 0, 0).toString('yyyy-MM-dd');
  1520. var dp = $('<div style="float:right" class="date" data-date="{0}" data-date-format="{1}" />'.f(today, 'yyyy-mm-dd')).appendTo(elem);
  1521. $('<input style="display:none" type="text" />').appendTo(dp);
  1522. $('<span class="add-on"><i class="glyphicon glyphicon-chevron-right"></i></span>').on('click', {op: "l"}, priv.dpOpChanged).appendTo(dp);
  1523. $('<span class="add-on"><i class="glyphicon glyphicon-chevron-left"></i></span>').on('click', {op: "r"}, priv.dpOpChanged).appendTo(dp);
  1524. dp.datepicker({weekStart:1});
  1525. dp.on('changeDate', {column: column, input: $('input.filter', elem)}, priv.dpClicked);
  1526. }
  1527. else
  1528. if (priv.options.debug) console.log('datepicker plugin not found');
  1529. }
  1530. elem.on('keyup', 'input.filter', {column: column}, priv.filterChanged);
  1531. break;
  1532. case "bool":
  1533. if (tooltip == undefined) tooltip = priv.options.types.bool.filterTooltip;
  1534. tooltip = (tooltip === true || tooltip == undefined) ? 'Toggle between:<br/>indeterminate,<br/>checked,<br/>unchecked' : tooltip === false ? '' : tooltip;
  1535. elem = $('<input class="filter indeterminate" checked type="checkbox" />');
  1536. elem.on('click', {column: column}, priv.filterChanged);
  1537. break;
  1538. case "p5:price":
  1539. case "p5:www_link":
  1540. case "p5:string":
  1541. case "string":
  1542. if (placeHolder == undefined) placeHolder = priv.options.types.string.placeHolder;
  1543. placeHolder = (placeHolder === true || placeHolder == undefined) ? '%' : placeHolder === false ? '' : placeHolder;
  1544. if (tooltip == undefined) tooltip = priv.options.types.string.filterTooltip;
  1545. tooltip = (tooltip === true || tooltip == undefined) ? 'Find str: str<br/>Find all but str: !str<br/>Find str inside: %str%' : tooltip === false ? '' : tooltip;
  1546. elem = $('<input placeholder="{0}" class="filter" type="text" size="8" />'.f(placeHolder));
  1547. elem.on('keyup', {column: column}, priv.filterChanged);
  1548. break;
  1549. case "special":
  1550. elem = $('<div>&nbsp;</div>');
  1551. break;
  1552. case "simpleLink":
  1553. elem = $('<div>&nbsp;</div>');
  1554. break;
  1555. case "geom":
  1556. if (placeHolder == undefined) placeHolder = priv.options.types.string.placeHolder;
  1557. placeHolder = (placeHolder === true || placeHolder == undefined) ? '%' : placeHolder === false ? '' : placeHolder;
  1558. elem = $('<input placeholder="{0}" class="filter" type="text" size="8" />'.f(placeHolder));
  1559. elem.on('keyup', {column: column}, priv.filterChanged);
  1560. break;
  1561. case "none":
  1562. elem = $('<div>&nbsp;</div>');
  1563. break;
  1564. }
  1565. if (false) {// tooltip OFF - (tooltip)
  1566. elem.tooltip({
  1567. title: tooltip.trim(),
  1568. html: true,
  1569. container: 'body',
  1570. trigger: 'focus',
  1571. placement: 'top',
  1572. delay: {
  1573. show: 500,
  1574. hide: 100
  1575. }
  1576. });
  1577. }
  1578. if (elem && props.filter) {
  1579. $.map(_state.filters.filterCols, function(colProps, col) {
  1580. if (col == column) {
  1581. var columnSettings = _data.cols[col];
  1582. if (columnSettings.type == 'bool') {
  1583. if (colProps.filter) elem.prop('checked', true).removeClass('indeterminate');
  1584. else if (!colProps.filter) elem.prop('checked', false).removeClass('indeterminate');
  1585. else if (colProps.filter == '') elem.addClass('indeterminate');
  1586. }
  1587. else elem.val(colProps.filter);
  1588. }
  1589. });
  1590. if (priv.options.forceFilterInit && undefined !== priv.options.forceFilterInit[column]) {
  1591. elem.prop('disabled', true);
  1592. }
  1593. elem.appendTo(headCell);
  1594. _filterFields[column] = elem;
  1595. }
  1596. }
  1597. currentNode.replaceWith(node);
  1598. };
  1599. priv.renderTableTfoot = function() {
  1600. _uiNode$Table.find('tfoot').remove();
  1601. _foot = $('<tfoot></tfoot>').insertAfter(_bodyNode);
  1602. //$(_uiNodeCont).next('.foot').replaceWith(_foot);
  1603. };
  1604. priv.renderFooter = function() {
  1605. priv.renderFooterInfo();
  1606. priv.renderFooterPagination();
  1607. priv.renderFooterPageSizes();
  1608. priv.renderFooterColumnPicker();
  1609. priv.renderFooterFunctions();
  1610. priv.renderFooterExport();
  1611. };
  1612. priv.renderFooterInfo = function() {
  1613. var nodeClass = 'tblAjax__' + 'footer__toolbar__info',
  1614. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1615. node;
  1616. if (priv.options.debug) console.log('Render: ', nodeClass);
  1617. node = $('<div class="foot-info ' + nodeClass + '"></div>');
  1618. //console.log('renderFooterInfo total', _data.total, 'page', _state.page, 'priv.options.pageSize', priv.options.pageSize);
  1619. var fromRow = Math.max(_state.page - 1, 0) * _state.pageSize;
  1620. var total = _data.total;
  1621. var toRow = Math.min(fromRow + _state.pageSize, total);
  1622. if (_data.total > 0) {
  1623. $('<p>Wiersze od {0} do {1} z {2}</p>'.f(fromRow + 1, toRow, total)).appendTo(node);
  1624. } else {
  1625. $('<p>Brak wierszy pasujących do kryteriów wyszukiwania</p>').appendTo(node);
  1626. }
  1627. currentNode.replaceWith(node);
  1628. };
  1629. priv.renderFooterPagination = function() {
  1630. var nodeClass = 'tblAjax__' + 'footer__toolbar__pagination',
  1631. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1632. node;
  1633. var currPage = _state.page;
  1634. var totalPages = Math.ceil(_data.total / _state.pageSize);
  1635. if (priv.options.debug) console.log('Render: ', nodeClass, '_data.total', _data.total, 'currPage', currPage);
  1636. /// console.log('Render: ', nodeClass, '_data.total', _data.total, 'currPage', currPage, '_state.page', _state.page);
  1637. if (_data.total > 0) {
  1638. node = $('<div class="btn-group ' + nodeClass + '"></div>');
  1639. //create the pager.
  1640. var lowerPage = currPage - 2;
  1641. var upperPage = currPage + 2;
  1642. if (upperPage > totalPages) {
  1643. var diff = upperPage - totalPages;
  1644. upperPage = totalPages;
  1645. lowerPage -= diff;
  1646. }
  1647. if (lowerPage < 1) lowerPage = 1;
  1648. if (upperPage < 5) upperPage = 5;
  1649. //$('<li class="{0}"><a href="#">&lt;&lt;</a></li>'.f(currPage == 1 ? 'disabled' : ''))
  1650. $('<button type="button" class="btn btn-default{0}">&lt;&lt;</button>'.f(currPage == 1 ? ' disabled' : ''))
  1651. .on('click', {pageIndex: 1}, priv.pageChanged)
  1652. .appendTo(node);
  1653. //$('<li class="{0}"><a href="#">&lt;</a></li>'.f(currPage == 1 ? 'disabled' : ''))
  1654. $('<button type="button" class="btn btn-default{0}">&lt;</button>'.f(currPage == 1 ? ' disabled' : ''))
  1655. .on('click', {pageIndex: currPage - 1}, priv.pageChanged)
  1656. .appendTo(node);
  1657. for (var i = lowerPage; i <= upperPage; i++) {
  1658. var link;
  1659. //if (i != currPage) link = $('<li class="{1}"><a href="#">{0}</a></li>'.f(i, i > totalPages ? 'disabled' : ''));
  1660. if (i != currPage) link = $('<button type="button" class="btn btn-default{1}">{0}</button>'.f(i, i > totalPages ? 'disabled' : ''));
  1661. //if (i == currPage) link = $('<li class="active"><a href="#">{0}</a></li>'.f(i));
  1662. if (i == currPage) link = $('<button type="button" class="btn btn-default active">{0}</button>'.f(i));
  1663. if (link) {
  1664. link.on('click', {pageIndex: i}, priv.pageChanged);
  1665. link.appendTo(node);
  1666. }
  1667. }
  1668. //$('<li class="{0}"><a href="#">&gt;</a></li>'.f(currPage == totalPages ? 'disabled' : ''))
  1669. $('<button type="button" class="btn btn-default{0}">&gt;</button>'.f(currPage == totalPages ? ' disabled' : ''))
  1670. .on('click', {pageIndex: currPage + 1}, priv.pageChanged)
  1671. .appendTo(node);
  1672. //$('<li class="{0}"><a href="#">&gt;&gt;</a></li>'.f(currPage == totalPages ? 'disabled' : ''))
  1673. $('<button type="button" class="btn btn-default{0}">&gt;&gt;</button>'.f(currPage == totalPages ? ' disabled' : ''))
  1674. .on('click', {pageIndex: totalPages}, priv.pageChanged)
  1675. .appendTo(node);
  1676. } else {
  1677. node = $('<span class="' + nodeClass + '"></span>');
  1678. }
  1679. currentNode.replaceWith(node);
  1680. };
  1681. priv.renderFooterPageSizes = function() {
  1682. var nodeClass = 'tblAjax__' + 'footer__toolbar__pagesizes',
  1683. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1684. node;
  1685. if (priv.options.debug) console.log('Render: ', nodeClass);
  1686. if (_data.total > 0 && priv.options.pageSizes.length > 0) {
  1687. node = $('<div class="btn-group dropup pagesize ' + nodeClass + '"></div>');
  1688. var btn = $('<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Liczba wierszy&nbsp;</button>').appendTo(node);
  1689. var span = $('<span class="caret"></span>').appendTo(btn);
  1690. var ul = $('<ul class="dropdown-menu" style="max-height:250px;overflow:auto;">').appendTo(node);
  1691. $.each(priv.options.pageSizes, function(index, val) {
  1692. var li = $('<li></li>').appendTo(ul);
  1693. if (val == priv.options.pageSize) {
  1694. $('<a style="color:#337AB7;">{0}</a>'.f(val)).appendTo(li);
  1695. } else {
  1696. $('<a href="#">{0}</a>'.f(val)).appendTo(li);
  1697. }
  1698. });
  1699. node.on('click', 'a', priv.pageSizeChanged);
  1700. } else {
  1701. node = $('<span class="' + nodeClass + '"></span>');
  1702. }
  1703. currentNode.replaceWith(node);
  1704. };
  1705. priv.renderFooterColumnPicker = function() {
  1706. var nodeClass = 'tblAjax__' + 'footer__toolbar__columnPicker',
  1707. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1708. node;
  1709. if (priv.options.debug) console.log('Render: ', nodeClass);
  1710. if (priv.options.columnPicker) {
  1711. node = $('<div class="btn-group dropup columnpicker ' + nodeClass + '"></div>');
  1712. var btn = $('<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Kolumny&nbsp;</button>').appendTo(node);
  1713. var span = $('<span class="caret"></span>').appendTo(btn);
  1714. var ul = $('<ul class="dropdown-menu" style="max-height:250px;overflow:auto;">').appendTo(node);
  1715. var selectedFilter = priv.modelColFilter_getSelected();
  1716. priv.modelColFilter_getFilters().map(function(colFltr) {
  1717. var li = $('<li></li>').appendTo(ul),
  1718. selected = (selectedFilter && selectedFilter == colFltr.name)? 'checked="checked"' : '',
  1719. input = '<input ' + selected + ' type="radio" style="margin:0"/>',
  1720. a = $('<a href="#" data-col_filter="' + colFltr.name + '" style="padding:0px 20px;">' + input + ' ' + colFltr.label + '</a>').appendTo(li);
  1721. if ('all' != colFltr.name && 'most_used' != colFltr.name) {
  1722. arm = $('<button data-col_filter="' + colFltr.name + '" class="pull-right btn btn-xs btn-link" style="margin:0;padding:0;border:0;color:red">' + '&times;' + '</a>').appendTo(a);
  1723. arm.on('click', priv.modelColFilter_onClickRemoveFilter)
  1724. }
  1725. });
  1726. {// if (!selectedFilter) {// save current filter
  1727. var li = $('<li style="text-align:center; clear:both"></li>').appendTo(ul)
  1728. priv.modelColFilter_getSaveBtn().appendTo(li);
  1729. }
  1730. $('<li class="divider"></li>').appendTo(ul);
  1731. $.each(_data.cols, function(col, props) {
  1732. if (props.type != "unique" && col != 'ID') {
  1733. var li = $('<li></li>').appendTo(ul),
  1734. label = (props.friendly || col).replace(/<br\/?>/g, ' '),
  1735. input = '<input {0} type="checkbox" title="{1}" value="{1}" style="margin:0"/>&nbsp;{2}'.f((props.hidden) ? '' : 'checked', col, label),
  1736. a = $('<a href="#" style="padding:0px 20px;">' + input + '</a>').appendTo(li);
  1737. }
  1738. });
  1739. node.on('click', 'input[type="checkbox"]', priv.columnPickerClicked);
  1740. node.on('click', 'a', priv.columnPickerLinkClicked);
  1741. } else {
  1742. node = $('<span class="' + nodeClass + '"></span>');
  1743. }
  1744. currentNode.replaceWith(node);
  1745. };
  1746. priv.renderFooterFunctions = function() {
  1747. var nodeClass = 'tblAjax__' + 'footer__toolbar__functions',
  1748. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1749. node;
  1750. if (priv.options.debug) console.log('Render: ', nodeClass);
  1751. if (priv.options.tblFunctions) {
  1752. node = $('<div class="btn-group ' + nodeClass + '"></div>');
  1753. $.map(priv.options.tblFunctions, function(funObj, funName){
  1754. var funHtml = $('<button class="btn btn-sm btn-default"></button>');
  1755. if (funObj.title) funHtml.attr('title', funObj.title);
  1756. if (funObj.method) funHtml.on('click', priv[funObj.method]);
  1757. else if (funObj.href) funHtml.on('click', {hash:funObj.href}, priv.routeChanged);
  1758. var funIconHtml = $('<i></i>');
  1759. if (funObj.icon) funIconHtml.attr('class', 'glyphicon glyphicon-' + funObj.icon);
  1760. funIconHtml.prependTo(funHtml);
  1761. funHtml.addClass('btn');
  1762. funHtml.appendTo(node);
  1763. });
  1764. } else {
  1765. node = $('<span class="' + nodeClass + '"></span>');
  1766. }
  1767. currentNode.replaceWith(node);
  1768. };
  1769. priv.renderFooterExport = function() {
  1770. var nodeClass = 'tblAjax__' + 'footer__toolbar__export',
  1771. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1772. node;
  1773. if (priv.options.debug) console.log('Render: ', nodeClass);
  1774. if (priv.options.exportFields && priv.options.exportFields.length) {
  1775. node = $('<div class="btn-group dropup pagesize ' + nodeClass + '"></div>');
  1776. var btn = $('<button class="btn btn-sm dropdown-toggle" data-toggle="dropdown" href="#">Export&nbsp;</button>').appendTo(node);
  1777. var span = $('<span class="caret"></span>').appendTo(btn);
  1778. var ul = $('<ul class="dropdown-menu" style="max-height:250px;padding:5px 20px 5px 8px;overflow:auto;">').appendTo(node);
  1779. $.each(_data.cols, function(col, props) {
  1780. if (-1 !== priv.options.exportFields.indexOf(col)) {
  1781. var li = $('<li></li>').appendTo(ul);
  1782. $('<input {0} type="checkbox" title="{1}" value="{1}" >&nbsp;{2}</input>'.f((_exportFieldsSelect[col])? 'checked' : '', col, props.friendly || col)).appendTo(li);
  1783. li.on('click', 'input', priv.exportFieldChanged);
  1784. }
  1785. });
  1786. var li = $('<li></li>').appendTo(ul);
  1787. $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do HTML</a>').appendTo(li);
  1788. li.on('click', 'a', priv.exportToHTML);
  1789. var li = $('<li></li>').appendTo(ul);
  1790. $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do CSV</a>').appendTo(li);
  1791. li.on('click', 'a', priv.exportToCSV);
  1792. var li = $('<li></li>').appendTo(ul);
  1793. $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share" title="Export do pliku CSV w kodowaniu Windows-1250"></i>Export do CSV (Windows-1250)</a>').appendTo(li);
  1794. li.on('click', 'a', priv.exportToCSVWinCP1250);
  1795. } else {
  1796. node = $('<span class="' + nodeClass + '"></span>');
  1797. }
  1798. currentNode.replaceWith(node);
  1799. };
  1800. priv.renderInlineEditBox = function() {
  1801. var nodeClass = 'tblAjax__' + 'inlineEditBox',
  1802. currentNode = $(_uiNodeCont).parent().children('.' + nodeClass),
  1803. node;
  1804. var node = $('<div class="' + nodeClass + ' modal fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>');
  1805. /// console.log('L.<?php echo __LINE__; ?> Render: priv.renderInlineEditBox, currentNode.html:', currentNode.html(), currentNode);
  1806. var modalWrap = $('<div class="modal-dialog"></div>').appendTo(node);
  1807. var modalWrap = $('<div class="modal-content"></div>').appendTo(modalWrap);
  1808. var frmInlineEdit = $('<form style="margin:0;padding:0;"></form>').appendTo(modalWrap);
  1809. var iebHead = $('<div class="modal-header" style="cursor:pointer">').appendTo(frmInlineEdit);
  1810. $('<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="glyphicon glyphicon-remove" style="color:red"></i></button>').appendTo(iebHead);
  1811. $('<h4 id="myModalLabel">Edytuj</h4>').appendTo(iebHead);
  1812. var iebBodyWrap = $('<div class="modal-body" style="padding:0"></div>').appendTo(frmInlineEdit);
  1813. var iebBody = $('<div style="padding:15px"></div>').appendTo(iebBodyWrap);
  1814. $('<input type="hidden" name="ID" value="">').appendTo(iebBody);
  1815. $('<input type="hidden" name="col" value="">').appendTo(iebBody);
  1816. $('<div class="inlineEditBox-cnt"></div>').appendTo(iebBody);
  1817. var iebFoot = $('<div class="modal-footer"></div>').appendTo(frmInlineEdit);
  1818. $('<button class="btn btn-close" data-dismiss="modal" aria-hidden="true">Zamknij</button>').appendTo(iebFoot);
  1819. var iebBtnSave = $('<input type="submit" value="Zapisz" class="btn btn-primary btn-save">').appendTo(iebFoot);
  1820. frmInlineEdit.on('submit', function() {
  1821. var inlineEditBox$Node = $(_uiNodeCont).parent().children('.tblAjax__inlineEditBox');
  1822. var data = inlineEditBox$Node.find('form').serialize();
  1823. inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
  1824. function notifyAjaxCallback(data) {
  1825. var notify = {};
  1826. notify.type = (data && data.type)? data.type : '';
  1827. notify.msg = (data && data.msg)? data.msg : '';
  1828. switch (notify.type) {
  1829. case 'success':
  1830. if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
  1831. break;
  1832. case 'info':
  1833. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  1834. break;
  1835. case 'error':
  1836. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  1837. break;
  1838. case 'warning':
  1839. notify.type = 'warn';
  1840. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  1841. break;
  1842. default:
  1843. notify.msg = 'Nieznany błąd';
  1844. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  1845. notify.type = '';
  1846. }
  1847. jQuery.notify(notify.msg, notify.type);
  1848. }
  1849. $.ajax({
  1850. data: data,
  1851. dataType: 'json',
  1852. type: "POST",
  1853. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT_INLINE_SAVE'
  1854. })
  1855. .done(function(data, textStatus, jqXHR){
  1856. notifyAjaxCallback(data);
  1857. publ.refresh();
  1858. inlineEditBox$Node.modal('hide');
  1859. })
  1860. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  1861. if (jqXHR.responseJSON) {
  1862. notifyAjaxCallback(jqXHR.responseJSON);
  1863. }
  1864. else {
  1865. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  1866. if (jqXHR.status == 404) {
  1867. jQuery.notify(jqXHR.responseText, 'error');
  1868. } else {
  1869. jQuery.notify(jqXHR.responseText, 'warn');
  1870. }
  1871. }
  1872. inlineEditBox$Node.modal('hide');
  1873. });
  1874. return false;
  1875. });
  1876. currentNode.replaceWith(node);
  1877. };
  1878. priv.exportFieldChanged = function(e) {
  1879. e.stopPropagation();
  1880. var column = $(this).val();
  1881. _exportFieldsSelect[column] = !_exportFieldsSelect[column];
  1882. };
  1883. priv.exportToHTML = function(e) {
  1884. priv.exportData('html', $(this), e);
  1885. };
  1886. priv.exportToCSV = function(e) {
  1887. priv.exportData('csv', $(this), e);
  1888. };
  1889. priv.exportToCSVWinCP1250 = function(e) {
  1890. priv.exportData('csv_cp1250', $(this), e);
  1891. };
  1892. priv.exportData = function(format, node, e) {
  1893. var exportFields = [];
  1894. $.each(_exportFieldsSelect, function(col, selected) {
  1895. if (selected) {
  1896. exportFields.push(col);
  1897. }
  1898. });
  1899. if (!exportFields.length) {
  1900. alert('Nie wybrano żadnych pól do eksportu.');
  1901. e.preventDefault();
  1902. return false;
  1903. }
  1904. var limit = 10000;
  1905. if (!_data.total || _data.total <= 0) {
  1906. alert('Brak rekordów do eksportu.');
  1907. e.preventDefault();
  1908. return false;
  1909. }
  1910. if (_data.total > limit) {
  1911. if (!confirm('Za dużo rekordów. Wyeksportowane zostaną tylko pierwsze ' + limit + ' z ' + _data.total + ' rekordów.')) {
  1912. e.preventDefault();
  1913. return false;
  1914. }
  1915. }
  1916. var exportUrl = 'index.php?_route=ViewTableAjax&_task=export&namespace=<?= $acl->getNamespace(); ?>';
  1917. exportUrl += '&format=' + format;
  1918. exportUrl += '&flds=' + exportFields.join(',');
  1919. exportUrl += '&sortCol=' + (_state.filters.currSortCol || '');
  1920. exportUrl += '&sortDir=' + (_state.filters.currSortFlip ? "desc" : "asc");
  1921. if (Object.keys(_state.filters.filterCols).length > 0) {
  1922. $.each(_state.filters.filterCols, function(col, colProps) {
  1923. if (colProps.filter && colProps.filter.length > 0) {
  1924. exportUrl += '&f_' + col + '=' + colProps.filter;
  1925. }
  1926. });
  1927. }
  1928. // specialFilters
  1929. $.each(_state.specialFilters, function(groupName, btnValue) {
  1930. if (btnValue.length > 0) {
  1931. exportUrl += '&sf_' + groupName + '=' + btnValue;
  1932. }
  1933. });
  1934. if (priv.options.forceFilterInit) {
  1935. $.map(priv.options.forceFilterInit, function(fltrProps, fltr) {
  1936. exportUrl += '&sf_' + fltr + '=' + fltrProps;
  1937. });
  1938. }
  1939. node.attr('href', exportUrl);
  1940. };
  1941. /*
  1942. calls the webservice(if defined).
  1943. used only inside priv.init
  1944. */
  1945. priv.update = function(callback) {
  1946. var skipCols, resetChecked;// undefined
  1947. if (!priv.options.url) {
  1948. if (priv.options.debug) console.log('no url found L.<?php echo __LINE__; ?>');
  1949. return;
  1950. }
  1951. if (priv.options.debug) console.log('requesting data from url:{0} data:{1} L.<?php echo __LINE__; ?>'.f(priv.options.url, JSON.stringify(priv.options.urlData) || ''));
  1952. var initUrlAdd = '',
  1953. filtersInitSet = false;
  1954. initUrlAdd += '&currSortCol=' + _state.filters.currSortCol;
  1955. initUrlAdd += '&currSortFlip=' + ((_state.filters.currSortCol)? "desc" : "asc");
  1956. if (Object.keys(_state.filters.filterCols).length > 0) {
  1957. $.each(_state.filters.filterCols, function(col, colProps) {
  1958. if (colProps.filter && colProps.filter.length > 0) {
  1959. initUrlAdd += '&f_' + col + '=' + colProps.filter;
  1960. filtersInitSet = true;
  1961. }
  1962. });
  1963. }
  1964. $.each(_state.specialFilters, function(groupName, btnValue) {
  1965. if (btnValue.length > 0) {
  1966. initUrlAdd += '&sf_' + groupName + '=' + btnValue;
  1967. filtersInitSet = true;
  1968. }
  1969. });
  1970. if (priv.options.forceFilterInit) {
  1971. $.map(priv.options.forceFilterInit, function(fltrProps, fltr) {
  1972. initUrlAdd += '&f_' + fltr + '=' + fltrProps;
  1973. filtersInitSet = true;
  1974. });
  1975. }
  1976. // p5UI__notifyAjaxCallback({type: 'info', msg: 'pobieranie danych (init) ...'});
  1977. fetch(priv.options.url + initUrlAdd, {
  1978. method: priv.options.urlPost ? 'POST' : 'GET',
  1979. credentials: 'same-origin',// add cookies
  1980. }).then(function (response) {
  1981. return response.json()
  1982. }).then(function (data) {
  1983. if (priv.options.debug) console.log('loadDataAjax:fetch: request finished L.<?php echo __LINE__; ?> data:', data);
  1984. if ('success' == data.type) {
  1985. // p5UI__notifyAjaxCallback(data);
  1986. if (data && data.cols) {
  1987. priv.setStateCols(data.cols, data.uniqueCol);
  1988. }
  1989. // set initial filters (_state.filters.filterCols)
  1990. if (filtersInitSet && _data && _data.cols) {
  1991. $.map(reqData, function(fltrValue, fltr){
  1992. var colName = null;
  1993. if (fltr.substr(0, 3) == 'sf_') {
  1994. colName = fltr.substr(3);
  1995. }
  1996. else if (fltr.substr(0, 2) == 'f_') {
  1997. colName = fltr.substr(2);
  1998. }
  1999. if (colName && _data.cols[colName]) {
  2000. //add the filter to the filter array
  2001. _state.filters.filterCols[colName] = {
  2002. filter: fltrValue,
  2003. colName: colName
  2004. };
  2005. }
  2006. });
  2007. }
  2008. // assign the new state (data)
  2009. state = {data: {}};
  2010. if (!skipCols) state.data.cols = data.cols || {};
  2011. state.data.rows = data.rows || [];
  2012. state.data.total = data.total || 0;
  2013. state.page = data.page || 0;
  2014. state.pageSize = data.pageSize || priv.options.pageSize;
  2015. state.filters = data.filters || {};
  2016. priv.setState(state);
  2017. if (typeof callback == "function") {
  2018. callback.call(this);
  2019. }
  2020. } else if ('error' == data.type) {
  2021. p5UI__notifyAjaxCallback(data);
  2022. } else {
  2023. p5UI__notifyAjaxCallback(data);
  2024. }
  2025. }).catch(function (e) {
  2026. console.log('loadDataAjax:fetch: ERR:', e);
  2027. });
  2028. };
  2029. /*
  2030. assigns the new data.
  2031. */
  2032. priv.setState = function(state) {
  2033. var oldState = _state,// TODO: use to check what really changed (use extend!)
  2034. renderParts = {};
  2035. if (state.data) {
  2036. if (state.data.cols && state.data.cols.length > 0) {// TODO: never happen, but if happend then rerender all
  2037. priv.setStateCols(state.data.cols, state.data.uniqueCol);
  2038. priv.setStateData(state.data);
  2039. renderParts['head'] = true;
  2040. } else {
  2041. priv.setStateData(state.data, true);
  2042. }
  2043. renderParts['body'] = true;
  2044. renderParts['foot_pagination'] = true;
  2045. }
  2046. if (state.hasOwnProperty('specialFilters')) {
  2047. _state.specialFilters = state.specialFilters;
  2048. renderParts['head__specialFilters'] = true;
  2049. }
  2050. if (state.hasOwnProperty('page')) {
  2051. if (state.page != _state.page) {
  2052. _state.page = state.page;
  2053. renderParts['foot_pagination'] = true;
  2054. }
  2055. }
  2056. if (state.hasOwnProperty('pageSize')) {
  2057. if (state.pageSize != _state.pageSize) {
  2058. _state.pageSize = state.pageSize;
  2059. renderParts['foot_pagination'] = true;
  2060. }
  2061. }
  2062. if (state.hasOwnProperty('filters')) {
  2063. /// console.log('L.<?php echo __LINE__; ?> setState::state.filters: ', state.filters);//TODO:DBG:RMME
  2064. priv.setStateFilters(state.filters);
  2065. // TODO: if state diff's
  2066. renderParts['head__specialFilters'] = true;
  2067. renderParts['foot_pagination'] = true;
  2068. }
  2069. renderParts = Object.keys(renderParts);
  2070. if (priv.options.debug) console.log('setState::renderParts: ', renderParts);//TODO:DBG:RMME
  2071. ///console.log('L.<?php echo __LINE__; ?> setState::renderParts: ', renderParts);//TODO:DBG:RMME
  2072. if (renderParts.length > 0) {
  2073. jQuery(_uiNodeCont).trigger('TableAjax:render', renderParts);
  2074. }
  2075. };
  2076. priv.setStateCols = function(cols, uniqueCol) {
  2077. _state.cols = cols;
  2078. _state.uniqueCol = uniqueCol;
  2079. // fix col name - props.column
  2080. $.each(_state.cols, function(col, props) {
  2081. props.column = col;
  2082. });
  2083. // fix col types - default 'string'
  2084. $.each(_state.cols, function(col, props) {
  2085. if (!props.type) cols[col].type = "string";
  2086. });
  2087. // fix props.filter - set true if not set - TODO: allow filter this col?
  2088. $.each(_state.cols, function(col, props) {
  2089. if (props.filter == undefined) props.filter = true;
  2090. });
  2091. if (_state.uniqueCol) {
  2092. //create a unique column definition
  2093. _state.cols["unique"] = {
  2094. column: "unique",
  2095. type: "unique",
  2096. index: -1,
  2097. hidden: true
  2098. };
  2099. }
  2100. _state.colsSorted = Object.keys(_state.cols).sort(function(a, b) {
  2101. return _state.cols[a].index - _state.cols[b].index;
  2102. });
  2103. };
  2104. priv.setStateFilters = function(stateFilters) {
  2105. var newFilterCols = {},
  2106. newSpecialFilters = {};
  2107. $.map(stateFilters, function(fltrProps, fltr) {
  2108. switch (fltr) {
  2109. case 'currSortCol': _state.filters.currSortCol = fltrProps; break;
  2110. case 'currSortFlip': _state.filters.currSortFlip = (fltrProps == 'desc')? true : false; break;
  2111. default:
  2112. if (fltr.substr(0, 2) == 'f_') {
  2113. newFilterCols[fltr.substr(2)] = {
  2114. filter: fltrProps,
  2115. colName: fltr.substr(2)
  2116. };
  2117. }
  2118. else if (fltr.substr(0, 3) == 'sf_') {
  2119. var groupName = fltr.substr(3);
  2120. if (priv.options.specialFilterFunctions.hasOwnProperty(groupName)) {
  2121. newSpecialFilters[groupName] = fltrProps;
  2122. }
  2123. }
  2124. }
  2125. });
  2126. _state.filters.filterCols = newFilterCols;
  2127. _state.specialFilters = newSpecialFilters;
  2128. };
  2129. priv.setStateData = function(pData, skipCols, resetChecked) {
  2130. var data = $.extend(true, {}, pData);
  2131. data.cols = _state.cols;// always use old cols - change cols mved to priv.setStateCols
  2132. _data = data;
  2133. _data.rowsOrg = _data.rows;
  2134. //we might have more/less data now. Recalculate stuff.
  2135. if (_state.page > 1) {
  2136. _totalPages = Math.ceil(_data.total / priv.options.pageSize);
  2137. }
  2138. //keep any previously checked rows around?
  2139. if (resetChecked === true || resetChecked === undefined)
  2140. _uniqueCols = {};
  2141. else {
  2142. for (var key in _uniqueCols)
  2143. _uniqueCols[key] = priv.getRow(key);
  2144. }
  2145. if (_state.uniqueCol) {
  2146. //add rows that needs to be pre-checked
  2147. $.each(_data.rows, function(index, row) {
  2148. if (row["checked"] === true)
  2149. _uniqueCols[row[_state.uniqueCol]] = row;
  2150. });
  2151. }
  2152. };
  2153. /*
  2154. sorts the data on the current sorting column
  2155. */
  2156. priv.sort = function() {
  2157. if (!_data.cols[_state.filters.currSortCol]) _state.filters.currSortCol = "";
  2158. if (!_state.filters.currSortCol) return;
  2159. publ.loadPage(0);
  2160. };
  2161. /*
  2162. helper that returns the underlying data by the unique value
  2163. */
  2164. priv.getRow = function(uniqueValue) {
  2165. var row;
  2166. $.each(_data.rowsOrg, function(i, r) {
  2167. if (r[_state.uniqueCol] == uniqueValue) {
  2168. row = r;
  2169. return false;
  2170. }
  2171. });
  2172. return row;
  2173. };
  2174. /*
  2175. when: typing a filter
  2176. what: triggers filtering on the value
  2177. */
  2178. priv.filterChanged = function(e) {
  2179. //clear old timer if we're typing fast enough
  2180. if (priv.options.debug) console.log('filterChanged L.<?php echo __LINE__; ?>');
  2181. if (_filterTimeout) {
  2182. clearTimeout(_filterTimeout);
  2183. if (priv.options.debug) console.log('filterChanged L.<?php echo __LINE__; ?> previous filtering cancelled');
  2184. }
  2185. var filter = this.value
  2186. , fltr = $(this)
  2187. , col = _data.cols[e.data.column]
  2188. , timeout = 300;
  2189. if (this.value) {
  2190. if (!fltr.hasClass('filter-active')) {
  2191. fltr.addClass('filter-active');
  2192. }
  2193. } else {
  2194. if (fltr.hasClass('filter-active')) {
  2195. fltr.removeClass('filter-active');
  2196. }
  2197. }
  2198. //boolean filters needs some special care
  2199. if (col.type == "bool" || col.type == "unique") {
  2200. timeout = 0;
  2201. var elem = $(this);
  2202. var cssClass = 'indeterminate';
  2203. if (elem.hasClass(cssClass)) {
  2204. e.preventDefault();
  2205. elem.removeClass(cssClass);
  2206. filter = true;
  2207. } else {
  2208. if (!elem.is(':checked')) {
  2209. filter = false;
  2210. } else {
  2211. elem.addClass(cssClass);
  2212. filter = '';
  2213. }
  2214. }
  2215. }
  2216. //add the filter to the filter array
  2217. _state.filters.filterCols[col.column] = {
  2218. filter: filter,
  2219. colName: col.column
  2220. };
  2221. //wait a few deciseconds before filtering
  2222. _filterTimeout = setTimeout(function(filterValue, colName) {
  2223. _state.filters.filterCols[colName] = {
  2224. filter: filterValue,
  2225. colName: colName
  2226. };
  2227. priv.filter();
  2228. }, timeout, filter, col.column);
  2229. };
  2230. priv.filtersClean = function(e) {
  2231. if (_filterTimeout) {
  2232. clearTimeout(_filterTimeout);
  2233. if (priv.options.debug) console.log('filtering cancelled - filtersClean');
  2234. }
  2235. var filtersActive = false;
  2236. $.map(_state.filters.filterCols, function(colProps, col) {
  2237. if (colProps.filter.length > 0) {
  2238. filtersActive = true;
  2239. colProps.filter = '';
  2240. }
  2241. });
  2242. if (filtersActive) {
  2243. // TODO: dont remove value from forceFilterInit fields - no field names in search fields?
  2244. /// TODO: rerender _head (thead.filter)
  2245. var elems = _uiNode$Table.find('thead').find('.filter').find('input');
  2246. elems.val('').prop('disabled', false);
  2247. elems.removeClass('filter-active');
  2248. priv.filter();
  2249. }
  2250. return false;
  2251. },
  2252. /**
  2253. * Filters the data.
  2254. */
  2255. priv.filter = function() {
  2256. if (!priv.options.filter) return;
  2257. if (Object.keys(_state.filters.filterCols).length == 0) return;
  2258. priv.loadPage(0);
  2259. };
  2260. /**
  2261. * Filters the data by specialFilter.
  2262. * when: click on special filter
  2263. * what: triggers filtering on the value
  2264. */
  2265. priv.specialFilterChanged = function(e) {
  2266. if (priv.options.debug) console.log('specialFilterChanged e.data:', e.data);
  2267. var state = {};
  2268. state.specialFilters = _state.specialFilters;
  2269. state.specialFilters[e.data.group] = e.data.value;
  2270. priv.setState(state);
  2271. publ.loadPage(0);
  2272. };
  2273. priv.longTextChanged = function(e) {
  2274. priv.options.longDesc = !priv.options.longDesc;
  2275. _bodyNode.find('td').each(function(ind, el){
  2276. var $el = jQuery(el);
  2277. if (!$el.attr('class') || $el.attr('class') == 'tbl-short-txt') {
  2278. //console.log(el.attr('class') + ': ' + el.text());
  2279. if (el.firstChild && el.firstChild.nodeName == 'SPAN') {
  2280. if (priv.options.longDesc) {
  2281. $el.addClass('tbl-short-txt');
  2282. var $elSpan = jQuery(el.firstChild);
  2283. $elSpan.tooltip({title: $elSpan.text(), placement: 'left'});
  2284. } else {
  2285. $el.removeClass('tbl-short-txt');
  2286. }
  2287. }
  2288. }
  2289. });
  2290. return false;
  2291. };
  2292. priv.mapEditorHide = function() {
  2293. priv.options.mapEditor = false;
  2294. if ('window' == priv.options.mapEditorContainer) {
  2295. //_mapEditorDialog.dialog("close");
  2296. _mapEditorDialog.dialog("destroy");
  2297. }
  2298. _mapEditorWrap.hide();
  2299. _mapEditor.hide();
  2300. };
  2301. priv.mapEditorShow = function() {
  2302. //console.log('TODO:mapEditorShow():', priv.options.mapEditorContainer, 'visible:', priv.options.mapEditor);
  2303. priv.options.mapEditor = true;
  2304. _mapEditor.show();
  2305. _mapEditorWrap.show();
  2306. _mapEditor.TableAjaxMap({
  2307. //debug: true,
  2308. wpsUrl: 'http://biuro.biall-net.pl/wps',
  2309. wfsUrl: 'http://biuro.biall-net.pl/wps',
  2310. showAddLayerWidget: <?php echo ($this->hasAdditionalLayers())? 'true' : 'false'; ?>,
  2311. zoomStrategyActivate: 14,
  2312. layerName: '<?php echo $this->getLabelHtml(); ?>',
  2313. addBtn: {
  2314. title: 'Przenieś mapę do okna',
  2315. displayClass: 'mapEditor-btnBackToWindow',
  2316. trigger: function() {
  2317. priv.mapEditorHide();
  2318. priv.options.mapEditorContainer = 'window';
  2319. priv.mapEditorShow();
  2320. priv.resizableMapDockNode('destroy');
  2321. }
  2322. },
  2323. onSaveFeature: function(selectedRecordId, selectedFeatureExtent) {
  2324. if (priv.options.debug) console.log('onSaveFeature (',selectedRecordId,'/',selectedFeatureExtent,') ', this);
  2325. if (!selectedRecordId) {
  2326. alert('Brak zaznaczonego rekordu - wybierz rekord z tabeli');
  2327. return;
  2328. }
  2329. function notifyAjaxCallback(data) {
  2330. var notify = {};
  2331. notify.type = (data && data.type)? data.type : '';
  2332. notify.msg = (data && data.msg)? data.msg : '';
  2333. switch (notify.type) {
  2334. case 'success':
  2335. if (!notify.msg) notify.msg = 'Aktualizacja danych dla rekordu ' + selectedRecordId;
  2336. break;
  2337. case 'info':
  2338. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  2339. break;
  2340. case 'error':
  2341. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  2342. break;
  2343. case 'warning':
  2344. notify.type = 'warn';
  2345. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  2346. break;
  2347. default:
  2348. notify.msg = 'Nieznany błąd';
  2349. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  2350. notify.type = '';
  2351. }
  2352. jQuery.notify(notify.msg, notify.type);
  2353. }
  2354. $.ajax({
  2355. data: {polygon: selectedFeatureExtent},
  2356. dataType: 'json',
  2357. type: "POST",
  2358. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=THE_GEOM_SAVE&ID=' + selectedRecordId
  2359. })
  2360. .done(function(data, textStatus, jqXHR){
  2361. notifyAjaxCallback(data);
  2362. //jQuery.notify('Aktualizacja danych dla rekordu ' + selectedRecordId, 'success');
  2363. publ.loadPage(0);// TODO: reload table data
  2364. })
  2365. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  2366. if (jqXHR.responseJSON) {
  2367. notifyAjaxCallback(jqXHR.responseJSON);
  2368. }
  2369. else {
  2370. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  2371. if (jqXHR.status == 404) {
  2372. jQuery.notify(jqXHR.responseText, 'error');
  2373. } else {
  2374. jQuery.notify(jqXHR.responseText, 'warn');
  2375. }
  2376. }
  2377. });
  2378. },
  2379. onSelectBox: function(bounds) {
  2380. if (undefined !== OpenLayers.Bounds && bounds instanceof OpenLayers.Bounds) {
  2381. var column = 'the_geom';
  2382. if (undefined !== _filterFields['the_geom']) {
  2383. var filter = 'BBOX:' + bounds.top + ',' + bounds.right + ',' + bounds.bottom + ',' + bounds.left;
  2384. _filterFields[column].val(filter);
  2385. _state.filters.filterCols[column] = {
  2386. filter: filter,
  2387. colName: column
  2388. };
  2389. priv.filter();
  2390. }
  2391. }
  2392. }
  2393. });
  2394. priv.mapEditorShowElement();
  2395. };
  2396. priv.mapEditorShowElement = function() {
  2397. if ('window' == priv.options.mapEditorContainer) {
  2398. var mapEditor = _mapEditorWrap.children('.mapEditor-map');
  2399. if (!mapEditor || !mapEditor.length) {
  2400. var tblCont = jQuery(_uiNodeCont).parent('.AjaxTableCont');
  2401. var mapEditor = tblCont.children('.AjaxTableCont-mapEditorContainer').children('.mapEditor-map');
  2402. if (!mapEditor || !mapEditor.length) {
  2403. // TODO: create new map
  2404. }
  2405. _mapEditorWrap.append(mapEditor);
  2406. }
  2407. _mapEditorWrap.css({padding:'5px'});
  2408. _mapEditorDialog = _mapEditorWrap.dialog({
  2409. width: 540,
  2410. minWidth: 400,
  2411. minHeight: 400,
  2412. open: function(e, ui) {
  2413. var n = jQuery(this),
  2414. mapWrap = n.children(":first"),
  2415. map = mapWrap.children(":first");
  2416. map.css({width: n.width() - 5, height: n.height() - 5});
  2417. _mapEditor.TableAjaxMapUpdateSize();
  2418. },
  2419. resizeStart: function(e, ui) {
  2420. jQuery(this).children(":first").children(":first").css({display:'none'});
  2421. },
  2422. resizeStop: function(e, ui){
  2423. var n = jQuery(this),
  2424. map = n.children(":first").children(":first");
  2425. n.css({width: n.parent().width()});
  2426. map.css({display: 'block', height: n.height(), width: n.width()});
  2427. _mapEditor.TableAjaxMapUpdateSize();
  2428. },
  2429. dragStop: function(e, ui){
  2430. _mapEditor.TableAjaxMapUpdateSize();// to prevent drag-zoom error
  2431. }
  2432. });
  2433. _mapEditorWrap.bind('dialogclose', function(e) {
  2434. priv.options.mapEditor = false;
  2435. });
  2436. var dialogTitleBar = _mapEditorDialog.parent().parent().find('.ui-dialog-titlebar');
  2437. var dialogTitleBarCloseBtn = dialogTitleBar.find('.ui-dialog-titlebar-close');
  2438. if (dialogTitleBarCloseBtn) {
  2439. var btnToggle = jQuery('<span style="width:18px;height:18px;position:absolute;top:50%;right:25px;margin-top:-9px;" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only"><i style="margin-top:3px;" class="glyphicon glyphicon-fullscreen"></i></span>');
  2440. btnToggle.on('click', function(e) {
  2441. priv.options.mapEditorContainer = 'dock';
  2442. _mapEditorWrap.dialog('close');
  2443. priv.mapEditorShowElement();
  2444. });
  2445. btnToggle.insertBefore(dialogTitleBarCloseBtn);
  2446. }
  2447. }
  2448. else if ('dock' == priv.options.mapEditorContainer) {
  2449. priv.resizableMapDockNode('prepare');
  2450. _mapEditor.TableAjaxMapUpdateSize();
  2451. }
  2452. };
  2453. priv.resizableMapDockNode = function(task) {
  2454. if ('prepare' == task) {
  2455. var mapEditor = _mapEditorWrap.children('.mapEditor-map');
  2456. if (mapEditor && mapEditor.length) {// map is inside _mapEditorWrap (window)
  2457. var mapDockNode = jQuery('<div class="AjaxTableCont-mapEditorContainer"></div>');
  2458. var tblCont = jQuery(_uiNodeCont).parent('.AjaxTableCont');
  2459. tblCont.children('.AjaxTableCont-mapEditorContainer').remove();
  2460. var breadcrumb = tblCont.children('.breadcrumb');
  2461. if (!breadcrumb || !breadcrumb.length) {
  2462. tblCont.prepend(mapDockNode);
  2463. } else {
  2464. mapDockNode.insertAfter(breadcrumb);
  2465. }
  2466. mapDockNode.append(mapEditor);
  2467. }
  2468. var mapDockResizable = mapEditor.parent();
  2469. mapDockResizable.resizable({handles: 's', minHeight: 300, minWidth: 300});
  2470. var resizeLineHeigth = 6;
  2471. mapDockResizable.children(":first").css({height: 'auto'});
  2472. mapDockResizable.css({marginBottom: resizeLineHeigth+'px'});
  2473. mapEditor.css({marginBottom: resizeLineHeigth+'px'});
  2474. mapEditor.children(":first").css({width: mapEditor.width()});
  2475. mapDockResizable.find('.ui-resizable-s').css({height:resizeLineHeigth+'px', bottom: '-'+resizeLineHeigth+'px'});
  2476. mapDockResizable.on('resizestart', function(event, ui) {
  2477. ui.element.children(":first").children(":first").css({display:'none'})
  2478. });
  2479. mapDockResizable.on('resizestop', function(event, ui) {
  2480. ui.element.children(":first").children(":first").css({display:'block', height: ui.element.height()});
  2481. });
  2482. } else if ('destroy' == task) {
  2483. var mapDockResizable = jQuery(_uiNodeCont).parent('.AjaxTableCont').children('.AjaxTableCont-mapEditorContainer');
  2484. mapDockResizable.resizable('destroy');
  2485. mapDockResizable.remove();
  2486. }
  2487. };
  2488. priv.mapEditorChanged = function(e) {
  2489. if (priv.options.debug) console.log('mapEditorChanged option(',priv.options.mapEditor,')');
  2490. priv.options.mapEditor = !priv.options.mapEditor;
  2491. if (priv.options.mapEditor) {
  2492. priv.mapEditorShow();
  2493. }
  2494. else {
  2495. priv.mapEditorHide();
  2496. }
  2497. return false;
  2498. };
  2499. /*
  2500. when: changing page in pager
  2501. what: triggers table to be created with new page
  2502. */
  2503. priv.pageChanged = function(e) {
  2504. e.preventDefault();
  2505. var totalPages = Math.ceil(_data.total / _state.pageSize);
  2506. if (e.data.pageIndex < 1 || e.data.pageIndex > totalPages) return;
  2507. //set the new page
  2508. _state.page = e.data.pageIndex;
  2509. publ.loadPage(_state.page);
  2510. };
  2511. /*
  2512. when: changing pagesize in pagesize dropdown
  2513. what: triggers table to be created with new pagesize
  2514. */
  2515. priv.pageSizeChanged = function(e) {
  2516. e.preventDefault();
  2517. var val = $(this).text();
  2518. if (priv.options.debug) console.log('pagesize changed to:{0}'.f(val));
  2519. if (parseInt(val) == priv.options.pageSize) {
  2520. return false;
  2521. }
  2522. priv.options.pageSize = parseInt(val);
  2523. publ.loadPage(1, priv.options.pageSize);
  2524. jQuery(_uiNodeCont).trigger('TableAjax:render', ['body', 'foot_pagination']);
  2525. priv.saveProfilePageSize(priv.options.pageSize);
  2526. };
  2527. /*
  2528. when: clicking a column
  2529. what: triggers table to be sorted by the column
  2530. */
  2531. priv.columnClicked = function(e) {
  2532. e.preventDefault();
  2533. if (priv.options.debug) console.log('col:{0} clicked'.f(e.data.column));
  2534. //set the new sorting column
  2535. if (_state.filters.currSortCol == e.data.column) _state.filters.currSortFlip = !_state.filters.currSortFlip;
  2536. _state.filters.currSortCol = e.data.column;
  2537. /// TODO: var state = {}; state.currSortCol = ''; state.currSortFlip = ''; priv.setState(state);
  2538. _headSort = undefined;
  2539. _body = undefined;
  2540. priv.sort();
  2541. };
  2542. priv.saveProfilePageSize = function(pageSize) {
  2543. var reqData = {};
  2544. reqData.pageSize = pageSize;
  2545. $.ajax({
  2546. data: reqData,
  2547. type: "POST",
  2548. dataType: 'json',
  2549. // async: true,
  2550. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=PAGE_SIZE_SAVE'
  2551. })
  2552. .done(function(data, textStatus, jqXHR){
  2553. if (data && data.type && data.type == 'info') {
  2554. jQuery.notify('Nie wprowadzono żadnych zmian', 'info');
  2555. } else {
  2556. jQuery.notify('Zapisano ustawienia', 'success');
  2557. }
  2558. })
  2559. .fail(function(){
  2560. jQuery.notify('Wystąpił błąd podczas zapisywania ustawień', 'error');
  2561. });
  2562. };
  2563. priv.saveHiddenCols = function() {
  2564. var reqData = {};
  2565. $.each(_data.cols, function(col, props) {
  2566. if (props.type != "unique" && col != 'unique' && col != 'ID') {
  2567. reqData[col] = (props.hidden)? 'HIDE' : 'SHOW';
  2568. }
  2569. });
  2570. $.ajax({
  2571. data: reqData,
  2572. type: "POST",
  2573. dataType: 'json',
  2574. // async: true,
  2575. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=HIDDEN_COLS_SAVE'
  2576. })
  2577. .done(function(data, textStatus, jqXHR){
  2578. if (data && data.type && data.type == 'info') {
  2579. jQuery.notify('Nie wprowadzono żadnych zmian', 'info');
  2580. } else {
  2581. jQuery.notify('Zapisano ustawienia', 'success');
  2582. }
  2583. })
  2584. .fail(function(){
  2585. jQuery.notify('Wystąpił błąd podczas zapisywania ustawień', 'error');
  2586. });
  2587. };
  2588. /*
  2589. when: clicking a column in columnpicker
  2590. what: triggers table to show/hide the column
  2591. */
  2592. priv.columnPickerClicked = function(e) {
  2593. e.stopPropagation();
  2594. var column = $(this).val();
  2595. //toggle column visibility
  2596. priv.modelColFilter_toggleColumn(column);
  2597. priv.saveHiddenCols();
  2598. //_data.cols[column].index = new priv.ext.XDate();
  2599. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body']);
  2600. };
  2601. priv.modelColFilter_init = function() {// run only once, set _state._modelColFilter {selected, filters: [ {name, label, visibleCols} ]}
  2602. var isAllSelected = true;
  2603. if (undefined === _state._modelColFilter) {
  2604. var columnFilters = [];
  2605. {
  2606. var fltrAll = {'name': 'all', 'label': 'Wszystkie', visibleCols: []};
  2607. $.each(_data.cols, function(col, props) {
  2608. if ("unique" == props.type) return;
  2609. fltrAll.visibleCols.push(col);
  2610. if (_data.cols[col].hidden) isAllSelected = false;
  2611. });
  2612. columnFilters.push(fltrAll);
  2613. }
  2614. // {
  2615. // var fltrMostUsed = {'name': 'most_used', 'label': 'Najczęściej używane', visibleCols: []};
  2616. // var fltrMostUsedLimit = 10;
  2617. // $.each(_data.cols, function(col, props) {
  2618. // if ("unique" == props.type) return;
  2619. // if (fltrMostUsedLimit-- > 0) {
  2620. // fltrMostUsed.visibleCols.push(col);
  2621. // }
  2622. // });
  2623. // columnFilters.push(fltrMostUsed);
  2624. // }
  2625. _state._modelColFilter = {
  2626. selected: (isAllSelected)? 'all' : null,
  2627. filters: columnFilters,
  2628. saveBtn: $('<button class="btn btn-xs btn-primary" disabled="disabled">Zapisz widoczne kolumny</button>')
  2629. };
  2630. _state._modelColFilter.saveBtn.on('click', priv.modelColFilter_saveBtnClicked)
  2631. if (priv.options.userTableFilterUrl) {
  2632. fetch(priv.options.userTableFilterUrl, {
  2633. method: 'POST',
  2634. headers: {
  2635. 'Content-Type': 'application/json'
  2636. },
  2637. credentials: 'same-origin',// add cookies
  2638. body: JSON.stringify({
  2639. namespace: '<?= $acl->getNamespace(); ?>',
  2640. })
  2641. }).then(function (response) {
  2642. return response.json()
  2643. }).then(function (result) {
  2644. if ('success' == result.type) {
  2645. // p5UI__notifyAjaxCallback(result)
  2646. _state._modelColFilter.filters = _state._modelColFilter.filters.filter(function (filter) {
  2647. return ('all' === filter.name || 'most_used' == filter.name)
  2648. }).concat(Object.keys(result.data).map(function (fltr) {
  2649. return {
  2650. name: fltr,
  2651. label: fltr,
  2652. visibleCols: result.data[fltr].split(',')
  2653. }
  2654. }))
  2655. jQuery(_uiNodeCont).trigger('TableAjax:render', ['foot__columnPicker']);
  2656. } else {
  2657. p5UI__notifyAjaxCallback(result)
  2658. }
  2659. }).catch(function (e) {
  2660. // TODO: show error ("ajax response error: " + e)
  2661. });
  2662. }
  2663. }
  2664. };
  2665. priv.modelColFilter_onClickRemoveFilter = function (e) {
  2666. e.preventDefault()
  2667. e.stopPropagation()
  2668. var filtrName = $(this).data('col_filter')
  2669. if (!filtrName) return
  2670. fetch('<?= Request::getPathUri() . "index.php?_route=ViewTableAjax&_task=rmUserTableFilterAjax" ?>', {
  2671. method: 'POST',
  2672. headers: {
  2673. 'Content-Type': 'application/json'
  2674. },
  2675. credentials: 'same-origin',// add cookies
  2676. body: JSON.stringify({
  2677. namespace: '<?= $acl->getNamespace(); ?>',
  2678. filtrName: filtrName,
  2679. })
  2680. }).then(function (response) {
  2681. return response.json()
  2682. }).then(function (result) {
  2683. if ('success' == result.type) {
  2684. p5UI__notifyAjaxCallback(result)
  2685. var userTableFilters = result.data;// resolve(result.data)
  2686. _state._modelColFilter.filters = _state._modelColFilter.filters.filter(function (filter) {
  2687. return ('all' === filter.name || 'most_used' == filter.name)
  2688. }).concat(Object.keys(userTableFilters).map(function (fltr) {
  2689. return {
  2690. name: fltr,
  2691. label: fltr,
  2692. visibleCols: userTableFilters[fltr].split(',')
  2693. }
  2694. }))
  2695. jQuery(_uiNodeCont).trigger('TableAjax:render', ['foot__columnPicker']);
  2696. } else {
  2697. p5UI__notifyAjaxCallback(result)
  2698. }
  2699. }).catch(function (e) {
  2700. p5UI__notifyAjaxCallback({ type: 'error', msg: new String(e) })
  2701. });
  2702. };
  2703. priv.modelColFilter_saveBtnClicked = function (e) {
  2704. swal({
  2705. title: 'Zapisz widoczne kolumny',
  2706. html: '',
  2707. animation: true,
  2708. input: 'text',
  2709. inputPlaceholder: 'nazwa filtra',
  2710. // inputValue: null,
  2711. // inputAttributes: {'step': '0.01'},
  2712. showCancelButton: true,
  2713. confirmButtonText: 'Zapisz',
  2714. showLoaderOnConfirm: true,
  2715. showCloseButton: true,
  2716. preConfirm: function(filtrName) {
  2717. return new Promise(function(resolve, reject) {
  2718. if (!filtrName) reject('Proszę podać nazwę filtra')
  2719. if (filtrName.length > 255) reject('Nazwa za długa')
  2720. fetch('<?= Request::getPathUri() . "index.php?_route=ViewTableAjax&_task=addUserTableFilterAjax" ?>', {
  2721. method: 'POST',
  2722. headers: {
  2723. 'Content-Type': 'application/json'
  2724. },
  2725. credentials: 'same-origin',// add cookies
  2726. body: JSON.stringify({
  2727. namespace: '<?= $acl->getNamespace(); ?>',
  2728. filtrName: filtrName,
  2729. visibleCols: Object.keys(_data.cols).filter(function(col) {
  2730. return !_data.cols[col].hidden
  2731. }).join(','),
  2732. })
  2733. }).then(function (response) {
  2734. return response.json()
  2735. }).then(function (result) {
  2736. if ('success' == result.type) {
  2737. p5UI__notifyAjaxCallback(result)
  2738. resolve(result.data)
  2739. } else {
  2740. p5UI__notifyAjaxCallback(result)
  2741. reject(result.msg || "Wystąpił błąd!")
  2742. }
  2743. }).catch(function (e) {
  2744. reject("ajax response error: " + e)
  2745. });
  2746. })
  2747. },
  2748. allowOutsideClick: false
  2749. }).then(function(userTableFilters) {
  2750. _state._modelColFilter.filters = _state._modelColFilter.filters.filter(function (filter) {
  2751. return ('all' === filter.name || 'most_used' == filter.name)
  2752. }).concat(Object.keys(userTableFilters).map(function (fltr) {
  2753. return {
  2754. name: fltr,
  2755. label: fltr,
  2756. visibleCols: userTableFilters[fltr].split(',')
  2757. }
  2758. }))
  2759. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body', 'foot__columnPicker']);
  2760. }).catch(function(e) {
  2761. // eg. hit Cancel
  2762. })
  2763. }
  2764. priv.modelColFilter_getSaveBtn = function () {
  2765. priv.modelColFilter_init();
  2766. return _state._modelColFilter.saveBtn
  2767. }
  2768. priv.modelColFilter_getFilters = function() {
  2769. priv.modelColFilter_init();
  2770. return _state._modelColFilter.filters;
  2771. };
  2772. priv.modelColFilter_getSelected = function() {
  2773. priv.modelColFilter_init();
  2774. return _state._modelColFilter.selected;
  2775. };
  2776. priv.modelColFilter_setFilter = function(filterKey) {
  2777. priv.modelColFilter_init();
  2778. _state._modelColFilter.selected = filterKey;
  2779. priv.modelColFilter_uiUncheckAllColFilters();
  2780. priv.modelColFilter_uiCheckColFilter(filterKey);
  2781. };
  2782. priv.modelColFilter_toggleColumn = function(column, value) {
  2783. priv.modelColFilter_init();
  2784. _state._modelColFilter.selected = null;
  2785. if (!_data.cols[column] || !_data.cols[column]) return;
  2786. _data.cols[column].hidden = (undefined !== value)? value : !_data.cols[column].hidden;
  2787. priv.modelColFilter_uiUncheckAllColFilters();
  2788. {
  2789. var isAllSelected = true;
  2790. $.each(_data.cols, function(col, props) {
  2791. if ("unique" == props.type) return;
  2792. if (_data.cols[col].hidden) isAllSelected = false;
  2793. });
  2794. if (isAllSelected) {
  2795. _state._modelColFilter.selected = 'all';
  2796. priv.modelColFilter_uiCheckColFilter('all');
  2797. }
  2798. }
  2799. };
  2800. priv.modelColFilter_uiUncheckAllColFilters = function() {
  2801. var nodeClass = 'tblAjax__' + 'footer__toolbar__columnPicker',
  2802. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass)
  2803. ;
  2804. currentNode.find('input[type="radio"]').prop("checked", false);
  2805. };
  2806. priv.modelColFilter_uiCheckColFilter = function(filterKey) {
  2807. var nodeClass = 'tblAjax__' + 'footer__toolbar__columnPicker',
  2808. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass)
  2809. ;
  2810. currentNode.find('input[type="radio"]').each(function(idx, input) {
  2811. var input$ = jQuery(input);
  2812. if (filterKey == jQuery(input$).parent().data('col_filter')) {
  2813. input$.prop("checked", true);
  2814. } else {
  2815. input$.prop("checked", false);
  2816. }
  2817. });
  2818. };
  2819. priv.columnPickerLinkClicked = function(e) {
  2820. e.stopPropagation();
  2821. var input$ = $(this).find('input'),
  2822. col_filter = $(this).data('col_filter'),
  2823. columnFilters = priv.modelColFilter_getFilters()
  2824. ;
  2825. if (col_filter) {
  2826. var filter = null;
  2827. $.each(columnFilters, function(idx, colFltr) {
  2828. if (col_filter == colFltr.name) {
  2829. filter = colFltr;
  2830. }
  2831. });
  2832. if (!filter) return;
  2833. $.each(_data.cols, function(col, props) {
  2834. var isHidden = (-1 === filter.visibleCols.indexOf(col));
  2835. priv.modelColFilter_toggleColumn(col, isHidden);
  2836. });
  2837. priv.modelColFilter_setFilter(col_filter);
  2838. priv.saveHiddenCols();
  2839. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body', 'foot__columnPicker']);
  2840. } else {
  2841. e.preventDefault();
  2842. if (input$.length != 1) return;
  2843. var column = input$.val();
  2844. if (!column) return;
  2845. //toggle column visibility
  2846. priv.modelColFilter_toggleColumn(column);
  2847. input$.prop("checked", !input$.is(':checked'));// update view
  2848. priv.saveHiddenCols();
  2849. //_data.cols[column].index = new priv.ext.XDate();
  2850. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body']);
  2851. }
  2852. };
  2853. priv.columnHideClicked = function(e) {
  2854. e.stopPropagation();
  2855. var column;
  2856. if (e.data && e.data.column) {
  2857. column = e.data.column;
  2858. } else {
  2859. return;
  2860. }
  2861. //toggle column visibility
  2862. priv.modelColFilter_toggleColumn(column);
  2863. priv.saveHiddenCols();
  2864. //_data.cols[column].index = new priv.ext.XDate();
  2865. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body', 'foot__columnPicker']);
  2866. };
  2867. /*
  2868. when: clicking a row checkbox
  2869. what: toggles checked state on row, and add/removes it from checked array
  2870. */
  2871. priv.rowChecked = function(e) {
  2872. var elem = $(this);
  2873. //get the row's unique value
  2874. var unique = elem.closest('tr').data('unique');
  2875. if (priv.options.debug) console.log('row({0}) {1}'.f(unique, elem.is(':checked') ? 'checked' : 'unchecked'));
  2876. //store the row in checked array
  2877. if (elem.is(':checked')) _uniqueCols[unique] = priv.getRow(unique);
  2878. else delete _uniqueCols[unique];
  2879. };
  2880. /*
  2881. when: clicking anywhere on a row
  2882. what: row data and other info is returned to caller
  2883. */
  2884. // priv.rowClicked = function(e) {// TODO: not used
  2885. // if (!_state.uniqueCol) {
  2886. // if (priv.options.debug) console.log('no unique column specified');
  2887. // return;
  2888. // }
  2889. // //gather callback data
  2890. // var elem = $(this);
  2891. // var column = _data.cols[elem.data('column')];
  2892. // var unique = elem.closest('tr').data('unique');
  2893. // var row = priv.getRow(unique);
  2894. // var isChecked = elem.closest('tr').find('.unique').is(':checked');
  2895. // //trigger callback
  2896. // if (typeof priv.options.rowClicked == 'function') {
  2897. // priv.options.rowClicked.call(e.target, {
  2898. // event: e,
  2899. // row: row,
  2900. // column: column,
  2901. // checked: isChecked
  2902. // });
  2903. // }
  2904. // };
  2905. /**
  2906. * Inline edit.
  2907. */
  2908. priv.rowDblClicked = function(e) {
  2909. var inlineEditBox$Node = $(_uiNodeCont).parent().children('.tblAjax__inlineEditBox');
  2910. // hide popover for typespecial fld on click
  2911. if (_popoverCellCurrent) {
  2912. _popoverCellCurrent.popover('hide');
  2913. }
  2914. // e.clientX: 1002; e.clientY: 245
  2915. if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
  2916. inlineEditBox$Node.modal();
  2917. inlineEditBox$Node.show();
  2918. inlineEditBox$Node.on('shown.bs.modal', function(e) {
  2919. var dialogBox = jQuery(this).find('.modal-dialog'),
  2920. modalBody = dialogBox.find('.modal-body'),
  2921. boudingRect = dialogBox.get(0).getBoundingClientRect();
  2922. dialogBox.css({position: 'absolute', margin:0, top: boudingRect.top, left: boudingRect.left});
  2923. modalBody.css({overflow: 'scroll'});
  2924. dialogBox.resizable({minHeight: 300, minWidth: 300, alsoResize: modalBody});
  2925. dialogBox.draggable({handle: '.modal-header'});
  2926. });
  2927. inlineEditBox$Node.on('hidden.bs.modal', function(e) {
  2928. var dialogBox = jQuery(this).find('.modal-dialog'),
  2929. modalBody = dialogBox.find('.modal-body');
  2930. dialogBox.removeAttr('style');
  2931. modalBody.removeAttr('style');
  2932. modalBody.css({padding: '0'});
  2933. dialogBox.resizable();
  2934. dialogBox.draggable();
  2935. dialogBox.resizable('destroy');
  2936. dialogBox.draggable('destroy');
  2937. });
  2938. inlineEditBox$Node.find('input[name=ID]').val(e.data.id);
  2939. inlineEditBox$Node.find('input[name=col]').val(e.data.col);
  2940. inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
  2941. $.ajax({
  2942. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT_INLINE&ID=' + e.data.id + '&col=' + e.data.col,
  2943. type: 'GET',
  2944. dataType: 'json',
  2945. success: function(data) {
  2946. if ('p5:www_link' == _.get(data, 'simpleType')) {
  2947. inlineEditBox$Node.find('.inlineEditBox-cnt').empty();
  2948. var label = jQuery('<label>');// for="' + data.htmlFieldName + '">');// "<label for="f22579" class="AjaxTableEdit-label"> ... </label>
  2949. label.attr('for', data.htmlFieldName);
  2950. label.attr('class', 'AjaxTableEdit-label');
  2951. inlineEditBox$Node.find('.inlineEditBox-cnt').append(label);
  2952. var inLabel = jQuery('<strong title="[' + data.idZasob + '] ' + data.fieldLabel + '">' + data.fieldLabel + '</strong>');
  2953. label.append(inLabel);
  2954. var frmItem = jQuery('<input>');
  2955. frmItem.attr('type', 'text');
  2956. frmItem.attr('name', data.htmlFieldName);
  2957. frmItem.attr('value', data.formItem.value);
  2958. frmItem.attr('maxlength', _.get(data, 'restrictions.maxLength', 255));
  2959. frmItem.attr('style', 'width:98%');
  2960. frmItem.attr('class', 'form-control');
  2961. frmItem.insertAfter(label);
  2962. } else {
  2963. var content = _.get(data, 'legacy_html', "Nieznany błąd");
  2964. inlineEditBox$Node.find('.inlineEditBox-cnt').html(content);
  2965. }
  2966. inlineEditBox$Node.find('.btn-save').show();
  2967. initDateTimePicker(inlineEditBox$Node);
  2968. inlineEditBox$Node.find('textarea').autosize();
  2969. var fld = inlineEditBox$Node.find('input[name^="f"]');
  2970. if (fld.length > 0 && !fld.hasClass('se_type-date')) {
  2971. fld.keydown(function(event) {
  2972. if (event.which == 13) {
  2973. event.preventDefault();
  2974. inlineEditBox$Node.find('form').submit();
  2975. }
  2976. });
  2977. }
  2978. (function setFocusAtFirstInlineEditFormFld(modal$node){
  2979. var fld, dbg = false;
  2980. if(dbg)console.log('focus...');
  2981. fld = modal$node.find('input[name^="f"]:first');
  2982. if (fld.length > 0 && !fld.hasClass('se_type-date')) {
  2983. if(dbg)console.log('set focus to first input element');
  2984. fld.focus(); return;
  2985. }
  2986. fld = modal$node.find('select[name^="f"]:first');
  2987. if (fld.length) {
  2988. if (fld.get(0).selectize) {
  2989. if(dbg)console.log('set focus to first typepecial element');
  2990. } else {
  2991. if(dbg)console.log('set focus to first select element');
  2992. fld.focus(); return;
  2993. }
  2994. }
  2995. if(dbg)console.log('set focus to close btn');
  2996. modal$node.find('.btn-close').focus();
  2997. })(inlineEditBox$Node);
  2998. },
  2999. error: function(err) {
  3000. if (priv.options.debug) console.log('err');
  3001. }
  3002. });
  3003. } else {
  3004. if (priv.options.debug) console.log('NO data');
  3005. return false;
  3006. }
  3007. };
  3008. priv.ajaxLoadTypeSpeciallCell = function(id, col) {
  3009. if (_popoverCellAjaxXhr) {
  3010. _popoverCellAjaxXhr.abort();
  3011. }
  3012. _popoverCellAjaxXhr = $.ajax({
  3013. type: 'GET',
  3014. url: 'index.php?_route=ViewTableAjax&_task=typeSpecialCell&namespace=<?= $acl->getNamespace(); ?>' + '&ID=' + id + '&col=' + col,
  3015. dataType: 'json',
  3016. contentType: "application/json; charset=utf-8",
  3017. data: '',
  3018. success: function(req){
  3019. if (_.get(req, 'data.tbl_id') > 0) {
  3020. var addHtml = '';
  3021. for (var i in req.data.items) {
  3022. var url = 'index.php?_route=ViewTableAjax';
  3023. url += '&namespace=' + req.namespace;
  3024. url += '&f_' + req.data.fld_name + '=' + req.data.items[i].id;
  3025. url += '&_hash=' + Math.random().toString(36).substring(2);
  3026. addHtml += '<a href="' + url + '">Wyszukaj ' + req.data.items[i].id + '</a>: ' + req.data.items[i].label;
  3027. addHtml += '<br>';
  3028. }
  3029. //_popoverCell.append(addHtml);// cache
  3030. if (_popoverCellCurrent) {
  3031. var popoverNodeId = _popoverCellCurrent.attr('aria-describedby');
  3032. if (popoverNodeId) {
  3033. jQuery('#' + popoverNodeId).find('.popoverCellContent').append(addHtml);
  3034. }
  3035. }
  3036. }
  3037. }
  3038. });
  3039. };
  3040. priv.popoverCellTypeSpecial = function(e) {
  3041. e.preventDefault();
  3042. e.stopPropagation();
  3043. if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
  3044. var lastId = _popoverCell.data('rowid'),
  3045. lastCol = _popoverCell.data('col'),
  3046. rowPK = e.data.id,
  3047. colName = e.data.col
  3048. ;
  3049. if (lastId == rowPK && lastCol == colName) {
  3050. //_popoverCellCurrent.popover('toggle');
  3051. }
  3052. else {
  3053. if (_popoverCellCurrent) {
  3054. _popoverCellCurrent.popover('destroy');
  3055. }
  3056. _popoverCell.data('rowid', rowPK);
  3057. _popoverCell.data('col', colName);
  3058. _popoverCell.html(e.data.value + '<div class="popoverCellContent loading" style="white-space:normal"></div>');
  3059. _popoverCellCurrent = jQuery(e.currentTarget);
  3060. // title : '<span class="text-info"><strong>title</strong></span> <button type="button" id="close" class="close">&times;</button>'
  3061. var opts = {
  3062. placement: 'left'
  3063. , trigger: 'click'
  3064. // , title: e.data.col + '<a href="#" class="glyphicon glyphicon-remove pull-right" onclick="return hidePopover();"></a>'
  3065. , title: '<div style="display:block;position:relative;padding:0 20px 0 0;">' + (e.data.friendly || colName) + ' <button type="button" class="close" onclick="return hidePopover();" style="position:absolute;right:0;top:0;">&times;</button>' + '</div>'
  3066. , html: true
  3067. , content: _popoverCell.html()
  3068. }
  3069. _popoverCellCurrent.popover(opts);
  3070. if (_data.cols[colName]) {
  3071. if (_data.cols[colName]._tsRetId > 0) {
  3072. _popoverCellCurrent.on('shown.bs.popover', function() {
  3073. priv.ajaxLoadTypeSpeciallCell(rowPK, colName);
  3074. });
  3075. }
  3076. }
  3077. _popoverCellCurrent.popover('show');
  3078. }
  3079. } else {
  3080. if (priv.options.debug) console.log('NO data');
  3081. return false;
  3082. }
  3083. return;
  3084. };
  3085. priv.routeChanged = function(e) {
  3086. hash = e.data.hash || '';
  3087. if (hash.length == 0) {
  3088. return;
  3089. }
  3090. if (hash.substring(0, 1) != '#') {
  3091. hash = '#' + hash;
  3092. }
  3093. location.hash = hash;
  3094. };
  3095. priv.refresh = function(e) {
  3096. e.preventDefault();
  3097. publ.loadPage(_state.page);
  3098. };
  3099. publ.init = function(options) {
  3100. if (priv.options.debug) console.log('TableAjax initialization...');
  3101. //merge supplied options with defaults
  3102. $.extend(priv.options, defaults, options);
  3103. priv.init();
  3104. return publ;
  3105. };
  3106. publ.refresh = function() {
  3107. publ.loadPage(_state.page);
  3108. };
  3109. publ.loadPage = function(page, pageSize) {
  3110. priv.loadPage(page, pageSize);
  3111. }
  3112. priv.loadPage = function(page, pageSize) {
  3113. var skipCols = true, // skipCols = true - prevent columns delete
  3114. resetChecked = false;
  3115. var reqData = {
  3116. page: page,
  3117. pageSize: (pageSize || priv.options.pageSize),
  3118. currSortCol: (_state.filters.currSortCol || ''),
  3119. currSortFlip: _state.filters.currSortFlip ? "desc" : "asc"
  3120. };
  3121. var urlAdd = '';
  3122. urlAdd += '&page=' + page;
  3123. urlAdd += '&pageSize=' + (pageSize || priv.options.pageSize);
  3124. urlAdd += '&currSortCol=' + (_state.filters.currSortCol || '');
  3125. urlAdd += '&currSortFlip=' + (_state.filters.currSortFlip ? "desc" : "asc");
  3126. if (Object.keys(_state.filters.filterCols).length > 0) {
  3127. $.each(_state.filters.filterCols, function(col, colProps) {
  3128. if (colProps.filter && colProps.filter.length > 0) {
  3129. urlAdd += '&f_' + col + '=' + colProps.filter;
  3130. }
  3131. });
  3132. skipCols = true;
  3133. }
  3134. // specialFilters
  3135. $.each(_state.specialFilters, function(groupName, btnValue) {
  3136. if (btnValue.length > 0) {
  3137. urlAdd += '&sf_' + groupName + '=' + btnValue;
  3138. }
  3139. });
  3140. if (priv.options.forceFilterInit) {
  3141. $.map(priv.options.forceFilterInit, function(fltrProps, fltr) {
  3142. urlAdd += '&f_' + fltr + '=' + fltrProps;
  3143. filtersInitSet = true;
  3144. });
  3145. }
  3146. _uiNode$Table.parent().parent().addClass('AjaxTable-loading');
  3147. // p5UI__notifyAjaxCallback({type: 'info', msg: 'pobieranie danych...'});
  3148. fetch(priv.options.url + urlAdd, {
  3149. method: priv.options.urlPost ? 'POST' : 'GET',
  3150. credentials: 'same-origin',// add cookies
  3151. }).then(function (response) {
  3152. return response.json()
  3153. }).then(function (data) {
  3154. if (priv.options.debug) console.log('loadDataAjax:fetch: request finished L.<?php echo __LINE__; ?> data:', data);
  3155. // p5UI__notifyAjaxCallback(data);
  3156. if ('success' == data.type) {
  3157. state = {data: {}};
  3158. if (!skipCols) state.data.cols = data.cols || {};
  3159. state.data.rows = data.rows || [];
  3160. state.data.total = data.total || 0;
  3161. state.page = data.page || 0;
  3162. state.pageSize = data.pageSize || priv.options.pageSize;
  3163. state.filters = data.filters || {};
  3164. priv.setState(state);
  3165. _uiNode$Table.parent().parent().removeClass('AjaxTable-loading');
  3166. } else if ('error' == data.type) {
  3167. p5UI__notifyAjaxCallback(data);
  3168. } else {
  3169. p5UI__notifyAjaxCallback(data);
  3170. }
  3171. }).catch(function (e) {
  3172. console.log('loadDataAjax:fetch: ERR:', e);
  3173. });
  3174. };
  3175. publ.getCurrentPage = function() {
  3176. return _state.page;
  3177. };
  3178. publ.popoverCellRemove = function() {
  3179. if (_popoverCellCurrent) {
  3180. _popoverCellCurrent.popover('destroy');
  3181. }
  3182. _popoverCell.data('rowid', -1);
  3183. _popoverCell.data('col', -1);
  3184. _popoverCell.html('');
  3185. };
  3186. return publ;
  3187. }
  3188. $.fn.TableAjax = function(options) {
  3189. options = options || {};
  3190. return this.each(function() {
  3191. options.id = this;
  3192. $(this).data('TableAjax', new TableAjax().init(options));
  3193. });
  3194. };
  3195. $.fn.TableAjaxLoadPage = function(page, pageSize) {
  3196. return this.each(function() {
  3197. var tblAjax = jQuery(this).data('TableAjax');
  3198. var curPage = page || tblAjax.getCurrentPage();
  3199. if (tblAjax) tblAjax.loadPage(curPage, pageSize);
  3200. });
  3201. };
  3202. $.fn.TableAjaxRefresh = function(page, pageSize) {
  3203. return this.each(function() {
  3204. var tblAjax = jQuery(this).data('TableAjax');
  3205. if (tblAjax) tblAjax.refresh();
  3206. });
  3207. };
  3208. String.prototype.format = String.prototype.f = function() {
  3209. var s = this;
  3210. i = arguments.length;
  3211. while (i--) s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
  3212. return s;
  3213. };
  3214. })(jQuery);
  3215. </script>
  3216. <?php
  3217. $filterInit = $this->_filterInit;
  3218. $forceFilterInit = $this->_forceFilterInit;
  3219. $pageSizes = $this->_pageSizes;
  3220. $pageSize = $this->_pageSize;
  3221. $rowFunctions = $this->_rowFunctions;//$this->_showRowFunctionsJson();
  3222. $exportFields = Core_AclHelper::getExportFieldList($acl);
  3223. ?>
  3224. <script>
  3225. function TableAjax__HIST_Route(args) {
  3226. var recordID = args;
  3227. if (typeof args == 'object') {
  3228. recordID = args.shift();
  3229. recordID = parseInt(recordID);
  3230. }
  3231. if (typeof recordID !== 'number' || recordID <= 0) {
  3232. // TODO: msg
  3233. return false;
  3234. }
  3235. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  3236. cont.hide();
  3237. // remove previous task content
  3238. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  3239. taskCnt.parent().remove();
  3240. taskCnt.remove();
  3241. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  3242. jQuery('<ul class="breadcrumb">' +
  3243. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  3244. '<li class="active">Historia rekordu</li>' +
  3245. '</ul>').appendTo(taskCont);
  3246. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  3247. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  3248. $.ajax({
  3249. dataType: 'json',
  3250. type: "GET",
  3251. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=HIST&ID=' + recordID,
  3252. })
  3253. .done(function(data, textStatus, jqXHR){
  3254. taskCnt.removeClass('AjaxTable-loading');
  3255. <?php if(DBG::isActive() && V::get('DBG', '', $_GET)) : ?>console.log('TODO #L.<?= __LINE__; ?> done loading HIST_AJAX - data:', data);<?php endif; ?>
  3256. histAjaxOut = '<fieldset>' +
  3257. '<legend>' + data['label'] +
  3258. '<span class="pull-right valign-btns-bottom">';
  3259. for (i in data['row_functions']) {
  3260. histAjaxOut += data['row_functions'][i];
  3261. // TODO: fetch more row functions
  3262. }
  3263. histAjaxOut += '</span>' +
  3264. '</legend>'
  3265. '</fieldset>';
  3266. if (!data['rows']) {
  3267. histAjaxOut += '<div class="alert alert-info">' +
  3268. '<h4>Brak danych</h4>' +
  3269. '</div>';
  3270. } else {
  3271. histAjaxOut += '<table class="table table-striped table-hover table-bordered table-condensed AjaxTableHist">' +
  3272. '<thead>' +
  3273. '<tr>' +
  3274. '<th>Data</th>' +
  3275. '<th>Autor</th>' +
  3276. '<th>Zmiany</th>' +
  3277. '</tr>' +
  3278. '</thead>' +
  3279. '<tbody>';
  3280. for (i in data['rows']) {
  3281. var row = data['rows'][i];
  3282. histAjaxOut += '<tr data-id_hist="' + row['ID'] + '">' +
  3283. '<td style="white-space:nowrap">' + row['_created'] + '</td>' +
  3284. '<td>' + row['_author'] + '</td>' +
  3285. '<td>';
  3286. for (j in row['changes']) {
  3287. var change = row['changes'][j];
  3288. var fieldName = change['fieldName'];
  3289. if (['ID', 'A_RECORD_UPDATE_DATE', 'A_RECORD_UPDATE_AUTHOR', 'A_RECORD_CREATE_DATE', 'A_RECORD_CREATE_AUTHOR'].indexOf(fieldName) >= 0) continue;
  3290. if ('N/S;' == change['value']) continue;
  3291. histAjaxOut += '<p>' +
  3292. '<em>' + (data['field_label'][fieldName] || fieldName) + '</em>: ';
  3293. histAjaxOut += (change['acl_read'])
  3294. ? change['value']
  3295. : '<span title="Brak uprawnień do odczytu tego pola">*****</span>'
  3296. if (change['revert_function_url']) {
  3297. histAjaxOut += ' <button' +
  3298. ' class="btn btn-xs btn-default"' +
  3299. ' onClick="return p5UI__ajaxLinkClick(this, \''+change['revert_function_url']+'\', \''+change['revert_function_data']+'\')"' +
  3300. ' title="Cofnij dane do tej wartości">' +
  3301. '<i class="glyphicon glyphicon-floppy-disk"></i> cofnij' +
  3302. '</button>';
  3303. }
  3304. histAjaxOut += '</p>';
  3305. }
  3306. histAjaxOut += '</td>' +
  3307. '</tr>';
  3308. }
  3309. histAjaxOut += '</tbody>' +
  3310. '</table>';
  3311. }
  3312. {// old view - flat table
  3313. histAjaxOut += '<div style="overflow-x:scroll; overflow-y:visible; padding-bottom:1px; margin:10px 0;">' +
  3314. '<table class="table table-striped table-hover table-bordered table-condensed AjaxTableHist">' +
  3315. '<thead>' +
  3316. '<tr>' + "\n";
  3317. histAjaxOut += '<th>Data</th>';
  3318. histAjaxOut += '<th>Autor</th>';
  3319. for (j in data['fields']) {
  3320. var fieldName = data['fields'][j];
  3321. histAjaxOut += '<th>' + (data['field_label'][fieldName] || fieldName).replace(/_/g, ' ') + '</th>';
  3322. }
  3323. histAjaxOut += '</tr>' +
  3324. '</thead>' +
  3325. '<tbody>';
  3326. for (i in data['rows']) {
  3327. var row = data['rows'][i];
  3328. histAjaxOut += '<tr>';
  3329. histAjaxOut += '<td><nobr>' + row['_created'] + '</nobr></td>';
  3330. histAjaxOut += '<td>' + row['_author'] + '</td>';
  3331. for (j in data['fields']) {
  3332. var fieldName = data['fields'][j];
  3333. histAjaxOut += '<td>';
  3334. ( (!(fieldName in row['changes']) || row['changes'][fieldName]['value'] == 'N/S;')
  3335. ? histAjaxOut += '<em>N/S;</em>'
  3336. : ( (row['changes'][fieldName]['acl_read'])
  3337. ? histAjaxOut += row['changes'][fieldName]['value']
  3338. : histAjaxOut += '<span title="Brak uprawnień do odczytu tego pola">*****</span>'
  3339. )
  3340. );
  3341. histAjaxOut += '</td>';
  3342. }
  3343. histAjaxOut += '</tr>';
  3344. }
  3345. histAjaxOut += '</tbody>' +
  3346. '</table>' +
  3347. '</div>';
  3348. }
  3349. jQuery(histAjaxOut).appendTo(taskCnt);
  3350. })
  3351. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  3352. taskCnt.removeClass('AjaxTable-loading');
  3353. if (jqXHR.responseJSON) {
  3354. notifyAjaxCallback(jqXHR.responseJSON);
  3355. }
  3356. else {
  3357. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  3358. if (jqXHR.status == 404) {
  3359. jQuery.notify(jqXHR.responseText, 'error');
  3360. } else {
  3361. jQuery.notify(jqXHR.responseText, 'warn');
  3362. }
  3363. }
  3364. console.log('TODO #L.<?= __LINE__; ?> fail loading HIST_AJAX - jqXHR.responseText:', jqXHR.responseText);
  3365. });
  3366. function notifyAjaxCallback(data) {
  3367. var notify = {};
  3368. notify.type = (data && data.type)? data.type : '';
  3369. notify.msg = (data && data.msg)? data.msg : '';
  3370. switch (notify.type) {
  3371. case 'success':
  3372. if (!notify.msg) notify.msg = 'OK';
  3373. break;
  3374. case 'info':
  3375. if (!notify.msg) notify.msg = '';
  3376. break;
  3377. case 'error':
  3378. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3379. break;
  3380. case 'warning':
  3381. notify.type = 'warn';
  3382. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3383. break;
  3384. default:
  3385. notify.msg = 'Nieznany błąd';
  3386. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  3387. notify.type = '';
  3388. }
  3389. jQuery.notify(notify.msg, notify.type);
  3390. }
  3391. //return false;
  3392. }
  3393. </script>
  3394. <script>
  3395. jQuery(document).ready(function(){
  3396. jQuery('#<?php echo $this->_htmlID; ?>').TableAjax({
  3397. url: '<?= $this->syncUrl; ?>&_hash=<?= $this->_htmlID; ?>&_task=loadDataAjax',// priv.options.url
  3398. userTableFilterUrl: '<?= ($this->_useUserTableFilter) ? $this->_useUserTableFilter : ''; ?>',
  3399. columnPicker: true,
  3400. filter: true,
  3401. filterInit: <?php echo json_encode($filterInit); ?>,
  3402. forceFilterInit: <?php echo json_encode($forceFilterInit); ?>,
  3403. debug: false,
  3404. height: 400,
  3405. sorting: true,
  3406. paging: true,
  3407. pageSize: <?php echo $pageSize; ?>,
  3408. pageSizes: <?php echo json_encode($pageSizes); ?>,
  3409. tblFunctions: {
  3410. shortdesc: {
  3411. icon: 'align-left',
  3412. title: 'Long desc',
  3413. method: 'longTextChanged'
  3414. },
  3415. <?php if ($hasGeomFlds) : ?>
  3416. mapeditor: {
  3417. icon: 'map-marker',
  3418. title: 'Mapa',
  3419. method: 'mapEditorChanged'
  3420. },
  3421. <?php endif; ?>
  3422. create: {
  3423. href: '#CREATE',
  3424. icon: 'plus',
  3425. title: 'Dodaj nowy rekord'
  3426. },
  3427. refresh: {
  3428. icon: 'refresh',
  3429. title: 'Odśwież dane',
  3430. method: 'refresh'
  3431. }
  3432. },
  3433. rowFunctions: <?php echo json_encode($rowFunctions); ?>,
  3434. exportFields: <?php echo json_encode($exportFields); ?>,
  3435. specialFilterFunctions: <?php
  3436. $fltrs = (method_exists($acl, 'getSpecialFilters')) ? $acl->getSpecialFilters() : null;
  3437. if (!empty($fltrs)) {
  3438. echo json_encode($fltrs);
  3439. } else {
  3440. echo 'false';
  3441. }
  3442. echo ',';
  3443. ?>
  3444. router: function() {
  3445. var routes = {
  3446. EDIT: function(args) {
  3447. var recordID = args;
  3448. if (typeof args == 'object') {
  3449. recordID = args.shift();
  3450. recordID = parseInt(recordID);
  3451. }
  3452. if (typeof recordID !== 'number' || recordID <= 0) {
  3453. // TODO: msg
  3454. return false;
  3455. }
  3456. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  3457. cont.hide();
  3458. // remove previous task content
  3459. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  3460. taskCnt.parent().remove();
  3461. taskCnt.remove();
  3462. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  3463. jQuery('<ul class="breadcrumb">' +
  3464. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  3465. '<li class="active">Edytuj rekord</li>' +
  3466. '</ul>').appendTo(taskCont);
  3467. taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  3468. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  3469. jQuery.ajax({
  3470. url: '<?= $this->syncUrl; ?>&_hash=<?= $this->_htmlID; ?>&_task=editForm&_primaryKey=' + recordID,
  3471. type: 'GET',
  3472. dataType: 'text',
  3473. data: '',
  3474. async: true,
  3475. success: function(data) {
  3476. taskCnt.removeClass('AjaxTable-loading');
  3477. jQuery(data).appendTo(taskCnt);
  3478. initDateTimePicker(taskCnt);
  3479. },
  3480. error: function(err) {
  3481. taskCnt.removeClass('AjaxTable-loading');
  3482. //console.log('request error: {0}'.f(err));
  3483. }
  3484. });
  3485. //return false;
  3486. },
  3487. HIST: TableAjax__HIST_Route,
  3488. FILES: function tableAjaxFiles(args) {
  3489. var recordID = args;
  3490. if (typeof args == 'object') {
  3491. recordID = args.shift();
  3492. recordID = parseInt(recordID);
  3493. }
  3494. if (typeof recordID !== 'number' || recordID <= 0) {
  3495. // TODO: msg
  3496. return false;
  3497. }
  3498. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  3499. cont.hide();
  3500. // remove previous task content
  3501. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  3502. taskCnt.parent().remove();
  3503. taskCnt.remove();
  3504. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  3505. jQuery('<ul class="breadcrumb">' +
  3506. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  3507. '<li class="active">Pliki</li>' +
  3508. '</ul>').appendTo(taskCont);
  3509. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTable-loading"></div>').appendTo(taskCont);
  3510. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  3511. jQuery.ajax({
  3512. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES&ID=' + recordID,
  3513. type: 'GET',
  3514. dataType: 'text',
  3515. data: '',
  3516. async: true,
  3517. success: function(data) {
  3518. taskCnt.removeClass('AjaxTable-loading');
  3519. //console.log('request finished L.<?php echo __LINE__; ?>', data);
  3520. jQuery(data).appendTo(taskCnt);
  3521. },
  3522. error: function(jqXHR, textStatus, errorThrown) {
  3523. //console.log('request error:', jqXHR.status, 'txt:', jqXHR.responseText, 'err:', jqXHR);
  3524. taskCnt.removeClass('AjaxTable-loading');
  3525. var txt = jqXHR.responseText || 'Error';
  3526. if (jqXHR.status == 404) {
  3527. jQuery('<div class="container"><div class="alert alert-danger">' + txt + '</div></div>').appendTo(taskCnt);
  3528. } else {
  3529. jQuery('<div class="container"><div class="alert alert-danger">' + txt + '</div></div>').appendTo(taskCnt);
  3530. }
  3531. }
  3532. });
  3533. //return false;
  3534. },
  3535. CREATE: function tableAjaxCreate() {
  3536. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  3537. cont.hide();
  3538. // remove previous task content
  3539. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  3540. taskCnt.parent().remove();
  3541. taskCnt.remove();
  3542. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  3543. jQuery('<ul class="breadcrumb">' +
  3544. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  3545. '<li class="active">Dodaj nowy rekord</li>' +
  3546. '</ul>').appendTo(taskCont);
  3547. taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  3548. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  3549. var reqData = {};
  3550. var forceFilterInit = <?php echo json_encode($forceFilterInit);// TODO: read from TableAjax ?>;
  3551. if (forceFilterInit) {
  3552. $.map(forceFilterInit, function(fltrProps, fltr) {
  3553. reqData['ff_' + fltr] = fltrProps;
  3554. });
  3555. }
  3556. jQuery.ajax({
  3557. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE',// TODO: mv to ViewTableAjax route
  3558. // TODO: url: 'index.php?_route=ViewTableAjax&_task=createForm&namespace=<?= $acl->getNamespace(); ?>&_hash=<?php echo $this->_htmlID; ?>',
  3559. type: 'GET',
  3560. dataType: 'text',
  3561. data: reqData,
  3562. async: true,
  3563. success: function(data) {
  3564. taskCnt.removeClass('AjaxTable-loading');
  3565. // console.log('request finished L.<?php echo __LINE__; ?>', data);
  3566. jQuery(data).appendTo(taskCnt);
  3567. initDateTimePicker(taskCnt);
  3568. },
  3569. error: function(err) {
  3570. taskCnt.removeClass('AjaxTable-loading');
  3571. //console.log('request error: {0}'.f(err));
  3572. }
  3573. });
  3574. //return false;
  3575. }
  3576. };
  3577. var routePath = location.hash;
  3578. //console.log('location.hash: ' + routePath);
  3579. if (location.hash == '' || location.hash == '#') {
  3580. return false;
  3581. }
  3582. if (routePath.charAt(0) == '#') {
  3583. routePath = routePath.substr(1);
  3584. }
  3585. //console.log('routePath: ' + routePath);
  3586. var parts = routePath.split('/');
  3587. var task = parts.shift();
  3588. //console.log('task(' + task + ') parts:');
  3589. //console.log(parts);
  3590. if (task in routes && typeof routes[task] == 'function') {
  3591. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  3592. if (con) {
  3593. var tblAjax = con.data('TableAjax');
  3594. if (tblAjax) {
  3595. tblAjax.popoverCellRemove();
  3596. }
  3597. }
  3598. routes[task](parts);
  3599. } else {
  3600. return false;
  3601. }
  3602. },
  3603. filtersClean: true,
  3604. longDesc: true
  3605. });
  3606. });
  3607. function tableAjaxBackToTable() {
  3608. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  3609. cont.show();
  3610. var taskCont = jQuery('#<?php echo $this->_htmlID . '_task'; ?>').parent();
  3611. taskCont.remove();
  3612. // reload first page
  3613. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  3614. con.TableAjaxLoadPage();// TODO: load current page
  3615. }
  3616. function tableAjaxCopy(args) {
  3617. var recordID = args;
  3618. if (typeof args == 'object') {
  3619. recordID = args.shift();
  3620. recordID = parseInt(recordID);
  3621. }
  3622. if (typeof recordID !== 'number' || recordID <= 0) {
  3623. // TODO: msg
  3624. return false;
  3625. }
  3626. if (!confirm('Czy na pewno chcesz utworzyc nowy rekord na podstawie danych z rekordu ID = ' + recordID + '?')) {
  3627. return false;
  3628. }
  3629. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  3630. function notifyAjaxCallback(data) {
  3631. var notify = {};
  3632. notify.type = (data && data.type)? data.type : '';
  3633. notify.msg = (data && data.msg)? data.msg : '';
  3634. switch (notify.type) {
  3635. case 'success':
  3636. if (!notify.msg) notify.msg = 'OK';
  3637. break;
  3638. case 'info':
  3639. if (!notify.msg) notify.msg = '';
  3640. break;
  3641. case 'error':
  3642. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3643. break;
  3644. case 'warning':
  3645. notify.type = 'warn';
  3646. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3647. break;
  3648. default:
  3649. notify.msg = 'Nieznany błąd';
  3650. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  3651. notify.type = '';
  3652. }
  3653. jQuery.notify(notify.msg, notify.type);
  3654. }
  3655. var reqData = {};
  3656. jQuery.ajax({
  3657. data: reqData,
  3658. dataType: 'json',
  3659. type: "GET",
  3660. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=COPY&ID=' + recordID,
  3661. })
  3662. .done(function(data, textStatus, jqXHR){
  3663. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  3664. con.TableAjaxRefresh();
  3665. notifyAjaxCallback(data);
  3666. })
  3667. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  3668. if (jqXHR.responseJSON) {
  3669. notifyAjaxCallback(jqXHR.responseJSON);
  3670. }
  3671. else {
  3672. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  3673. if (jqXHR.status == 404) {
  3674. jQuery.notify(jqXHR.responseText, 'error');
  3675. } else {
  3676. jQuery.notify(jqXHR.responseText, 'warn');
  3677. }
  3678. }
  3679. });
  3680. return false;
  3681. }
  3682. function hidePopover() {
  3683. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  3684. if (con) {
  3685. var tblAjax = con.data('TableAjax');
  3686. if (tblAjax) {
  3687. tblAjax.popoverCellRemove();
  3688. }
  3689. }
  3690. return false;
  3691. }
  3692. function <?php echo $jsToogleFiltrProcesuFunctionName; ?>(n) {
  3693. var $n = jQuery(n);
  3694. var $ul = $n.next();
  3695. if ($n.data('fetched')) return false;
  3696. function parseProcesInitData(pInitData) {
  3697. var procesInitMapHtml = '';
  3698. if (!pInitData) {
  3699. return '<li><a href="#">' + "Brak danych" + '</a></li>';
  3700. } else {
  3701. function _viewProcesInitListItem(pInitId, gotoIds, pInitList) {
  3702. var label = pInitList[pInitId];
  3703. var jsInfo = "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=" + pInitId + "&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;";
  3704. var out = '<a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=' + pInitId + '&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="' + "{" + pInitId + "} " + label + '">';// TODO: change to _route=ViewTableAjax&typeName=p5_default_db:{tblName}
  3705. out += ' <i class="glyphicon glyphicon-info-sign"';
  3706. out += ' onclick="' + jsInfo + '"';
  3707. out += ' style="color:#aaa;"';
  3708. out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
  3709. out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
  3710. out += " {" + pInitId + "} " + label;
  3711. out += '</a>';
  3712. return out;
  3713. }
  3714. function _viewProcesGotoAndRetListItem(gotoId, pInitList) {
  3715. var label = pInitList[gotoId];
  3716. var jsInfo = "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=" + gotoId + "&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;";
  3717. var out = '';
  3718. out += '<a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=' + gotoId + '&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="' + "{" + gotoId + "} " + label + '">';// TODO: change to _route=ViewTableAjax&typeName=p5_default_db:{tblName}
  3719. out += ' <span style="padding:10px;"></span>';
  3720. out += ' <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>';
  3721. out += ' <i class="glyphicon glyphicon-info-sign"';
  3722. out += ' onclick="' + jsInfo + '"';
  3723. out += ' style="color:#aaa;"';
  3724. out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
  3725. out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
  3726. out += " {" + gotoId + "} " + label;
  3727. out += '</a>';
  3728. return out;
  3729. }
  3730. function _viewProcesGotoAndRetLvl2ListItem(gotoLvl2Id, pInitList) {
  3731. var label = pInitList[gotoLvl2Id];
  3732. var jsInfo = "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=" + gotoLvl2Id + "&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;";
  3733. var out = '';
  3734. out += '<a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=' + gotoLvl2Id + '&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="' + "{" + gotoLvl2Id + "} " + label + '">';// TODO: change to _route=ViewTableAjax&typeName=p5_default_db:{tblName}
  3735. out += ' <span style="padding:20px;"></span>';
  3736. out += ' <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>';
  3737. out += ' <i class="glyphicon glyphicon-info-sign"';
  3738. out += ' onclick="' + jsInfo + '"';
  3739. out += ' style="color:#aaa;"';
  3740. out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
  3741. out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
  3742. out += " {" + gotoLvl2Id + "} " + label;
  3743. out += '</a>';
  3744. return out;
  3745. }
  3746. var sel = '',
  3747. liStyle = "white-space:nowrap; overflow:hidden; max-width:500px; /* text-overflow:ellipsis; */";
  3748. $.map(pInitData.mapTree, function(gotoIds, vInitId) {
  3749. sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
  3750. procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
  3751. procesInitMapHtml += _viewProcesInitListItem(vInitId, gotoIds, pInitData.pInitList);
  3752. procesInitMapHtml += '</li>' + "\n";
  3753. $.map(gotoIds, function(gotoLvl2Ids, gotoId) {
  3754. sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
  3755. procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
  3756. procesInitMapHtml += _viewProcesGotoAndRetListItem(gotoId, pInitData.pInitList);
  3757. procesInitMapHtml += '</li>' + "\n";
  3758. $.map(gotoLvl2Ids, function(vBool, gotoLvl2Id) {
  3759. sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
  3760. procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
  3761. procesInitMapHtml += _viewProcesGotoAndRetLvl2ListItem(gotoLvl2Id, pInitData.pInitList);
  3762. procesInitMapHtml += '</li>' + "\n";
  3763. });
  3764. });
  3765. });
  3766. }
  3767. return procesInitMapHtml;
  3768. }
  3769. jQuery.ajax({
  3770. data: null,
  3771. dataType: 'json',
  3772. type: "GET",
  3773. async: true,
  3774. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=PROCES_INIT_FILTR',
  3775. })
  3776. .always(function(data, textStatus, jqXHR) {
  3777. var type = data.type || null,
  3778. msg = data.msg || "Error",
  3779. pInitData = data.pInitData || null;
  3780. if (type) {
  3781. if ('success' == type) {
  3782. $ul.html(parseProcesInitData(pInitData));
  3783. } else if ('error' == type) {
  3784. $ul.html('<li><a href="#">' + msg + '</a></li>');
  3785. } else {
  3786. $ul.html('<li><a href="#">Wystapił błąd podczas pobierania listy procesów</a></li>');
  3787. }
  3788. } else {
  3789. $ul.html('<li><a href="#">Wystapił błąd podczas pobierania listy procesów</a></li>');
  3790. }
  3791. $n.data('fetched', true);
  3792. });
  3793. return false;
  3794. }
  3795. </script>
  3796. <?php
  3797. UI::setTitle($this->_acl->getRawLabel(100) . " - " . UI::getTitle());
  3798. $out = ob_get_contents();
  3799. ob_end_clean();
  3800. return $out;
  3801. }
  3802. public function _viewProcesInitListItem($vInitId, $gotoIds, $pInitList) {
  3803. $vLabel = $pInitList[$vInitId];
  3804. $kId = $vInitId;
  3805. ?>
  3806. <a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=<?php echo $kId; ?>&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="<?php echo htmlspecialchars("{{$kId}} {$vLabel}"); ?>">
  3807. <i class="glyphicon glyphicon-info-sign"
  3808. onclick="window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=<?php echo $kId; ?>&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;"
  3809. style="color:#aaa;"
  3810. onmouseover="this.style.color='#337AB7'"
  3811. onmouseout="this.style.color='#aaa'"></i>
  3812. <?php echo "{{$kId}} {$vLabel}"; ?>
  3813. </a>
  3814. <?php
  3815. }
  3816. public function _viewProcesGotoAndRetListItem($vGotoId, $pInitList) {
  3817. $vLabel = $pInitList[$vGotoId];
  3818. $kId = $vGotoId;
  3819. // TODO:?: prevent to execute procedure
  3820. ?>
  3821. <a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=<?php echo $kId; ?>&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="<?php echo htmlspecialchars("{{$kId}} {$vLabel}"); ?>">
  3822. <span style="padding:10px;"></span>
  3823. <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>
  3824. <i class="glyphicon glyphicon-info-sign"
  3825. onclick="window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=<?php echo $kId; ?>&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;"
  3826. style="color:#aaa;"
  3827. onmouseover="this.style.color='#337AB7'"
  3828. onmouseout="this.style.color='#aaa'"></i>
  3829. <?php echo "{{$kId}} {$vLabel}"; ?>
  3830. </a>
  3831. <?php
  3832. }
  3833. public function _viewProcesGotoAndRetLvl2ListItem($vGotoLvl2Id, $pInitList) {
  3834. $vLabel = $pInitList[$vGotoLvl2Id];
  3835. $kId = $vGotoLvl2Id;
  3836. // TODO:?: prevent to execute procedure
  3837. ?>
  3838. <a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=<?php echo $kId; ?>&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="<?php echo htmlspecialchars("{{$kId}} {$vLabel}"); ?>">
  3839. <span style="padding:20px;"></span>
  3840. <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>
  3841. <i class="glyphicon glyphicon-info-sign"
  3842. onclick="window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=<?php echo $kId; ?>&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;"
  3843. style="color:#aaa;"
  3844. onmouseover="this.style.color='#337AB7'"
  3845. onmouseout="this.style.color='#aaa'"></i>
  3846. <?php echo "{{$kId}} {$vLabel}"; ?>
  3847. </a>
  3848. <?php
  3849. }
  3850. public function hasAdditionalLayers() {
  3851. $layers = TableAjaxMap::getAdditionalLayers($this->_zasobID);
  3852. return !empty($layers);
  3853. }
  3854. public function ajaxTask($task) {
  3855. switch ($task) {
  3856. case 'EDIT_INLINE': {
  3857. $this->sendAjaxResponseJson('ajaxInlineEdit', $_REQUEST);
  3858. break;
  3859. }
  3860. case 'EDIT_INLINE_SAVE': {
  3861. $this->sendAjaxResponseJson('ajaxEditInlineSave', $_REQUEST);
  3862. break;
  3863. }
  3864. case 'COPY': {
  3865. $this->sendAjaxResponseJson('ajaxCopy', $_REQUEST);
  3866. break;
  3867. }
  3868. case 'CREATE': {
  3869. $this->sendAjaxCreate($_REQUEST);
  3870. break;
  3871. }
  3872. case 'CREATE_SAVE': {
  3873. $this->sendAjaxResponseJson('ajaxCreateSave', $_REQUEST);
  3874. break;
  3875. }
  3876. case 'HIST': {
  3877. $this->sendAjaxResponseJson('ajaxHist', $_REQUEST);
  3878. break;
  3879. }
  3880. case 'FILES': {
  3881. try {
  3882. $id = V::get('ID', 0, $_REQUEST, 'int');
  3883. if ($id <= 0) throw new HttpException("404", 404);
  3884. $this->sendAjaxFiles($id, $_REQUEST);
  3885. } catch (HttpException $e) {
  3886. Http::sendHeaderByCode($e->getCode());
  3887. echo $e->getMessage();
  3888. //UI::alert('danger', $e->getMessage());
  3889. } catch (Exception $e) {
  3890. echo '<div class="container">';
  3891. UI::alert('danger', $e->getMessage());
  3892. echo '</div>';
  3893. }
  3894. break;
  3895. }
  3896. case 'FILES_UPLOAD': {
  3897. $this->sendAjaxResponseJson('ajaxFileUpload', $_REQUEST);
  3898. break;
  3899. }
  3900. case 'FILES_LIST': {
  3901. $this->sendAjaxResponseJson('ajaxFileList', $_REQUEST);
  3902. break;
  3903. }
  3904. case 'FILE_REMOVE': {
  3905. $args = array();
  3906. $args['ID'] = V::get('ID', '', $_REQUEST);
  3907. $args['filename'] = V::get('filename', '', $_POST);
  3908. $this->sendAjaxResponseJson('ajaxFileRemove', $args);
  3909. break;
  3910. }
  3911. case 'filePermsRefresh': {
  3912. $this->sendAjaxResponseJson('ajaxFilePermsRefresh', $_REQUEST);
  3913. break;
  3914. }
  3915. case 'FILES_CONN_TBL_LIST': {
  3916. $id = V::get('ID', 0, $_REQUEST, 'int');
  3917. if ($id > 0) {
  3918. $this->sendAjaxFilesConnTblList($id, $_REQUEST);
  3919. } else {
  3920. echo '404';
  3921. }
  3922. break;
  3923. }
  3924. case 'TYPESPECIAL': {
  3925. $fldID = V::get('fldID', 0, $_REQUEST, 'int');
  3926. if ($fldID > 0) {
  3927. $this->sendTypeSpecial($fldID, $_REQUEST);
  3928. } else {
  3929. echo '404';
  3930. }
  3931. break;
  3932. }
  3933. case 'HIDDEN_COLS_SAVE': {
  3934. $this->sendAjaxResponseJson('ajaxHiddenColsSave', $_POST);
  3935. break;
  3936. }
  3937. case 'PAGE_SIZE_SAVE': {
  3938. $this->sendAjaxResponseJson('ajaxPageSizeSave', $_POST);
  3939. break;
  3940. }
  3941. case 'THE_GEOM_SAVE': {
  3942. $this->sendAjaxResponseJson('ajaxTheGeomSave', $_REQUEST);
  3943. break;
  3944. }
  3945. case 'PROCES_INIT_FILTR': {
  3946. $this->sendAjaxResponseJson('ajaxProcesInitFiltr', $_REQUEST);
  3947. break;
  3948. }
  3949. default:
  3950. $this->sendAjaxResponseJson('ajaxData', $_REQUEST);
  3951. }
  3952. }
  3953. /**
  3954. * ajax url: &_task=EDIT_INLINE
  3955. * @param $rowID - $_GET['ID']
  3956. * @param $fieldName - $_GET['col']
  3957. */
  3958. private function ajaxInlineEdit() {
  3959. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3960. $args = $_REQUEST;
  3961. $rowID = V::get('ID', 0, $_REQUEST, 'int');
  3962. $fieldName = V::get('col', '', $_REQUEST);
  3963. if ($rowID <= 0 || empty($fieldName)) throw new HttpException("404", 404);
  3964. $response = array();
  3965. ob_start();
  3966. $fieldID = $this->_acl->getFieldIdByName($fieldName);
  3967. if (!$fieldID) {
  3968. echo "404: No field by name ({$fieldName})";
  3969. exit;
  3970. }
  3971. $response['idZasob'] = $fieldID;
  3972. $response['htmlFieldName'] = "f{$fieldID}";
  3973. if ($DBG) echo "fieldID: {$fieldID}\n";
  3974. $row = $this->_acl->getItem($rowID);
  3975. if (!$row) {
  3976. echo "404: No item ID({$rowID})";
  3977. exit;
  3978. }
  3979. if (!$this->_acl->canReadObjectField($fieldName, $row)) {
  3980. if ($DBG) echo " R not allowed\n";
  3981. } else {
  3982. if ($DBG) echo " R allowed\n";
  3983. }
  3984. if (!$this->_acl->canWriteObjectField($fieldName, $row)) {
  3985. if ($DBG) echo " W not allowed\n";
  3986. } else {
  3987. if ($DBG) echo " W allowed\n";
  3988. }
  3989. $fieldVal = '';
  3990. if ($this->_acl->canReadObjectField($fieldName, $row)) {
  3991. $fieldVal = V::get($fieldName, $fieldVal, $row);
  3992. } else {
  3993. $fieldVal = '*****';
  3994. }
  3995. $fieldVal = V::get("f{$fieldID}", $fieldVal, $_POST);
  3996. $vCol = $this->_acl->getField($fieldID);
  3997. $vCol['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
  3998. $response['fieldLabel'] = $vCol['label'];
  3999. $tsValues = array();
  4000. $typeSpecial = Typespecial::getInstance($fieldID, $vCol['name']);
  4001. if ($typeSpecial) {
  4002. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$fieldID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
  4003. $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $row->ID, $fieldName, V::get($fieldName, $fieldVal, $row));
  4004. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$fieldID.') specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValues);echo'</pre>';}
  4005. if (!empty($specialValues)) {
  4006. $tsValues[$row->ID] = implode('<br>', $specialValues);
  4007. }
  4008. }
  4009. $fieldParams = array('widthClass'=>'inside-modal', 'maxGrid'=>6);
  4010. if (!empty($tsValues[$row->ID])) $fieldParams['typespecialValue'] = $tsValues[$row->ID];
  4011. if (!empty($tsValues[$row->ID])) $response['typespecialValue'] = $tsValues[$row->ID];
  4012. $vDefault = $this->_acl->getColDefault($fieldName);
  4013. if (!empty($vDefault)) $fieldParams['default'] = $vDefault;
  4014. if (!empty($vDefault)) $response['defaultValue'] = $vDefault;
  4015. {
  4016. try {
  4017. $item = $this->_acl->getFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $row);
  4018. $response['formItem'] = $item;
  4019. if (!empty($item['rawColType']['simpleType'])) $response['simpleType'] = $item['rawColType']['simpleType'];
  4020. if (!empty($item['rawColType']['restrictions'])) $response['restrictions'] = $item['rawColType']['restrictions'];
  4021. echo '<div style="display:none">';
  4022. DBG::_(true, true, "item", $item, __CLASS__, __FUNCTION__, __LINE__);
  4023. echo '</div>';
  4024. } catch (Exception $e) {
  4025. echo '<div style="display:none">';
  4026. UI::alert('danger', $e->getMessage());
  4027. echo '</div>';
  4028. }
  4029. }
  4030. ?>
  4031. <label for="<?php echo "f{$fieldID}"; ?>" class="AjaxTableEdit-label">
  4032. <strong title="<?php echo "[{$fieldID}] {$fieldName}"; ?>"><?php echo "{$vCol['label']}"; ?></strong>
  4033. <?php if (!empty($vCol['opis'])) : ?>
  4034. <em><?php echo $vCol['opis']; ?></em>
  4035. <?php endif; ?>
  4036. </label>
  4037. <?php
  4038. if (!$this->_acl->canWriteObjectField($fieldName, $row)) {
  4039. // TODO: hide Zapisz btn on frontend side
  4040. if (!$this->_acl->canReadObjectField($fieldName, $row)) {
  4041. UI::alert('warning', "Brak uprawnień do odczytu i zapisu");
  4042. } else {
  4043. echo '<p style="margin-top:16px">' . $fieldVal . '</p>';
  4044. UI::alert('warning', "Brak uprawnień do zapisu");
  4045. }
  4046. } else {
  4047. echo $this->_acl->showFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $row);
  4048. if ($typeSpecial
  4049. || $this->_acl->isDateField($fieldName)
  4050. || $this->_acl->isDateTimeField($fieldName)
  4051. ) {
  4052. echo '<p style="padding:120px 0;"></p>';
  4053. }
  4054. }
  4055. $response['legacy_html'] = ob_get_clean();
  4056. //$response['legacy_html'] = utf8_encode($response['legacy_html']);// pl chars bug
  4057. return $response;
  4058. }
  4059. private function ajaxEditInlineSave($args) {
  4060. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  4061. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  4062. $fieldName = V::get('col', '', $_REQUEST);
  4063. if (empty($primaryKey)) throw new HttpException("Wrong param id!", 400);
  4064. if (empty($fieldName)) throw new HttpException("Wrong param col!", 400);
  4065. $fieldID = $this->_acl->getFieldIdByName($fieldName);
  4066. if (!$fieldID) throw new HttpException("Field not exists!", 404);
  4067. $item = $this->_acl->getItem($primaryKey);
  4068. if (!$item) throw new HttpException("Item not exists!", 404);
  4069. $itemFromUser = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  4070. if (!isset($itemFromUser[$fieldName])) throw new HttpException("Field not set!", 400);
  4071. $itemPatch = array();
  4072. $itemPatch[$fieldName] = V::get($fieldName, null, $itemFromUser);
  4073. $itemPatch[$primaryKeyField] = $primaryKey;
  4074. $response = new stdClass();
  4075. try {
  4076. $affected = $this->_acl->updateItem($itemPatch);
  4077. if ($affected > 0) {
  4078. $response->type = 'success';
  4079. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  4080. } else if ($affected == 0) {
  4081. $response->type = 'info';
  4082. $response->msg = "Nie wprowadzono żadnych zmian";
  4083. }
  4084. $response->record = $this->_acl->getItem($primaryKey);
  4085. }
  4086. catch (Exception $e) {
  4087. $response->type = 'error';
  4088. $response->msg = $e->getMessage();
  4089. }
  4090. return $response;
  4091. }
  4092. public function sendAjaxEdit($id, $args) {
  4093. header("Content-type: text/plain");
  4094. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4095. $acl = $this->_acl;
  4096. $record = (array)$acl->getItem($id);
  4097. if (!$acl->canWriteRecord($record) && !$acl->hasPermSuperWrite()) {
  4098. UI::alert('danger', "Brak dostępu do rekordu");// TODO: more info - reason
  4099. return;
  4100. }
  4101. $fieldsList = array();
  4102. foreach ($acl->getFieldListByIdZasob() as $kID => $fieldName) {
  4103. if ($fieldName == 'ID') continue;
  4104. $field['name'] = $fieldName;
  4105. $field['opis'] = $acl->getFieldOpis($fieldName);
  4106. $field['label'] = $acl->getFieldLabel($fieldName);
  4107. if (empty($field['label'])) $field['label'] = str_replace('_', ' ', $fieldName);
  4108. $fieldsList[$kID] = $field;
  4109. }
  4110. $cols = array();
  4111. foreach ($fieldsList as $kID => $field) {
  4112. $cols[$kID] = '';
  4113. if ($this->_acl->canReadObjectField($field['name'], $record)) {
  4114. $cols[$kID] = V::get($field['name'], '', $record);
  4115. } else {
  4116. $cols[$kID] = '*****';
  4117. }
  4118. // if ($acl->canReadObjectField($field['name'])) {
  4119. // $cols[$kID] = V::get($field['name'], '', $record);
  4120. // } else {
  4121. // $cols[$kID] = '*****';
  4122. // }
  4123. $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
  4124. }
  4125. $tsValues = array();
  4126. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fieldsList (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($fieldsList);echo'</pre>';}
  4127. if (!empty($fieldsList)) {
  4128. foreach ($fieldsList as $vColID => $vCol) {
  4129. $typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
  4130. if ($typeSpecial) {
  4131. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vColID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
  4132. $colValue = V::get($vCol['name'], '', $record);
  4133. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">V::get('.$vCol['name'].', "", $record) (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($colValue);echo'</pre>';}
  4134. $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $record['ID'], $vCol['name'], $colValue);
  4135. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vColID.') specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValues);echo'</pre>';}
  4136. if (!empty($specialValues)) {
  4137. $tsValues[$vColID] = implode('<br>', $specialValues);
  4138. }
  4139. }
  4140. }
  4141. }
  4142. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">tsValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($tsValues);echo'</pre>';}
  4143. $rowFunctionsOut = $this->_showRowFunctions($record['ID'], array('edit', 'cp'), true);
  4144. ?>
  4145. <div class="container AjaxFrmHorizontalEdit" style="max-width:940px">
  4146. <form class="form-horizontal" action="" method="post" id="EDIT_FRM_<?php echo $this->_htmlID; ?>">
  4147. <fieldset>
  4148. <legend>Edycja rekordu Nr <?php echo $record['ID']; ?><span class="pull-right valign-btns-bottom"><?php echo $rowFunctionsOut; ?></span></legend>
  4149. <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
  4150. <?php if ($acl->canWriteObjectField($vCol['name'], $record)) : ?>
  4151. <div class="form-group">
  4152. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  4153. <i class="glyphicon glyphicon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?php echo htmlspecialchars($vCol['opis']); ?>" data-original-title="<?php echo "[{$kID}] {$vCol['name']}"; ?>"></i>
  4154. </label>
  4155. <div class="col-xs-12 col-sm-9 col-md-10">
  4156. <?php
  4157. $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
  4158. if (!empty($tsValues[$kID])) {
  4159. $fieldParams['typespecialValue'] = $tsValues[$kID];
  4160. }
  4161. echo $acl->showFormItem('W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record);
  4162. ?>
  4163. </div>
  4164. </div>
  4165. <?php elseif ($acl->canReadObjectField($vCol['name'], $record)) : ?>
  4166. <div class="form-group">
  4167. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  4168. <i class="glyphicon glyphicon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?php echo htmlspecialchars($vCol['opis']); ?>" data-original-title="<?php echo "[{$kID}] {$vCol['name']}"; ?>"></i>
  4169. </label>
  4170. <div class="col-xs-12 col-sm-9 col-md-10">
  4171. <p style="margin-top:5px;">
  4172. <?php
  4173. //echo $acl->showFormItem('R', $kID, "f{$kID}", $cols[$kID], array('appendBack'=>true), $record);
  4174. if (!empty($tsValues[$kID])) {
  4175. echo $tsValues[$kID];
  4176. } else if (!empty($record[ $vCol['name'] ])) {
  4177. echo $record[ $vCol['name'] ];
  4178. }
  4179. ?>
  4180. </p>
  4181. </div>
  4182. </div>
  4183. <?php endif; ?>
  4184. <?php endforeach; ?>
  4185. <div class="form-group">
  4186. <div class="col-xs-offset-0 col-xs-12 col-sm-offset-3 col-sm-9 col-md-offset-2 col-md-10">
  4187. <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Zapisz</button>
  4188. </div>
  4189. </div>
  4190. </fieldset>
  4191. </form>
  4192. <p style="padding:100px 0;"></p>
  4193. </div>
  4194. <script>
  4195. jQuery(document).ready(function(){
  4196. jQuery('textarea').autosize();
  4197. jQuery('.frm-help').popover({trigger:'hover'});
  4198. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
  4199. var formData = {};
  4200. jQuery(this).serializeArray().map(function(i) { formData[i.name] = i.value; });// TODO: edit Widget - send only updated fields
  4201. // TODO: change Edit btn to return to edit record with fields -> show form
  4202. var taskCont = jQuery('#<?php echo $this->_htmlID; ?>_task').parent();
  4203. //taskCont.empty();
  4204. taskCont.children().fadeOut('slow');
  4205. var alertCntWrap = jQuery('<div class="AjaxTableAlert AjaxTable-loading"></div>').prependTo(taskCont)
  4206. , alertCnt = jQuery('<div class="container"></div>').prependTo(alertCntWrap);
  4207. jQuery('<div class="alert alert-danger"><div style="padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;"> zapisywanie ... </div></div>').appendTo(alertCnt);
  4208. function notifyAjaxCallback(data) {
  4209. var notify = {}, outMsg = '';
  4210. notify.type = (data && data.type)? data.type : '';
  4211. notify.msg = (data && data.msg)? data.msg : '';
  4212. switch (notify.type) {
  4213. case 'success':
  4214. if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
  4215. break;
  4216. case 'info':
  4217. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  4218. break;
  4219. case 'error':
  4220. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  4221. break;
  4222. case 'warning':
  4223. notify.type = 'warn';
  4224. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  4225. break;
  4226. default:
  4227. notify.msg = 'Nieznany błąd';
  4228. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  4229. notify.type = '';
  4230. }
  4231. jQuery.notify(notify.msg, notify.type);
  4232. var alertType = ('error' == data.type) ? 'danger' : data.type;
  4233. outMsg = '<div class="alert alert-' + alertType + '">' + notify.msg + '</div>';
  4234. return outMsg;
  4235. }
  4236. superagent
  4237. .post('<?= $this->syncUrl; ?>&_hash=<?= $this->_htmlID; ?>&_task=editSaveAjax')
  4238. .type('json') // header ĺapplication/x-www-form-urlencoded' requires type('form');
  4239. .send({
  4240. namespace: '<?= $acl->getNamespace(); ?>',
  4241. primaryKey: '<?= $record['ID']; ?>',
  4242. form: formData
  4243. })
  4244. .set('Accept', 'application/json')
  4245. .end(function(err, res) {
  4246. var payload;
  4247. if (err || !res.ok || 'application/json' !== res.type) {
  4248. payload = {type: 'warning', msg: res.body.msg || 'Wystąpiły błędy', body: res.body};
  4249. } else {
  4250. payload = {type: 'success', msg: res.body.msg || '', body: res.body};
  4251. }
  4252. var data = res.body;
  4253. alertCntWrap.removeClass('AjaxTable-loading');
  4254. alertCnt.empty();
  4255. if (false === ['success', 'info'].indexOf(payload.type)) {
  4256. jQuery(errorTxt).appendTo(alertCnt);
  4257. var errLinks = jQuery('<div class="breadcrumb"></div>').appendTo(alertCnt);
  4258. jQuery('<a href="#" onclick="return tableAjaxBackToTable();"> <i class="icon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>').appendTo(errLinks);
  4259. var backToEditBtn = jQuery('<a href="#EDIT/<?php echo $id; ?>/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-small"> <i class="icon-pencil"></i> Popraw dane <?php echo $id; ?></a>').appendTo(errLinks);
  4260. backToEditBtn.on('click', function(){
  4261. alertCnt.remove();
  4262. taskCont.children().fadeIn('slow');
  4263. return false;
  4264. });
  4265. } else {
  4266. var outMsg = notifyAjaxCallback(payload);
  4267. var out = '';
  4268. out += outMsg;
  4269. out += '<div class="breadcrumb">' +
  4270. ' <a href="#" onclick="return tableAjaxBackToTable();" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>' +
  4271. ' <a href="#EDIT/<?php echo $id; ?>/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-pencil"></i> Edytuj rekord <?php echo $id; ?></a>' +
  4272. '</div>';
  4273. jQuery(out).appendTo(alertCnt);
  4274. // add rowFunctions from response
  4275. if (data && data.rowFunctions && data.primaryKey) {
  4276. var rowFunWrapNode = $('<div class="container"></div>').insertAfter(alertCnt);
  4277. var rowFunListNode = $('<ul></ul>').appendTo(rowFunWrapNode);
  4278. var keys = Object.keys(data.rowFunctions),
  4279. total = keys.length,
  4280. moreFuncBtnNode,
  4281. moreFunctions = [],
  4282. idx
  4283. ;
  4284. moreFunctions = keys.splice(3);
  4285. keys.forEach(function(key) {
  4286. var cellNode = $('<li></li>');
  4287. var funObj = data.rowFunctions[key],
  4288. funcNode = p5UI_TableAjax_generateFunctionNode(funObj, data.primaryKey, {ico: true, label: true})
  4289. ;
  4290. funcNode.appendTo(cellNode);
  4291. cellNode.appendTo(rowFunListNode);
  4292. });
  4293. }
  4294. }
  4295. });
  4296. return false;
  4297. });
  4298. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value input').on('input', function(e) {
  4299. var input, btn, btnIco;
  4300. input = jQuery(e.target);
  4301. btn = input.next('.button-appendBack');
  4302. btnIco = btn.find('.glyphicon');
  4303. if (btn.attr('title') != input.val()) {
  4304. btnIco.show();
  4305. } else {
  4306. btnIco.hide();
  4307. }
  4308. });
  4309. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value').find('.button-appendBack').on('click', function(e) {
  4310. var input, btn, btnIco;
  4311. btn = jQuery(this);
  4312. btnIco = btn.find('.glyphicon');
  4313. input = btn.prev();
  4314. if (input.is('input')) {
  4315. if (btn.attr('title') != input.val()) {
  4316. input.val(btn.attr('title'));
  4317. btnIco.hide();
  4318. }
  4319. }
  4320. });
  4321. });
  4322. </script>
  4323. <?php
  4324. exit;
  4325. }
  4326. private function sendAjaxCreate($args) {
  4327. $acl = $this->_acl;
  4328. header("Content-type: text/plain");
  4329. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4330. if (!Core_AclHelper::hasCreatePerms($acl)) {
  4331. ?>
  4332. <div class="container">
  4333. <div class="alert alert-danger">
  4334. Brak uprawnień do utworzenia nowego rekordu.
  4335. </div>
  4336. </div>
  4337. <?php
  4338. return;
  4339. }
  4340. $cols = array();
  4341. $forceFilterInit = array();
  4342. $defaultAclGroup = User::getDefaultAclGroup();
  4343. if ($defaultAclGroup) {
  4344. $forceFilterInit['A_ADM_COMPANY'] = $defaultAclGroup;
  4345. $forceFilterInit['A_CLASSIFIED'] = $defaultAclGroup;
  4346. }
  4347. foreach ($_GET as $k => $v) {
  4348. if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  4349. $fldName = substr($k, 3);
  4350. $forceFilterInit[$fldName] = $v;
  4351. }
  4352. }
  4353. $fieldsList = $this->_acl->getFields();
  4354. foreach ($fieldsList as $kID => $vCol) {
  4355. $defaultValue = '';
  4356. if ($vCol['name'] == 'ID') {
  4357. unset($fieldsList[$kID]);
  4358. continue;
  4359. }
  4360. if (!empty($forceFilterInit[$vCol['name']])) {
  4361. $defaultValue = $forceFilterInit[$vCol['name']];
  4362. }
  4363. // TODO: read from session cache
  4364. $cols[$kID] = V::get("f{$kID}", $defaultValue, $_POST);
  4365. $fieldsList[$kID]['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
  4366. }
  4367. ?>
  4368. <div class="container AjaxFrmHorizontalEdit">
  4369. <form class="form-horizontal" action="" method="post" id="CREATE_FRM_<?php echo $this->_htmlID; ?>">
  4370. <fieldset>
  4371. <legend>Dodaj nowy rekord</legend>
  4372. <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
  4373. <?php if ($this->_acl->canCreateField($vCol['name'])) : ?>
  4374. <div class="form-group">
  4375. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  4376. <i class="glyphicon glyphicon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?php echo htmlspecialchars($vCol['opis']); ?>" data-original-title="<?php echo "[{$kID}] {$vCol['name']}"; ?>"></i>
  4377. </label>
  4378. <div class="col-xs-12 col-sm-9 col-md-10">
  4379. <?php
  4380. $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
  4381. echo $this->_acl->showFormItem('C', $kID, "f{$kID}", $cols[$kID], $fieldParams);
  4382. ?>
  4383. </div>
  4384. </div>
  4385. <?php endif; ?>
  4386. <?php endforeach; ?>
  4387. <div class="form-group">
  4388. <div class="col-xs-offset-0 col-xs-12 col-sm-offset-3 col-sm-9 col-md-offset-2 col-md-10">
  4389. <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Dodaj rekord</button>
  4390. </div>
  4391. </div>
  4392. </fieldset>
  4393. </form>
  4394. </div>
  4395. <script>
  4396. jQuery(document).ready(function(){
  4397. jQuery('textarea').autosize();
  4398. jQuery('.frm-help').popover({trigger:'hover'});
  4399. jQuery('#CREATE_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
  4400. var data = jQuery(this).serialize();
  4401. var taskContLast = jQuery('#<?php echo $this->_htmlID; ?>_task'),
  4402. taskCont = taskContLast.parent();
  4403. taskContLast.fadeOut('slow');
  4404. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  4405. jQuery('<div class="alert alert-danger"><div style="padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;"> save ... </div></div>').appendTo(taskCnt);
  4406. function notifyAjaxCallback(data) {
  4407. var notify = {};
  4408. notify.type = (data && data.type)? data.type : '';
  4409. notify.msg = (data && data.msg)? data.msg : '';
  4410. switch (notify.type) {
  4411. case 'success':
  4412. if (!notify.msg) notify.msg = 'OK';
  4413. break;
  4414. case 'info':
  4415. if (!notify.msg) notify.msg = '';
  4416. break;
  4417. case 'error':
  4418. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  4419. break;
  4420. case 'warning':
  4421. notify.type = 'warn';
  4422. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  4423. break;
  4424. default:
  4425. notify.msg = 'Nieznany błąd';
  4426. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  4427. notify.type = '';
  4428. }
  4429. jQuery.notify(notify.msg, notify.type);
  4430. }
  4431. $.ajax({
  4432. data: data,
  4433. dataType: 'json',
  4434. type: "POST",
  4435. async: true,
  4436. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE_SAVE'
  4437. })
  4438. .always(function(dataOrJqXHR){
  4439. var data;
  4440. if (dataOrJqXHR && 'readyState' in dataOrJqXHR && 'status' in dataOrJqXHR) {
  4441. if ('responseJSON' in dataOrJqXHR) {
  4442. data = dataOrJqXHR.responseJSON;
  4443. } else {
  4444. data = {};
  4445. data.msg = dataOrJqXHR.responseText || 'Nieznany błąd';
  4446. if (dataOrJqXHR.status == 404) {
  4447. data.type = 'error';
  4448. } else {
  4449. data.type = 'warning';
  4450. }
  4451. }
  4452. }
  4453. else {
  4454. data = dataOrJqXHR;
  4455. }
  4456. notifyAjaxCallback(data);
  4457. taskCnt.removeClass('AjaxTable-loading');
  4458. taskCnt.empty();
  4459. if (data.type == 'error' || data.type == 'warning') {
  4460. var out = '<div class="container">' +
  4461. '<div class="alert alert-danger">' +
  4462. '<h4>Wystąpiły błędy!</h4>' + data.msg +
  4463. (('errors' in data)? '<p>' + data.errors + '</p>' : '') +
  4464. '</div>';
  4465. out += '<div class="breadcrumb">' +
  4466. ' <a class="create-fix" href="#CREATE/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-arrow-left"></i> Wróć do formularza i popraw dane</a></li>' +
  4467. '</div>' +
  4468. '</div>';
  4469. jQuery(out).appendTo(taskCnt);
  4470. var taskContLastNode = taskContLast
  4471. , taskCntNode = taskCnt;
  4472. taskCnt.find('.create-fix').click(function(){
  4473. taskCntNode.remove();
  4474. taskContLastNode.fadeIn('slow');
  4475. return false;
  4476. });
  4477. }
  4478. else if (data.type == 'success') {
  4479. var msg = '';
  4480. if (data.id && data.id > 0) {
  4481. msg = 'Utworzono pomyślnie rekord: ID = ' + data.id;
  4482. } else if (data.msg) {
  4483. msg = data.msg;
  4484. } else {
  4485. msg = 'OK';
  4486. }
  4487. var out = '<div class="container">';
  4488. out += '<div class="alert alert-success">' + msg + '</div>';
  4489. out += '<div class="breadcrumb">' +
  4490. ' <a href="#" onclick="return tableAjaxBackToTable();" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>' +
  4491. ' <a href="#EDIT/' + data.id + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-pencil"></i> Edytuj rekord ' + data.id + '</a>' +
  4492. ' <a href="#CREATE/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-plus"></i> Dodaj nowy rekord</a></li>' +
  4493. '</div>';
  4494. out += '</div>';
  4495. jQuery(out).appendTo(taskCnt);
  4496. }
  4497. });
  4498. return false;
  4499. });
  4500. });
  4501. </script>
  4502. <?php
  4503. exit;
  4504. }
  4505. private function ajaxCreateSave($args) {
  4506. $response = new stdClass();
  4507. $createdId = null;
  4508. try {
  4509. $item = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  4510. $createdId = $this->_acl->addItem($item);
  4511. if ($createdId) {
  4512. $response->type = 'success';
  4513. $response->msg = "Utworzono pomyślnie rekord nr {$createdId}";
  4514. $response->id = $createdId;
  4515. $response->record = $this->_acl->getItem($createdId);
  4516. }
  4517. else {
  4518. $response->type = 'error';
  4519. $response->msg = "Nie udało się utworzyć nowego rekordu!";
  4520. }
  4521. }
  4522. catch (Exception $e) {
  4523. $response->type = 'error';
  4524. $response->msg = $e->getMessage();
  4525. }
  4526. return $response;
  4527. }
  4528. private function ajaxCopy($args) {
  4529. $id = V::get('ID', 0, $_REQUEST, 'int');
  4530. if ($id <= 0) {
  4531. throw new HttpException("Wrong param ID!", 404);
  4532. }
  4533. $item = $this->_acl->getItem($id);
  4534. if (!$item) {
  4535. throw new HttpException("Item '{$id}' not exists!", 404);
  4536. }
  4537. $response = new stdClass();
  4538. $itemCopy = $this->_acl->createItemCopy($item);
  4539. $createdId = null;
  4540. try {
  4541. $createdId = $this->_acl->addItem($itemCopy);
  4542. if ($createdId) {
  4543. $response->type = 'success';
  4544. $response->msg = "Rekord skopiowany pomyślnie - utworzono rekord nr {$createdId}";
  4545. $response->id = $createdId;
  4546. $response->record = $this->_acl->getItem($createdId);
  4547. }
  4548. else {
  4549. $response->type = 'error';
  4550. $response->msg = "Nie udało się skopiować rekordu!";
  4551. }
  4552. }
  4553. catch (Exception $e) {
  4554. $response->type = 'error';
  4555. $response->msg = "Wystąpiły błędy!";
  4556. $response->msg = $e->getMessage();
  4557. }
  4558. return $response;
  4559. }
  4560. private function ajaxHist($args) {
  4561. $jsonResponse = array();
  4562. $id = V::get('ID', 0, $args, 'int');
  4563. $acl = $this->_acl;
  4564. $record = $acl->getItem($id);
  4565. if (!$record) throw new HttpException("404: No item ID({$id})", 404);
  4566. $visibleCols = $acl->getRealFieldList();
  4567. $rowsHist = $acl->getHistItems($id);
  4568. $jsonResponse['row_functions'] = $this->_parseRowFunctions($record->ID, array('hist', 'cp'), $showLabel = true);
  4569. $visibleColsWithIds = array();
  4570. $visibleColsLabels = array();
  4571. foreach ($visibleCols as $vColName) {
  4572. $fldId = $acl->getFieldIdByName($vColName);
  4573. if ($fldId) {
  4574. $visibleColsWithIds[$fldId] = $vColName;
  4575. $label = $acl->getFieldLabel($vColName);
  4576. $label = (!$label)? $vColName : '<span title="' . "[{$fldId}] {$vColName}" . '">' . $label . '</span>';
  4577. $visibleColsLabels[$fldId] = $label;
  4578. }
  4579. }
  4580. $jsonResponse['label'] = "Historia rekordu Nr {$id}";
  4581. $jsonResponse['fields'] = array_values($visibleColsWithIds);
  4582. $jsonResponse['field_label'] = $visibleColsLabels;
  4583. if (empty($rowsHist)) return $jsonResponse;
  4584. $jsonResponse['rows'] = array();
  4585. foreach ($rowsHist as $histRow) {
  4586. $histItem = array();
  4587. $histItem['ID'] = V::get('ID', '', $histRow);
  4588. $histItem['_created'] = V::get('_created', '', $histRow);
  4589. $histItem['_author'] = V::get('_author', '', $histRow);
  4590. $histItem['changes'] = array();
  4591. foreach ($visibleColsWithIds as $fldId => $fieldName) {
  4592. if (!array_key_exists($fieldName, (array)$histRow)) continue;
  4593. $value = V::get($fieldName, '', $histRow);
  4594. if ('N/S;' == $value) continue;
  4595. $changeItem = array();
  4596. $changeItem['fieldName'] = $fieldName;
  4597. $changeItem['acl_read'] = $acl->canReadObjectField($fieldName, $record);
  4598. if ($changeItem['acl_read']) {
  4599. $changeItem['value'] = V::get($fieldName, '', $histRow);
  4600. }
  4601. if ('the_geom' == $fieldName && $acl->canWriteObjectField($fieldName, $record)) {
  4602. $sourceName = $acl->getSourceName();
  4603. if ('default_db' == $sourceName && !empty($value)) {
  4604. $typeName = $acl->getName();
  4605. $idHist = V::get('ID', '', $histRow);
  4606. $changeItem['revert_function_url'] = Request::getPathUri() . "index.php?_route=ViewTableAjax&typeName=p5_{$sourceName}:{$typeName}&_task=revertFromHistAjax&ID={$id}&idHist={$idHist}&fieldName={$fieldName}";
  4607. $changeItem['revert_function_data'] = "ID={$id}&idHist={$idHist}&fieldName={$fieldName}";
  4608. }
  4609. }
  4610. $histItem['changes'][$fieldName] = $changeItem;
  4611. }
  4612. $jsonResponse['rows'][] = $histItem;
  4613. }
  4614. return $jsonResponse;
  4615. }
  4616. public function ajaxFileUpload($args) {
  4617. $id = V::get('ID', 0, $args, 'int');
  4618. if ($id <= 0) throw new HttpException("404", 404);
  4619. $dbID = $this->_acl->getDB();
  4620. $db = DB::getDB($dbID);
  4621. if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  4622. $record = $this->_acl->getItem($id);
  4623. if (!$record) throw new HttpException("No item ID({$rowID})", 404);
  4624. if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  4625. if (!$this->_acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  4626. $tblName = $this->_acl->getName();
  4627. $confTblName = "{$tblName}_COLUMN";
  4628. $folderConfAll = FoldersConfig::getRawData();
  4629. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
  4630. $folderConf = FoldersConfig::getAll($confTblName);
  4631. $uploader = new FileUploader($confTblName, $record);
  4632. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
  4633. $uploader->findFolder();
  4634. $errorMsg = '';
  4635. if (!empty($args['SCANS_COLUMN_ADD'])) {
  4636. $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
  4637. }
  4638. else {
  4639. $uploaded = $uploader->tryUploadAjax($errorMsg);
  4640. }
  4641. $retJson = new stdClass();
  4642. if (!$uploaded) throw new Exception($errorMsg);
  4643. $uploadedFileName = '';
  4644. $uploadedFile = $uploader->getLastUploadedFile();
  4645. if ($uploadedFile) {
  4646. $uploadedFileName = explode('/', $uploadedFile);
  4647. $uploadedFileName = end($uploadedFileName);
  4648. }
  4649. //echo '{"type":"SUCCESS", "string": "Plik został poprawnie wgrany do odpowiedniego katalogu '.$uploadedFileName.'"}';
  4650. $retJson->type = 'SUCCESS';
  4651. $retJson->msg = "Plik został poprawnie wgrany do odpowiedniego katalogu {$uploadedFileName}";
  4652. if (!empty($uploadedFileName)) {
  4653. $sqlObj = new stdClass();
  4654. $sqlObj->ID = $record->ID;
  4655. $sqlObj->M_DIST_FILES = "Wgrano plik {$uploadedFileName}";
  4656. $db->UPDATE_OBJ($this->_tbl, $sqlObj);
  4657. }
  4658. return $retJson;
  4659. }
  4660. public function ajaxFileRemove($args) {
  4661. $id = V::get('ID', 0, $args, 'int');
  4662. if ($id <= 0) throw new HttpException("404", 404);
  4663. $filename = V::get('filename', '', $args);
  4664. if (empty($filename)) throw new Exception("Nie wybrano pliku do usunięcia");
  4665. $dbID = $this->_acl->getDB();
  4666. $db = DB::getDB($dbID);
  4667. if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  4668. $record = $this->_acl->getItem($id);
  4669. if (!$record) throw new HttpException("No item ID({$rowID})", 404);
  4670. if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  4671. if (!$this->_acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  4672. $tblName = $this->_acl->getName();
  4673. $confTblName = "{$tblName}_COLUMN";
  4674. $folderConfAll = FoldersConfig::getRawData();
  4675. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
  4676. $folderConf = FoldersConfig::getAll($confTblName);
  4677. $uploader = new FileUploader($confTblName, $record);
  4678. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
  4679. $uploader->findFolder();
  4680. $errorMsg = '';
  4681. $removed = $uploader->tryRemoveFromAjax($filename, $errorMsg);
  4682. if (!$removed) throw new Exception($errorMsg);
  4683. $retJson = new stdClass();
  4684. $retJson->type = 'SUCCESS';
  4685. $retJson->msg = 'Plik został poprawnie usunięty';
  4686. return $retJson;
  4687. }
  4688. public function ajaxFileList($args) {
  4689. $id = V::get('ID', 0, $args, 'int');
  4690. if ($id <= 0) throw new HttpException("404", 404);
  4691. $dbID = $this->_acl->getDB();
  4692. $db = DB::getDB($dbID);
  4693. if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  4694. $record = $this->_acl->getItem($id);
  4695. if (!$record) throw new HttpException("No item ID({$rowID})", 404);
  4696. if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  4697. $tblName = $this->_acl->getName();
  4698. $confTblName = "{$tblName}_COLUMN";
  4699. $folderConfAll = FoldersConfig::getRawData();
  4700. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
  4701. $folderConf = FoldersConfig::getAll($confTblName);
  4702. $uploader = new FileUploader($confTblName, $record);
  4703. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
  4704. $uploader->findFolder();
  4705. $mainFolder = $uploader->getDestFolder();
  4706. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4707. $localPath = $uploader->getLocalPath();
  4708. $folderWeb = $uploader->getFolderWeb();
  4709. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4710. return $jsonFiles;
  4711. }
  4712. private function ajaxFilePermsRefresh($args) {
  4713. $id = V::get('ID', 0, $args, 'int');
  4714. if ($id <= 0) throw new HttpException("Wrong param ID", 404);
  4715. $dbID = $this->_acl->getDB();
  4716. $db = DB::getDB($dbID);
  4717. if (!$db) throw new HttpException("No DB", 406);
  4718. $record = $this->_acl->getItem($id);
  4719. if (!$record) throw new Exception("No item ID({$rowID})", 404);
  4720. $tblName = $this->_acl->getName();
  4721. // TODO: SyncPermsCustomTables->getRecordTask($tbl, $id);
  4722. $sql_L_APPOITMENT_USER = V::get('L_APPOITMENT_USER', '', $record);
  4723. $sql_A_ADM_COMPANY = V::get('A_ADM_COMPANY', '', $record);
  4724. $sql_A_CLASSIFIED = V::get('A_CLASSIFIED', '', $record);
  4725. $mainDB = DB::getDB();
  4726. if ('IN7_MK_BAZA_DYSTRYBUCJI' == $tblName) {
  4727. $sql = "insert into `_SYNC_FILE_PERMS` (
  4728. `ID_PROJECT`,
  4729. `A_SYNCHRONIZED`
  4730. )
  4731. values (
  4732. '{$record->ID}'
  4733. , 0
  4734. )
  4735. ON DUPLICATE KEY UPDATE
  4736. `A_SYNCHRONIZED`=0
  4737. ";
  4738. }
  4739. else if ('IN7_DZIENNIK_KORESP' == $tblName) {
  4740. $sql = "insert into `_SYNC_FILE_PERMS` (
  4741. `ID_PROJECT`,
  4742. `A_SYNCHRONIZED`
  4743. )
  4744. values (
  4745. '{$record->ID_PROJECT}'
  4746. , 0
  4747. )
  4748. ON DUPLICATE KEY UPDATE
  4749. `A_SYNCHRONIZED`=0
  4750. ";
  4751. }
  4752. else {
  4753. $sql = "insert into `_SYNC_TABLE_FILE_PERMS` (
  4754. `TBL_NAME`,
  4755. `TBL_ID`,
  4756. `L_APPOITMENT_USER`,
  4757. `A_ADM_COMPANY`,
  4758. `A_CLASSIFIED`,
  4759. `A_SYNCHRONIZED`
  4760. )
  4761. values (
  4762. '{$tblName}'
  4763. , '{$id}'
  4764. , '{$sql_L_APPOITMENT_USER}'
  4765. , '{$sql_A_ADM_COMPANY}'
  4766. , '{$sql_A_CLASSIFIED}'
  4767. , 0
  4768. )
  4769. ON DUPLICATE KEY UPDATE
  4770. `A_SYNCHRONIZED`=0
  4771. ";
  4772. }
  4773. $res = $mainDB->query($sql);
  4774. if ($mainDB->has_errors()) {
  4775. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';
  4776. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($mainDB->get_errors());echo'</pre>';
  4777. throw new Exception("Nie udało się dodać zadania");
  4778. }
  4779. // TODO: this blocks browser ajax query
  4780. //$limit = 3;
  4781. //while ($limit--) {
  4782. // sleep(10);
  4783. // TODO: check if task is done
  4784. //}
  4785. $confTblName = "{$tblName}_COLUMN";
  4786. $folderConfAll = FoldersConfig::getRawData();
  4787. if (!FoldersConfig::hasConfig($confTblName)) {
  4788. throw new Exception("Brak danych konfiguracyjnych ({$tblName})", 404);
  4789. }
  4790. $folderConf = FoldersConfig::getAll($confTblName);
  4791. $uploader = new FileUploader($confTblName, $record);
  4792. if (!$uploader->setConfig($folderConf)) {
  4793. throw new Exception("Błąd danych konfiguracyjnych ({$tblName})", 404);
  4794. }
  4795. $uploader->findFolder();
  4796. $mainFolder = $uploader->getDestFolder();
  4797. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4798. $localPath = $uploader->getLocalPath();
  4799. $folderWeb = $uploader->getFolderWeb();
  4800. $jsonData = new stdClass();
  4801. $jsonData->msg = 'Zadanie dodane';
  4802. $jsonData->type = 'success';
  4803. $jsonData->files = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4804. return $jsonData;
  4805. }
  4806. private function sendAjaxFilesConnTblList($id, $args) {
  4807. header("Content-type: application/json");
  4808. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4809. $dbID = $this->_acl->getDB();
  4810. $db = DB::getDB($dbID);
  4811. if (!$db) {
  4812. header('HTTP/1.0 406 Not Acceptable');
  4813. echo 'No DB (' . $dbID . ')';
  4814. exit;
  4815. }
  4816. $record = $this->_acl->getItem($id);
  4817. if (!$record) {
  4818. header('HTTP/1.0 404 Not Found');
  4819. echo 'No item ID(' . $rowID . ')';
  4820. exit;
  4821. }
  4822. $connTblName = '';
  4823. $connTblID = V::get('connTblID', 0, $_REQUEST, 'int');
  4824. if ($connTblID <= 0) {
  4825. header('HTTP/1.0 406 Not Acceptable');
  4826. echo 'No conn Table ID';
  4827. exit;
  4828. }
  4829. $connTblTypespecials = $this->getConnectedTblTypespecials($connTblID);
  4830. if (empty($connTblTypespecials)) {
  4831. header('HTTP/1.0 406 Not Acceptable');
  4832. echo "No conn Table (ID={$connTblID})";
  4833. exit;
  4834. }
  4835. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">connTblTypespecials (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($connTblTypespecials);echo'</pre>';}
  4836. if(1) {
  4837. header('HTTP/1.0 404 Not Found');
  4838. echo 'TODO: ...';
  4839. exit;
  4840. }
  4841. $tblName = $this->_acl->getName();
  4842. $confTblName = "{$tblName}_COLUMN";
  4843. $folderConfAll = FoldersConfig::getRawData();
  4844. if (!FoldersConfig::hasConfig($confTblName)) {
  4845. header('HTTP/1.0 404 Not Found');
  4846. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
  4847. exit;
  4848. }
  4849. $folderConf = FoldersConfig::getAll($confTblName);
  4850. $uploader = new FileUploader($confTblName, $record);
  4851. if (!$uploader->setConfig($folderConf)) {
  4852. header('HTTP/1.0 404 Not Found');
  4853. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
  4854. exit;
  4855. }
  4856. $uploader->findFolder();
  4857. $mainFolder = $uploader->getDestFolder();
  4858. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4859. $localPath = $uploader->getLocalPath();
  4860. $folderWeb = $uploader->getFolderWeb();
  4861. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4862. echo json_encode($jsonFiles);
  4863. exit;
  4864. }
  4865. public function convertFileListToJson($files, $folderWeb, $localPath, $mainFolder) {
  4866. $jsonFiles = array();
  4867. if (!is_array($files) || empty($files)) {
  4868. return $jsonFiles;
  4869. }
  4870. sort($files);
  4871. foreach ($files as $vFilePath) {
  4872. $file = new stdClass();
  4873. $file->name = str_replace("{$localPath}/{$mainFolder}/", '', $vFilePath);
  4874. //$file->name = explode('/', $vFilePath);
  4875. //$file->name = end($file->name);
  4876. $file->size = filesize($vFilePath);
  4877. $file->sizeStr = V::humanFileSize($file->size);
  4878. $file->type = '';
  4879. $file->created = date("Y-m-d H:i:s", filectime($vFilePath));
  4880. $file->web = str_replace($localPath, $folderWeb, $vFilePath);
  4881. $jsonFiles[] = $file;
  4882. }
  4883. return $jsonFiles;
  4884. }
  4885. private function getConnectedTables() {
  4886. $connTbls = array();
  4887. return $connTbls;// TODO: OFF - hardlinki tworzone w bash_sync_perms.php
  4888. $fields = $this->_acl->getVirtualFieldListByIdZasob();
  4889. if (!empty($fields)) {
  4890. foreach ($fields as $vColID => $vCol) {
  4891. $typeSpecial = Typespecial::getInstance($vColID);
  4892. if ($typeSpecial) {
  4893. $tsConnTbls = $typeSpecial->getTblAliasList();
  4894. if (!empty($tsConnTbls)) {
  4895. foreach ($tsConnTbls as $kID => $vName) {
  4896. $connTbls[$kID] = $vName;
  4897. }
  4898. }
  4899. }
  4900. }
  4901. }
  4902. return $connTbls;
  4903. }
  4904. private function getConnectedTblTypespecials($connTblID) {
  4905. $connTblTypespecials = array();
  4906. $fields = $this->_acl->getVirtualFieldListByIdZasob();
  4907. if (!empty($fields)) {
  4908. foreach ($fields as $vColID => $vCol) {
  4909. $typeSpecial = Typespecial::getInstance($vColID);
  4910. if ($typeSpecial) {
  4911. $tsConnTbls = $typeSpecial->getTblAliasList();
  4912. if (array_key_exists($connTblID, $tsConnTbls)) {
  4913. $connTblTypespecials[] = $typeSpecial;
  4914. }
  4915. }
  4916. }
  4917. }
  4918. return $connTblTypespecials;
  4919. }
  4920. private function sendAjaxFiles($id, $args) {
  4921. header("Content-type: text/plain");
  4922. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4923. $dbID = $this->_acl->getDB();
  4924. $db = DB::getDB($dbID);
  4925. if (!$db) throw new HttpException("", 406);
  4926. $record = $this->_acl->getItem($id);
  4927. if (!$record) throw new HttpException("404: No item ID({$rowID})", 404);
  4928. if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  4929. $tblName = $this->_acl->getName();
  4930. $confTblName = "{$tblName}_COLUMN";
  4931. $folderConfAll = FoldersConfig::getRawData();
  4932. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych", 404);
  4933. $folderConf = FoldersConfig::getAll($confTblName);
  4934. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$folderConf (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($folderConf);echo'</pre>';
  4935. $uploader = new FileUploader($confTblName, $record);
  4936. $errMsg = '';
  4937. if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})" . '<br>' . "\n" . $errMsg, 404);
  4938. $uploader->findFolder();
  4939. if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">uploader (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($uploader);echo'</pre>'; }
  4940. $mainFolder = $uploader->getDestFolder();
  4941. if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">mainFolder (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($mainFolder);echo'</pre>'; }
  4942. if (!$mainFolder) {
  4943. $destFolderPath = $uploader->getDestLocalPath(true);
  4944. $folderCreated = $uploader->tryCreateDestFolder($destFolderPath);
  4945. if ($folderCreated) {
  4946. //UI::alert('info', "Utworzono katalog");
  4947. $uploader->findFolder();
  4948. $mainFolder = $uploader->getDestFolder();
  4949. } else {
  4950. UI::alert('warning', "Nie udało się utworzyć katalogu");
  4951. }
  4952. }
  4953. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4954. if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">files (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($files);echo'</pre>'; }
  4955. $sharePoint = V::get('share_point', null, $folderConf);
  4956. if ($sharePoint) {
  4957. if ('//' == substr($mainFolder, 0, 2)) {
  4958. $sharePoint = FoldersConfig::getNfsOsPath() . "{$mainFolder}";
  4959. } else {
  4960. $sharePoint = FoldersConfig::getNfsOsPath() . "{$sharePoint}/{$mainFolder}";
  4961. }
  4962. }
  4963. $localPath = $uploader->getLocalPath();
  4964. $folderWeb = $uploader->getFolderWeb();
  4965. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4966. if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">jsonFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($jsonFiles);echo'</pre>'; }
  4967. $folderSkanyConf = FoldersConfig::getAll('SCANS_COLUMN');
  4968. $skanyLocalPath = V::get('mount_point', null, $folderSkanyConf);
  4969. $skanySharePoint = V::get('share_point', null, $folderSkanyConf);
  4970. $skanyFolderWeb = V::get('www_share_point', null, $folderSkanyConf);
  4971. $skanyFiles = $uploader->getFilesFromSkany($folderSkanyConf, false);
  4972. sort($skanyFiles);
  4973. $fileTypes = FoldersConfig::getAll('m_dist_files_types');
  4974. $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('files', 'cp'), true);
  4975. $fileIndexField = V::get('DEST_FILE_INDEX_FIELD', 'ID', $folderConf);
  4976. $fileIndex = V::get($fileIndexField, $record->ID, $record);
  4977. ?>
  4978. <script src="stuff/jquery.form.js"></script>
  4979. <div class="container">
  4980. <h4 style="margin:20px 0 3px 0;">Pliki w katalogu
  4981. <?php if ($sharePoint) : ?>
  4982. <a href="<?php echo $sharePoint; ?>"><span class="glyphicon glyphicon-folder-open"></span><code><?php echo $mainFolder; ?></code></a>
  4983. <?php else : ?>
  4984. <code><?php echo $mainFolder; ?></code>
  4985. <?php endif; ?>
  4986. <span class="pull-right valign-btns-bottom">
  4987. <span id="FILES_LIST_ACTIONS_<?php echo $this->_htmlID; ?>"></span>
  4988. <?php echo $rowFunctionsOut; ?>
  4989. </span>
  4990. </h4>
  4991. <div style="clear:both; max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">
  4992. <table class="table table-bordered table-hover">
  4993. <colgroup>
  4994. <col style="">
  4995. <col style="width:30px;">
  4996. <?php if ($sharePoint) : ?>
  4997. <col style="width:30px;">
  4998. <?php endif; ?>
  4999. <col style="width:80px;">
  5000. <col style="width:140px;">
  5001. </colgroup>
  5002. <tbody id="FILES_LIST_<?php echo $this->_htmlID; ?>">
  5003. <?php if (empty($mainFolder)) : ?>
  5004. <tr>
  5005. <td colspan="5">
  5006. <div class="alert alert-warning">
  5007. <h4>Brak folderu!</h4>
  5008. Folder dla tego rekordu nie został utworzony.
  5009. </div>
  5010. </td>
  5011. </tr>
  5012. <?php elseif (empty($files)) : ?>
  5013. <tr>
  5014. <td colspan="5">
  5015. <div class="alert alert-info">
  5016. <h4>Brak plików</h4>
  5017. </div>
  5018. </td>
  5019. </tr>
  5020. <?php endif; ?>
  5021. </tbody>
  5022. </table>
  5023. </div>
  5024. <br>
  5025. <br>
  5026. <?php if (!$this->_acl->canWriteRecord($record)) : ?>
  5027. <div class="alert alert-warning">
  5028. Brak uprawnień do dodawania plików
  5029. </div>
  5030. <?php else : ?>
  5031. <div id="FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>"></div>
  5032. <form enctype="multipart/form-data" method="POST" action="" id="FILES_FRM_<?php echo $this->_htmlID; ?>" class="form-inline">
  5033. <input type="hidden" name="M_DIST_UPLOAD_SOURCE" value="local">
  5034. <ul id="FILES_TAB_<?php echo $this->_htmlID; ?>" class="nav nav-tabs" style="margin:0;">
  5035. <li class="active"><a href="#local" data-toggle="local">Wybierz plik lokalny</a></li>
  5036. <li><a href="#scan" data-toggle="scan">Wybierz plik ze skanów</a></li>
  5037. </ul>
  5038. <div id="myTabContent" class="tab-content">
  5039. <div class="tab-pane fade in active" id="local" style="text-align: center;">
  5040. <input name="M_DIST_FILES_NAME" type="file" size="60" class="field-upload btn" style="width:86%;margin:10px auto;padding:10px 4%;background:#eee;text-align:center;" ondragover="this.style.backgroundColor='#D9EDF7'" ondragleave="this.style.backgroundColor='#eee'" ondragend="this.style.backgroundColor='#eee'">
  5041. </div>
  5042. <div class="tab-pane fade" id="scan">
  5043. <?php if (empty($skanyFiles)) : ?>
  5044. <div class="alert alert-info">
  5045. <h4>Brak plików</h4>
  5046. <?php if(!empty($skanyFolderWeb)) echo "skonfiguruj urządzenie biurowe aby wysyłało skany na ftp://skaner:(h*a*s*l*o)@".$_SERVER['SERVER_NAME']." <br> lub <a href=".FoldersConfig::getNfsOsPath().$skanySharePoint.">".FoldersConfig::getNfsOsPath().$skanySharePoint."</a>"; ?>
  5047. </div>
  5048. <?php else : ?>
  5049. <div style="max-height:150px; overflow:auto; border-bottom:1px solid #ddd;">
  5050. <table class="table table-bordered table-hover">
  5051. <colgroup>
  5052. <col style="width:30px;">
  5053. <col style="">
  5054. <col style="width:30px;">
  5055. <col style="width:80px;">
  5056. <col style="width:140px;">
  5057. </colgroup>
  5058. <tbody>
  5059. <?php foreach ($skanyFiles as $vFilePath) : ?>
  5060. <tr>
  5061. <?php
  5062. $vFileName = explode('/', $vFilePath);
  5063. $vFileName = end($vFileName);
  5064. $vFileSize = filesize($vFilePath);
  5065. $vFileSizeOut = V::humanFileSize($vFileSize);
  5066. ?>
  5067. <td><input style="margin:0" type="radio" name="SCANS_COLUMN_ADD" value="<?php echo $vFileName; ?>"></td>
  5068. <td><div style="overflow:hidden; white-space:nowrap" title="<?php echo $vFileName; ?>"><?php echo $vFileName; ?></div></td>
  5069. <td style="white-space:nowrap; text-align:center"><a href="<?php echo str_replace($skanyLocalPath, $skanyFolderWeb, $vFilePath); ?>" target="_blank" class="glyphicon glyphicon-download-alt"></a></td>
  5070. <td style="white-space:nowrap; text-align:right"><?php echo $vFileSizeOut; ?></td>
  5071. <td style="white-space:nowrap"><?php echo date("Y-m-d H:i:s", filectime($vFilePath)); ?></td>
  5072. </tr>
  5073. <?php endforeach; ?>
  5074. </tbody>
  5075. </table>
  5076. </div>
  5077. <?php endif; ?>
  5078. </div>
  5079. </div>
  5080. <br>
  5081. <h4>Ustal nazwę pliku zgodną z obiegiem dokumentów
  5082. <?php //TODO: link do procesu o obiegu dokumentów <i class="glyphicon glyphicon-question-sign" style="cursor:help" title="działa w nowszych przeglądarkach jak Firefox, Chrome"></i> ?>
  5083. </h4>
  5084. <table style="width:100%" class="table table-bordered">
  5085. <tr>
  5086. <th>Nr</th>
  5087. <th>Typ</th>
  5088. <th style="width:40%;">Opis <i class="glyphicon glyphicon-question-sign" title="kogo dotyczy / czego / sprawa / nazwa_firmy itp"></i></th>
  5089. <th style="width:16%">Data wersji</th>
  5090. <th style="width:12%">Numer wersji</th>
  5091. </tr>
  5092. <tr>
  5093. <td>
  5094. <?php echo $fileIndex; ?>
  5095. </td>
  5096. <td>
  5097. <select class="form-control" name="M_DIST_FILES_TYPE">
  5098. <?php foreach ($fileTypes as $kType => $vLabel) : ?>
  5099. <option value="<?php echo $kType; ?>"<?php if ($kType == 'TODO') { echo ' selected="selected"'; } ?> ><?php echo $vLabel; ?></option>
  5100. <?php endforeach; ?>
  5101. </select>
  5102. <br>
  5103. <label class="checkbox">
  5104. <input type="checkbox" name="M_DIST_FILES_TYPE_AUTO">
  5105. Wykrycie automatyczne typu z wysylanego pliku
  5106. </label>
  5107. <label class="checkbox">
  5108. <input type="checkbox" name="M_DIST_FILES_TEMP">
  5109. Plik tymczasowy / roboczy / nieoficjalny (_TEMP)
  5110. </label>
  5111. </td>
  5112. <td>
  5113. <input class="form-control" style="width:100%" type="text" name="M_DIST_FILES_DESCRIPTION" value="" maxlength="50">
  5114. <br><label>jeśli nie zostanie podany to zostanie automatycznie wygenerowany na podstawie nazwy pliku wysyłanego</label>
  5115. </td>
  5116. <td>
  5117. <div class="input-group">
  5118. <input name="M_DIST_FILES_DATE" type="text" value="<?php echo date('Y-m-d');?>" class="se_type-date form-control" data-format="yyyy-MM-dd" maxlength="10"><span class="input-group-addon">
  5119. <span class="glyphicon glyphicon-calendar"></span>
  5120. </span>
  5121. </div>
  5122. <!--
  5123. <input class="form-control" type="date" name="M_DIST_FILES_DATE" value="<?php echo date('Y-m-d');?>" maxlength="10">
  5124. -->
  5125. <br><label>jeśli nie zostanie podana to zostanie ustawiona na dzisiaj (<?php echo date('Y-m-d');?>)</label>
  5126. </td>
  5127. <td>
  5128. <input class="form-control" style="width:100%" type="number" name="M_DIST_FILES_VERSION">
  5129. <br>
  5130. <label class="checkbox">
  5131. <input type="checkbox" name="M_DIST_FILES_VERSION_AUTO">
  5132. Automatycznie dodaj wersje
  5133. </label>
  5134. </td>
  5135. </tr>
  5136. <tr>
  5137. <td colspan="5">
  5138. <div id="FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>"></div>
  5139. <p>
  5140. <input type="submit" value="Wyślij" class="btn btn-primary"> wybrany plik do folderu:
  5141. </p>
  5142. <p>
  5143. <code><b><?php echo $uploader->getDestPathShare(true); ?></b></code>
  5144. <br><i style="color:#777">(Jeśli folder nie istnieje to zostanie utworzony automatycznie)</i>
  5145. </p>
  5146. </td>
  5147. </tr>
  5148. </table>
  5149. </form>
  5150. </div>
  5151. <?php endif; ?>
  5152. <script>
  5153. function fileListUpdateAjax<?php echo $this->_htmlID; ?>() {
  5154. var postData = {};
  5155. jQuery.ajax({
  5156. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES_LIST&ID=<?php echo $record->ID; ?>',
  5157. type: 'POST',
  5158. //dataType: 'json',
  5159. //contentType: "application/json; charset=utf-8",
  5160. data: postData,
  5161. success: function(data) {
  5162. fileListUpdate<?php echo $this->_htmlID; ?>(data);
  5163. },
  5164. error: function(jhr, textStatus, errorThrown) {
  5165. console.log('request error: ', errorThrown, ' textStatus: ', textStatus);
  5166. }
  5167. });
  5168. }
  5169. function fileListUpdate<?php echo $this->_htmlID; ?>(fileListJson) {
  5170. var fileListNode = jQuery('#FILES_LIST_<?php echo $this->_htmlID; ?>');
  5171. fileListNode.empty();
  5172. fileListJson.map(function(file){
  5173. var node = $('<tr></tr>');
  5174. <?php if (!$this->_acl->canWriteRecord($record)) : ?>
  5175. var fFun = null;
  5176. <?php else : ?>
  5177. var fFun = $('<i class="glyphicon glyphicon-remove" style="cursor:pointer" data-filename="' + file.name + '"></i>');
  5178. <?php endif; ?>
  5179. var fNameCell = $('<td style="overflow: hidden;"></td>');
  5180. var fName = $('<div style="overflow:hidden; white-space:nowrap;" title="' + file.name + '"></div>');
  5181. if (fFun) fName.append(fFun);
  5182. fName.append(file.name);
  5183. fName.appendTo(fNameCell);
  5184. node.append(fNameCell);
  5185. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:center;">' + '<a href="' + file.web + '" target="_blank" class="glyphicon glyphicon-download-alt"></a>' + '</td>');
  5186. <?php if ($sharePoint) : ?>
  5187. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:center;">' + '<a href="<?php echo $sharePoint; ?>/' + file.name + '" target="_blank" class="glyphicon glyphicon-folder-open"></a>' + '</td>');
  5188. <?php endif; ?>
  5189. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:right;">' + file.sizeStr + '</td>');
  5190. node.append('<td style="overflow:hidden; white-space:nowrap;">' + file.created + '</td>');
  5191. node.appendTo(fileListNode);
  5192. if (fFun) {
  5193. $(fFun).click(function(e){
  5194. var n = $(e.target);
  5195. var fname= n.data('filename');
  5196. if (!fname) {
  5197. return false;
  5198. }
  5199. if (confirm('Czy jesteś pewien, że chcesz usunąć plik o nazwie ' + fname + '?')) {
  5200. var postData = {filename: fname};
  5201. jQuery.ajax({
  5202. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILE_REMOVE&ID=<?php echo $record->ID; ?>',
  5203. type: 'POST',
  5204. //dataType: 'json',
  5205. //contentType: "application/json; charset=utf-8",
  5206. data: postData,
  5207. success: function(data) {
  5208. if (data && data.type) {
  5209. if (data.type == 'SUCCESS') {
  5210. n.parents('tr').remove();
  5211. //console.log('TODO: SUCCESS msg: ', data.msg);
  5212. }
  5213. else if (data.type == 'error') {
  5214. console.log('TODO: ERROR msg: ', data.msg);
  5215. }
  5216. } else {
  5217. console.log('TODO: ??? data: ', data);
  5218. }
  5219. },
  5220. error: function(jhr, textStatus, errorThrown) {
  5221. console.log('rm error: ', errorThrown, ' textStatus: ', textStatus);
  5222. }
  5223. });
  5224. }
  5225. });
  5226. }
  5227. });
  5228. }
  5229. function connTblListUpdateAjax<?php echo $this->_htmlID; ?>(connTblID) {
  5230. var postData = {};
  5231. // clear current file list
  5232. jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list').empty();
  5233. jQuery.ajax({
  5234. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES_CONN_TBL_LIST&ID=<?php echo $record->ID; ?>&connTblID=' + connTblID,
  5235. type: 'POST',
  5236. //dataType: 'json',
  5237. //contentType: "application/json; charset=utf-8",
  5238. data: postData,
  5239. success: function(data) {
  5240. connTblListUpdate<?php echo $this->_htmlID; ?>(data);
  5241. },
  5242. error: function(jqXHR, textStatus, errorThrown) {
  5243. var txt = jqXHR.responseText || 'Error';
  5244. jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list').html('<tr><td colspan="6"><div class="alert alert-danger">' + txt + '</div></td></tr>');
  5245. if (priv.options.debug) console.log('connTblListUpdateAjax error: ', errorThrown, ' textStatus: ', textStatus);
  5246. }
  5247. });
  5248. }
  5249. function connTblListUpdate<?php echo $this->_htmlID; ?>(fileListJson) {
  5250. var fileListNode = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list');
  5251. fileListNode.empty();
  5252. fileListJson.map(function(file){
  5253. var node = $('<tr></tr>');
  5254. var fNameCell = $('<td style="overflow: hidden;"></td>');
  5255. var fName = $('<div style="overflow:hidden; white-space:nowrap;" title="' + file.name + '"></div>');
  5256. fName.append(file.name);
  5257. fName.appendTo(fNameCell);
  5258. node.append(fNameCell);
  5259. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:center;">' + '<a href="' + file.web + '" target="_blank" class="glyphicon glyphicon-download-alt"></a>' + '</td>');
  5260. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:right;">' + file.sizeStr + '</td>');
  5261. node.append('<td style="overflow:hidden; white-space:nowrap;">' + file.created + '</td>');
  5262. node.appendTo(fileListNode);
  5263. });
  5264. }
  5265. function fileListActions<?php echo $this->_htmlID; ?>() {
  5266. var filePermsReload = jQuery('#FILES_LIST_ACTIONS_<?php echo $this->_htmlID; ?>');
  5267. var btnReload = jQuery('<button class="btn-link btn-sm" title="odśwież uprawnienia do plików"><span class="glyphicon glyphicon-refresh"></span>Odśwież</button>');
  5268. btnReload.on('click', function(e) {
  5269. //console.log('TODO: click reload perms...');
  5270. function notifyAjaxCallback(data) {
  5271. var notify = {};
  5272. notify.type = (data && data.type)? data.type : '';
  5273. notify.msg = (data && data.msg)? data.msg : '';
  5274. switch (notify.type) {
  5275. case 'success':
  5276. if (!notify.msg) notify.msg = 'OK';
  5277. break;
  5278. case 'info':
  5279. if (!notify.msg) notify.msg = '';
  5280. break;
  5281. case 'error':
  5282. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  5283. break;
  5284. case 'warning':
  5285. notify.type = 'warn';
  5286. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  5287. break;
  5288. default:
  5289. notify.msg = 'Nieznany błąd';
  5290. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  5291. notify.type = '';
  5292. }
  5293. jQuery.notify(notify.msg, notify.type);
  5294. }
  5295. var reqData = {};
  5296. jQuery.ajax({
  5297. data: reqData,
  5298. dataType: 'json',
  5299. type: "GET",
  5300. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=filePermsRefresh&ID=<?php echo $record->ID; ?>',
  5301. })
  5302. .done(function(data, textStatus, jqXHR){
  5303. notifyAjaxCallback(data);
  5304. if (data && data.files) {
  5305. fileListUpdate<?php echo $this->_htmlID; ?>(data.files);
  5306. }
  5307. })
  5308. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  5309. if (jqXHR.responseJSON) {
  5310. notifyAjaxCallback(jqXHR.responseJSON);
  5311. }
  5312. else {
  5313. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  5314. if (jqXHR.status == 404) {
  5315. jQuery.notify(jqXHR.responseText, 'error');
  5316. } else {
  5317. jQuery.notify(jqXHR.responseText, 'warn');
  5318. }
  5319. }
  5320. });
  5321. });
  5322. filePermsReload.append(btnReload);
  5323. }
  5324. jQuery(document).ready(function(){
  5325. $('#FILES_TAB_<?php echo $this->_htmlID; ?> a').click(function(e) {
  5326. e.preventDefault();
  5327. $(this).tab('show');
  5328. })
  5329. .on('shown.bs.tab', function(e) {
  5330. var fileSource = $(e.target).data('toggle')
  5331. , frm = jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>').get(0);
  5332. if (frm['M_DIST_UPLOAD_SOURCE']) {
  5333. frm['M_DIST_UPLOAD_SOURCE'].value = fileSource;
  5334. }
  5335. })
  5336. jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>').ajaxForm({
  5337. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES_UPLOAD&ID=<?php echo $record->ID; ?>',
  5338. beforeSubmit: function(args, $form, options) {
  5339. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit()...');
  5340. var argsMap = [];
  5341. args.map(function(v, k) {
  5342. argsMap[v.name] = v.value;
  5343. });
  5344. // validate
  5345. if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'local') {
  5346. if (!argsMap['M_DIST_FILES_NAME']) {
  5347. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit() M_DIST_UPLOAD_SOURCE=local && !M_DIST_FILES_NAME');
  5348. return false;
  5349. }
  5350. }
  5351. else if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'scan') {
  5352. if (!argsMap['SCANS_COLUMN_ADD']) {
  5353. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit() M_DIST_UPLOAD_SOURCE=scan && !SCANS_COLUMN_ADD');
  5354. return false;
  5355. }
  5356. }
  5357. else {
  5358. return false;
  5359. }
  5360. var $out = $('#FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>');
  5361. $out.html('Wysyłanie...');
  5362. },
  5363. success: function(data) {
  5364. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->success()...');
  5365. var $out = $('#FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>');
  5366. var btnClose = '<button type="button" class="close" data-dismiss="alert"><i class="glyphicon glyphicon-remove"></i></button>';
  5367. if (typeof data == 'object') {
  5368. if (data.type == 'error') {
  5369. $out.html('<div class="alert alert-danger">' + btnClose + data.msg + '</div>');
  5370. } else if (data.type == 'SUCCESS') {
  5371. $out.html('<div class="alert alert-success">' + btnClose + data.msg + '</div>');
  5372. fileListUpdateAjax<?php echo $this->_htmlID; ?>();
  5373. // TODO: scanFileListUpdateAjax...
  5374. }
  5375. } else {
  5376. if (data.substr(0, 7) == 'WARNING') {
  5377. data = data.substr(7);
  5378. $out.html('<div class="alert alert-warning">' + btnClose + data + '</div>');
  5379. } else if (data.substr(0, 5) == 'error') {
  5380. data = data.substr(5);
  5381. $out.html('<div class="alert alert-danger">' + btnClose + data + '</div>');
  5382. } else if (data.substr(0, 7) == 'SUCCESS') {
  5383. data = data.substr(7);
  5384. $out.html('<div class="alert alert-success">' + btnClose + data + '</div>');
  5385. fileListUpdateAjax<?php echo $this->_htmlID; ?>();
  5386. // TODO: scanFileListUpdateAjax...
  5387. } else if (data.substr(0, 4) == 'INFO') {
  5388. data = data.substr(4);
  5389. $out.html('<div class="alert alert-info">' + btnClose + data + '</div>');
  5390. }
  5391. }
  5392. }
  5393. });
  5394. fileListActions<?php echo $this->_htmlID; ?>();
  5395. var fileList = <?php echo json_encode($jsonFiles); ?>;
  5396. fileListUpdate<?php echo $this->_htmlID; ?>(fileList);
  5397. var connTbls = <?php echo json_encode($this->getConnectedTables()); ?>;
  5398. if (connTbls) {
  5399. var connTblsOut = '';
  5400. for(var key in connTbls) {
  5401. connTblsOut += '<button class="btn btn-sm btn-default conn-tbl-load" data-zasobid="' + key + '">' + connTbls[key] + '</button>';
  5402. };
  5403. if (connTblsOut) {
  5404. connTblsOut = 'Pliki w powiązanych tabelach: <div class="btn-group">' + connTblsOut + '</div>';
  5405. connTblsOut += '<div style="max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">' +
  5406. '<table class="table table-bordered table-hover">' +
  5407. '<colgroup>' +
  5408. '<col style="">' +
  5409. '<col style="width:30px;">' +
  5410. <?php if ($sharePoint) : ?>
  5411. '<col style="width:30px;">' +
  5412. <?php endif; ?>
  5413. '<col style="width:80px;">' +
  5414. '<col style="width:140px;">' +
  5415. '</colgroup>' +
  5416. '<tbody class="files-list">' +
  5417. '</tbody>' +
  5418. '</table>' +
  5419. '</div>';
  5420. var _connTblsWrap = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>');
  5421. _connTblsWrap.css('marginBottom', '26px');
  5422. _connTblsWrap.html(connTblsOut);
  5423. _connTblsWrap.find('.conn-tbl-load').each(function(){
  5424. jQuery(this).click(function(e){
  5425. var tblID = jQuery(e.target).data('zasobid');
  5426. if (tblID) {
  5427. connTblListUpdateAjax<?php echo $this->_htmlID; ?>(tblID);
  5428. }// TODO: else show error
  5429. });
  5430. });
  5431. }
  5432. }
  5433. initDateTimePicker(jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>'));
  5434. });
  5435. </script>
  5436. <?php
  5437. exit;
  5438. }
  5439. private function sendTypeSpecial($fldID, $args) {
  5440. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  5441. header("Content-type: application/json");
  5442. $fldName = '';
  5443. $fld = $this->_acl->getField($fldID);
  5444. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fld('.$fldID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($fld);echo'</pre>';}
  5445. if (!$fld) {
  5446. // 404
  5447. } else {
  5448. $fldName = $fld['name'];
  5449. }
  5450. $jsonData = array();
  5451. $typeSpecial = Typespecial::getInstance($fldID, $fldName);
  5452. if ($typeSpecial) {
  5453. $query = V::get('q', '', $_REQUEST);
  5454. $rawRows = null;
  5455. $rows = $typeSpecial->getValuesWithExports($query);
  5456. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">rows('.$query.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($rows);echo'</pre>';}
  5457. foreach ($rows as $kID => $vItem) {
  5458. $itemJson = new stdClass();
  5459. $itemJson->id = $vItem->id;
  5460. $itemJson->name = $vItem->param_out;
  5461. if (!empty($vItem->exports)) {
  5462. $itemJson->exports = $vItem->exports;
  5463. }
  5464. if (!empty($vItem->{'$order'})) {
  5465. $itemJson->{'$order'} = $vItem->{'$order'};
  5466. }
  5467. $jsonData[] = $itemJson;
  5468. }
  5469. }
  5470. /*
  5471. MENU_INIT:VIEWTABLE_AJAX
  5472. ZASOB_ID:1188
  5473. _task:TYPESPECIAL
  5474. fldID:3866
  5475. Form Dataview sourceview URL encoded
  5476. q:te
  5477. */
  5478. echo json_encode($jsonData);
  5479. exit;
  5480. }
  5481. public function ajaxData($args) {// executed from url: "{$this->syncUrl"&_hash={$this->_htmlID}&_task=loadDataAjax"
  5482. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  5483. $acl = $this->_acl;
  5484. $pageSize = V::get('pageSize', $this->_pageSize, $args, 'int');
  5485. $page = V::get('page', 0, $args, 'int');
  5486. $currSortCol = V::get('currSortCol', '', $args);
  5487. $currSortFlip = V::get('currSortFlip', '', $args);
  5488. if ($page > 0) {
  5489. $page -= 1;
  5490. }
  5491. $params = array();
  5492. $params['limit'] = $pageSize;
  5493. $params['limitstart'] = $page * $params['limit'];
  5494. $params['order_by'] = ($currSortCol)? $currSortCol : '';
  5495. $params['order_dir'] = $currSortFlip;
  5496. foreach ($args as $k => $v) {
  5497. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  5498. $params[$k] = $v;
  5499. }
  5500. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  5501. $params[$k] = $v;
  5502. }
  5503. }
  5504. $filters = new stdClass();
  5505. $filters->currSortCol = $currSortCol;
  5506. $filters->currSortFlip = $currSortFlip;
  5507. foreach ($args as $k => $v) {
  5508. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  5509. $filters->{$k} = $v;
  5510. }
  5511. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  5512. $filters->{$k} = $v;
  5513. }
  5514. }
  5515. $this->setFilters($filters);
  5516. $vCols = $acl->getVirtualFieldListByIdZasob();
  5517. if (!empty($vCols)) {
  5518. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">vCols (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCols);echo'</pre>';}
  5519. }
  5520. $visibleCols = $acl->getVisibleFieldListByIdZasob();
  5521. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">visibleCols (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($visibleCols);echo'</pre>';}
  5522. $jsonData = new stdClass();
  5523. $jsonData->page = $page + 1;
  5524. $jsonData->pageSize = $pageSize;
  5525. $jsonData->filters = $filters;
  5526. $jsonData->cols = new stdClass();
  5527. $jsonData->uniqueCol = $acl->getPrimaryKeyField();
  5528. $ind = 0;
  5529. foreach ($visibleCols as $fieldID => $col) {
  5530. $ind++;
  5531. $columnConfig = (object)array('index'=>$ind);
  5532. if (in_array($col, array('A_STATUS','A_STATUS_CURRENT','A_SERVICES_STATUS_CURRENT'))) {
  5533. $columnConfig->format = '<div class="cell-A_STATUS-{0}">{0}</div>';
  5534. }
  5535. else if (in_array($col, array('Status'))) {
  5536. // Ahmes problems Status colors
  5537. $columnConfig->format = '<div class="cell-Status-{0}">{0}</div>';
  5538. }
  5539. else if ($acl->isGeomField($col)) {
  5540. $columnConfig->type = 'geom';
  5541. }
  5542. if ('' !== ($label = $acl->getFieldLabel($col))) {
  5543. $columnConfig->friendly = $label;
  5544. }
  5545. $colType = $acl->getFieldType($col);
  5546. if ($colType) {// @see MarkTableAjaxFilterColType
  5547. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">field('.$col.') $colType (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($colType);echo'</pre>';}
  5548. if ($colType['type'] == 'date') {
  5549. //$columnConfig->type = 'date';// TODO: require datetimepicker
  5550. }
  5551. if (!empty($colType['simpleType'])) $columnConfig->type = $colType['simpleType'];
  5552. } else {// typespecial - no type
  5553. $columnConfig->type = 'special';
  5554. }
  5555. $columnConfig->xsdType = $acl->getXsdFieldType($col);
  5556. if ($columnConfig->xsdType) {
  5557. $ex = explode(":", $columnConfig->xsdType);
  5558. switch ($ex[0]) {
  5559. case 'ref':
  5560. case 'alias_ref':
  5561. if (3 != count($ex)) throw new HttpException("Schema Error for field({$col}) xsdType({$columnConfig->xsdType})", 500);
  5562. $columnConfig->type = 'ref';
  5563. $columnConfig->xsdRefUri = Api_WfsNs::getNsUri($ex[1]);
  5564. $columnConfig->xsdRefType = $ex[2];
  5565. $columnConfig->xsdRefNsPrefix = $ex[1];
  5566. break;
  5567. case 'xsd':
  5568. switch ($ex[1]) {
  5569. case 'string': $columnConfig->type = 'string'; break;
  5570. case 'ind': $columnConfig->type = 'number'; break;// TODO: bug 'ind'?
  5571. }
  5572. break;
  5573. case 'p5':
  5574. switch ($ex[1]) {
  5575. case 'alias': {
  5576. $format = $acl->getXsdFieldParam($col, 'format');
  5577. if ($format) $columnConfig->format = $format;
  5578. } break;
  5579. case 'string': {
  5580. $columnConfig->type = 'p5:string';
  5581. $columnConfig->formatByValue = $acl->getXsdFieldParam($col, 'formatByValue');
  5582. } break;
  5583. }
  5584. break;
  5585. }
  5586. }
  5587. $typeSpecial = Typespecial::getInstance($fieldID, $col);
  5588. if ($typeSpecial) {
  5589. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">typeSpecial (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
  5590. $columnConfig->_tsRetId = $typeSpecial->getReturnId();
  5591. if ($columnConfig->_tsRetId == 0) {
  5592. $tsParamOut = V::get('param_out', null, $typeSpecial);
  5593. if ($tsParamOut) {
  5594. $tsFormat = V::get('format', null, $tsParamOut);
  5595. $tsValues = V::get('values', null, $tsParamOut);
  5596. $tsAliases = V::get('alias', null, $tsParamOut);
  5597. if (false !== strpos($tsFormat, '<a') && !empty($tsValues) && !empty($tsAliases)) {
  5598. $tsAliasMap = array();
  5599. /* [values] => Array([ID] => 1467), [alias] => Array([1467] => ID) */
  5600. $bugTsColsNotVisible = array();
  5601. foreach ($tsValues as $kVarName => $vIdZasob) {
  5602. if (array_key_exists($vIdZasob, $tsAliases)) {
  5603. $tsAliasMap[$kVarName] = $tsAliases[$vIdZasob];
  5604. } else {
  5605. $bugTsColsNotVisible[] = "noAliasFor {$vIdZasob}";
  5606. }
  5607. if (!array_key_exists($vIdZasob, $visibleCols)) {
  5608. $bugTsColsNotVisible[] = $vIdZasob;
  5609. }
  5610. }
  5611. if (empty($bugTsColsNotVisible)) {
  5612. $tsSimpleLink = new stdClass();
  5613. $tsSimpleLink->format = $tsFormat;
  5614. $tsSimpleLink->aliasMap = $tsAliasMap;
  5615. $columnConfig->_tsSimpleLink = $tsSimpleLink;
  5616. $columnConfig->type = 'simpleLink';
  5617. } else {
  5618. $columnConfig->_tsSimpleLinkBug = $bugTsColsNotVisible;
  5619. }
  5620. }
  5621. }
  5622. }
  5623. }
  5624. if ($columnConfig->xsdType) {// fix fields type p5:typeSpecialSimpleLink (previously defined by Typespecial)
  5625. switch ($columnConfig->xsdType) {
  5626. case 'p5:typeSpecialSimpleLink': {
  5627. $columnConfig->type = 'simpleLink';
  5628. $columnConfig->_tsRetId = 0;
  5629. $columnConfig->_tsSimpleLink = new stdClass();
  5630. $columnConfig->_tsSimpleLink->format = $acl->getXsdFieldParam($col, 'format');
  5631. $columnConfig->_tsSimpleLink->aliasMap = $acl->getXsdFieldParam($col, 'aliasMap');
  5632. } break;
  5633. }
  5634. }
  5635. // @see ajaxHiddenColsSave
  5636. if (UserProfile::isHiddenColumn($acl->getID(), $fieldID)) {
  5637. $columnConfig->hidden = true;
  5638. }
  5639. $columnConfig->description = $acl->getFieldOpis($col);
  5640. $jsonData->cols->{$col} = $columnConfig;
  5641. }
  5642. $jsonData->rows = array();
  5643. $queryFeatures = $acl->buildQuery($params);
  5644. $jsonData->total = $queryFeatures->getTotal();
  5645. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">get_total (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($jsonData->total);echo'</pre>';}
  5646. $listItems = $queryFeatures->getItems();
  5647. $primaryKeyField = $acl->getPrimaryKeyField();
  5648. $items = []; foreach ($listItems as $item) $items[ $item[$primaryKeyField] ] = $item;
  5649. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">items (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($items);echo'</pre>';}
  5650. // TODO: add virtual data by Typespecial
  5651. if (!empty($vCols) && !empty($items)) {
  5652. foreach ($vCols as $vColID => $vCol) {
  5653. $colType = $acl->getFieldTypeById($vColID);
  5654. if ($colType) continue;// pomin Typespecial dla realnych komorek w bazie danych
  5655. $typeSpecial = Typespecial::getInstance($vColID, $vCol);
  5656. if ($typeSpecial) {
  5657. $columnConfig = V::get($vCol, null, $jsonData->cols);
  5658. if ($columnConfig && !empty($columnConfig->_tsSimpleLink)) {
  5659. // pomin simple link values - mved to js render
  5660. } else {
  5661. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vColID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
  5662. $ids = array_keys($items);
  5663. $specialValues = $typeSpecial->getValuesByIds($this->_zasobID, $ids);
  5664. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vCol.') specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValues);echo'</pre>';}
  5665. if (!empty($specialValues)) foreach ($specialValues as $kItemID => $vValues) {
  5666. $tsValue = implode('<br>', $vValues);
  5667. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Item['.$kItemID.'].'.$vCol.' specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($items[$kItemID]);echo'</pre>';}
  5668. if (!empty($items[$kItemID][$vCol]) && !empty($tsValue)) {
  5669. $items[$kItemID][$vCol] .= ": {$tsValue}";
  5670. } else {
  5671. $items[$kItemID][$vCol] = $tsValue;
  5672. }
  5673. }
  5674. }
  5675. }
  5676. }
  5677. }
  5678. {
  5679. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__ = [];}
  5680. $p5Alias = [];
  5681. foreach ((array)$jsonData->cols as $fieldName => $conf) {
  5682. if ('p5:alias' == V::get('xsdType', '', $conf)) {
  5683. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__[$fieldName] = $conf;}
  5684. $aliasType = $acl->getXsdFieldParam($fieldName, 'type');// 'type' => 'sql_table_alias',
  5685. if ('sql_table_alias' == $aliasType) {
  5686. $p5Alias[$fieldName] = (array)$conf;
  5687. $p5Alias[$fieldName]['type'] = 'sql_table_alias';
  5688. $p5Alias[$fieldName]['local_join_key'] = $acl->getXsdFieldParam($fieldName, 'local_join_key');// 'local_join_key' => 'ID',
  5689. $p5Alias[$fieldName]['remote_table_name'] = $acl->getXsdFieldParam($fieldName, 'remote_table_name');// 'remote_table_name' => 'CRM_LISTA_ZASOBOW_ORDERS_summary_view',
  5690. $p5Alias[$fieldName]['remote_join_key'] = $acl->getXsdFieldParam($fieldName, 'remote_join_key');// 'remote_join_key' => 'ID',
  5691. $p5Alias[$fieldName]['remote_column_value'] = $acl->getXsdFieldParam($fieldName, 'remote_column_value');// 'remote_column_value' => 'SUM_POS',
  5692. } else if ('sql_query_alias' == $aliasType) {
  5693. $p5Alias[$fieldName] = (array)$conf;
  5694. $p5Alias[$fieldName]['type'] = 'sql_query_alias';
  5695. $p5Alias[$fieldName]['local_join_key'] = $acl->getXsdFieldParam($fieldName, 'local_join_key');
  5696. $p5Alias[$fieldName]['join_query_format'] = $acl->getXsdFieldParam($fieldName, 'join_query_format');
  5697. }
  5698. }
  5699. }
  5700. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$p5Alias'] = $p5Alias;}
  5701. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$aliasValuesRaw'] = [];}
  5702. if ($p5Alias) {
  5703. $sqlLocalTableName = $acl->getRootTableName();
  5704. $primaryKeyField = $acl->getPrimaryKeyField();
  5705. foreach ($p5Alias as $fieldName => $conf) {
  5706. $aliasValuesRaw = [];
  5707. if ('sql_table_alias' == $conf['type']) {
  5708. $localKeys = [];
  5709. $localKeyName = V::get('local_join_key', '', $conf);
  5710. if ($localKeyName) {
  5711. if (!array_key_exists($localKeyName, $localKeys)) {
  5712. $localKeys[$localKeyName] = [];
  5713. foreach ($items as $item) {
  5714. $keyLocal = V::get($localKeyName, 0, $item);
  5715. if ($keyLocal) $localKeys[$localKeyName][] = DB::getPDO()->quote($keyLocal, PDO::PARAM_STR);
  5716. }
  5717. }
  5718. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$localKeys'] = $localKeys;}
  5719. if (!empty($localKeys[$localKeyName])) {
  5720. $sqlRemoteTable = V::get('remote_table_name', '', $conf);
  5721. $sqlRemoteValueFieldName = V::get('remote_column_value', '', $conf);
  5722. $sqlRemoteKeyName = V::get('remote_join_key', '', $conf);
  5723. $sqlLocalKeyName = $acl->getSqlFieldName($localKeyName);
  5724. $aliasValuesRaw = DB::getPDO()->fetchAllByKey("
  5725. select r.{$sqlRemoteKeyName} as {$sqlLocalKeyName}, r.{$sqlRemoteValueFieldName} as remote_value
  5726. from {$sqlRemoteTable} r
  5727. where r.{$sqlRemoteKeyName} in(" . implode(",", $localKeys[$localKeyName]) . ")
  5728. ", $sqlLocalKeyName);
  5729. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$aliasValuesRaw'][$fieldName] = $aliasValuesRaw;}
  5730. }
  5731. }
  5732. } else if ('sql_query_alias' == $conf['type']) {
  5733. $localKeys = [];
  5734. $localKeyName = V::get('local_join_key', '', $conf);
  5735. $sqlFormat = V::get('join_query_format', '', $conf);
  5736. if ($localKeyName && $sqlFormat) {
  5737. if (!array_key_exists($localKeyName, $localKeys)) {
  5738. $localKeys[$localKeyName] = [];
  5739. foreach ($items as $item) {
  5740. $keyLocal = V::get($localKeyName, 0, $item);
  5741. if ($keyLocal) $localKeys[$localKeyName][] = DB::getPDO()->quote($keyLocal, PDO::PARAM_STR);
  5742. }
  5743. }
  5744. }
  5745. if (!empty($localKeys[$localKeyName])) {
  5746. $sql = str_replace('{sql_in_local_join_key}', implode(",", $localKeys[$localKeyName]), $sqlFormat);
  5747. $sqlLocalKeyName = $acl->getSqlFieldName($localKeyName);
  5748. $aliasValuesRaw = DB::getPDO()->fetchAllByKey($sql, $sqlLocalKeyName);
  5749. }
  5750. }
  5751. DBG::log($aliasValuesRaw, 'array', '$aliasValuesRaw');
  5752. if (!empty($aliasValuesRaw)) {
  5753. if(V::get('DBG_P5', '', $_GET)){echo '{ "$aliasValuesRaw": '.json_encode($aliasValuesRaw).', "dbg": [' . "\n";}
  5754. array_walk($items, function (&$item) use ($fieldName, $sqlLocalKeyName, $aliasValuesRaw) {
  5755. $sqlValue = V::get($sqlLocalKeyName, null, $item);
  5756. if(V::get('DBG_P5', '', $_GET)){echo '{ "sqlValue": "'.$sqlValue.'", "remote_value": "'.$aliasValuesRaw[$sqlValue]['remote_value'].'", "item": '.json_encode($item) . '},' . "\n";}
  5757. if ($sqlValue !== null && array_key_exists($sqlValue, $aliasValuesRaw)) {
  5758. if(V::get('DBG_P5', '', $_GET)){echo '{ "TODO_update_value": "'.$aliasValuesRaw[$sqlValue]['remote_value'].'"},' . "\n";}
  5759. $item[$fieldName] = $aliasValuesRaw[$sqlValue]['remote_value'];
  5760. if(V::get('DBG_P5', '', $_GET)){echo '{ "TODO_updated_value": "'.$item[$fieldName].'"},' . "\n";}
  5761. }
  5762. });
  5763. if(V::get('DBG_P5', '', $_GET)){echo "\n".'{}]}';die();}
  5764. }
  5765. }
  5766. }
  5767. }
  5768. foreach ($items as $item) {
  5769. // TODO: hide items without 'R'
  5770. foreach ($visibleCols as $fieldName) {
  5771. // TODO: ID default 'R'
  5772. if (!$acl->canReadObjectField($fieldName, $item)) $item[$fieldName] = '*****';
  5773. // null => empty string
  5774. if (!isset($item[$fieldName]) || (!$item[$fieldName] && $item[$fieldName] !== '0')) {
  5775. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">isEmptyString['.$fieldName.'] (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($item[$fieldName]);echo'</pre>';}
  5776. $item[$fieldName] = '';
  5777. }
  5778. }
  5779. $jsonData->rows[] = $item;
  5780. }
  5781. $jsonData->type = 'success';
  5782. $jsonData->msg = 'pobrano nowe dane';
  5783. return $jsonData;
  5784. }
  5785. private function fixEmptyValueFromUser($fieldID) {// TODO: moved to TableAcl->fixEmptyValueFromUser
  5786. $value = '';
  5787. $type = $this->_acl->getFieldTypeById($fieldID);
  5788. if ($type) {
  5789. if ($type['type'] == 'date') {
  5790. $value = $type['default'];
  5791. }
  5792. // fix bug when field is unique and is null allowed: change empty string to null
  5793. if ($type['null']) {
  5794. $value = 'NULL';
  5795. }
  5796. // fix bug when field is enum and is set to '0': for php '0' is empty
  5797. if (substr($type['type'], 0, 4) == 'enum') {// && $args["f{$fieldID}"] === '0') {
  5798. if (false !== strpos($type['type'], "''")) {
  5799. // enum('', '1','2')
  5800. $value = '';
  5801. } else if (false !== strpos($type['type'], "'0'")) {
  5802. // enum('0', '1','2')
  5803. $value = '0';
  5804. } else {
  5805. $value = $type['default'];
  5806. }
  5807. }
  5808. }
  5809. return $value;
  5810. }
  5811. /**
  5812. * set hidden cols in $_SESSION['USER_PROFILE'][$this->_zasobID];
  5813. * $_SESSION['USER_PROFILE'][$this->_zasobID][fld_id] => boolean
  5814. */
  5815. private function ajaxHiddenColsSave($args) {
  5816. $response = new stdClass();
  5817. if (empty($args)) {
  5818. $response->type = 'info';
  5819. return $response;
  5820. }
  5821. UserProfile::load();
  5822. // clean up old, wrong values
  5823. if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
  5824. unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
  5825. }
  5826. $colVis = UserProfile::getHiddenCols($this->_zasobID);
  5827. $fields = $this->_acl->getFieldListByIdZasob();
  5828. foreach ($fields as $idField => $fieldName) {
  5829. if (isset($args[$fieldName])) {
  5830. if ($args[$fieldName] == 'SHOW') {
  5831. $colVis[$idField] = 1;
  5832. } else if ($args[$fieldName] == 'HIDE') {
  5833. $colVis[$idField] = 0;
  5834. }
  5835. }
  5836. }
  5837. UserProfile::setHiddenCols($this->_zasobID, $colVis);
  5838. UserProfile::save();
  5839. $response->type = 'success';
  5840. return $response;
  5841. }
  5842. private function ajaxPageSizeSave($args) {
  5843. $response = new stdClass();
  5844. if (empty($args)) {
  5845. $response->type = 'info';
  5846. return $response;
  5847. }
  5848. $pageSize = V::get('pageSize', 0, $args, 'int');
  5849. UserProfile::load();
  5850. // clean up old, wrong values
  5851. if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
  5852. unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
  5853. }
  5854. $tableAjaxSettings = UserProfile::getTableAjaxSettings();
  5855. $tableAjaxSettings['pageSize'] = $pageSize;
  5856. UserProfile::setTableAjaxSettings($tableAjaxSettings);
  5857. UserProfile::save();
  5858. $response->type = 'success';
  5859. return $response;
  5860. }
  5861. private function ajaxTheGeomSave($args) {
  5862. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  5863. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  5864. $polygon = V::get('polygon', 0, $args);
  5865. $geomFieldName = 'the_geom';
  5866. if ($primaryKey <= 0) {
  5867. throw new HttpException("Wrong param ID", 404);
  5868. }
  5869. // TODO: validate polygon - ex.: POLYGON((2072030.2315435 7234115.910678,2072029.4815435 7234093.660678,2072115.2315435 7234091.160678,2072115.4815435 7234113.660678,2072115.2315435 7234113.660678,2072094.2315435 7234113.910678,2072030.2315435 7234115.910678)))
  5870. $record = $this->_acl->getItem($primaryKey);
  5871. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  5872. throw new HttpException("Brak dostępu do rekordu", 403);
  5873. }
  5874. if (!$this->_acl->canWriteObjectField($geomFieldName, $record)) {
  5875. throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  5876. }
  5877. $itemPatch = array();
  5878. $itemPatch[$geomFieldName] = "GeomFromText('{$polygon}')";
  5879. $itemPatch[$primaryKeyField] = $primaryKey;
  5880. $response = new stdClass();
  5881. try {
  5882. $affected = $this->_acl->updateItem($itemPatch);
  5883. if ($affected > 0) {
  5884. $response->type = 'success';
  5885. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  5886. } else if ($affected == 0) {
  5887. $response->type = 'info';
  5888. $response->msg = "Nie wprowadzono żadnych zmian";
  5889. }
  5890. $response->record = $this->_acl->getItem($primaryKey);
  5891. }
  5892. catch (Exception $e) {
  5893. $response->type = 'error';
  5894. $response->msg = $e->getMessage();
  5895. }
  5896. return $response;
  5897. }
  5898. private function sendAjaxResponseJson($method, $args) {
  5899. try {
  5900. $response = $this->{$method}($args);
  5901. }
  5902. catch (HttpException $e) {
  5903. $response = new stdClass();
  5904. $response->type = 'error';
  5905. $response->msg = $e->getMessage();
  5906. $response->errorCode = $e->getCode();
  5907. Http::sendHeaderByCode($e->getCode());
  5908. }
  5909. catch (Exception $e) {
  5910. $response = new stdClass();
  5911. $response->type = 'error';
  5912. $response->msg = $e->getMessage();
  5913. $response->errorCode = $e->getCode();
  5914. }
  5915. header('Content-type: application/json');
  5916. if (!$response) $response = new stdClass();
  5917. echo json_encode($response);
  5918. exit;
  5919. }
  5920. private function ajaxProcesInitFiltr($args) {// ajax task 'PROCES_INIT_FILTR'
  5921. $response = new stdClass();
  5922. $pInitList = array();// [proces_init_id] => label (DESC)
  5923. if (!$this->_showProcesInit) {
  5924. $response->type = 'error';
  5925. return $response;
  5926. }
  5927. $userAcl = User::getAcl();
  5928. $pInitList = $userAcl->getTableProcesInitList($this->_zasobID);
  5929. if (!empty($pInitList)) {
  5930. $procesIds = array_keys($pInitList);
  5931. $mapTree = ACL::getProcesInitMapTreeOnlyIds($procesIds);
  5932. DBG::_('DBG_MAP', '1', "mapTree", $mapTree, __CLASS__, __FUNCTION__, __LINE__);
  5933. DBG::_('DBG_MAP', '1', "pInitList", $pInitList, __CLASS__, __FUNCTION__, __LINE__);
  5934. $pInitListSelected = $this->getProcesInitSelected();
  5935. $response->pInitData = new stdClass();
  5936. $response->pInitData->pInitList = $pInitList;
  5937. $response->pInitData->mapTree = $mapTree;
  5938. $response->pInitData->pInitListSelected = $pInitListSelected;
  5939. }
  5940. $response->type = 'success';
  5941. return $response;
  5942. }
  5943. }