TableAjax.php 224 KB

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