TableAjax.php 245 KB

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