TableAjax.php 218 KB

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