TableAjax.php 241 KB

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