TableAjax.php 226 KB

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