TableAjax.php 235 KB

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