TableAjax.php 238 KB

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