TableAjax.php 225 KB

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