| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972 |
- <?php
- Lib::loadClass('ViewAjax');
- Lib::loadClass('TableAjaxMap');
- Lib::loadClass('Typespecial');
- Lib::loadClass('SE_Layout');
- Lib::loadClass('FoldersConfig');
- Lib::loadClass('FileUploader');
- Lib::loadClass('UserProfile');
- Lib::loadClass('ProcesHelper');
- Lib::loadClass('Router');
- class TableAjax extends ViewAjax {
- private $_cnf = '';// Column
- private $_htmlID = '';
- private $_rowFunctions = array();
- private $_pageSize = 10;
- private $_pageSizes = array();
- private $_filterInit = null;
- private $_forceFilterInit = null;
- private $_showProcesInit = true;
- public function __construct($tblAcl) {
- $this->_tbl = $tblAcl->getName();
- $this->_acl = $tblAcl;
- $this->_zasobID = $tblAcl->getID();
- $this->_pageSize = 10;
- {
- UserProfile::load();
- $tableAjaxSettings = UserProfile::getTableAjaxSettings();
- $this->_pageSize = V::get('pageSize', 10, $tableAjaxSettings, 'int');
- }
- $this->_pageSizes = array(10, 20, 50, 100);// default page sizes
- $this->_filterInit = new stdClass();
- $hash = V::get('_hash', '', $_GET);
- if ($hash) {
- $this->_htmlID = $hash;
- $this->_readState();
- } else {
- $this->_htmlID = $this->generateHtmlID();
- $this->_readState();
- }
- }
- public function showProcesInit($bool = true) {
- $this->_showProcesInit = $bool;
- }
- private function _hasStateFilterInit() {
- return array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache']) && array_key_exists('_filterInit', $_SESSION['TableAjax_Cache'][$this->_htmlID]);
- }
- // TODO: read state from cache by key $this->_htmlID
- // TODO: load filters and state: table, edit, add, etc.
- // TODO: save this data in Workspace 1, 2, 3, etc.
- // TODO: default filters in VIEWTABLE_AJAX
- // $tbl->setLabel($zasobObj->OPIS);
- // $tbl->setFilterInit($filterInit);
- // $tbl->addRowFunction('edit');
- // $tbl->addRowFunction('hist');
- // $tbl->addRowFunction('files');
- // $tbl->addRowFunction('cp');
- private function _readState() {
- if (!array_key_exists('TableAjax_Cache', $_SESSION)) {
- $_SESSION['TableAjax_Cache'] = array();
- }
- //trigger_error("F." . __FUNCTION__ . " (" . (array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) . ")", E_USER_NOTICE);
- //trigger_error("F." . __FUNCTION__ . " (".basename($_SERVER['SCRIPT_FILENAME'])."::_filterInit: " . json_encode($_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit']) . ")", E_USER_NOTICE);
- if (array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) {
- foreach ($_SESSION['TableAjax_Cache'][$this->_htmlID] as $k => $v) {
- //trigger_error("F." . __FUNCTION__ . " key: ({$k})", E_USER_NOTICE);
- switch ($k) {
- case '_label':
- $this->_label = $v;
- break;
- case '_filterInit':
- $this->_filterInit = $v;
- break;
- case '_rowFunctions':
- $this->_rowFunctions = $v;
- break;
- default:
-
- }
- }
- }
- }
- protected function _saveState($key = null) {
- if (!array_key_exists('TableAjax_Cache', $_SESSION)) {
- $_SESSION['TableAjax_Cache'] = array();
- }
- if (!array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) {
- $_SESSION['TableAjax_Cache'][$this->_htmlID] = array();
- }
- if (!$key) {
- $_SESSION['TableAjax_Cache'][$this->_htmlID]['_label'] = $this->_label;
- $_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'] = $this->_filterInit;
- $_SESSION['TableAjax_Cache'][$this->_htmlID]['_rowFunctions'] = $this->_rowFunctions;
- } else if ($key == '_label') {
- $_SESSION['TableAjax_Cache'][$this->_htmlID]['_label'] = $this->_label;
- } else if ($key == '_filterInit') {
- $_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'] = $this->_filterInit;
- } else if ($key == '_rowFunctions') {
- $_SESSION['TableAjax_Cache'][$this->_htmlID]['_rowFunctions'] = $this->_rowFunctions;
- }
- }
- public function setPageSizes($pageSizes) {
- $this->_pageSizes = $pageSizes;
- }
- public function setFilterInit($filterInit) {
- if ($this->_hasStateFilterInit()) {
- return;
- }
- $this->_filterInit = (object)$filterInit;
- $this->_saveState();
- }
- /**
- * @param array $forceFilterInit
- */
- public function setForceFilterInit($forceFilterInit) {
- $this->_forceFilterInit = (object)$forceFilterInit;
- }
- private function setFilters($filterInit) {
- $this->_filterInit = (object)$filterInit;
- $this->_saveState();
- }
- public function addRowFunction($funName, $funParams = array()) {
- $defaultRowFunction = array();
- //$defaultRowFunction['edit'] = '<a href="#EDIT/{0}" class="glyphicon glyphicon-pencil" title="Edytuj rekord"></a>';
- //$defaultRowFunction['hist'] = '<a href="#HIST/{0}" class="glyphicon glyphicon-book" title="Historia"></a>';
- //$defaultRowFunction['files'] = '<a href="#FILES/{0}" class="glyphicon glyphicon-folder-open" title="Pliki"></a>';
- //$defaultRowFunction['cp'] = '<a href="#" class="glyphicon glyphicon-plus-sign" title="Kopiuj rekord" onclick="return tableAjaxCopy({0});"></a>';
- $defaultRowFunction['edit'] = array('href'=>'#EDIT/{0}', 'ico'=>'glyphicon glyphicon-pencil', 'title'=>'Edytuj rekord');
- $defaultRowFunction['hist'] = array('href'=>'#HIST/{0}', 'ico'=>'glyphicon glyphicon-book', 'title'=>'Historia');
- $defaultRowFunction['files'] = array('href'=>'#FILES/{0}', 'ico'=>'glyphicon glyphicon-folder-open', 'title'=>'Pliki');
- $defaultRowFunction['cp'] = array('href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});');
- if (array_key_exists($funName, $defaultRowFunction)) {
- $this->_rowFunctions[$funName] = $defaultRowFunction[$funName];
- }
- else {
- $this->_rowFunctions[$funName] = $funParams;
- }
- $this->_saveState('_rowFunctions');
- }
- private function _parseRowFunctions($recordID = null, $pomin = array(), $showLabel = false) {
- $rowFunctions = array();
- foreach ($this->_rowFunctions as $kFunName => $vParams) {
- if (in_array($kFunName, $pomin)) continue;
- //$rowFunctionsOut .= str_replace('{0}', $recordID, $vUrl);
- $attrs = array();
- // $defaultRowFunction['cp'] = (object)array('href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});');
- $label = '';
- $ico = '';
- foreach ($vParams as $kParamName => $v) {
- if ($kParamName == 'ico') {
- $ico = '<span class="' . $v . '"></span>';
- continue;
- }
- $attr = $v;
- if ($recordID > 0) {
- $attr = str_replace('{0}', $recordID, $attr);
- }
- if ($showLabel && $kParamName == 'title') {
- $label = $attr;
- }
- $attr = $kParamName . '="' . $attr . '"';
- $attrs[] = $attr;
- }
- $rowFunctions[$kFunName] = '<a ' . implode(' ', $attrs) . '>' . "{$ico} {$label} " . '</a>';
- }
- return $rowFunctions;
- }
- private function _showRowFunctions($recordID = null, $pomin = array(), $showLabel = false) {
- $rowFunctionsOut = $this->_parseRowFunctions($recordID, $pomin, $showLabel);
- $rowFunctionsOut = implode('', $rowFunctionsOut);
- return $rowFunctionsOut;
- }
- private function _showRowFunctionsJson($recordID = null, $pomin = array(), $showLabel = false) {
- $rowFunctions = $this->_parseRowFunctions($recordID, $pomin, $showLabel);
- $rowFunctions = (object)$rowFunctions;
- return $rowFunctions;
- }
- private function _showExportFieldsJson() {
- $exportFields = $this->_acl->getExportFieldList();
- return $exportFields;
- }
- private function getProcesInitSelected() {
- $userAcl = User::getAcl();
- return $userAcl->getPermsFiltrProcesId();
- }
- public function allowTreeView() {
- if ($this->_tbl == 'CRM_LISTA_ZASOBOW') return true;
- if ($this->_tbl == 'CRM_PROCES') return true;
- return false;
- }
- public function hasGeomFields() {
- $hasGeomFields = false;
- $fieldsList = $this->_acl->getFields();
- foreach ($fieldsList as $kID => $vCol) {
- if ($this->_acl->isGeomField($vCol['name'])) {
- if ($this->_acl->hasFieldPerm($kID, 'R')) {
- $hasGeomFields = true;
- break;
- }
- }
- }
- return $hasGeomFields;
- }
- public function render() {
- $hasGeomFlds = $this->hasGeomFields();
- $tblAjaxMap = null;
- if ($hasGeomFlds) {
- $tblAjaxMap = new TableAjaxMap($this->_acl, 512, 400);
- }
- $hasPermCreate = $this->_acl->hasCreatePerms();
- $jsToogleFiltrProcesuFunctionName = 'tableAjaxToggleFiltrProcesInit';
- ob_start();
- ?>
- <div class="container">
- <?php SE_Layout::showMessagesForTable($this->_tbl); ?>
- </div>
- <?php if ($tblAjaxMap) $tblAjaxMap->printCSS(); ?>
- <?php if ($tblAjaxMap) $tblAjaxMap->printJS(); ?>
- <script src="stuff/jquery-ui-1.10.4.custom.min.js"></script>
- <link rel="stylesheet" type="text/css" href="stuff/jquery-ui-smoothness/jquery-ui-1.10.4.custom.min.css">
- <style type="text/css">
- .AjaxTable{max-width:100%;background-color:transparent;border-collapse:collapse;border-spacing:0;}
- .AjaxTableCont {position:relative; margin:10px 0; width:100%; overflow-x:auto; border:none;}
- .AjaxTable *,
- .AjaxTable.table {white-space:nowrap; width:auto;}
- .AjaxTable .popover * {white-space:normal;}
- .AjaxTable p {margin:0;}
- .AjaxTable td, .AjaxTable th {line-height:18px;}
- .AjaxTable i {margin: 0 0 0 2px;opacity: 0.5;}
- .AjaxTable span.filter {background-color:#999;}
- .AjaxTable .indeterminate {opacity: 0.4;-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=40)";filter:alpha(opacity=40);}
- .AjaxTable .columnpicker li, .AjaxTable .actions li {padding-left:5px;}
- .AjaxTableCont .btn-toolbar {margin:2px 0 0 0;}
- .AjaxTableCont .btn-toolbar .btn-group {vertical-align:top;}
- .AjaxTable input[type=checkbox] {margin:0;padding:0;height:13px;}
- .AjaxTable input[type=text].filter {margin:0;padding:0 5px;box-shadow:none;width:100%;background:#eee;color:#000;}
- .AjaxTable input[type=text].filter {border-width:2px 0;border-color:#eee;border-style:solid;}
- .AjaxTable input[type=text].filter-active {border-color:#00ACCC;}
- .AjaxTable .date-wrap {width:100%;min-width:115px;}
- .AjaxTable .dateWrap .add-on {margin:0;padding:0;background:none;border:none;float:right;cursor:pointer;}
- .AjaxTableCont .dropdown-menu {max-height:250px;padding:0 20px 0 0;overflow:auto;}
- .AjaxTable .actions a {padding:0;margin:0;}
- .AjaxTableCont .text-right {text-align:right}
- .AjaxTableCont .breadcrumb em {color:#bbb;}
- .AjaxTable-loading .head-info {background:url(./icon/loading.gif) no-repeat left top; background-position:0 6px;}
- .AjaxTable-loading .loading-info,
- .AjaxTableCont .tblAjax__inlineEditBox .loading-info {display:block; padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;}
- .AjaxTableCont .loading-info {display:none;}
- .AjaxTableCont .tblAjax__inlineEditBox .loading-info {display:block;}
- .AjaxTableCont .table {margin-bottom:0px;}
- .AjaxTableCont .stickyCol1 a { color:#333; }
- .AjaxTableCont .stickyCol1 a:hover { color:#337AB7; text-decoration:none; }
- .AjaxTableTaskCnt {padding:0 10px 10px 10px;}
- .AjaxTable .tbl-short-txt{max-width:140px; overflow:hidden;}
- .AjaxTable .tbl-short-txt span{display:block; height:18px;}
- .AjaxTable .tooltip-inner{white-space:normal;}
- .AjaxTable thead .sort .ta-ordering {cursor:pointer;}
- .AjaxTable thead .sort .ta-ordering span {margin:0 10px 0 0; padding:0; background-repeat:no-repeat; background-position:right top;}
- .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;}
- .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;}
- .AjaxTable thead .sort .ta-ordering {position:relative;}
- .AjaxTable thead .sort th .hover-show:hover{background-color:#000; background-image:url(stuff/twitter-bootstrap/img/glyphicons-halflings-white.png);}
- .AjaxTable thead .sort th .hover-show{display:none;}
- .AjaxTable thead .sort th:hover .hover-show{display:inline;}
- .AjaxTable thead .sort .ta-ordering .remove-cell {position:absolute; top:6px; right:2px; display:none; color:#f00;}
- .AjaxTable thead .sort .ta-ordering:hover .remove-cell {display:block;}
- .AjaxTableCont .pagination { margin:0; }
- .AjaxTableCont .pagination a { line-height:16px; }
- .AjaxTableCont .AjaxTableEdit-label { display:block; margin:0 0 3px 0; font-size:12px !important; line-height:16px !important; }
- .AjaxTableCont .AjaxTableEdit-label code { padding:0; white-space:nowrap; background-color:transparent; border:none; color:#777; font-size:10px !important; line-height:14px !important; }
- .AjaxTableCont .AjaxTableEdit .show-last-value .button-appendBack .glyphicon,
- .AjaxTableCont .AjaxFrmHorizontalEdit .show-last-value .button-appendBack .glyphicon {display:none;}
- .AjaxTableHist em {color:silver;}
- .AjaxTableCont .foot * { font-size:12px !important; }
- .AjaxTableCont .foot { margin:10px; }
- .AjaxTableCont .foot .foot-info { float:left; padding:0 20px; }
- .AjaxTableCont .foot .foot-info p { line-height:16px; margin:5px 0; }
- .AjaxTable-loading .foot .foot-info {padding-left:20px; background:url(./icon/loading.gif) no-repeat left top;}
- .tblAjax__head__specialFilter {margin:0;padding:4px 4px 4px 127px;}
- .tblAjax__head__specialFilter .btn-group {margin:0 4px;padding:0;}
- .tblAjax__head__specialFilter .btn-group .glyphicon-remove {color:#f00;}
- .tblAjax__head__specialFilter .btn-group button.disabled .glyphicon-remove {color:#bbb;}
- /* overwrite bootstrap table border */
- .AjaxTable, .AjaxTableEdit,
- .AjaxTable td, .AjaxTableEdit td,
- .AjaxTable th, .AjaxTableEdit th { border-color:#999; }
- /* cell A_STATUS */
- .AjaxTable .cell-A_STATUS-NORMAL { background:#aeffae; color:#000; text-align:center; }
- .AjaxTable .cell-A_STATUS-WAITING { background:#ffd2ff; color:#000; text-align:center; }
- .AjaxTable .cell-A_STATUS-MONITOR { background:#cccaff; color:#000; text-align:center; }
- .AjaxTable .cell-A_STATUS-WARNING { background:#ffbaba; color:#000; text-align:center; }
- .AjaxTable .cell-A_STATUS-DELETED { background:#e0e0e0; color:#808080; text-align:center; }
- .AjaxTable .cell-A_STATUS-OFF_SOFT { background:#fce3b7; color:#808080; text-align:center; }
- .AjaxTable .cell-A_STATUS-OFF_HARD { background:#eee; color:#808080; text-align:center; }
- /* cell Status */
- .AjaxTable .cell-Status-U { background:rgb(0,176,80); color:#000; text-align:center; }
- .AjaxTable .cell-Status-NU { background:#f00; color:#000; text-align:center; }
- .AjaxTable .cell-Status-P { background:rgb(112,48,160); color:#000; text-align:center; }
- .AjaxTable .cell-Status-PT { background:rgb(127,127,127); color:#000; text-align:center; }
- .AjaxTable .cell-Status-O { background:rgb(0,176,240); color:#000; text-align:center; }
- .AjaxTable .cell-Status-DZ { background:rgb(0,112,192); color:#000; text-align:center; }
- .AjaxTable .cell-Status-Z {}
- /* map */
- .AjaxTable .cell-mapfld { cursor:pointer; }
- .AjaxTable .cell-mapfld:hover { opacity:1; }
- .AjaxTable .cell-mapfld-remove { display:none; }
- .AjaxTable .cell-mapfld-hasValue .cell-mapfld-select { color:#f00; }
- .AjaxTable .cell-mapfld-hasValue .cell-mapfld-remove { display:inline-block; }
- .AjaxTableCont .mapEditor { position:absolute; bottom:0; right:6px; width:512px; height:318px; overflow:hidden; color:#eee; border:1px solid #999; }
- .AjaxTableCont .mapEditor-panel { height:16px; padding:0 6px; background:#999; border-bottom:1px solid #eee; }
- .AjaxTableCont .mapEditor-panel a { display:block; float:right; padding:0 6px; font-weight:bold; font-size:12px; line-height:16px; color:#fff; }
- .AjaxTableCont .mapEditor-panel a:hover { color:#006CD7; text-decoration:none; }
- .AjaxTableCont .mapEditor-panel a.mapEditor-panel-close:hover { color:#f00; }
- .AjaxTableCont .mapEditor-map { background:#fff; height:400px; }
- .AjaxTableCont-mapEditorContainer .mapEditor-map { border:1px solid #999; overflow:hidden; }
- /* .mapEditor-btnBackToWindow "olControlSave",overview_replacement */
- .olControlEditingToolbar .mapEditor-btnBackToWindowItemInactive,
- .olControlEditingToolbar .mapEditor-btnBackToWindowItemActive {
- background-image: url(icon/map.window.png);
- background-position: 0 0;
- background-repeat: no-repeat;
- }
- /*
- .mapEditor-btnBackToWindowItemInactive { background-image: url(stuff/open-layers/theme/default/img/overview_replacement.gif); }
- .mapEditor-btnBackToWindowItemActive { background-image: url(stuff/open-layers/theme/default/img/overview_replacement.gif); }
- */
- .ui-dialog-content .mapEditor-btnBackToWindowItemInactive,
- .ui-dialog-content .mapEditor-btnBackToWindowItemActive { display:none; }
- .AjaxTableCont .valign-btns-bottom a { vertical-align:text-bottom; font-weight:normal; font-size:12px; line-height:14px; }
- .ui-resizable-s { bottom:0; }
- .ui-resizable-e { right:0; }
- .AjaxTableCont-mapEditorContainer .ui-resizable-s { background-color:#ddd; }
- .AjaxTableCont-mapEditorContainer .ui-resizable-s:hover { background-color:#888; }
- </style>
- <div class="AjaxTableCont">
- <ul class="breadcrumb">
- <li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>
- <!-- TODO: if has perm 'C' then add btn to create new record -->
- <?php if ($hasPermCreate) : ?>
- <li><a title="Dodaj nowy rekord"
- class=""
- href="#CREATE"><span class="glyphicon glyphicon-plus"></span> Dodaj nowy rekord</a></li>
- <?php endif; ?>
- <?php if ($this->_showProcesInit) : ?>
- <div class="btn-group pull-right">
- <a class="btn btn-xs btn-info dropdown-toggle"
- data-toggle="dropdown"
- href="#"
- title="Uruchom filtr procesu powiązanego z tabelą <?php echo $this->getLabel(); ?>"
- onclick="return <?php echo $jsToogleFiltrProcesuFunctionName; ?>(this);">
- Filtr procesu <span class="caret"></span>
- </a>
- <ul class="dropdown-menu pull-left">
- <li class="disabled"><a href="#" onclick="return false;"> loading ... </a></li>
- </ul>
- </div>
- <?php endif; ?>
- <?php if ($this->_tbl == 'IN7_MK_BAZA_DYSTRYBUCJI') : ?>
- <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>
- <?php elseif ($this->allowTreeView()) : ?>
- <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>
- <?php endif; ?>
- </ul>
- <div id="<?php echo $this->_htmlID; ?>"></div>
- </div>
- <script>
- (function($) {
- var TableAjaxGeomField = function() {
- var priv = {}; //private api
- var publ = {}; //public api
- priv.options = {};
- var defaults = {
- recordID: '',
- fieldValue: '',
- hasValueClassName: 'TableAjaxGeomField-hasValue',
- linkClassNamePrefix: 'TableAjaxGeomField',
- linkSelectClassName: 'select',
- linkSelectAddClassNames: '', // 'glyphicon glyphicon-map-marker'
- linkRemoveClassName: 'remove',
- linkRemoveAddClassNames: '', // 'glyphicon glyphicon-remove'
- removeUrl: '',
- onSelect: null,
- onRemove: null,
- debug: false
- };
- priv.init = function() {
- priv.render();
- };
- priv.render = function() {
- var state = priv.options;
- var cellMapSelect = jQuery('<i title="Pokaż/utwórz obiekt na mapie"></i>');
- cellMapSelect.addClass(state.linkClassNamePrefix + '-' + state.linkSelectClassName);
- if (state.linkSelectAddClassNames) {
- cellMapSelect.addClass(state.linkSelectAddClassNames);
- }
- cellMapSelect.on('click', {recordID: priv.options.recordID, fieldValue: priv.options.fieldValue}, function(e) {
- if (typeof state.onSelect == "function") {
- state.onSelect.call(this, e.data.recordID, e.data.fieldValue);
- }
- });
- var cellMapRemove = jQuery('<i title="Usuń obiekt z mapy"></i>');
- cellMapRemove.addClass(state.linkClassNamePrefix + '-' + state.linkRemoveClassName);
- if (state.linkRemoveAddClassNames) {
- cellMapRemove.addClass(state.linkRemoveAddClassNames);
- }
- cellMapRemove.on('click', {recordID: state.recordID, fieldValue: state.fieldValue}, function(e) {
- if (typeof state.onRemove == "function") {
- state.onRemove.call(this, publ, e.data.recordID, e.data.fieldValue);
- }
- });
- var node = $(state.id);
- node.empty();
- node.addClass(state.linkClassNamePrefix);
- node.removeClass(state.hasValueClassName);
- if (state.fieldValue) {
- node.addClass(state.hasValueClassName);
- }
- node.append(cellMapSelect);
- node.append(cellMapRemove);
- };
- publ.setValue = function(value) {
- if (priv.options.debug) console.log('TEST setValue: ', value, 'this', this);
- priv.options.fieldValue = value;
- priv.render();
- };
- publ.init = function(options) {
- if (priv.options.debug) console.log('TableAjaxGeomField initialization...', options);
- //merge supplied options with defaults
- $.extend(priv.options, defaults, options);
- priv.init();
- return publ;
- };
- return publ;
- };
- $.fn.TableAjaxGeomFieldSetValue = function(value) {
- return this.each(function() {
- var tblAjaxMapGeomFld = $(this).data('TableAjaxGeomField');
- if (tblAjaxMapGeomFld) {
- tblAjaxMapGeomFld.setValue(value);
- }
- });
- return this;
- };
- $.fn.TableAjaxGeomField = function(options) {
- options = options || {};
- return this.each(function() {
- options.id = this;
- if (!$(this).data('TableAjaxGeomField')) {
- $(this).data('TableAjaxGeomField', new TableAjaxGeomField().init(options));
- }
- });
- return this;
- };
- }(jQuery));
- (function($, undefined) {
- var TableAjax = function() {
- var priv = {}; //private api
- var publ = {}; //public api
- priv.options = {};
- var defaults = {
- url: '', //webservice url
- urlData: '', //webservice params
- urlPost: false, //use POST instead of GET
- debug: false, //prints debug info to console
- filter: false, //show filter row
- filterInit: false,// init filters data
- forceFilterInit: false,
- columnPicker: false, //show columnpicker
- checkboxes: false, //show body checkboxes
- actions: '', //holds action links
- pageSize: 10, //current pagesize
- pageSizes: [10, 20, 30, 40, 50, 'All'], //available pagesizes
- hidePagerOnEmpty: false, //removes pager if no rows
- types: { //type specific options
- string: {},
- number: {},
- bool: {},
- date: {}
- },
- rowFunctions: false,
- tblFunctions: false,
- specialFilterFunctions: false,
- filtersClean: false,
- router: false,
- longDesc: false,
- exportFields: [],
- mapEditor: false, // mapEditor visible or not
- mapEditorContainer: 'window' // 'window' or 'dock'
- };
- var _uiNodeCont; // container holding table
- var _uiNode$Table; // the table node
- var _head; // table header
- var _headSort; // table header sorting row
- var _headFilter; // table header columns filter row
- var _headSpecialFilter; // table header special filter row
- var _bodyNode; // table body
- var _body; // TODO: table body need render?
- var _foot; // table footer
- var _inlineEditBox; // inline edit box with form
- var _popoverCell; // inline popover cell
- var _popoverCellCurrent; // inline popover cell
- var _popoverCellAjaxXhr;
- var _mapEditor; // map editor node
- var _mapEditorWrap; // map editor wrapper node
- var _mapEditorDialog; // map editor jquery ui dialog node
- var _state = {};// state - to replace variables below (date, ...)
- var _data; //columns and rows
- var _totalPages; // total pages
- var _currDpOp; // clicked datetimepicker operator
- var _filterFields = {}; // array with filter DOM elements
- var _filterTimeout; // timer for delayed filtering
- var _uniqueCols = {}; // array with checked rows /// TODO: mv to _state.
- var _checkToggleChecked = false; // check-all toggle state
- var _exportFieldsSelect = {};
- var _tableWidth;
- /*
- initialize the plugin.
- */
- priv.init = function() {
- _uiNodeCont = priv.options.id;
- _state = {};// init state
- _state.page = 1;
- _state.specialFilters = {};
- _state.filters = {};
- _state.filters.currSortCol = '';
- _state.filters.currSortFlip = false;
- _state.filters.filterCols = {};
- priv.initEvents();
- priv.initialRender();// set up _uiNode$...
- priv.options.types.string = ((priv.options.types || {}).string || {});
- priv.options.types.number = ((priv.options.types || {}).number || {});
- priv.options.types.bool = ((priv.options.types || {}).bool || {});
- priv.options.types.date = ((priv.options.types || {}).date || {});
- if (priv.options.mapEditorContainer != 'dock'
- && priv.options.mapEditorContainer != 'window') {
- priv.options.mapEditorContainer = 'window';
- }
- if (priv.options.filterInit) {
- priv.setStateFilters(priv.options.filterInit);
- }
- $.each(priv.options.exportFields, function(ind, col) {
- _exportFieldsSelect[col] = true;
- });
- //try call webservice for data
- priv.update(priv.options.router);
- if (typeof priv.options.router == "function") {
- $(window).bind('hashchange', function() {
- priv.options.router.apply(this);
- });
- }
- };
- priv.initEvents = function() {
- jQuery(_uiNodeCont).on('TableAjax:render', priv.onRender);
- };
- priv.onRender = function(e) {
- if (priv.options.debug) console.log('onRender.arguments:', arguments.length, arguments, 'e:', e);
- if (arguments.length > 1) {
- for (var i=1; i<arguments.length; i++) {
- switch (arguments[i]) {
- case 'head': _head = undefined; break;
- case 'body': _body = undefined; break;
- case 'foot': _foot = undefined; break;
- case 'foot_pagination': {
- priv.renderFooterInfo();
- priv.renderFooterPagination();
- priv.renderFooterPageSizes();
- }
- break;
- case 'footer__toolbar__info': priv.renderFooterInfo(); break;
- case 'footer__toolbar__pagination': priv.renderFooterPagination(); break;
- case 'footer__toolbar__pagesizes': priv.renderFooterPageSizes(); break;
- case 'foot__columnPicker': priv.renderFooterColumnPicker(); break;
- case 'head__specialFilters': priv.renderHeadSpecialFilters(); break;
- }
- }
- priv.renderTable();
- }
- };
- priv.initialRender = function() {
- _uiNode$Table = $('<table class="AjaxTable table table-striped table-hover table-bordered table-condensed"></table>').appendTo(_uiNodeCont);
- _head = $('<thead></thead>').prependTo(_uiNode$Table);
- _headSort = $('<tr class="sort tblAjax__head__sort"></tr>').prependTo(_head);
- _headFilter = $('<tr class="filter tblAjax__head__filter"></tr>').appendTo(_head);
- _bodyNode = $('<tbody></tbody>').insertAfter(_head);
- $('<tfoot></tfoot>').insertAfter(_bodyNode);
- _foot = $('<div class="foot tblAjax__footer"></div>').insertAfter(_uiNodeCont);
- var footToolbar = $('<div class="btn-toolbar tblAjax__footer__toolbar"></div>').appendTo(_foot);
- $('<span class="tblAjax__footer__toolbar__info"></span>').appendTo(footToolbar);
- $('<span class="tblAjax__footer__toolbar__pagination"></span>').appendTo(footToolbar);
- $('<span class="tblAjax__footer__toolbar__pagesizes"></span>').appendTo(footToolbar);
- $('<span class="tblAjax__footer__toolbar__columnPicker"></span>').appendTo(footToolbar);
- $('<span class="tblAjax__footer__toolbar__functions"></span>').appendTo(footToolbar);
- $('<span class="tblAjax__footer__toolbar__export"></span>').appendTo(footToolbar);
- _mapEditorWrap = $('<div class="mapEditor" style="display:none"></div>').insertAfter(_foot);
- _mapEditor = $('<div class="mapEditor-map"></div>').appendTo(_mapEditorWrap);
- _popoverCell = $('<div class="popoverCell" style="display:none"></div>').insertAfter(_foot);
- $('<div class="tblAjax__inlineEditBox"></div>').insertAfter(_foot);
- $('<div class="btn-toolbar tblAjax__head__specialFilter"></div>').insertBefore(_uiNodeCont);
- priv.renderInlineEditBox();// .tblAjax__inlineEditBox
- _foot = _head = _body = _headSort = _headFilter = undefined;// TODO: refactor
- /// console.log('L.<?php echo __LINE__; ?> priv.initialRender, _uiNode$Table: ', _uiNode$Table.html())
- }
- /*
- creates the table with all its parts and handlers.
- note that only the parts we need is created.
- (yeah, the function is huge)
- */
- priv.renderTable = function() {
- //create table itself
- /// console.log('renderTable:: _data', _data);//TODO:DBG:RMME
- /// console.log('renderTable:: _uiNode$Table', _uiNode$Table);//TODO:DBG:RMME
- //create the header which will later hold both sorting and filtering
- /// console.log('L.<?php echo __LINE__; ?> renderTable:: _head', _head);//TODO:DBG:RMME
- if (!_head) {
- _headSort = _headFilter = _headSpecialFilter = undefined;
- //_head = $('<thead></thead>');
- // $('<tr class="sort"></tr>').prependTo(_head);
- //_uiNode$Table.find('thead').replaceWith(_head);
- _head = _uiNode$Table.find('thead');
- }
- //create the header sorting row
- if (!_headSort) {
- /// console.log('L.<?php echo __LINE__; ?> renderTable::renderTableTheadSort...');//TODO:DBG:RMME
- priv.renderTableTheadSort();
- }
- //create the header filtering row
- if (!_headFilter && priv.options.filter) {
- /// console.log('L.<?php echo __LINE__; ?> renderTable::renderTableTheadFilter...');//TODO:DBG:RMME
- priv.renderTableTheadFilter();
- _headFilter = true;
- }
- //create the header special filters row
- if (!_headSpecialFilter && priv.options.specialFilterFunctions) {
- priv.renderHeadSpecialFilters();
- _headSpecialFilter = true;
- }
- //create the body
- if (!_body) {
- _uiNode$Table.find('tbody').remove();
- _bodyNode = $('<tbody></tbody>').insertAfter(_head);
- //_bodyNode.on('change', '.unique', priv.rowChecked);
- //find out what rows to show next...
- var rowsAdded = 0;
- //slice out the chunk of data we need and create rows
- $.each(_data.rows, function(index, props) {
- var rowNode = priv.renderRow(props);
- if (rowNode) rowNode.appendTo(_bodyNode);
- rowsAdded++;
- //enough rows created?
- if (rowsAdded >= priv.options.pageSize) {
- return false;
- }
- });
- if (_state.page == 1) {
- _totalPages = Math.ceil(_data.total / priv.options.pageSize);
- }
- //pad with empty rows if we're at last page.
- if (_state.page == _totalPages) {
- while (rowsAdded < priv.options.pageSize) {
- var rowNode = priv.renderRowEmptyNode();
- if (rowNode) rowNode.appendTo(_bodyNode);
- rowsAdded++;
- }
- }
- }
- //create the footer
- if (!_foot) {
- priv.renderTableTfoot();
- priv.renderFooter();
- }
- _foot = $(_uiNodeCont).next('.foot');
- var stickyCol1Width = (12 + 3) * 4 + 2 * 5 + 1;
- var stickyCol2Width = 50 + 2 * 5 + 1;
- if (undefined === _tableWidth) {
- _tableWidth = true;
- var contW = jQuery(_uiNodeCont).width();
- var th1 = _uiNode$Table.find('.stickyCol1:first');
- var th2 = th1.next();
- var th1W = th1.innerWidth();
- var th2W = 50 + 2 * 5;//th2.innerWidth();
- var colsW = stickyCol1Width + stickyCol2Width;
- jQuery(_uiNodeCont).css({width:'' + (contW - colsW) + 'px', marginLeft:'' + colsW + 'px', overflowX:'scroll', overflowY:'visible', paddingBottom:'1px'});
- }
- _uiNode$Table.find('.stickyCol1').css({position:'absolute',
- left:'0',
- top:'auto',
- width:'' + stickyCol1Width + 'px',
- });
- //_uiNode$Table.find('.filter').find('.stickyCol1').css({height:'34px'});
- var sortStickyColHeight = _uiNode$Table.find('.sort').find('th:last').outerHeight();
- _uiNode$Table.find('.sort').find('.stickyCol1').css({height: sortStickyColHeight + 'px'});
- _uiNode$Table.find('.sort').find('.stickyCol2').css({height: sortStickyColHeight + 'px'});
- _uiNode$Table.find('.stickyCol2').css({position:'absolute',
- left:'' + (stickyCol1Width) + 'px',
- top:'auto',
- width:'' + stickyCol2Width + 'px',
- borderRight: '1px solid silver'
- });
- if (_data.total == 0 && priv.options.hidePagerOnEmpty) {
- $('.btn-toolbar', _foot).remove();
- }
- if (priv.options.debug) console.log('table created L.<?php echo __LINE__; ?>');
- if (typeof priv.options.tableCreated == 'function') {
- priv.options.tableCreated.call(_uiNode$Table.get(0), {table: _uiNode$Table.get(0)});
- }
- };
- priv.renderRow = function(props) {
- var rowNode = $('<tr></tr>'),
- uniqueColName = _state.uniqueCol,
- rowPK = (uniqueColName in props)? props[uniqueColName] : null,
- cellNode
- ;
- if (priv.options.rowFunctions || priv.options.filtersClean) {
- cellNode = priv.renderCellRowFunctions(priv.options.rowFunctions, rowPK, props);
- cellNode.addClass('text-right stickyCol1');
- cellNode.appendTo(rowNode);
- }
- //create checkbox
- if (_state.uniqueCol && priv.options.checkboxes) {
- var check = _uniqueCols[props[_state.uniqueCol]] != undefined ? 'checked' : '';
- var checkable = props['checkable'] === false ? 'disabled' : '';
- cellNode = $('<td></td>').appendTo(rowNode);
- $('<input class="unique" {0} {1} type="checkbox" />'.f(check, checkable)).appendTo(cellNode);
- }
- if (uniqueColName) rowNode.data('unique', rowPK);
- //create cells
- for (var i = 0; i < _state.colsSorted.length; i++) {
- var columnName = _state.colsSorted[i],
- columnProps = _data.cols[columnName],
- val = '',
- cellNode,
- cellCnt,
- format,
- showTooltip
- ;
- if (!columnProps) continue;
- if (columnProps.hidden) continue;// TODO: "unique" is hidden
- val = props[columnName];
- cellNode = $('<td></td>').appendTo(rowNode);
- if (columnName !== uniqueColName) {
- cellNode.on('dblclick', {id:rowPK, col:columnName}, priv.rowDblClicked);
- }
- if (i == 1) {// primaryKey(ID)
- cellCnt = $('<div></div>').appendTo(cellNode);// fix dblclick for copy
- cellNode.addClass('stickyCol2');
- } else {
- cellCnt = $('<span></span>').appendTo(cellNode);
- }
- cellNode.data('column', columnName);
- if (val === undefined) continue;
- format = props[columnName + 'Format'] || columnProps.format || '{0}';
- showTooltip = true;
- switch (columnProps.type) {
- case "string":
- cellCnt.html(format.f(val));
- break;
- case "number":
- val = Number(val);
- var forceDecimals = !isNaN(columnProps.decimals);
- if (forceDecimals) cellCnt.html(format.f(val.toFixed(columnProps.decimals)));
- else {
- (val || 0) % 1 === 0
- ? cellCnt.html(format.f(val))
- : cellCnt.html(format.f(val.toFixed(priv.options.types.number.decimals || 2)));
- }
- break;
- case "date":
- cellCnt.html(format.f(val));
- break;
- case "bool":
- $('<input type="checkbox" {0} disabled />'.f(val ? "checked" : "")).appendTo(cellCnt);
- break;
- case "special":
- cellCnt.html(format.f(val));
- break;
- case "simpleLink":
- var valLink = String(val);
- if (undefined !== columnProps._tsRetId
- && (0 === columnProps._tsRetId || '0' === columnProps._tsRetId)
- && undefined !== columnProps._tsSimpleLink) {
- valLink = columnProps._tsSimpleLink.format;
- $.each(columnProps._tsSimpleLink.aliasMap, function(i, v) {
- //console.log('simpleLink aliasMap columnName:', columnName, 'i:', i, 'v:', v, 'props['+v+']', props[v], 'val', val, 'typeof val', typeof val);
- if (undefined !== props[v]) {
- valLink = valLink.replace(new RegExp('\{' + i + '\}', 'g'), props[v]);
- }
- });
- }
- cellCnt.html(format.f(valLink));
- break;
- case "geom":
- cellCnt.TableAjaxGeomField({
- recordID: rowPK,
- fieldValue: val,
- hasValueClassName: 'cell-mapfld-hasValue',
- //removeUrl: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=THE_GEOM_REMOVE&ID=' + rowPK,
- linkClassNamePrefix: 'cell-mapfld',
- linkSelectClassName: 'select',
- linkSelectAddClassNames: 'glyphicon glyphicon-map-marker',
- linkRemoveClassName: 'remove',
- linkRemoveAddClassNames: 'glyphicon glyphicon-remove',
- onSelect: function(recordID, geomShape) {
- if (priv.options.debug) console.log('recordID:', recordID, 'geomShape:', geomShape);
- priv.mapEditorShow();
- _mapEditor.TableAjaxMapSelectRecord(recordID, geomShape);
- },
- onRemove: function(geomField, recordID, geomShape) {
- if (confirm('Czy usunąć obiekt z mapy dla rekordu ' + recordID + '?')) {
- if (!recordID) return;
- var selectedRecordId = recordID;
- function notifyAjaxCallback(data) {
- var notify = {};
- notify.type = (data && data.type)? data.type : '';
- notify.msg = (data && data.msg)? data.msg : '';
- switch (notify.type) {
- case 'success':
- if (!notify.msg) notify.msg = 'Usunięto obiekt z mapy dla rekordu ' + selectedRecordId;
- break;
- case 'info':
- if (!notify.msg) notify.msg = 'Rekord nie był powiązany z żadnym obiektem na mapie';
- break;
- case 'error':
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- case 'warning':
- notify.type = 'warn';
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- default:
- notify.msg = 'Nieznany błąd';
- if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
- notify.type = '';
- }
- jQuery.notify(notify.msg, notify.type);
- }
- $.ajax({
- data: {},
- dataType: 'json',
- type: "POST",
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=THE_GEOM_REMOVE&ID=' + recordID
- })
- .done(function(data, textStatus, jqXHR){
- notifyAjaxCallback(data);
- if (priv.options.debug) console.log('data.record.the_geom:', data.record.the_geom);
- if (data && data.record && data.record.the_geom) {
- if (priv.options.debug) console.log('data.record.the_geom:2:', data.record.the_geom);
- geomField.setValue(data.record.the_geom);
- }
- else if (data && data.record) {
- if (priv.options.debug) console.log('data.record.the_geom:2:', data.record.the_geom);
- geomField.setValue(data.record.the_geom);
- }
- _mapEditor.TableAjaxMapRefresh();
- })
- .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
- if (jqXHR.responseJSON) {
- notifyAjaxCallback(jqXHR.responseJSON);
- }
- else {
- var txt = jqXHR.responseText || 'Wystąpiły błędy';
- if (jqXHR.status == 404) {
- jQuery.notify(jqXHR.responseText, 'error');
- } else {
- jQuery.notify(jqXHR.responseText, 'warn');
- }
- }
- });
- }
- }
- });
- break;
- }
- if (columnProps._tsRetId) {
- showTooltip = false;
- if (columnProps._tsRetId > 0) {
- cellCnt.on('click', {id:rowPK, col:columnName, friendly:columnProps.friendly, value:format.f(val)}, priv.popoverCellTypeSpecial);
- }
- }
- if (i > 1 && priv.options.longDesc) {// TODO: use better check for columns: functions and pk
- cellNode.addClass('tbl-short-txt');
- if (showTooltip) {
- cellCnt.tooltip({title: cellCnt.text(), placement: 'left'});
- }
- }
- }
- return rowNode;
- };
- priv.renderCellRowFunctions = function(rowFunctions, rowPK, rowProps) {
- var cellNode = $('<td></td>'),
- keys = Object.keys(rowFunctions),
- total = keys.length,
- moreFuncBtnNode,
- moreFunctions = [],
- idx
- ;
- if (priv.options.debug) console.log('TableAjax::renderCellRowFunctions: rowFunctions', rowFunctions);
- idx = keys.indexOf('hist');
- if (idx !== -1) {
- histFunc = keys.splice(idx, 1);
- keys.push('hist');
- }
- moreFunctions = keys.splice(3);
- keys.forEach(function(key) {
- var funObj = rowFunctions[key],
- funcNode = priv.generateFunctionNode(funObj, rowPK, {ico: true, label: false})
- ;
- funcNode.appendTo(cellNode);
- });
- moreFuncBtnNode = $('<a href="#" style="margin:0 2px;text-decoration:none" title="Więcej funkcji dla rekordu nr '+rowPK+'" class="glyphicon glyphicon-menu-hamburger"> </a>');
- moreFuncBtnNode.on('click', {rowPK: rowPK, rowFunctions: rowFunctions, more: moreFunctions}, priv.popoverCellMoreFunctions);
- moreFuncBtnNode.appendTo(cellNode);
- return cellNode;
- };
- priv.popoverCellMoreFunctions = function(e) {
- e.preventDefault();
- e.stopPropagation();
- if (priv.options.debug) console.log('TableAjax::popoverCellMoreFunctions: rowPK', e.data.rowPK, 'moreFunctions', e.data.more, 'rowFunctions', e.data.rowFunctions);
- if ('rowPK' in e.data && e.data.rowPK > 0) {
- var lastId = _popoverCell.data('rowid'),
- lastCol = _popoverCell.data('col'),
- rowPK = e.data.rowPK,
- moreFunctions = e.data.more,
- rowFunctions = e.data.rowFunctions,
- funcListNode
- ;
- if (lastId == e.data.rowPK && lastCol == 'moreFunctions') {
- //_popoverCellCurrent.popover('toggle');
- }
- else {
- if (_popoverCellCurrent) {
- _popoverCellCurrent.popover('destroy');
- }
- _popoverCell.data('rowid', rowPK);
- _popoverCell.data('col', 'rowFunctions');
- _popoverCell.empty();
- funcListNode = $('<ul class="list-unstyled"></ul>').appendTo(_popoverCell);
- moreFunctions.forEach(function(funcName) {
- var funcItemNode = $('<li></li>').appendTo(funcListNode),
- funObj = rowFunctions[funcName],
- funcNode = priv.generateFunctionNode(funObj, rowPK, {ico: true, label: true})
- ;
- funcItemNode.append(funcNode);
- });
- _popoverCell.append('<div class="popoverCellContent" style="white-space:normal"></div>');
- _popoverCellCurrent = jQuery(e.currentTarget);
- // title : '<span class="text-info"><strong>title</strong></span> <button type="button" id="close" class="close">×</button>'
- var opts = {
- container: 'body',
- placement: 'right',
- trigger: 'click',
- template: '',
- html: true,
- content: _popoverCell.html()
- }
- opts.template += '<div class="popover" role="tooltip" style="max-width:400px;width:300px;">';
- {
- opts.template += '<div class="arrow"></div>';
- //opts.template += '<h3 class="popover-title"></h3>';
- opts.template += '<div style="display:block;position:relative;">';
- {
- opts.template += '<div class="popover-title">';
- opts.template += '</div>';
- opts.template += '<button type="button" class="close" onclick="return hidePopover();" style="position:absolute;right:8px;top:6px;">×</button>';
- }
- opts.template += '</div>';
- opts.template += '<div class="popover-content"></div>';
- }
- opts.template += '</div>';
- _popoverCellCurrent.popover(opts);
- _popoverCellCurrent.on('shown.bs.popover', function(e) {
- if (_popoverCellCurrent) {
- var popoverNodeId = _popoverCellCurrent.attr('aria-describedby');
- if (popoverNodeId) {
- jQuery('#' + popoverNodeId).find('.popoverCellContent').html('<p class="text-muted">Pobieranie funkcji...<p>');
- }
- }
- priv.ajaxLoadMoreFunctionsCell(rowPK);
- });
- _popoverCellCurrent.popover('show');
- }
- } else {
- if (priv.options.debug) console.log('NO data');
- return false;
- }
- return;
- };
- priv.generateFunctionNode = function(funObj, rowPK, props) {
- var defaultsProps = {
- ico: true,
- label: false
- },
- props = $.extend({}, defaultsProps, props);
- funcNode = $('<a href="#" style="margin:0 2px;"></a>')
- ;
- if ('href' in funObj) funcNode.attr('href', funObj.href.f(rowPK));
- if (props.ico) {
- if ('ico' in funObj) funcNode.append('<span class="' + funObj.ico + '"></span>');
- }
- if ('onclick' in funObj) funcNode.attr('onclick', funObj.onclick.f(rowPK));
- if ('title' in funObj) funcNode.attr('title', funObj.title);
- if (props.label) {
- if ('title' in funObj) funcNode.append(' ' + funObj.title);
- }
- return funcNode;
- };
- priv.ajaxLoadMoreFunctionsCell = function(rowPK) {
- if (_popoverCellAjaxXhr) {
- _popoverCellAjaxXhr.abort();
- }
- _popoverCellAjaxXhr = $.ajax({
- type: 'GET',
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=MORE_FUNCTIONS_CELL&ID=' + rowPK,
- dataType: 'json',
- contentType: "application/json; charset=utf-8",
- data: ''
- })
- .done(function(data, textStatus, jqXHR){
- if (data && 'success' === data.type) {
- var popoverCellContent,
- rowFunctions = []
- ;
- if (data.rowFunctions && data.rowFunctions.length > 0) {
- rowFunctions = data.rowFunctions;
- }
- if (rowFunctions.length > 0) {
- var popoverCellContent = $('<ul class="list-unstyled"></ul>');
- rowFunctions.forEach(function(funObj) {
- var funcItemNode = $('<li></li>').appendTo(popoverCellContent),
- funcNode = priv.generateFunctionNode(funObj, rowPK, {ico: true, label: true})
- ;
- funcItemNode.append(funcNode);
- });
- } else {
- popoverCellContent = '<p class="text-muted">Brak dodatkowych funkcji</p>';
- }
- //_popoverCell.append(popoverCellContent);// cache
- if (_popoverCellCurrent) {
- var popoverNodeId = _popoverCellCurrent.attr('aria-describedby');
- if (popoverNodeId) {
- var pooverCntNode = jQuery('#' + popoverNodeId).find('.popoverCellContent');
- pooverCntNode.empty().append(popoverCellContent);
- if (rowFunctions.length <= 0) {
- pooverCntNode.find('p.text-muted').delay(600).hide(300);
- }
- }
- }
- }
- });
- };
- priv.renderRowEmptyNode = function() {
- var rowNode = $('<tr></tr>');
- if (priv.options.rowFunctions || priv.options.filtersClean) {
- $('<td class="text-right stickyCol1"> </td>').appendTo(rowNode);
- }
- if (_state.uniqueCol && priv.options.checkboxes) {
- $('<td><input disabled type="checkbox" /></td>').appendTo(rowNode);
- }
- for (var i = 0; i < _state.colsSorted.length; i++) {
- var columnName = _state.colsSorted[i],
- columnProps = _data.cols[columnName]
- ;
- if (!columnProps) return;
- if (columnProps.hidden) continue;// "unique" is hidden - TODO: rm "unique" from _state.colsSorted ?
- if (i == 1) {// TODO: 1 is pk - use better check
- $('<td class="stickyCol2"> </td>').appendTo(rowNode);
- } else {
- $('<td> </td>').appendTo(rowNode);
- }
- }
- return rowNode;
- };
- priv.renderTableTheadSort = function() {
- var nodeClass = 'tblAjax__' + 'head__sort',
- currentNode = _uiNode$Table.find('thead').find('.' + nodeClass),
- node;
- // currentNode.find('i').tooltip('hide');
- node = $('<tr class="sort ' + nodeClass + '"></tr>');
- //create the functions column
- if (priv.options.rowFunctions || priv.options.filtersClean) {
- var headCell = $('<th class="text-right head-info stickyCol1"></th>').appendTo(node);
- $.map(priv.options.tblFunctions, function(funObj, funName){
- var funHtml = $('<a></a>');
- funHtml.attr('href', funObj.href || '#');
- if (funObj.title) funHtml.attr('title', funObj.title);
- if (funObj.icon) funHtml.html('<span class="glyphicon glyphicon-' + funObj.icon + '"></span> ');
- if (funObj.method && priv[funObj.method] && typeof priv[funObj.method] == 'function') {
- funHtml.on('click', priv[funObj.method]);
- }
- funHtml.appendTo(headCell);
- });
- }
- //create the checkall toggle
- if (_state.uniqueCol && priv.options.checkboxes) {
- var checked = _checkToggleChecked ? 'checked' : '';
- var headCell = $('<th></th>').appendTo(node);
- var elem = $('<input {0} class="checkToggle" type="checkbox" />'.f(checked)).appendTo(headCell);
- elem.on('change', priv.checkToggleChanged);
- }
- //create the sortable headers
- for (var i = 0; i < _state.colsSorted.length; i++) {
- var column = _state.colsSorted[i];
- var props = _data.cols[column];
- if (!props.hidden) {
- var headCell = $('<th class="ta-ordering"></th>').appendTo(node);
- if (i == 1) headCell.addClass('stickyCol2');
- if (false) {// TODO: old way
- var link = $('<a class="pull-left" href="#">{0}</a>'.f(props.friendly || column));
- link.on('click', {column: column}, priv.columnClicked).appendTo(headCell);
- if (props.tooltip) {
- $('<i class="glyphicon glyphicon-info-sign"></i>').tooltip({
- title: props.tooltip.trim(),
- html: true,
- container: 'body',
- placement: "top",
- delay: {
- show: 500,
- hide: 100
- }
- }).appendTo(link);
- }
- //Add sort arrow
- if (column == _state.filters.currSortCol) {
- if (_state.filters.currSortFlip) $('<i class="glyphicon glyphicon-chevron-down pull-right"></i>').appendTo(headCell);
- else $('<i class="glyphicon glyphicon-chevron-up pull-right"></i>').appendTo(headCell);
- }
- //Add hide btn
- if (column != 'ID') {
- var hideColBtn = $('<i class="glyphicon glyphicon-remove pull-right hover-show"></i>');
- hideColBtn.on('click', {column: column}, priv.columnHideClicked);
- hideColBtn.appendTo(headCell);
- }
- }
- if (props.type != 'special' && props.type != 'geom') {
- headCell.on('click', {column: column}, priv.columnClicked);
- }
- var colTitle = column;
- if (props.description && props.description.length > 0) {
- colTitle = props.description;
- colTitle += ' (' + column + ')';
- }
- else if (props._tsRetId > 0) {
- colTitle = 'Kliknij na pole i przejdź do powiązanych rekordów (' + colTitle + ')';
- }
- if (props.friendly) {
- var headCnt = $('<span class="pull-left" title="{1}">{0}</span>'.f(props.friendly, colTitle));
- } else {
- var headCnt = $('<span class="pull-left" title="{1}">{0}</span>'.f(column, colTitle));
- }
- headCnt.appendTo(headCell);
- //Add sort arrow
- if (column == _state.filters.currSortCol) {
- if (_state.filters.currSortFlip) headCell.addClass('ta-ordering-down');
- else headCell.addClass('ta-ordering-up');
- }
- if (column != 'ID') {
- var hideColBtn = $('<i class="glyphicon glyphicon-remove remove-cell"></i>');
- hideColBtn.on('click', {column: column}, priv.columnHideClicked);
- hideColBtn.appendTo(headCell);
- }
- }
- }
- currentNode.replaceWith(node);
- };
- priv.renderHeadSpecialFilters = function() {
- var nodeClass = 'tblAjax__' + 'head__specialFilter',
- currentNode = $(_uiNodeCont).prev('.' + nodeClass),
- node;
- /// console.log('L.<?php echo __LINE__; ?> renderTable::renderTableTheadFilter...');//TODO:DBG:RMME
- if (!priv.options.specialFilterFunctions) {
- return;
- }
- var node = $('<div class="btn-toolbar tblAjax__head__specialFilter"></div>');
- $.map(priv.options.specialFilterFunctions, function(groupObj, groupName) {
- var btnHtml, btnSelected, groupHtml = $('<div class="btn-group"></div>');
- // _state.specialFilters[e.data.group] = e.data.value;
- if (groupName in _state.specialFilters) {
- btnSelected = _state.specialFilters[groupName];
- }
- if (groupObj.icon) {
- $('<button class="btn btn-xs btn-default" title="' + groupName + '"><i class="' + groupObj.icon + '"></i></button>').appendTo(groupHtml);
- }
- $.map(groupObj.btns, function(btnObj, btnName) {
- btnHtml = $('<button class="btn btn-xs btn-default' + ((btnSelected && btnSelected == btnObj.value)? ' active' : '') + '">' + btnName + '</button>').appendTo(groupHtml);
- btnHtml.on('click', {group: groupName, value: btnObj.value}, priv.specialFilterChanged);
- });
- btnHtml = $('<button class="btn btn-xs btn-default' + ((!btnSelected)? ' disabled' : '') + '" title="Kasuj filtr"><i class="glyphicon glyphicon-remove"></i></button>').appendTo(groupHtml);
- btnHtml.on('click', {group: groupName, value: ''}, priv.specialFilterChanged);
- groupHtml.appendTo(node);
- });
- currentNode.replaceWith(node);
- };
- priv.renderTableTheadFilter = function() {
- var nodeClass = 'tblAjax__' + 'head__filter',
- currentNode = _uiNode$Table.find('thead').find('.' + nodeClass),
- node;
- // currentNode.find('i').tooltip('hide');
- node = $('<tr class="filter ' + nodeClass + '"></tr>');
- //_head.find(".filter").remove();
- //_headFilter = $('<tr class="filter"></tr>').appendTo(_head);
- var headCell;
- var elem;
- var placeHolder = '';
- var tooltip = '';
- //create the functions column
- if (priv.options.rowFunctions || priv.options.filtersClean) {
- var headCell = $('<th class="text-right stickyCol1"></th>').appendTo(node);
- headCell.css({padding: '0'});
- if (priv.options.filtersClean) {
- var elem = $('<button title="Kasuj filtry" class="btn btn-xs btn-link glyphicon glyphicon-remove"></button>').appendTo(headCell);
- elem.on('click', priv.filtersClean);
- }
- }
- //create the filter checkbox
- if (_state.uniqueCol && priv.options.checkboxes) {
- tooltip = priv.options.types.bool.filterTooltip || 'Toggle between:<br/>indeterminate,<br/>checked,<br/>unchecked';
- headCell = $('<th></th>').appendTo(node);
- elem = $('<input class="filter indeterminate" checked type="checkbox" />').appendTo(headCell);
- $.map(_state.filters.filterCols, function(colProps, col) {
- if (col == "unique") {
- if (colProps.filter) elem.prop('checked', true).removeClass('indeterminate');
- else if (!colProps.filter) elem.prop('checked', false).removeClass('indeterminate');
- else if (colProps.filter == '') elem.addClass('indeterminate');
- }
- });
- if (tooltip) {
- elem.tooltip({
- title: tooltip.trim(),
- html: true,
- container: 'body',
- trigger: 'hover',
- placement: 'top',
- delay: {
- show: 500,
- hide: 100
- }
- });
- }
- elem.on('click', {column: "unique"}, priv.filterChanged);
- }
- //create the column filters
- for (var i = 0; i < _state.colsSorted.length; i++) {
- var column = _state.colsSorted[i];
- var props = _data.cols[column];
- tooltip = props.filterTooltip === true ? undefined : props.filterTooltip === false ? '' : props.filterTooltip;
- placeHolder = props.placeHolder === true ? undefined : props.placeHolder === false ? '' : props.placeHolder;
- if (!props.hidden) {
- headCell = $('<th></th>').appendTo(node);
- headCell.css({padding: '0'});
- if (i == 1) headCell.addClass('stickyCol2');
- // @mark MarkTableAjaxFilterColType
- switch (props.type || 'string') {
- case "number":
- if (placeHolder == undefined) placeHolder = priv.options.types.number.placeHolder;
- placeHolder = (placeHolder === true || placeHolder == undefined) ? '10..20 =50' : placeHolder === false ? '' : placeHolder;
- if (tooltip == undefined) tooltip = priv.options.types.number.filterTooltip;
- tooltip = (tooltip === true || tooltip == undefined) ? 'Values 10 to 20:<br/>10..20<br/>Values exactly 50:<br/>=50' : tooltip === false ? '' : tooltip;
- elem = $('<input placeholder="{0}" class="filter" type="text" />'.f(placeHolder));
- elem.on('keyup', {column: column}, priv.filterChanged);
- break;
- case "date":
- if (placeHolder == undefined) placeHolder = priv.options.types.date.placeHolder;
- placeHolder = (placeHolder === true || placeHolder == undefined) ? '-7..0' : placeHolder === false ? '' : placeHolder;
- if (tooltip == undefined) tooltip = priv.options.types.date.filterTooltip;
- tooltip = (tooltip === true || tooltip == undefined) ? 'Today:<br/>0..1<br/>A week today excluded:<br/>-7..0' : tooltip === false ? '' : tooltip;
- elem = $('<div><input placeholder="{0}" class="filter" type="text" /></div>'.f(placeHolder));
- if (priv.options.types.date.datePicker === true || priv.options.types.date.datePicker == undefined)
- {
- if ($().datepicker)
- {
- elem.addClass('date-wrap');
- var today = 0;//new priv.ext.XDate(false).setHours(0, 0, 0, 0).toString('yyyy-MM-dd');
- var dp = $('<div style="float:right" class="date" data-date="{0}" data-date-format="{1}" />'.f(today, 'yyyy-mm-dd')).appendTo(elem);
- $('<input style="display:none" type="text" />').appendTo(dp);
- $('<span class="add-on"><i class="glyphicon glyphicon-chevron-right"></i></span>').on('click', {op: "l"}, priv.dpOpChanged).appendTo(dp);
- $('<span class="add-on"><i class="glyphicon glyphicon-chevron-left"></i></span>').on('click', {op: "r"}, priv.dpOpChanged).appendTo(dp);
- dp.datepicker({weekStart:1});
- dp.on('changeDate', {column: column, input: $('input.filter', elem)}, priv.dpClicked);
- }
- else
- if (priv.options.debug) console.log('datepicker plugin not found');
- }
- elem.on('keyup', 'input.filter', {column: column}, priv.filterChanged);
- break;
- case "bool":
- if (tooltip == undefined) tooltip = priv.options.types.bool.filterTooltip;
- tooltip = (tooltip === true || tooltip == undefined) ? 'Toggle between:<br/>indeterminate,<br/>checked,<br/>unchecked' : tooltip === false ? '' : tooltip;
- elem = $('<input class="filter indeterminate" checked type="checkbox" />');
- elem.on('click', {column: column}, priv.filterChanged);
- break;
- case "string":
- if (placeHolder == undefined) placeHolder = priv.options.types.string.placeHolder;
- placeHolder = (placeHolder === true || placeHolder == undefined) ? '%' : placeHolder === false ? '' : placeHolder;
- if (tooltip == undefined) tooltip = priv.options.types.string.filterTooltip;
- tooltip = (tooltip === true || tooltip == undefined) ? 'Find str: str<br/>Find all but str: !str<br/>Find str inside: %str%' : tooltip === false ? '' : tooltip;
- elem = $('<input placeholder="{0}" class="filter" type="text" size="8" />'.f(placeHolder));
- elem.on('keyup', {column: column}, priv.filterChanged);
- break;
- case "special":
- elem = $('<div> </div>');
- break;
- case "simpleLink":
- elem = $('<div> </div>');
- break;
- case "geom":
- if (placeHolder == undefined) placeHolder = priv.options.types.string.placeHolder;
- placeHolder = (placeHolder === true || placeHolder == undefined) ? '%' : placeHolder === false ? '' : placeHolder;
- elem = $('<input placeholder="{0}" class="filter" type="text" size="8" />'.f(placeHolder));
- elem.on('keyup', {column: column}, priv.filterChanged);
- break;
- case "none":
- elem = $('<div> </div>');
- break;
- }
- if (false) {// tooltip OFF - (tooltip)
- elem.tooltip({
- title: tooltip.trim(),
- html: true,
- container: 'body',
- trigger: 'focus',
- placement: 'top',
- delay: {
- show: 500,
- hide: 100
- }
- });
- }
- if (elem && props.filter) {
- $.map(_state.filters.filterCols, function(colProps, col) {
- if (col == column) {
- var columnSettings = _data.cols[col];
- if (columnSettings.type == 'bool') {
- if (colProps.filter) elem.prop('checked', true).removeClass('indeterminate');
- else if (!colProps.filter) elem.prop('checked', false).removeClass('indeterminate');
- else if (colProps.filter == '') elem.addClass('indeterminate');
- }
- else elem.val(colProps.filter);
- }
- });
- if (priv.options.forceFilterInit && undefined !== priv.options.forceFilterInit[column]) {
- elem.prop('disabled', true);
- }
- elem.appendTo(headCell);
- _filterFields[column] = elem;
- }
- }
- }
- currentNode.replaceWith(node);
- };
- priv.renderTableTfoot = function() {
- _uiNode$Table.find('tfoot').remove();
- _foot = $('<tfoot></tfoot>').insertAfter(_bodyNode);
- //$(_uiNodeCont).next('.foot').replaceWith(_foot);
- };
- priv.renderFooter = function() {
- priv.renderFooterInfo();
- priv.renderFooterPagination();
- priv.renderFooterPageSizes();
- priv.renderFooterColumnPicker();
- priv.renderFooterFunctions();
- priv.renderFooterExport();
- };
- priv.renderFooterInfo = function() {
- var nodeClass = 'tblAjax__' + 'footer__toolbar__info',
- currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
- node;
- if (priv.options.debug) console.log('Render: ', nodeClass);
- node = $('<div class="foot-info ' + nodeClass + '"></div>');
- //console.log('renderFooterInfo total', _data.total, 'page', _state.page, 'priv.options.pageSize', priv.options.pageSize);
- var fromRow = Math.max(_state.page - 1, 0) * _state.pageSize;
- var total = _data.total;
- var toRow = Math.min(fromRow + _state.pageSize, total);
- if (_data.total > 0) {
- $('<p>Wiersze od {0} do {1} z {2}</p>'.f(fromRow + 1, toRow, total)).appendTo(node);
- } else {
- $('<p>Brak wierszy pasujących do kryteriów wyszukiwania</p>').appendTo(node);
- }
- currentNode.replaceWith(node);
- };
- priv.renderFooterPagination = function() {
- var nodeClass = 'tblAjax__' + 'footer__toolbar__pagination',
- currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
- node;
- var currPage = _state.page;
- var totalPages = Math.ceil(_data.total / _state.pageSize);
- if (priv.options.debug) console.log('Render: ', nodeClass, '_data.total', _data.total, 'currPage', currPage);
- /// console.log('Render: ', nodeClass, '_data.total', _data.total, 'currPage', currPage, '_state.page', _state.page);
- if (_data.total > 0) {
- node = $('<div class="btn-group ' + nodeClass + '"></div>');
- //create the pager.
- var lowerPage = currPage - 2;
- var upperPage = currPage + 2;
- if (upperPage > totalPages) {
- var diff = upperPage - totalPages;
- upperPage = totalPages;
- lowerPage -= diff;
- }
- if (lowerPage < 1) lowerPage = 1;
- if (upperPage < 5) upperPage = 5;
- //$('<li class="{0}"><a href="#"><<</a></li>'.f(currPage == 1 ? 'disabled' : ''))
- $('<button type="button" class="btn btn-default{0}"><<</button>'.f(currPage == 1 ? ' disabled' : ''))
- .on('click', {pageIndex: 1}, priv.pageChanged)
- .appendTo(node);
- //$('<li class="{0}"><a href="#"><</a></li>'.f(currPage == 1 ? 'disabled' : ''))
- $('<button type="button" class="btn btn-default{0}"><</button>'.f(currPage == 1 ? ' disabled' : ''))
- .on('click', {pageIndex: currPage - 1}, priv.pageChanged)
- .appendTo(node);
- for (var i = lowerPage; i <= upperPage; i++) {
- var link;
- //if (i != currPage) link = $('<li class="{1}"><a href="#">{0}</a></li>'.f(i, i > totalPages ? 'disabled' : ''));
- if (i != currPage) link = $('<button type="button" class="btn btn-default{1}">{0}</button>'.f(i, i > totalPages ? 'disabled' : ''));
- //if (i == currPage) link = $('<li class="active"><a href="#">{0}</a></li>'.f(i));
- if (i == currPage) link = $('<button type="button" class="btn btn-default active">{0}</button>'.f(i));
- if (link) {
- link.on('click', {pageIndex: i}, priv.pageChanged);
- link.appendTo(node);
- }
- }
- //$('<li class="{0}"><a href="#">></a></li>'.f(currPage == totalPages ? 'disabled' : ''))
- $('<button type="button" class="btn btn-default{0}">></button>'.f(currPage == totalPages ? ' disabled' : ''))
- .on('click', {pageIndex: currPage + 1}, priv.pageChanged)
- .appendTo(node);
- //$('<li class="{0}"><a href="#">>></a></li>'.f(currPage == totalPages ? 'disabled' : ''))
- $('<button type="button" class="btn btn-default{0}">>></button>'.f(currPage == totalPages ? ' disabled' : ''))
- .on('click', {pageIndex: totalPages}, priv.pageChanged)
- .appendTo(node);
- } else {
- node = $('<span class="' + nodeClass + '"></span>');
- }
- currentNode.replaceWith(node);
- };
- priv.renderFooterPageSizes = function() {
- var nodeClass = 'tblAjax__' + 'footer__toolbar__pagesizes',
- currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
- node;
- if (priv.options.debug) console.log('Render: ', nodeClass);
- if (_data.total > 0 && priv.options.pageSizes.length > 0) {
- node = $('<div class="btn-group dropup pagesize ' + nodeClass + '"></div>');
- var btn = $('<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Liczba wierszy </button>').appendTo(node);
- var span = $('<span class="caret"></span>').appendTo(btn);
- var ul = $('<ul class="dropdown-menu">').appendTo(node);
- $.each(priv.options.pageSizes, function(index, val) {
- var li = $('<li></li>').appendTo(ul);
- if (val == priv.options.pageSize) {
- $('<a style="color:#337AB7;">{0}</a>'.f(val)).appendTo(li);
- } else {
- $('<a href="#">{0}</a>'.f(val)).appendTo(li);
- }
- });
- node.on('click', 'a', priv.pageSizeChanged);
- } else {
- node = $('<span class="' + nodeClass + '"></span>');
- }
- currentNode.replaceWith(node);
- };
- priv.renderFooterColumnPicker = function() {
- var nodeClass = 'tblAjax__' + 'footer__toolbar__columnPicker',
- currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
- node;
- if (priv.options.debug) console.log('Render: ', nodeClass);
- if (priv.options.columnPicker) {
- node = $('<div class="btn-group dropup columnpicker ' + nodeClass + '"></div>');
- var btn = $('<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Kolumny </button>').appendTo(node);
- var span = $('<span class="caret"></span>').appendTo(btn);
- var ul = $('<ul class="dropdown-menu">').appendTo(node);
- $.each(_data.cols, function(col, props) {
- if (props.type != "unique" && col != 'ID') {
- var li = $('<li></li>').appendTo(ul),
- label = props.friendly || col;
- label = label.replace(/<br\/?>/g, ' ');
- $('<input {0} type="checkbox" title="{1}" value="{1}" > {2}</input>'.f((props.hidden) ? '' : 'checked', col, label)).appendTo(li);
- }
- });
- node.on('click', 'input', priv.columnPickerClicked);
- } else {
- node = $('<span class="' + nodeClass + '"></span>');
- }
- currentNode.replaceWith(node);
- };
- priv.renderFooterFunctions = function() {
- var nodeClass = 'tblAjax__' + 'footer__toolbar__functions',
- currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
- node;
- if (priv.options.debug) console.log('Render: ', nodeClass);
- if (priv.options.tblFunctions) {
- node = $('<div class="btn-group ' + nodeClass + '"></div>');
- $.map(priv.options.tblFunctions, function(funObj, funName){
- var funHtml = $('<button class="btn btn-sm btn-default"></button>');
- if (funObj.title) funHtml.attr('title', funObj.title);
- if (funObj.method) funHtml.on('click', priv[funObj.method]);
- else if (funObj.href) funHtml.on('click', {hash:funObj.href}, priv.routeChanged);
- var funIconHtml = $('<i></i>');
- if (funObj.icon) funIconHtml.attr('class', 'glyphicon glyphicon-' + funObj.icon);
- funIconHtml.prependTo(funHtml);
- funHtml.addClass('btn');
- funHtml.appendTo(node);
- });
- } else {
- node = $('<span class="' + nodeClass + '"></span>');
- }
- currentNode.replaceWith(node);
- };
- priv.renderFooterExport = function() {
- var nodeClass = 'tblAjax__' + 'footer__toolbar__export',
- currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
- node;
- if (priv.options.debug) console.log('Render: ', nodeClass);
- if (priv.options.exportFields.length) {
- node = $('<div class="btn-group dropup pagesize ' + nodeClass + '"></div>');
- var btn = $('<button class="btn btn-sm dropdown-toggle" data-toggle="dropdown" href="#">Export </button>').appendTo(node);
- var span = $('<span class="caret"></span>').appendTo(btn);
- var ul = $('<ul class="dropdown-menu">').appendTo(node);
- $.each(_data.cols, function(col, props) {
- if (-1 !== priv.options.exportFields.indexOf(col)) {
- var li = $('<li></li>').appendTo(ul);
- $('<input {0} type="checkbox" title="{1}" value="{1}" > {2}</input>'.f((_exportFieldsSelect[col])? 'checked' : '', col, props.friendly || col)).appendTo(li);
- li.on('click', 'input', priv.exportFieldChanged);
- }
- });
- var li = $('<li></li>').appendTo(ul);
- $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do HTML</a>').appendTo(li);
- li.on('click', 'a', priv.exportToHTML);
- var li = $('<li></li>').appendTo(ul);
- $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do CSV</a>').appendTo(li);
- li.on('click', 'a', priv.exportToCSV);
- } else {
- node = $('<span class="' + nodeClass + '"></span>');
- }
- currentNode.replaceWith(node);
- };
- priv.renderInlineEditBox = function() {
- var nodeClass = 'tblAjax__' + 'inlineEditBox',
- currentNode = $(_uiNodeCont).parent().children('.' + nodeClass),
- node;
- var node = $('<div class="' + nodeClass + ' modal fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>');
- /// console.log('L.<?php echo __LINE__; ?> Render: priv.renderInlineEditBox, currentNode.html:', currentNode.html(), currentNode);
- var modalWrap = $('<div class="modal-dialog"></div>').appendTo(node);
- var modalWrap = $('<div class="modal-content"></div>').appendTo(modalWrap);
- var frmInlineEdit = $('<form style="margin:0;padding:0;"></form>').appendTo(modalWrap);
- var iebHead = $('<div class="modal-header" style="cursor:pointer">').appendTo(frmInlineEdit);
- $('<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="glyphicon glyphicon-remove" style="color:red"></i></button>').appendTo(iebHead);
- $('<h4 id="myModalLabel">Edytuj</h4>').appendTo(iebHead);
- var iebBodyWrap = $('<div class="modal-body" style="padding:0"></div>').appendTo(frmInlineEdit);
- var iebBody = $('<div style="padding:15px"></div>').appendTo(iebBodyWrap);
- $('<input type="hidden" name="ID" value="">').appendTo(iebBody);
- $('<input type="hidden" name="col" value="">').appendTo(iebBody);
- $('<div class="inlineEditBox-cnt"></div>').appendTo(iebBody);
- var iebFoot = $('<div class="modal-footer"></div>').appendTo(frmInlineEdit);
- $('<button class="btn" data-dismiss="modal" aria-hidden="true">Zamknij</button>').appendTo(iebFoot);
- var iebBtnSave = $('<input type="submit" value="Zapisz" class="btn btn-primary btn-save">').appendTo(iebFoot);
- frmInlineEdit.on('submit', function() {
- var inlineEditBox$Node = $(_uiNodeCont).parent().children('.tblAjax__inlineEditBox');
- var data = inlineEditBox$Node.find('form').serialize();
- inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
- function notifyAjaxCallback(data) {
- var notify = {};
- notify.type = (data && data.type)? data.type : '';
- notify.msg = (data && data.msg)? data.msg : '';
- switch (notify.type) {
- case 'success':
- if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
- break;
- case 'info':
- if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
- break;
- case 'error':
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- case 'warning':
- notify.type = 'warn';
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- default:
- notify.msg = 'Nieznany błąd';
- if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
- notify.type = '';
- }
- jQuery.notify(notify.msg, notify.type);
- }
- $.ajax({
- data: data,
- dataType: 'json',
- type: "POST",
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT_INLINE_SAVE'
- })
- .done(function(data, textStatus, jqXHR){
- notifyAjaxCallback(data);
- publ.refresh();
- inlineEditBox$Node.modal('hide');
- })
- .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
- if (jqXHR.responseJSON) {
- notifyAjaxCallback(jqXHR.responseJSON);
- }
- else {
- var txt = jqXHR.responseText || 'Wystąpiły błędy';
- if (jqXHR.status == 404) {
- jQuery.notify(jqXHR.responseText, 'error');
- } else {
- jQuery.notify(jqXHR.responseText, 'warn');
- }
- }
- inlineEditBox$Node.modal('hide');
- });
- return false;
- });
- currentNode.replaceWith(node);
- };
- priv.exportFieldChanged = function(e) {
- e.stopPropagation();
- var column = $(this).val();
- _exportFieldsSelect[column] = !_exportFieldsSelect[column];
- };
- priv.exportToHTML = function(e) {
- priv.exportData('html', $(this), e);
- };
- priv.exportToCSV = function(e) {
- priv.exportData('csv', $(this), e);
- };
- priv.exportData = function(format, node, e) {
- var exportFields = [];
- $.each(_exportFieldsSelect, function(col, selected) {
- if (selected) {
- exportFields.push(col);
- }
- });
- if (!exportFields.length) {
- alert('Nie wybrano żadnych pól do eksportu.');
- e.preventDefault();
- return false;
- }
- var limit = 10000;
- if (!_data.total || _data.total <= 0) {
- alert('Brak rekordów do eksportu.');
- e.preventDefault();
- return false;
- }
- if (_data.total > limit) {
- if (!confirm('Za dużo rekordów. Wyeksportowane zostaną tylko pierwsze ' + limit + ' z ' + _data.total + ' rekordów.')) {
- e.preventDefault();
- return false;
- }
- }
- var exportUrl = 'index.php?MENU_INIT=VIEWTABLE_AJAX_EXPORT&ZASOB_ID=<?php echo $this->_zasobID; ?>';
- if ('csv' == format) exportUrl += '&HEADER_NOT_INIT=YES';
- exportUrl += '&format=' + format;
- exportUrl += '&flds=' + exportFields.join(',');
- exportUrl += '&sortCol=' + (_state.filters.currSortCol || '');
- exportUrl += '&sortDir=' + (_state.filters.currSortFlip ? "desc" : "asc");
- if (Object.keys(_state.filters.filterCols).length > 0) {
- $.each(_state.filters.filterCols, function(col, colProps) {
- if (colProps.filter && colProps.filter.length > 0) {
- exportUrl += '&f_' + col + '=' + colProps.filter;
- }
- });
- }
- // specialFilters
- $.each(_state.specialFilters, function(groupName, btnValue) {
- if (btnValue.length > 0) {
- exportUrl += '&sf_' + groupName + '=' + btnValue;
- }
- });
- if (priv.options.forceFilterInit) {
- $.map(priv.options.forceFilterInit, function(fltrProps, fltr) {
- exportUrl += '&sf_' + fltr + '=' + fltrProps;
- });
- }
- node.attr('href', exportUrl);
- };
- /*
- calls the webservice(if defined).
- used only inside priv.init
- */
- priv.update = function(callback) {
- var skipCols, resetChecked;// undefined
- if (!priv.options.url) {
- if (priv.options.debug) console.log('no url found L.<?php echo __LINE__; ?>');
- return;
- }
- 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) || ''));
- var initUrlAdd = '',
- reqData = {},
- filtersInitSet = false;
- initUrlAdd += '&currSortCol=' + _state.filters.currSortCol;
- initUrlAdd += '&currSortFlip=' + ((_state.filters.currSortCol)? "desc" : "asc");
- if (Object.keys(_state.filters.filterCols).length > 0) {
- $.each(_state.filters.filterCols, function(col, colProps) {
- if (colProps.filter && colProps.filter.length > 0) {
- initUrlAdd += '&f_' + col + '=' + colProps.filter;
- filtersInitSet = true;
- }
- });
- }
- $.each(_state.specialFilters, function(groupName, btnValue) {
- if (btnValue.length > 0) {
- initUrlAdd += '&sf_' + groupName + '=' + btnValue;
- filtersInitSet = true;
- }
- });
- if (priv.options.forceFilterInit) {
- $.map(priv.options.forceFilterInit, function(fltrProps, fltr) {
- reqData['f_' + fltr] = fltrProps;
- filtersInitSet = true;
- });
- }
- $.ajax({
- url: priv.options.url + initUrlAdd,
- type: priv.options.urlPost ? 'POST' : 'GET',
- dataType: 'json',
- contentType: "application/json; charset=utf-8",
- data: reqData,
- async: true,
- success: function(data) {
- if (priv.options.debug) console.log('request finished L.<?php echo __LINE__; ?>');
- // assign the new data
- if (data && data.cols) {
- priv.setStateCols(data.cols, data.uniqueCol);
- }
- // set initial filters (_state.filters.filterCols)
- if (filtersInitSet && _data && _data.cols) {
- $.map(reqData, function(fltrValue, fltr){
- var colName = null;
- if (fltr.substr(0, 3) == 'sf_') {
- colName = fltr.substr(3);
- }
- else if (fltr.substr(0, 2) == 'f_') {
- colName = fltr.substr(2);
- }
- if (colName && _data.cols[colName]) {
- //add the filter to the filter array
- _state.filters.filterCols[colName] = {
- filter: fltrValue,
- colName: colName
- };
- }
- });
- }
- // assign the new state (data)
- state = {data: {}};
- if (!skipCols) state.data.cols = data.cols || {};
- state.data.rows = data.rows || [];
- state.data.total = data.total || 0;
- state.page = data.page || 0;
- state.pageSize = data.pageSize || priv.options.pageSize;
- state.filters = data.filters || {};
- priv.setState(state);
- if (typeof callback == "function")
- callback.call(this);
- },
- error: function(err) {
- //console.log('request error: {0}'.f(JSON.stringify(err)));
- if (typeof callback == "function")
- callback.call(this);
- }
- });
- };
- /*
- assigns the new data.
- */
- priv.setState = function(state) {
- var oldState = _state,// TODO: use to check what really changed (use extend!)
- renderParts = {};
- if (state.data) {
- if (state.data.cols && state.data.cols.length > 0) {// TODO: never happen, but if happend then rerender all
- priv.setStateCols(state.data.cols, state.data.uniqueCol);
- priv.setStateData(state.data);
- renderParts['head'] = true;
- } else {
- priv.setStateData(state.data, true);
- }
- renderParts['body'] = true;
- renderParts['foot_pagination'] = true;
- }
- if (state.hasOwnProperty('specialFilters')) {
- _state.specialFilters = state.specialFilters;
- renderParts['head__specialFilters'] = true;
- }
- if (state.hasOwnProperty('page')) {
- if (state.page != _state.page) {
- _state.page = state.page;
- renderParts['foot_pagination'] = true;
- }
- }
- if (state.hasOwnProperty('pageSize')) {
- if (state.pageSize != _state.pageSize) {
- _state.pageSize = state.pageSize;
- renderParts['foot_pagination'] = true;
- }
- }
- if (state.hasOwnProperty('filters')) {
- /// console.log('L.<?php echo __LINE__; ?> setState::state.filters: ', state.filters);//TODO:DBG:RMME
- priv.setStateFilters(state.filters);
- // TODO: if state diff's
- renderParts['head__specialFilters'] = true;
- renderParts['foot_pagination'] = true;
- }
- renderParts = Object.keys(renderParts);
- if (priv.options.debug) console.log('setState::renderParts: ', renderParts);//TODO:DBG:RMME
- ///console.log('L.<?php echo __LINE__; ?> setState::renderParts: ', renderParts);//TODO:DBG:RMME
- if (renderParts.length > 0) {
- jQuery(_uiNodeCont).trigger('TableAjax:render', renderParts);
- }
- };
- priv.setStateCols = function(cols, uniqueCol) {
- _state.cols = cols;
- _state.uniqueCol = uniqueCol;
- // fix col name - props.column
- $.each(_state.cols, function(col, props) {
- props.column = col;
- });
- // fix col types - default 'string'
- $.each(_state.cols, function(col, props) {
- if (!props.type) cols[col].type = "string";
- });
- // fix props.filter - set true if not set - TODO: allow filter this col?
- $.each(_state.cols, function(col, props) {
- if (props.filter == undefined) props.filter = true;
- });
- if (_state.uniqueCol) {
- //create a unique column definition
- _state.cols["unique"] = {
- column: "unique",
- type: "unique",
- index: -1,
- hidden: true
- };
- }
- _state.colsSorted = Object.keys(_state.cols).sort(function(a, b) {
- return _state.cols[a].index - _state.cols[b].index;
- });
- };
- priv.setStateFilters = function(stateFilters) {
- var newFilterCols = {},
- newSpecialFilters = {};
- $.map(stateFilters, function(fltrProps, fltr) {
- switch (fltr) {
- case 'currSortCol': _state.filters.currSortCol = fltrProps; break;
- case 'currSortFlip': _state.filters.currSortFlip = (fltrProps == 'desc')? true : false; break;
- default:
- if (fltr.substr(0, 2) == 'f_') {
- newFilterCols[fltr.substr(2)] = {
- filter: fltrProps,
- colName: fltr.substr(2)
- };
- }
- else if (fltr.substr(0, 3) == 'sf_') {
- var groupName = fltr.substr(3);
- if (priv.options.specialFilterFunctions.hasOwnProperty(groupName)) {
- newSpecialFilters[groupName] = fltrProps;
- }
- }
- }
- });
- _state.filters.filterCols = newFilterCols;
- _state.specialFilters = newSpecialFilters;
- };
- priv.setStateData = function(pData, skipCols, resetChecked) {
- var data = $.extend(true, {}, pData);
- data.cols = _state.cols;// always use old cols - change cols mved to priv.setStateCols
- _data = data;
- _data.rowsOrg = _data.rows;
- //we might have more/less data now. Recalculate stuff.
- if (_state.page > 1) {
- _totalPages = Math.ceil(_data.total / priv.options.pageSize);
- }
- //keep any previously checked rows around?
- if (resetChecked === true || resetChecked === undefined)
- _uniqueCols = {};
- else {
- for (var key in _uniqueCols)
- _uniqueCols[key] = priv.getRow(key);
- }
- if (_state.uniqueCol) {
- //add rows that needs to be pre-checked
- $.each(_data.rows, function(index, row) {
- if (row["checked"] === true)
- _uniqueCols[row[_state.uniqueCol]] = row;
- });
- }
- };
- /**
- * Filters the data.
- */
- priv.filter = function() {
- if (!priv.options.filter) return;
- if (Object.keys(_state.filters.filterCols).length == 0) return;
- publ.loadPage(0);
- };
- /*
- sorts the data on the current sorting column
- */
- priv.sort = function() {
- if (!_data.cols[_state.filters.currSortCol]) _state.filters.currSortCol = "";
- if (!_state.filters.currSortCol) return;
- publ.loadPage(0);
- };
- /*
- helper that returns the underlying data by the unique value
- */
- priv.getRow = function(uniqueValue) {
- var row;
- $.each(_data.rowsOrg, function(i, r) {
- if (r[_state.uniqueCol] == uniqueValue) {
- row = r;
- return false;
- }
- });
- return row;
- };
- /*
- when: typing a filter
- what: triggers filtering on the value
- */
- priv.filterChanged = function(e) {
- //clear old timer if we're typing fast enough
- if (priv.options.debug) console.log('filterChanged L.<?php echo __LINE__; ?>');
- if (_filterTimeout) {
- clearTimeout(_filterTimeout);
- if (priv.options.debug) console.log('filtering cancelled');
- }
- var filter = this.value
- , fltr = $(this)
- , col = _data.cols[e.data.column]
- , timeout = 300;
- if (this.value) {
- if (!fltr.hasClass('filter-active')) {
- fltr.addClass('filter-active');
- }
- } else {
- if (fltr.hasClass('filter-active')) {
- fltr.removeClass('filter-active');
- }
- }
- //boolean filters needs some special care
- if (col.type == "bool" || col.type == "unique") {
- timeout = 0;
- var elem = $(this);
- var cssClass = 'indeterminate';
- if (elem.hasClass(cssClass)) {
- e.preventDefault();
- elem.removeClass(cssClass);
- filter = true;
- } else {
- if (!elem.is(':checked')) {
- filter = false;
- } else {
- elem.addClass(cssClass);
- filter = '';
- }
- }
- }
- //add the filter to the filter array
- _state.filters.filterCols[col.column] = {
- filter: filter,
- colName: col.column
- };
- //wait a few deciseconds before filtering
- _filterTimeout = setTimeout(function() {
- _filterTimeout = undefined;
- priv.filter();
- }, timeout);
- };
- priv.filtersClean = function(e) {
- if (_filterTimeout) {
- clearTimeout(_filterTimeout);
- if (priv.options.debug) console.log('filtering cancelled - filtersClean');
- }
- var filtersActive = false;
- $.map(_state.filters.filterCols, function(colProps, col) {
- if (colProps.filter.length > 0) {
- filtersActive = true;
- colProps.filter = '';
- }
- });
- if (filtersActive) {
- // TODO: dont remove value from forceFilterInit fields - no field names in search fields?
- /// TODO: rerender _head (thead.filter)
- var elems = _uiNode$Table.find('thead').find('.filter').find('input');
- elems.val('').prop('disabled', false);
- elems.removeClass('filter-active');
- priv.filter();
- }
- return false;
- },
- /**
- * Filters the data by specialFilter.
- * when: click on special filter
- * what: triggers filtering on the value
- */
- priv.specialFilterChanged = function(e) {
- if (priv.options.debug) console.log('specialFilterChanged e.data:', e.data);
- var state = {};
- state.specialFilters = _state.specialFilters;
- state.specialFilters[e.data.group] = e.data.value;
- priv.setState(state);
- publ.loadPage(0);
- };
- priv.longTextChanged = function(e) {
- priv.options.longDesc = !priv.options.longDesc;
- _bodyNode.find('td').each(function(ind, el){
- var $el = jQuery(el);
- if (!$el.attr('class') || $el.attr('class') == 'tbl-short-txt') {
- //console.log(el.attr('class') + ': ' + el.text());
- if (el.firstChild && el.firstChild.nodeName == 'SPAN') {
- if (priv.options.longDesc) {
- $el.addClass('tbl-short-txt');
- var $elSpan = jQuery(el.firstChild);
- $elSpan.tooltip({title: $elSpan.text(), placement: 'left'});
- } else {
- $el.removeClass('tbl-short-txt');
- }
- }
- }
- });
- return false;
- };
- priv.mapEditorHide = function() {
- priv.options.mapEditor = false;
- if ('window' == priv.options.mapEditorContainer) {
- //_mapEditorDialog.dialog("close");
- _mapEditorDialog.dialog("destroy");
- }
- _mapEditorWrap.hide();
- _mapEditor.hide();
- };
- priv.mapEditorShow = function() {
- //console.log('TODO:mapEditorShow():', priv.options.mapEditorContainer, 'visible:', priv.options.mapEditor);
- priv.options.mapEditor = true;
- _mapEditor.show();
- _mapEditorWrap.show();
- _mapEditor.TableAjaxMap({
- //debug: true,
- wpsUrl: 'http://biuro.biall-net.pl/wps',
- wfsUrl: 'http://biuro.biall-net.pl/wps',
- showAddLayerWidget: <?php echo ($this->hasAdditionalLayers())? 'true' : 'false'; ?>,
- zoomStrategyActivate: 14,
- layerName: '<?php echo $this->getLabelHtml(); ?>',
- addBtn: {
- title: 'Przenieś mapę do okna',
- displayClass: 'mapEditor-btnBackToWindow',
- trigger: function() {
- priv.mapEditorHide();
- priv.options.mapEditorContainer = 'window';
- priv.mapEditorShow();
- priv.resizableMapDockNode('destroy');
- }
- },
- onSaveFeature: function(selectedRecordId, selectedFeatureExtent) {
- if (priv.options.debug) console.log('onSaveFeature (',selectedRecordId,'/',selectedFeatureExtent,') ', this);
- if (!selectedRecordId) {
- alert('Brak zaznaczonego rekordu - wybierz rekord z tabeli');
- return;
- }
- function notifyAjaxCallback(data) {
- var notify = {};
- notify.type = (data && data.type)? data.type : '';
- notify.msg = (data && data.msg)? data.msg : '';
- switch (notify.type) {
- case 'success':
- if (!notify.msg) notify.msg = 'Aktualizacja danych dla rekordu ' + selectedRecordId;
- break;
- case 'info':
- if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
- break;
- case 'error':
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- case 'warning':
- notify.type = 'warn';
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- default:
- notify.msg = 'Nieznany błąd';
- if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
- notify.type = '';
- }
- jQuery.notify(notify.msg, notify.type);
- }
- $.ajax({
- data: {polygon: selectedFeatureExtent},
- dataType: 'json',
- type: "POST",
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=THE_GEOM_SAVE&ID=' + selectedRecordId
- })
- .done(function(data, textStatus, jqXHR){
- notifyAjaxCallback(data);
- //jQuery.notify('Aktualizacja danych dla rekordu ' + selectedRecordId, 'success');
- publ.loadPage(0);// TODO: reload table data
- })
- .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
- if (jqXHR.responseJSON) {
- notifyAjaxCallback(jqXHR.responseJSON);
- }
- else {
- var txt = jqXHR.responseText || 'Wystąpiły błędy';
- if (jqXHR.status == 404) {
- jQuery.notify(jqXHR.responseText, 'error');
- } else {
- jQuery.notify(jqXHR.responseText, 'warn');
- }
- }
- });
- },
- onSelectBox: function(bounds) {
- if (undefined !== OpenLayers.Bounds && bounds instanceof OpenLayers.Bounds) {
- var column = 'the_geom';
- if (undefined !== _filterFields['the_geom']) {
- var filter = 'BBOX:' + bounds.top + ',' + bounds.right + ',' + bounds.bottom + ',' + bounds.left;
- _filterFields[column].val(filter);
- _state.filters.filterCols[column] = {
- filter: filter,
- colName: column
- };
- priv.filter();
- }
- }
- }
- });
- priv.mapEditorShowElement();
- };
- priv.mapEditorShowElement = function() {
- if ('window' == priv.options.mapEditorContainer) {
- var mapEditor = _mapEditorWrap.children('.mapEditor-map');
- if (!mapEditor || !mapEditor.length) {
- var tblCont = jQuery(_uiNodeCont).parent('.AjaxTableCont');
- var mapEditor = tblCont.children('.AjaxTableCont-mapEditorContainer').children('.mapEditor-map');
- if (!mapEditor || !mapEditor.length) {
- // TODO: create new map
- }
- _mapEditorWrap.append(mapEditor);
- }
- _mapEditorWrap.css({padding:'5px'});
- _mapEditorDialog = _mapEditorWrap.dialog({
- width: 540,
- minWidth: 400,
- minHeight: 400,
- open: function(e, ui) {
- var n = jQuery(this),
- mapWrap = n.children(":first"),
- map = mapWrap.children(":first");
- map.css({width: n.width() - 5, height: n.height() - 5});
- _mapEditor.TableAjaxMapUpdateSize();
- },
- resizeStart: function(e, ui) {
- jQuery(this).children(":first").children(":first").css({display:'none'});
- },
- resizeStop: function(e, ui){
- var n = jQuery(this),
- map = n.children(":first").children(":first");
- n.css({width: n.parent().width()});
- map.css({display: 'block', height: n.height(), width: n.width()});
- _mapEditor.TableAjaxMapUpdateSize();
- },
- dragStop: function(e, ui){
- _mapEditor.TableAjaxMapUpdateSize();// to prevent drag-zoom error
- }
- });
- _mapEditorWrap.bind('dialogclose', function(e) {
- priv.options.mapEditor = false;
- });
- var dialogTitleBar = _mapEditorDialog.parent().parent().find('.ui-dialog-titlebar');
- var dialogTitleBarCloseBtn = dialogTitleBar.find('.ui-dialog-titlebar-close');
- if (dialogTitleBarCloseBtn) {
- 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>');
- btnToggle.on('click', function(e) {
- priv.options.mapEditorContainer = 'dock';
- _mapEditorWrap.dialog('close');
- priv.mapEditorShowElement();
- });
- btnToggle.insertBefore(dialogTitleBarCloseBtn);
- }
- }
- else if ('dock' == priv.options.mapEditorContainer) {
- priv.resizableMapDockNode('prepare');
- _mapEditor.TableAjaxMapUpdateSize();
- }
- };
- priv.resizableMapDockNode = function(task) {
- if ('prepare' == task) {
- var mapEditor = _mapEditorWrap.children('.mapEditor-map');
- if (mapEditor && mapEditor.length) {// map is inside _mapEditorWrap (window)
- var mapDockNode = jQuery('<div class="AjaxTableCont-mapEditorContainer"></div>');
- var tblCont = jQuery(_uiNodeCont).parent('.AjaxTableCont');
- tblCont.children('.AjaxTableCont-mapEditorContainer').remove();
- var breadcrumb = tblCont.children('.breadcrumb');
- if (!breadcrumb || !breadcrumb.length) {
- tblCont.prepend(mapDockNode);
- } else {
- mapDockNode.insertAfter(breadcrumb);
- }
- mapDockNode.append(mapEditor);
- }
- var mapDockResizable = mapEditor.parent();
- mapDockResizable.resizable({handles: 's', minHeight: 300, minWidth: 300});
- var resizeLineHeigth = 6;
- mapDockResizable.children(":first").css({height: 'auto'});
- mapDockResizable.css({marginBottom: resizeLineHeigth+'px'});
- mapEditor.css({marginBottom: resizeLineHeigth+'px'});
- mapEditor.children(":first").css({width: mapEditor.width()});
- mapDockResizable.find('.ui-resizable-s').css({height:resizeLineHeigth+'px', bottom: '-'+resizeLineHeigth+'px'});
- mapDockResizable.on('resizestart', function(event, ui) {
- ui.element.children(":first").children(":first").css({display:'none'})
- });
- mapDockResizable.on('resizestop', function(event, ui) {
- ui.element.children(":first").children(":first").css({display:'block', height: ui.element.height()});
- });
- } else if ('destroy' == task) {
- var mapDockResizable = jQuery(_uiNodeCont).parent('.AjaxTableCont').children('.AjaxTableCont-mapEditorContainer');
- mapDockResizable.resizable('destroy');
- mapDockResizable.remove();
- }
- };
- priv.mapEditorChanged = function(e) {
- if (priv.options.debug) console.log('mapEditorChanged option(',priv.options.mapEditor,')');
- priv.options.mapEditor = !priv.options.mapEditor;
- if (priv.options.mapEditor) {
- priv.mapEditorShow();
- }
- else {
- priv.mapEditorHide();
- }
- return false;
- };
- /*
- when: changing page in pager
- what: triggers table to be created with new page
- */
- priv.pageChanged = function(e) {
- e.preventDefault();
- var totalPages = Math.ceil(_data.total / _state.pageSize);
- if (e.data.pageIndex < 1 || e.data.pageIndex > totalPages) return;
- //set the new page
- _state.page = e.data.pageIndex;
- publ.loadPage(_state.page);
- };
- /*
- when: changing pagesize in pagesize dropdown
- what: triggers table to be created with new pagesize
- */
- priv.pageSizeChanged = function(e) {
- e.preventDefault();
- var val = $(this).text();
- if (priv.options.debug) console.log('pagesize changed to:{0}'.f(val));
- if (parseInt(val) == priv.options.pageSize) {
- return false;
- }
- priv.options.pageSize = parseInt(val);
- publ.loadPage(1, priv.options.pageSize);
- jQuery(_uiNodeCont).trigger('TableAjax:render', ['body', 'foot_pagination']);
- priv.saveProfilePageSize(priv.options.pageSize);
- };
- /*
- when: clicking a column
- what: triggers table to be sorted by the column
- */
- priv.columnClicked = function(e) {
- e.preventDefault();
- if (priv.options.debug) console.log('col:{0} clicked'.f(e.data.column));
- //set the new sorting column
- if (_state.filters.currSortCol == e.data.column) _state.filters.currSortFlip = !_state.filters.currSortFlip;
- _state.filters.currSortCol = e.data.column;
- /// TODO: var state = {}; state.currSortCol = ''; state.currSortFlip = ''; priv.setState(state);
- _headSort = undefined;
- _body = undefined;
- priv.sort();
- };
- priv.saveProfilePageSize = function(pageSize) {
- var reqData = {};
- reqData.pageSize = pageSize;
- $.ajax({
- data: reqData,
- type: "POST",
- dataType: 'json',
- // async: true,
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=PAGE_SIZE_SAVE'
- })
- .done(function(data, textStatus, jqXHR){
- if (data && data.type && data.type == 'info') {
- jQuery.notify('Nie wprowadzono żadnych zmian', 'info');
- } else {
- jQuery.notify('Zapisano ustawienia', 'success');
- }
- })
- .fail(function(){
- jQuery.notify('Wystąpił błąd podczas zapisywania ustawień', 'error');
- });
- };
- priv.saveHiddenCols = function() {
- var reqData = {};
- $.each(_data.cols, function(col, props) {
- if (props.type != "unique" && col != 'unique' && col != 'ID') {
- reqData[col] = (props.hidden)? 'HIDE' : 'SHOW';
- }
- });
- $.ajax({
- data: reqData,
- type: "POST",
- dataType: 'json',
- // async: true,
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=HIDDEN_COLS_SAVE'
- })
- .done(function(data, textStatus, jqXHR){
- if (data && data.type && data.type == 'info') {
- jQuery.notify('Nie wprowadzono żadnych zmian', 'info');
- } else {
- jQuery.notify('Zapisano ustawienia', 'success');
- }
- })
- .fail(function(){
- jQuery.notify('Wystąpił błąd podczas zapisywania ustawień', 'error');
- });
- };
- /*
- when: clicking a column in columnpicker
- what: triggers table to show/hide the column
- */
- priv.columnPickerClicked = function(e) {
- e.stopPropagation();
- var column = $(this).val();
- //toggle column visibility
- _data.cols[column].hidden = !_data.cols[column].hidden;
- priv.saveHiddenCols();
- //_data.cols[column].index = new priv.ext.XDate();
- jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body']);
- };
- priv.columnHideClicked = function(e) {
- e.stopPropagation();
- var column;
- if (e.data && e.data.column) {
- column = e.data.column;
- } else {
- return;
- }
- //toggle column visibility
- _data.cols[column].hidden = !_data.cols[column].hidden;
- priv.saveHiddenCols();
- //_data.cols[column].index = new priv.ext.XDate();
- jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body', 'foot__columnPicker']);
- };
- /*
- when: clicking a row checkbox
- what: toggles checked state on row, and add/removes it from checked array
- */
- priv.rowChecked = function(e) {
- var elem = $(this);
- //get the row's unique value
- var unique = elem.closest('tr').data('unique');
- if (priv.options.debug) console.log('row({0}) {1}'.f(unique, elem.is(':checked') ? 'checked' : 'unchecked'));
- //store the row in checked array
- if (elem.is(':checked')) _uniqueCols[unique] = priv.getRow(unique);
- else delete _uniqueCols[unique];
- };
- /*
- when: clicking anywhere on a row
- what: row data and other info is returned to caller
- */
- // priv.rowClicked = function(e) {// TODO: not used
- // if (!_state.uniqueCol) {
- // if (priv.options.debug) console.log('no unique column specified');
- // return;
- // }
- // //gather callback data
- // var elem = $(this);
- // var column = _data.cols[elem.data('column')];
- // var unique = elem.closest('tr').data('unique');
- // var row = priv.getRow(unique);
- // var isChecked = elem.closest('tr').find('.unique').is(':checked');
- // //trigger callback
- // if (typeof priv.options.rowClicked == 'function') {
- // priv.options.rowClicked.call(e.target, {
- // event: e,
- // row: row,
- // column: column,
- // checked: isChecked
- // });
- // }
- // };
- /**
- * Inline edit.
- */
- priv.rowDblClicked = function(e) {
- var inlineEditBox$Node = $(_uiNodeCont).parent().children('.tblAjax__inlineEditBox');
- // hide popover for typespecial fld on click
- if (_popoverCellCurrent) {
- _popoverCellCurrent.popover('hide');
- }
- // e.clientX: 1002; e.clientY: 245
- if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
- inlineEditBox$Node.modal();
- inlineEditBox$Node.show();
- inlineEditBox$Node.on('shown.bs.modal', function(e) {
- var dialogBox = jQuery(this).find('.modal-dialog'),
- modalBody = dialogBox.find('.modal-body'),
- boudingRect = dialogBox.get(0).getBoundingClientRect();
- dialogBox.css({position: 'absolute', margin:0, top: boudingRect.top, left: boudingRect.left});
- modalBody.css({overflow: 'scroll'});
- dialogBox.resizable({minHeight: 300, minWidth: 300, alsoResize: modalBody});
- dialogBox.draggable({handle: '.modal-header'});
- });
- inlineEditBox$Node.on('hidden.bs.modal', function(e) {
- var dialogBox = jQuery(this).find('.modal-dialog'),
- modalBody = dialogBox.find('.modal-body');
- dialogBox.removeAttr('style');
- modalBody.removeAttr('style');
- modalBody.css({padding: '0'});
- dialogBox.resizable();
- dialogBox.draggable();
- dialogBox.resizable('destroy');
- dialogBox.draggable('destroy');
- });
- inlineEditBox$Node.find('input[name=ID]').val(e.data.id);
- inlineEditBox$Node.find('input[name=col]').val(e.data.col);
- inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
- $.ajax({
- 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,
- type: 'GET',
- dataType: 'text',
- data: '',
- async: true,
- success: function(data) {
- inlineEditBox$Node.find('.inlineEditBox-cnt').html(data);
- inlineEditBox$Node.find('.btn-save').show();
- initDateTimePicker(inlineEditBox$Node);
- inlineEditBox$Node.find('textarea').autosize();
- var fld = inlineEditBox$Node.find('input[id^="f"]');
- if (fld && !fld.hasClass('se_type-date')) {
- fld.focus();
- fld.keydown(function(event) {
- if (event.which == 13) {
- event.preventDefault();
- inlineEditBox$Node.find('form').submit();
- }
- });
- }
- },
- error: function(err) {
- if (priv.options.debug) console.log('err');
- }
- });
- } else {
- if (priv.options.debug) console.log('NO data');
- return false;
- }
- };
- priv.ajaxLoadTypeSpeciallCell = function(id, col) {
- if (_popoverCellAjaxXhr) {
- _popoverCellAjaxXhr.abort();
- }
- _popoverCellAjaxXhr = $.ajax({
- type: 'GET',
- 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,
- dataType: 'json',
- contentType: "application/json; charset=utf-8",
- data: '',
- success: function(req){
- if (req.data && req.data.tbl_id > 0) {
- var addHtml = '';
- for(var i in req.data.items){
- var url = 'index.php?MENU_INIT=VIEWTABLE_AJAX';
- url += '&ZASOB_ID=' + req.data.tbl_id;
- url += '&f_' + req.data.fld_name + '=' + req.data.items[i].id;
- url += '&_hash=' + Math.random().toString(36).substring(2);
- addHtml += '<a href="' + url + '">Wyszukaj ' + req.data.items[i].id + '</a>: ' + req.data.items[i].label;
- addHtml += '<br>';
- }
- //_popoverCell.append(addHtml);// cache
- if (_popoverCellCurrent) {
- var popoverNodeId = _popoverCellCurrent.attr('aria-describedby');
- if (popoverNodeId) {
- jQuery('#' + popoverNodeId).find('.popoverCellContent').append(addHtml);
- }
- }
- }
- }
- });
- };
- priv.popoverCellTypeSpecial = function(e) {
- e.preventDefault();
- e.stopPropagation();
- if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
- var lastId = _popoverCell.data('rowid'),
- lastCol = _popoverCell.data('col'),
- rowPK = e.data.id,
- colName = e.data.col
- ;
- if (lastId == rowPK && lastCol == colName) {
- //_popoverCellCurrent.popover('toggle');
- }
- else {
- if (_popoverCellCurrent) {
- _popoverCellCurrent.popover('destroy');
- }
- _popoverCell.data('rowid', rowPK);
- _popoverCell.data('col', colName);
- _popoverCell.html(e.data.value + '<div class="popoverCellContent loading" style="white-space:normal"></div>');
- _popoverCellCurrent = jQuery(e.currentTarget);
- // title : '<span class="text-info"><strong>title</strong></span> <button type="button" id="close" class="close">×</button>'
- var opts = {
- placement: 'left'
- , trigger: 'click'
- // , title: e.data.col + '<a href="#" class="glyphicon glyphicon-remove pull-right" onclick="return hidePopover();"></a>'
- , 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;">×</button>' + '</div>'
- , html: true
- , content: _popoverCell.html()
- }
- _popoverCellCurrent.popover(opts);
- if (_data.cols[colName]) {
- if (_data.cols[colName]._tsRetId > 0) {
- _popoverCellCurrent.on('shown.bs.popover', function() {
- priv.ajaxLoadTypeSpeciallCell(rowPK, colName);
- });
- }
- }
- _popoverCellCurrent.popover('show');
- }
- } else {
- if (priv.options.debug) console.log('NO data');
- return false;
- }
- return;
- };
- priv.routeChanged = function(e) {
- hash = e.data.hash || '';
- if (hash.length == 0) {
- return;
- }
- if (hash.substring(0, 1) != '#') {
- hash = '#' + hash;
- }
- location.hash = hash;
- };
- priv.refresh = function(e) {
- e.preventDefault();
- publ.loadPage(_state.page);
- };
- publ.init = function(options) {
- if (priv.options.debug) console.log('TableAjax initialization...');
- //merge supplied options with defaults
- $.extend(priv.options, defaults, options);
- priv.init();
- return publ;
- };
- publ.refresh = function() {
- publ.loadPage(_state.page);
- };
- publ.loadPage = function(page, pageSize) {
- var skipCols = true, // skipCols = true - prevent columns delete
- resetChecked = false;
- var reqData = {
- page: page,
- pageSize: (pageSize || priv.options.pageSize),
- currSortCol: (_state.filters.currSortCol || ''),
- currSortFlip: _state.filters.currSortFlip ? "desc" : "asc"
- };
- if (Object.keys(_state.filters.filterCols).length > 0) {
- $.each(_state.filters.filterCols, function(col, colProps) {
- if (colProps.filter && colProps.filter.length > 0) {
- reqData['f_' + col] = colProps.filter;
- }
- });
- skipCols = true;
- }
- // specialFilters
- $.each(_state.specialFilters, function(groupName, btnValue) {
- if (btnValue.length > 0) {
- reqData['sf_' + groupName] = btnValue;
- }
- });
- if (priv.options.forceFilterInit) {
- $.map(priv.options.forceFilterInit, function(fltrProps, fltr) {
- reqData['f_' + fltr] = fltrProps;
- filtersInitSet = true;
- });
- }
- _uiNode$Table.parent().parent().addClass('AjaxTable-loading');
- $.ajax({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>',
- type: 'GET',
- dataType: 'json',
- contentType: "application/json; charset=utf-8",
- data: reqData,
- async: true,
- success: function(data) {
- state = {data: {}};
- state.data.rows = data.rows || [];
- state.data.total = data.total || 0;
- state.page = data.page || 0;
- state.pageSize = data.pageSize || priv.options.pageSize;
- state.filters = data.filters || {};
- priv.setState(state);
- _uiNode$Table.parent().parent().removeClass('AjaxTable-loading');
- },
- error: function(err) {
- if (priv.options.debug) console.log('request error: {0}'.f(JSON.stringify(err)));
- }
- });
- };
- publ.getCurrentPage = function() {
- return _state.page;
- };
- publ.popoverCellRemove = function() {
- if (_popoverCellCurrent) {
- _popoverCellCurrent.popover('destroy');
- }
- _popoverCell.data('rowid', -1);
- _popoverCell.data('col', -1);
- _popoverCell.html('');
- };
- return publ;
- }
- $.fn.TableAjax = function(options) {
- options = options || {};
- return this.each(function() {
- options.id = this;
- $(this).data('TableAjax', new TableAjax().init(options));
- });
- };
- $.fn.TableAjaxLoadPage = function(page, pageSize) {
- return this.each(function() {
- var tblAjax = jQuery(this).data('TableAjax');
- var curPage = page || tblAjax.getCurrentPage();
- if (tblAjax) tblAjax.loadPage(curPage, pageSize);
- });
- };
- $.fn.TableAjaxRefresh = function(page, pageSize) {
- return this.each(function() {
- var tblAjax = jQuery(this).data('TableAjax');
- if (tblAjax) tblAjax.refresh();
- });
- };
- String.prototype.format = String.prototype.f = function() {
- var s = this;
- i = arguments.length;
- while (i--) s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
- return s;
- };
- })(jQuery);
- </script>
- <?php
- $filterInit = $this->_filterInit;
- $forceFilterInit = $this->_forceFilterInit;
- $pageSizes = $this->_pageSizes;
- $pageSize = $this->_pageSize;
- $rowFunctions = $this->_rowFunctions;//$this->_showRowFunctionsJson();
- $exportFields = $this->_showExportFieldsJson();
- ?>
- <script>
- jQuery(document).ready(function(){
- jQuery('#<?php echo $this->_htmlID; ?>').TableAjax({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>',
- columnPicker: true,
- filter: true,
- filterInit: <?php echo json_encode($filterInit); ?>,
- forceFilterInit: <?php echo json_encode($forceFilterInit); ?>,
- debug: false,
- height: 400,
- sorting: true,
- paging: true,
- pageSize: <?php echo $pageSize; ?>,
- pageSizes: <?php echo json_encode($pageSizes); ?>,
- tblFunctions: {
- shortdesc: {
- icon: 'align-left',
- title: 'Long desc',
- method: 'longTextChanged'
- },
- <?php if ($hasGeomFlds) : ?>
- mapeditor: {
- icon: 'map-marker',
- title: 'Mapa',
- method: 'mapEditorChanged'
- },
- <?php endif; ?>
- create: {
- href: '#CREATE',
- icon: 'plus',
- title: 'Dodaj nowy rekord'
- },
- refresh: {
- icon: 'refresh',
- title: 'Odśwież dane',
- method: 'refresh'
- }
- },
- rowFunctions: <?php echo json_encode($rowFunctions); ?>,
- exportFields: <?php echo json_encode($exportFields); ?>,
- specialFilterFunctions: <?php
- $fltrs = $this->_acl->getSpecialFilters();
- if (!empty($fltrs)) {
- echo json_encode($fltrs);
- } else {
- echo 'false';
- }
- echo ',';
- ?>
- router: function() {
- var routes = {
- EDIT: function(args) {
- var recordID = args;
- if (typeof args == 'object') {
- recordID = args.shift();
- recordID = parseInt(recordID);
- }
- if (typeof recordID !== 'number' || recordID <= 0) {
- // TODO: msg
- return false;
- }
- var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
- cont.hide();
- // remove previous task content
- var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
- taskCnt.parent().remove();
- taskCnt.remove();
- var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
- jQuery('<ul class="breadcrumb">' +
- '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
- '<li class="active">Edytuj rekord</li>' +
- '</ul>').appendTo(taskCont);
- taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
- jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
- jQuery.ajax({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT&ID=' + recordID,
- type: 'GET',
- dataType: 'text',
- data: '',
- async: true,
- success: function(data) {
- taskCnt.removeClass('AjaxTable-loading');
- jQuery(data).appendTo(taskCnt);
- initDateTimePicker(taskCnt);
- },
- error: function(err) {
- taskCnt.removeClass('AjaxTable-loading');
- //console.log('request error: {0}'.f(err));
- }
- });
- //return false;
- },
- HIST: function(args) {
- var recordID = args;
- if (typeof args == 'object') {
- recordID = args.shift();
- recordID = parseInt(recordID);
- }
- if (typeof recordID !== 'number' || recordID <= 0) {
- // TODO: msg
- return false;
- }
- var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
- cont.hide();
- // remove previous task content
- var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
- taskCnt.parent().remove();
- taskCnt.remove();
- var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
- jQuery('<ul class="breadcrumb">' +
- '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
- '<li class="active">Historia rekordu</li>' +
- '</ul>').appendTo(taskCont);
- var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
- jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
- jQuery.ajax({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=HIST&ID=' + recordID,
- type: 'GET',
- dataType: 'text',
- data: '',
- async: true,
- success: function(data) {
- taskCnt.removeClass('AjaxTable-loading');
- //console.log('request finished L.<?php echo __LINE__; ?>');
- jQuery(data).appendTo(taskCnt);
- },
- error: function(err) {
- taskCnt.removeClass('AjaxTable-loading');
- //console.log('request error: {0}'.f(err));
- }
- });
- //return false;
- },
- FILES: function tableAjaxFiles(args) {
- var recordID = args;
- if (typeof args == 'object') {
- recordID = args.shift();
- recordID = parseInt(recordID);
- }
- if (typeof recordID !== 'number' || recordID <= 0) {
- // TODO: msg
- return false;
- }
- var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
- cont.hide();
- // remove previous task content
- var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
- taskCnt.parent().remove();
- taskCnt.remove();
- var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
- jQuery('<ul class="breadcrumb">' +
- '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
- '<li class="active">Pliki</li>' +
- '</ul>').appendTo(taskCont);
- var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTable-loading"></div>').appendTo(taskCont);
- jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
- jQuery.ajax({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES&ID=' + recordID,
- type: 'GET',
- dataType: 'text',
- data: '',
- async: true,
- success: function(data) {
- taskCnt.removeClass('AjaxTable-loading');
- //console.log('request finished L.<?php echo __LINE__; ?>', data);
- jQuery(data).appendTo(taskCnt);
- },
- error: function(jqXHR, textStatus, errorThrown) {
- //console.log('request error:', jqXHR.status, 'txt:', jqXHR.responseText, 'err:', jqXHR);
- taskCnt.removeClass('AjaxTable-loading');
- var txt = jqXHR.responseText || 'Error';
- if (jqXHR.status == 404) {
- jQuery('<div class="container"><div class="alert alert-danger">' + txt + '</div></div>').appendTo(taskCnt);
- } else {
- jQuery('<div class="container"><div class="alert alert-danger">' + txt + '</div></div>').appendTo(taskCnt);
- }
- }
- });
- //return false;
- },
- CREATE: function tableAjaxCreate() {
- var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
- cont.hide();
- // remove previous task content
- var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
- taskCnt.parent().remove();
- taskCnt.remove();
- var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
- jQuery('<ul class="breadcrumb">' +
- '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
- '<li class="active">Dodaj nowy rekord</li>' +
- '</ul>').appendTo(taskCont);
- taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
- jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
- var reqData = {};
- var forceFilterInit = <?php echo json_encode($forceFilterInit);// TODO: read from TableAjax ?>;
- if (forceFilterInit) {
- $.map(forceFilterInit, function(fltrProps, fltr) {
- reqData['ff_' + fltr] = fltrProps;
- });
- }
- jQuery.ajax({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE',
- type: 'GET',
- dataType: 'text',
- data: reqData,
- async: true,
- success: function(data) {
- taskCnt.removeClass('AjaxTable-loading');
- //console.log('request finished L.<?php echo __LINE__; ?>');
- jQuery(data).appendTo(taskCnt);
- initDateTimePicker(taskCnt);
- },
- error: function(err) {
- taskCnt.removeClass('AjaxTable-loading');
- //console.log('request error: {0}'.f(err));
- }
- });
- //return false;
- }
- };
- var routePath = location.hash;
- //console.log('location.hash: ' + routePath);
- if (location.hash == '' || location.hash == '#') {
- return false;
- }
- if (routePath.charAt(0) == '#') {
- routePath = routePath.substr(1);
- }
- //console.log('routePath: ' + routePath);
- var parts = routePath.split('/');
- var task = parts.shift();
- //console.log('task(' + task + ') parts:');
- //console.log(parts);
- if (task in routes && typeof routes[task] == 'function') {
- routes[task](parts);
- } else {
- return false;
- }
- },
- filtersClean: true,
- longDesc: true
- });
- });
- function tableAjaxBackToTable() {
- var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
- cont.show();
- var taskCont = jQuery('#<?php echo $this->_htmlID . '_task'; ?>').parent();
- taskCont.remove();
- // reload first page
- var con = jQuery('#<?php echo $this->_htmlID; ?>');
- con.TableAjaxLoadPage();// TODO: load current page
- }
- function tableAjaxCopy(args) {
- var recordID = args;
- if (typeof args == 'object') {
- recordID = args.shift();
- recordID = parseInt(recordID);
- }
- if (typeof recordID !== 'number' || recordID <= 0) {
- // TODO: msg
- return false;
- }
- if (!confirm('Czy na pewno chcesz utworzyc nowy rekord na podstawie danych z rekordu ID = ' + recordID + '?')) {
- return false;
- }
- var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
- function notifyAjaxCallback(data) {
- var notify = {};
- notify.type = (data && data.type)? data.type : '';
- notify.msg = (data && data.msg)? data.msg : '';
- switch (notify.type) {
- case 'success':
- if (!notify.msg) notify.msg = 'OK';
- break;
- case 'info':
- if (!notify.msg) notify.msg = '';
- break;
- case 'error':
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- case 'warning':
- notify.type = 'warn';
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- default:
- notify.msg = 'Nieznany błąd';
- if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
- notify.type = '';
- }
- jQuery.notify(notify.msg, notify.type);
- }
- var reqData = {};
- jQuery.ajax({
- data: reqData,
- dataType: 'json',
- type: "GET",
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=COPY&ID=' + recordID,
- })
- .done(function(data, textStatus, jqXHR){
- var con = jQuery('#<?php echo $this->_htmlID; ?>');
- con.TableAjaxRefresh();
- notifyAjaxCallback(data);
- })
- .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
- if (jqXHR.responseJSON) {
- notifyAjaxCallback(jqXHR.responseJSON);
- }
- else {
- var txt = jqXHR.responseText || 'Wystąpiły błędy';
- if (jqXHR.status == 404) {
- jQuery.notify(jqXHR.responseText, 'error');
- } else {
- jQuery.notify(jqXHR.responseText, 'warn');
- }
- }
- });
- return false;
- }
- function hidePopover() {
- var con = jQuery('#<?php echo $this->_htmlID; ?>');
- if (con) {
- var tblAjax = con.data('TableAjax');
- if (tblAjax) {
- tblAjax.popoverCellRemove();
- }
- }
- return false;
- }
- function <?php echo $jsToogleFiltrProcesuFunctionName; ?>(n) {
- var $n = jQuery(n);
- var $ul = $n.next();
- if ($n.data('fetched')) return false;
- function parseProcesInitData(pInitData) {
- var procesInitMapHtml = '';
- if (!pInitData) {
- return '<li><a href="#">' + "Brak danych" + '</a></li>';
- } else {
- function _viewProcesInitListItem(pInitId, gotoIds, pInitList) {
- var label = pInitList[pInitId];
- 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;";
- 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 + '">';
- out += ' <i class="glyphicon glyphicon-info-sign"';
- out += ' onclick="' + jsInfo + '"';
- out += ' style="color:#aaa;"';
- out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
- out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
- out += " {" + pInitId + "} " + label;
- out += '</a>';
- return out;
- }
- function _viewProcesGotoAndRetListItem(gotoId, pInitList) {
- var label = pInitList[gotoId];
- 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;";
- var out = '';
- 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 + '">';
- out += ' <span style="padding:10px;"></span>';
- out += ' <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>';
- out += ' <i class="glyphicon glyphicon-info-sign"';
- out += ' onclick="' + jsInfo + '"';
- out += ' style="color:#aaa;"';
- out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
- out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
- out += " {" + gotoId + "} " + label;
- out += '</a>';
- return out;
- }
- function _viewProcesGotoAndRetLvl2ListItem(gotoLvl2Id, pInitList) {
- var label = pInitList[gotoLvl2Id];
- 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;";
- var out = '';
- 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 + '">';
- out += ' <span style="padding:20px;"></span>';
- out += ' <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>';
- out += ' <i class="glyphicon glyphicon-info-sign"';
- out += ' onclick="' + jsInfo + '"';
- out += ' style="color:#aaa;"';
- out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
- out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
- out += " {" + gotoLvl2Id + "} " + label;
- out += '</a>';
- return out;
- }
- var sel = '',
- liStyle = "white-space:nowrap; overflow:hidden; max-width:500px; /* text-overflow:ellipsis; */";
- $.map(pInitData.mapTree, function(gotoIds, vInitId) {
- sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
- procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
- procesInitMapHtml += _viewProcesInitListItem(vInitId, gotoIds, pInitData.pInitList);
- procesInitMapHtml += '</li>' + "\n";
- $.map(gotoIds, function(gotoLvl2Ids, gotoId) {
- sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
- procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
- procesInitMapHtml += _viewProcesGotoAndRetListItem(gotoId, pInitData.pInitList);
- procesInitMapHtml += '</li>' + "\n";
- $.map(gotoLvl2Ids, function(vBool, gotoLvl2Id) {
- sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
- procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
- procesInitMapHtml += _viewProcesGotoAndRetLvl2ListItem(gotoLvl2Id, pInitData.pInitList);
- procesInitMapHtml += '</li>' + "\n";
- });
- });
- });
- }
- return procesInitMapHtml;
- }
- jQuery.ajax({
- data: null,
- dataType: 'json',
- type: "GET",
- async: true,
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=PROCES_INIT_FILTR',
- })
- .always(function(data, textStatus, jqXHR) {
- var type = data.type || null,
- msg = data.msg || "Error",
- pInitData = data.pInitData || null;
- if (type) {
- if ('success' == type) {
- $ul.html(parseProcesInitData(pInitData));
- } else if ('error' == type) {
- $ul.html('<li><a href="#">' + msg + '</a></li>');
- } else {
- $ul.html('<li><a href="#">Wystapił błąd podczas pobierania listy procesów</a></li>');
- }
- } else {
- $ul.html('<li><a href="#">Wystapił błąd podczas pobierania listy procesów</a></li>');
- }
- $n.data('fetched', true);
- });
- return false;
- }
- </script>
- <?php
- $out = ob_get_contents();
- ob_end_clean();
- return $out;
- }
- public function _viewProcesInitListItem($vInitId, $gotoIds, $pInitList) {
- $vLabel = $pInitList[$vInitId];
- $kId = $vInitId;
- ?>
- <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}"); ?>">
- <i class="glyphicon glyphicon-info-sign"
- 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;"
- style="color:#aaa;"
- onmouseover="this.style.color='#337AB7'"
- onmouseout="this.style.color='#aaa'"></i>
- <?php echo "{{$kId}} {$vLabel}"; ?>
- </a>
- <?php
- }
- public function _viewProcesGotoAndRetListItem($vGotoId, $pInitList) {
- $vLabel = $pInitList[$vGotoId];
- $kId = $vGotoId;
- // TODO:?: prevent to execute procedure
- ?>
- <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}"); ?>">
- <span style="padding:10px;"></span>
- <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>
- <i class="glyphicon glyphicon-info-sign"
- 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;"
- style="color:#aaa;"
- onmouseover="this.style.color='#337AB7'"
- onmouseout="this.style.color='#aaa'"></i>
- <?php echo "{{$kId}} {$vLabel}"; ?>
- </a>
- <?php
- }
- public function _viewProcesGotoAndRetLvl2ListItem($vGotoLvl2Id, $pInitList) {
- $vLabel = $pInitList[$vGotoLvl2Id];
- $kId = $vGotoLvl2Id;
- // TODO:?: prevent to execute procedure
- ?>
- <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}"); ?>">
- <span style="padding:20px;"></span>
- <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>
- <i class="glyphicon glyphicon-info-sign"
- 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;"
- style="color:#aaa;"
- onmouseover="this.style.color='#337AB7'"
- onmouseout="this.style.color='#aaa'"></i>
- <?php echo "{{$kId}} {$vLabel}"; ?>
- </a>
- <?php
- }
- public function hasAdditionalLayers() {
- $layers = TableAjaxMap::getAdditionalLayers($this->_zasobID);
- return !empty($layers);
- }
- public function ajaxTask($task) {
- switch ($task) {
- case 'EDIT': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- if ($id > 0) {
- $this->sendAjaxEdit($id, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'EDIT_SAVE': {
- $this->sendAjaxResponseJson('ajaxEditSave', $_REQUEST);
- break;
- }
- case 'EDIT_INLINE': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- $col = V::get('col', '', $_REQUEST);
- if ($id > 0 && !empty($col)) {
- $this->sendAjaxEditInline($id, $col, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'EDIT_INLINE_SAVE': {
- $this->sendAjaxResponseJson('ajaxEditInlineSave', $_REQUEST);
- break;
- }
- case 'COPY': {
- $this->sendAjaxResponseJson('ajaxCopy', $_REQUEST);
- break;
- }
- case 'CREATE': {
- $this->sendAjaxCreate($_REQUEST);
- break;
- }
- case 'CREATE_SAVE': {
- $this->sendAjaxResponseJson('ajaxCreateSave', $_REQUEST);
- break;
- }
- case 'HIST': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- if ($id > 0) {
- $this->sendAjaxHistory($id, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'FILES': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- if ($id > 0) {
- $this->sendAjaxFiles($id, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'FILES_UPLOAD': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- if ($id > 0) {
- $this->sendAjaxFilesUpload($id, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'FILES_LIST': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- if ($id > 0) {
- $this->sendAjaxFilesList($id, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'FILE_REMOVE': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- if ($id > 0) {
- $this->sendAjaxFileRemove($id, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'filePermsRefresh': {
- $this->sendAjaxResponseJson('ajaxFilePermsRefresh', $_REQUEST);
- break;
- }
- case 'FILES_CONN_TBL_LIST': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- if ($id > 0) {
- $this->sendAjaxFilesConnTblList($id, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'TYPESPECIAL': {
- $fldID = V::get('fldID', 0, $_REQUEST, 'int');
- if ($fldID > 0) {
- $this->sendTypeSpecial($fldID, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'TYPESPECIALL_CELL': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- $col = V::get('col', '', $_REQUEST);
- if ($id > 0 && !empty($col)) {
- $this->sendTypeSpecialCell($id, $col, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'MORE_FUNCTIONS_CELL': {
- $this->sendAjaxResponseJson('ajaxMoreFunctionsCell', $_REQUEST);
- break;
- }
- case 'HIDDEN_COLS_SAVE': {
- $this->sendAjaxResponseJson('ajaxHiddenColsSave', $_POST);
- break;
- }
- case 'PAGE_SIZE_SAVE': {
- $this->sendAjaxResponseJson('ajaxPageSizeSave', $_POST);
- break;
- }
- case 'THE_GEOM_SAVE': {
- $this->sendAjaxResponseJson('ajaxTheGeomSave', $_REQUEST);
- break;
- }
- case 'THE_GEOM_REMOVE': {
- $this->sendAjaxResponseJson('ajaxTheGeomRemove', $_REQUEST);
- break;
- }
- case 'PROCES_INIT_FILTR': {
- $this->sendAjaxResponseJson('ajaxProcesInitFiltr', $_REQUEST);
- break;
- }
- default:
- $this->sendAjaxResponseJson('ajaxData', $_REQUEST);
- }
- }
- /**
- * ajax url: &_task=EDIT_INLINE
- * @param $rowID - $_GET['ID']
- * @param $fieldName - $_GET['col']
- */
- private function sendAjaxEditInline($rowID, $fieldName, $args) {
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- header("Content-type: text/plain");
- $fieldID = $this->_acl->getFieldIdByName($fieldName);
- if (!$fieldID) {
- echo "404: No field by name ({$fieldName})";
- exit;
- }
- if ($DBG) echo "fieldID: {$fieldID}\n";
- $row = $this->_acl->getItem($rowID);
- if (!$row) {
- echo "404: No item ID({$rowID})";
- exit;
- }
- if (!$this->_acl->isAllowed($fieldID, 'R', $row)) {
- if ($DBG) echo " R not allowed\n";
- } else {
- if ($DBG) echo " R allowed\n";
- }
- if (!$this->_acl->isAllowed($fieldID, 'W', $row)) {
- if ($DBG) echo " W not allowed\n";
- } else {
- if ($DBG) echo " W allowed\n";
- }
- $fieldVal = '';
- if ($this->_acl->isAllowed($fieldID, 'R', $row)) {
- $fieldVal = V::get($fieldName, $fieldVal, $row);
- } else {
- $fieldVal = '*****';
- }
- $fieldVal = V::get("f{$fieldID}", $fieldVal, $_POST);
- $vCol = $this->_acl->getField($fieldID);
- $vCol['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
- $tsValues = array();
- $typeSpecial = Typespecial::getInstance($fieldID, $vCol['name']);
- if ($typeSpecial) {
- 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>';}
- $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $row->ID, $fieldName, V::get($fieldName, $fieldVal, $row));
- 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>';}
- if (!empty($specialValues)) {
- $tsValues[$row->ID] = implode('<br>', $specialValues);
- }
- }
- ?>
- <label for="<?php echo "f{$fieldID}"; ?>" class="AjaxTableEdit-label">
- <strong title="<?php echo "[{$fieldID}] {$fieldName}"; ?>"><?php echo "{$vCol['label']}"; ?></strong>
- <?php if (!empty($vCol['opis'])) : ?>
- <em><?php echo $vCol['opis']; ?></em>
- <?php $perms = $this->_acl->getFieldPerms($fieldID); SE_Layout::hotKeyDBG($perms); ?>
- <?php endif; ?>
- </label>
- <?php
- $fieldParams = array('widthClass'=>'inside-modal', 'maxGrid'=>6);
- if (!empty($tsValues[$row->ID])) {
- $fieldParams['typespecialValue'] = $tsValues[$row->ID];
- }
- $vDefault = $this->_acl->getColDefault($fieldName);
- if (!empty($vDefault)) {
- $fieldParams['default'] = $vDefault;
- }
- echo $this->_acl->showFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $row);
- if ($typeSpecial
- || $this->_acl->isDateField($fieldName)
- || $this->_acl->isDateTimeField($fieldName)
- ) {
- echo '<p style="padding:120px 0;"></p>';
- }
- exit;
- }
- private function ajaxEditInlineSave($args) {
- $primaryKeyField = $this->_acl->getPrimaryKeyField();
- $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
- $fieldName = V::get('col', '', $_REQUEST);
- if (empty($primaryKey) || empty($fieldName)) {
- throw new HttpException("Wrong param id or col!", 400);
- }
- $fieldID = $this->_acl->getFieldIdByName($fieldName);
- if (!$fieldID) {
- throw new HttpException("Field not exists!", 404);
- }
- $item = $this->_acl->getItem($primaryKey);
- if (!$item) {
- throw new HttpException("Item not exists!", 404);
- }
- $itemFromUser = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
- if (!isset($itemFromUser[$fieldName])) {
- throw new HttpException("Field not set!", 400);
- }
- $itemPatch = array();
- $itemPatch[$fieldName] = V::get($fieldName, null, $itemFromUser);
- $itemPatch[$primaryKeyField] = $primaryKey;
- $response = new stdClass();
- try {
- $affected = $this->_acl->updateItem($itemPatch);
- if ($affected > 0) {
- $response->type = 'success';
- $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
- } else if ($affected == 0) {
- $response->type = 'info';
- $response->msg = "Nie wprowadzono żadnych zmian";
- }
- $response->record = $this->_acl->getItem($primaryKey);
- }
- catch (Exception $e) {
- $response->type = 'error';
- $response->msg = $e->getMessage();
- }
- return $response;
- }
- private function sendAjaxEdit($id, $args) {
- header("Content-type: text/plain");
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- $cols = array();
- $record = $this->_acl->getItem($id);
- if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
- echo '<div class="alert alert-danger">';
- echo "Brak dostępu do rekordu";// TODO: more info - reason
- echo '</div>';
- return;
- }
- $fieldsList = $this->_acl->getFields();
- foreach ($fieldsList as $kID => $vCol) {
- if ($vCol['name'] == 'ID') {
- unset($fieldsList[$kID]);
- continue;
- }
- $cols[$kID] = '';
- if ($this->_acl->isAllowed($kID, 'R', $record)) {
- $cols[$kID] = V::get($vCol['name'], '', $record);
- } else {
- $cols[$kID] = '*****';
- }
- $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
- $fieldsList[$kID]['label'] = (!empty($vCol['label']))? $vCol['label'] : str_replace('_', ' ', $vCol['name']);
- }
- $tsValues = array();
- 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>';}
- if (!empty($fieldsList)) {
- foreach ($fieldsList as $vColID => $vCol) {
- $typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
- if ($typeSpecial) {
- 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>';}
- $colValue = V::get($vCol['name'], '', $record);
- 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>';}
- $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $record->ID, $vCol['name'], $colValue);
- 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>';}
- if (!empty($specialValues)) {
- $tsValues[$vColID] = implode('<br>', $specialValues);
- }
- }
- }
- }
- 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>';}
- $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('edit', 'cp'), true);
- ?>
- <div class="container AjaxFrmHorizontalEdit" style="max-width:940px">
- <form class="form-horizontal" action="" method="post" id="EDIT_FRM_<?php echo $this->_htmlID; ?>">
- <fieldset>
- <legend>Edycja rekordu Nr <?php echo $record->ID; ?><span class="pull-right valign-btns-bottom"><?php echo $rowFunctionsOut; ?></span></legend>
- <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
- <?php if ($this->_acl->isAllowed($kID, 'W', $record)) : ?>
- <div class="form-group">
- <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
- <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>
- <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
- </label>
- <div class="col-xs-12 col-sm-9 col-md-10">
- <?php
- $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
- if (!empty($tsValues[$kID])) {
- $fieldParams['typespecialValue'] = $tsValues[$kID];
- }
- echo $this->_acl->showFormItem('W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record);
- ?>
- </div>
- </div>
- <?php elseif ($this->_acl->isAllowed($kID, 'R', $record)) : ?>
- <div class="form-group">
- <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
- <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>
- <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
- </label>
- <div class="col-xs-12 col-sm-9 col-md-10">
- <p style="margin-top:5px;">
- <?php
- //echo $this->_acl->showFormItem('R', $kID, "f{$kID}", $cols[$kID], array('appendBack'=>true), $record);
- if (!empty($tsValues[$kID])) {
- echo $tsValues[$kID];
- } else if (!empty($record->{$vCol['name']})) {
- echo $record->{$vCol['name']};
- }
- ?>
- </p>
- </div>
- </div>
- <?php endif; ?>
- <?php endforeach; ?>
- <div class="form-group">
- <div class="col-xs-offset-0 col-xs-12 col-sm-offset-3 col-sm-9 col-md-offset-2 col-md-10">
- <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Zapisz</button>
- </div>
- </div>
- </fieldset>
- </form>
- <p style="padding:100px 0;"></p>
- </div>
- <script>
- jQuery(document).ready(function(){
- jQuery('textarea').autosize();
- jQuery('.frm-help').popover({trigger:'hover'});
- jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
- var data = jQuery(this).serialize();
- // TODO: change Edit btn to return to edit record with fields -> show form
- var taskCont = jQuery('#<?php echo $this->_htmlID; ?>_task').parent();
- //taskCont.empty();
- taskCont.children().fadeOut('slow');
- var alertCntWrap = jQuery('<div class="AjaxTableAlert AjaxTable-loading"></div>').prependTo(taskCont)
- , alertCnt = jQuery('<div class="container"></div>').prependTo(alertCntWrap);
- 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);
- function notifyAjaxCallback(data) {
- var notify = {}, outMsg = '';
- notify.type = (data && data.type)? data.type : '';
- notify.msg = (data && data.msg)? data.msg : '';
- switch (notify.type) {
- case 'success':
- if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
- break;
- case 'info':
- if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
- break;
- case 'error':
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- case 'warning':
- notify.type = 'warn';
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- default:
- notify.msg = 'Nieznany błąd';
- if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
- notify.type = '';
- }
- jQuery.notify(notify.msg, notify.type);
- var alertType = ('error' == notify.type) ? 'danger' : notify.type;
- outMsg = '<div class="alert alert-' + alertType + '">' + notify.msg + '</div>';
- return outMsg;
- }
- $.ajax({
- data: data,
- dataType: 'json',
- type: "POST",
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT_SAVE&ID=<?php echo $record->ID; ?>',
- })
- .done(function(data, textStatus, jqXHR){
- var outMsg = notifyAjaxCallback(data);
- alertCntWrap.removeClass('AjaxTable-loading');
- //console.log('request finished L.<?php echo __LINE__; ?>');
- alertCnt.empty();
- var out = '';
- out += outMsg;
- out += '<div class="breadcrumb">' +
- ' <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>' +
- ' <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>' +
- '</div>';
- jQuery(out).appendTo(alertCnt);
- })
- .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
- if (jqXHR.responseJSON) {
- notifyAjaxCallback(jqXHR.responseJSON);
- }
- else {
- var txt = jqXHR.responseText || 'Wystąpiły błędy';
- if (jqXHR.status == 404) {
- jQuery.notify(jqXHR.responseText, 'error');
- } else {
- jQuery.notify(jqXHR.responseText, 'warn');
- }
- }
- alertCntWrap.removeClass('AjaxTable-loading');
- //console.log('Request Error: {0}: {1}'.f(textStatus, errorThrown));
- alertCnt.empty();
- jQuery(errorTxt).appendTo(alertCnt);
- var errLinks = jQuery('<div class="breadcrumb"></div>').appendTo(alertCnt);
- jQuery('<a href="#" onclick="return tableAjaxBackToTable();"> <i class="icon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>').appendTo(errLinks);
- 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);
- backToEditBtn.on('click', function(){
- alertCnt.remove();
- taskCont.children().fadeIn('slow');
- return false;
- });
- });
- return false;
- });
- jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value input').on('input', function(e) {
- var input, btn, btnIco;
- input = jQuery(e.target);
- btn = input.next('.button-appendBack');
- btnIco = btn.find('.glyphicon');
- //console.log('title',btn.attr('title'),'val',input.val(),'input', input, 'btn', btn);
- if (btn.attr('title') != input.val()) {
- btnIco.show();
- } else {
- btnIco.hide();
- }
- });
- jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value').find('.button-appendBack').on('click', function(e) {
- var input, btn, btnIco;
- btn = jQuery(this);
- btnIco = btn.find('.glyphicon');
- input = btn.prev();
- //console.log('title',btn.attr('title'),'val',input.val(),'input', input, 'btn', btn);
- if (input.is('input')) {
- if (btn.attr('title') != input.val()) {
- input.val(btn.attr('title'));
- btnIco.hide();
- }
- }
- });
- });
- </script>
- <?php
- exit;
- }
- private function ajaxEditSave($args) {
- $primaryKeyField = $this->_acl->getPrimaryKeyField();
- $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
- if (empty($primaryKey)) {
- throw new HttpException("Wrong param id!", 400);
- }
- $item = $this->_acl->getItem($primaryKey);
- if (!$item) {
- throw new HttpException("Item not exists!", 404);
- }
- $itemFromUser = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
- $response = new stdClass();
- try {
- $itemFromUser[$primaryKeyField] = $primaryKey;
- $affected = $this->_acl->updateItem($itemFromUser);
- if ($affected > 0) {
- $response->type = 'success';
- $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
- } else if ($affected == 0) {
- $response->type = 'info';
- $response->msg = "Nie wprowadzono żadnych zmian";
- }
- $response->record = $this->_acl->getItem($primaryKey);
- }
- catch (Exception $e) {
- $response->type = 'error';
- $response->msg = "Wystąpiły błędy!";
- $response->msg .= $e->getMessage();
- }
- return $response;
- }
- private function sendAjaxCreate($args) {
- header("Content-type: text/plain");
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- if (!$this->_acl->hasCreatePerms()) {
- ?>
- <div class="container">
- <div class="alert alert-danger">
- Brak uprawnień do utworzenia nowego rekordu.
- </div>
- </div>
- <?php
- return;
- }
- $cols = array();
- $forceFilterInit = array();
- $defaultAclGroup = User::getDefaultAclGroup();
- if ($defaultAclGroup) {
- $forceFilterInit['A_ADM_COMPANY'] = $defaultAclGroup;
- $forceFilterInit['A_CLASSIFIED'] = $defaultAclGroup;
- }
- foreach ($_GET as $k => $v) {
- if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
- $fldName = substr($k, 3);
- $forceFilterInit[$fldName] = $v;
- }
- }
- $fieldsList = $this->_acl->getFields();
- foreach ($fieldsList as $kID => $vCol) {
- $defaultValue = '';
- if ($vCol['name'] == 'ID') {
- unset($fieldsList[$kID]);
- continue;
- }
- if (!empty($forceFilterInit[$vCol['name']])) {
- $defaultValue = $forceFilterInit[$vCol['name']];
- }
- // TODO: read from session cache
- $cols[$kID] = V::get("f{$kID}", $defaultValue, $_POST);
- $fieldsList[$kID]['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
- }
- ?>
- <div class="container AjaxFrmHorizontalEdit">
- <form class="form-horizontal" action="" method="post" id="CREATE_FRM_<?php echo $this->_htmlID; ?>">
- <fieldset>
- <legend>Dodaj nowy rekord</legend>
- <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
- <?php if ($this->_acl->isAllowed($kID, 'C')) : ?>
- <div class="form-group">
- <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
- <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>
- <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
- </label>
- <div class="col-xs-12 col-sm-9 col-md-10">
- <?php
- $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
- echo $this->_acl->showFormItem('C', $kID, "f{$kID}", $cols[$kID], $fieldParams);
- ?>
- </div>
- </div>
- <?php endif; ?>
- <?php endforeach; ?>
- <div class="form-group">
- <div class="col-xs-offset-0 col-xs-12 col-sm-offset-3 col-sm-9 col-md-offset-2 col-md-10">
- <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Dodaj rekord</button>
- </div>
- </div>
- </fieldset>
- </form>
- </div>
- <script>
- jQuery(document).ready(function(){
- jQuery('textarea').autosize();
- jQuery('.frm-help').popover({trigger:'hover'});
- jQuery('#CREATE_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
- var data = jQuery(this).serialize();
- var taskContLast = jQuery('#<?php echo $this->_htmlID; ?>_task'),
- taskCont = taskContLast.parent();
- taskContLast.fadeOut('slow');
- var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
- 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);
- function notifyAjaxCallback(data) {
- var notify = {};
- notify.type = (data && data.type)? data.type : '';
- notify.msg = (data && data.msg)? data.msg : '';
- switch (notify.type) {
- case 'success':
- if (!notify.msg) notify.msg = 'OK';
- break;
- case 'info':
- if (!notify.msg) notify.msg = '';
- break;
- case 'error':
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- case 'warning':
- notify.type = 'warn';
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- default:
- notify.msg = 'Nieznany błąd';
- if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
- notify.type = '';
- }
- jQuery.notify(notify.msg, notify.type);
- }
- $.ajax({
- data: data,
- dataType: 'json',
- type: "POST",
- async: true,
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE_SAVE'
- })
- .always(function(dataOrJqXHR){
- var data;
- if (dataOrJqXHR && 'readyState' in dataOrJqXHR && 'status' in dataOrJqXHR) {
- if ('responseJSON' in dataOrJqXHR) {
- data = dataOrJqXHR.responseJSON;
- } else {
- data = {};
- data.msg = dataOrJqXHR.responseText || 'Nieznany błąd';
- if (dataOrJqXHR.status == 404) {
- data.type = 'error';
- } else {
- data.type = 'warning';
- }
- }
- }
- else {
- data = dataOrJqXHR;
- }
- notifyAjaxCallback(data);
- taskCnt.removeClass('AjaxTable-loading');
- taskCnt.empty();
- if (data.type == 'error' || data.type == 'warning') {
- var out = '<div class="container">' +
- '<div class="alert alert-danger">' +
- '<h4>Wystąpiły błędy!</h4>' + data.msg +
- (('errors' in data)? '<p>' + data.errors + '</p>' : '') +
- '</div>';
- out += '<div class="breadcrumb">' +
- ' <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>' +
- '</div>' +
- '</div>';
- jQuery(out).appendTo(taskCnt);
- var taskContLastNode = taskContLast
- , taskCntNode = taskCnt;
- taskCnt.find('.create-fix').click(function(){
- taskCntNode.remove();
- taskContLastNode.fadeIn('slow');
- return false;
- });
- }
- else if (data.type == 'success') {
- var msg = '';
- if (data.id && data.id > 0) {
- msg = 'Utworzono pomyślnie rekord: ID = ' + data.id;
- } else if (data.msg) {
- msg = data.msg;
- } else {
- msg = 'OK';
- }
- var out = '<div class="container">';
- out += '<div class="alert alert-success">' + msg + '</div>';
- out += '<div class="breadcrumb">' +
- ' <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>' +
- ' <a href="#EDIT/' + data.id + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-pencil"></i> Edytuj rekord ' + data.id + '</a>' +
- ' <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>' +
- '</div>';
- out += '</div>';
- jQuery(out).appendTo(taskCnt);
- }
- });
- return false;
- });
- });
- </script>
- <?php
- exit;
- }
- private function ajaxCreateSave($args) {
- $response = new stdClass();
- $createdId = null;
- try {
- $item = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
- $createdId = $this->_acl->addItem($item);
- if ($createdId) {
- $response->type = 'success';
- $response->msg = "Utworzono pomyślnie rekord nr {$createdId}";
- $response->id = $createdId;
- $response->record = $this->_acl->getItem($createdId);
- }
- else {
- $response->type = 'error';
- $response->msg = "Nie udało się utworzyć nowego rekordu!";
- }
- }
- catch (Exception $e) {
- $response->type = 'error';
- $response->msg = "Wystąpiły błędy!";
- $response->msg = $e->getMessage();
- }
- return $response;
- }
- private function ajaxCopy($args) {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- if ($id <= 0) {
- throw new HttpException("Wrong param ID!", 404);
- }
- $item = $this->_acl->getItem($id);
- if (!$item) {
- throw new HttpException("Item '{$id}' not exists!", 404);
- }
- $response = new stdClass();
- $itemCopy = $this->_acl->createItemCopy($item);
- $createdId = null;
- try {
- $createdId = $this->_acl->addItem($itemCopy);
- if ($createdId) {
- $response->type = 'success';
- $response->msg = "Rekord skopiowany pomyślnie - utworzono rekord nr {$createdId}";
- $response->id = $createdId;
- $response->record = $this->_acl->getItem($createdId);
- }
- else {
- $response->type = 'error';
- $response->msg = "Nie udało się utworzyć nowego rekordu!";
- }
- }
- catch (Exception $e) {
- $response->type = 'error';
- $response->msg = "Wystąpiły błędy!";
- $response->msg = $e->getMessage();
- }
- return $response;
- }
- private function sendAjaxHistory($id, $args) {
- header("Content-type: text/plain");
- $record = $this->_acl->getItem($id);
- if (!$record) {
- header('HTTP/1.0 404 Not Found');
- echo "404: No item ID({$rowID})";
- exit;
- }
- $visibleCols = $this->_acl->getRealFieldList();
- $rowsHist = $this->_acl->getHistItems($id);
- $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('hist', 'cp'), true);
- $visibleColsWithIds = array();
- $visibleColsLabels = array();
- foreach ($visibleCols as $vColName) {
- $fldId = $this->_acl->getFieldIdByName($vColName);
- if ($fldId) {
- $visibleColsWithIds[$fldId] = $vColName;
- $label = $this->_acl->getFieldLabel($fldId);
- $label = (!$label)? $vColName : '<span title="' . "[{$fldId}] {$vColName}" . '">' . $label . '</span>';
- $visibleColsLabels[$fldId] = $label;
- }
- }
- ?>
- <fieldset>
- <legend>Historia rekordu Nr <?php echo $id; ?>
- <span class="pull-right valign-btns-bottom"><?php echo $rowFunctionsOut; ?></span>
- </legend>
- </fieldset>
- <?php if (empty($rowsHist)) : ?>
- <div class="alert alert-info">
- <h4>Brak danych</h4>
- </div>
- <?php else: ?>
- <table class="table table-striped table-hover table-bordered table-condensed AjaxTableHist">
- <thead>
- <tr>
- <th>Data</th>
- <th>User</th>
- <th>Zmiany</th>
- </tr>
- </thead>
- <tbody>
- <?php foreach ($rowsHist as $row) : ?>
- <tr>
- <td style="white-space:nowrap"><?php echo $row->_created; ?></td>
- <td><?php echo $row->_author; ?></td>
- <td>
- <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
- <?php if (in_array($colName, array('ID', 'A_RECORD_UPDATE_DATE', 'A_RECORD_UPDATE_AUTHOR', 'A_RECORD_CREATE_DATE', 'A_RECORD_CREATE_AUTHOR'))) continue; ?>
- <?php if ($row->$colName == 'N/S;') continue; ?>
- <p><em><?php echo $visibleColsLabels[$fldId]; ?></em>:
- <?php if ($this->_acl->isAllowed($fldId, 'R', $record)) : ?>
- <?php echo $row->$colName; ?>
- <?php else : ?>
- <span title="Brak uprawnień do odczytu tego pola">*****</span>
- <?php endif; ?>
- </p>
- <?php endforeach; ?>
- </td>
- </tr>
- <?php endforeach; ?>
- </tbody>
- </table>
- <div style="overflow-x:scroll; overflow-y:visible; padding-bottom:1px; margin:10px 0;">
- <table class="table table-striped table-hover table-bordered table-condensed AjaxTableHist">
- <thead>
- <tr>
- <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
- <th><?php echo str_replace('_', ' ', $visibleColsLabels[$fldId]); ?></th>
- <?php endforeach; ?>
- </tr>
- </thead>
- <tbody>
- <?php foreach ($rowsHist as $row) : ?>
- <tr>
- <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
- <td>
- <?php if ($row->$colName == 'N/S;') : ?>
- <em>N/S;</em>
- <?php elseif ($this->_acl->isAllowed($fldId, 'R', $record)) : ?>
- <?php echo $row->$colName; ?>
- <?php else : ?>
- <span title="Brak uprawnień do odczytu tego pola">*****</span>
- <?php endif; ?>
- </td>
- <?php endforeach; ?>
- </tr>
- <?php endforeach; ?>
- </tbody>
- </table>
- </div>
- <?php endif; ?>
- <?php
- exit;
- }
- /**
- * Returns text/plain with type at first line: ERROR, WARNING, INFO, SUCCESS
- */
- private function sendAjaxFilesUpload($id, $args) {
- // http://www.sitepoint.com/html5-ajax-file-upload/
- //$ajaxFileName = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
- //header("Content-type: text/plain");
- header("Content-type: application/json");
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- $dbID = $this->_acl->getDB();
- $db = DB::getDB($dbID);
- if (!$db) {
- header('HTTP/1.0 406 Not Acceptable');
- echo '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
- exit;
- }
- $record = $this->_acl->getItem($id);
- if (!$record) {
- header('HTTP/1.0 404 Not Found');
- echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
- exit;
- }
- $tblName = $this->_acl->getName();
- $confTblName = "{$tblName}_COLUMN";
- $folderConfAll = FoldersConfig::getRawData();
- if (!FoldersConfig::hasConfig($confTblName)) {
- header('HTTP/1.0 404 Not Found');
- echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych(' . $tblName . ')"}';
- exit;
- }
- $folderConf = FoldersConfig::getAll($confTblName);
- $uploader = new FileUploader($confTblName, $record);
- $errMsg = '';
- if (!$uploader->setConfig($folderConf, $errMsg)) {
- header('HTTP/1.0 404 Not Found');
- echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych(' . $tblName . ') <br>' . $errMsg . '"}';
- exit;
- }
- $uploader->findFolder();
- $errorMsg = '';
- if (!empty($_POST['SCANS_COLUMN_ADD'])) {
- $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
- }
- else {
- $uploaded = $uploader->tryUploadAjax($errorMsg);
- }
- if ($uploaded) {
- $uploadedFileName = '';
- $uploadedFile = $uploader->getLastUploadedFile();
- if ($uploadedFile) {
- $uploadedFileName = explode('/', $uploadedFile);
- $uploadedFileName = end($uploadedFileName);
- }
- echo '{"type":"SUCCESS", "string": "Plik został poprawnie wgrany do odpowiedniego katalogu '.$uploadedFileName.'"}';
- if (!empty($uploadedFileName)) {
- $sqlObj = new stdClass();
- $sqlObj->ID = $record->ID;
- $sqlObj->M_DIST_FILES = "Wgrano plik {$uploadedFileName}";
- $db->UPDATE_OBJ($this->_tbl, $sqlObj);
- }
- } else {
- echo '{"type":"ERROR", "string": "' . $errorMsg . '"}';
- }
- exit;
- }
- private function sendAjaxFileRemove($id, $args) {
- header("Content-type: application/json");
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- if (empty($_POST['filename'])) {
- echo '{"type":"ERROR", "string": "Nie wybrano pliku do usunięcia"}';
- exit;
- }
- $dbID = $this->_acl->getDB();
- $db = DB::getDB($dbID);
- if (!$db) {
- header('HTTP/1.0 406 Not Acceptable');
- echo '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
- exit;
- }
- $record = $this->_acl->getItem($id);
- if (!$record) {
- header('HTTP/1.0 404 Not Found');
- echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
- exit;
- }
- $tblName = $this->_acl->getName();
- $confTblName = "{$tblName}_COLUMN";
- $folderConfAll = FoldersConfig::getRawData();
- if (!FoldersConfig::hasConfig($confTblName)) {
- header('HTTP/1.0 404 Not Found');
- echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
- exit;
- }
- $folderConf = FoldersConfig::getAll($confTblName);
- $uploader = new FileUploader($confTblName, $record);
- if (!$uploader->setConfig($folderConf)) {
- header('HTTP/1.0 404 Not Found');
- echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
- exit;
- }
- $uploader->findFolder();
- $errorMsg = '';
- $removed = $uploader->tryRemoveFromAjax($_POST['filename'], $errorMsg);
- if (!$removed) {
- echo '{"type":"ERROR", "string": "{' . $errorMsg . '}"}';
- } else {
- echo '{"type":"SUCCESS","string":"Plik został poprawnie usunięty"}';
- }
- exit;
- }
- private function sendAjaxFilesList($id, $args) {
- header("Content-type: application/json");
- $dbID = $this->_acl->getDB();
- $db = DB::getDB($dbID);
- if (!$db) {
- header('HTTP/1.0 406 Not Acceptable');
- echo '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
- exit;
- }
- $record = $this->_acl->getItem($id);
- if (!$record) {
- header('HTTP/1.0 404 Not Found');
- echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
- exit;
- }
- $tblName = $this->_acl->getName();
- $confTblName = "{$tblName}_COLUMN";
- $folderConfAll = FoldersConfig::getRawData();
- if (!FoldersConfig::hasConfig($confTblName)) {
- header('HTTP/1.0 404 Not Found');
- echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
- exit;
- }
- $folderConf = FoldersConfig::getAll($confTblName);
- $uploader = new FileUploader($confTblName, $record);
- if (!$uploader->setConfig($folderConf)) {
- header('HTTP/1.0 404 Not Found');
- echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
- exit;
- }
- $uploader->findFolder();
- $mainFolder = $uploader->getDestFolder();
- $files = $uploader->getFilesFromFolder($mainFolder, false, true);
- $localPath = $uploader->getLocalPath();
- $folderWeb = $uploader->getFolderWeb();
- $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
- echo json_encode($jsonFiles);
- exit;
- }
- private function ajaxFilePermsRefresh($args) {
- header("Content-type: application/json");
- $id = V::get('ID', 0, $args, 'int');
- if ($id <= 0) throw new HttpException("Wrong param ID", 404);
- $dbID = $this->_acl->getDB();
- $db = DB::getDB($dbID);
- if (!$db) throw new HttpException("No DB", 406);
- $record = $this->_acl->getItem($id);
- if (!$record) throw new Exception("No item ID({$rowID})", 404);
- $tblName = $this->_acl->getName();
- // TODO: SyncPermsCustomTables->getRecordTask($tbl, $id);
- $sql_L_APPOITMENT_USER = V::get('L_APPOITMENT_USER', '', $record);
- $sql_A_ADM_COMPANY = V::get('A_ADM_COMPANY', '', $record);
- $sql_A_CLASSIFIED = V::get('A_CLASSIFIED', '', $record);
- $mainDB = DB::getDB();
- if ('IN7_MK_BAZA_DYSTRYBUCJI' == $tblName) {
- $sql = "insert into `_SYNC_FILE_PERMS` (
- `ID_PROJECT`,
- `A_SYNCHRONIZED`
- )
- values (
- '{$record->ID}'
- , 0
- )
- ON DUPLICATE KEY UPDATE
- `A_SYNCHRONIZED`=0
- ";
- }
- else if ('IN7_DZIENNIK_KORESP' == $tblName) {
- $sql = "insert into `_SYNC_FILE_PERMS` (
- `ID_PROJECT`,
- `A_SYNCHRONIZED`
- )
- values (
- '{$record->ID_PROJECT}'
- , 0
- )
- ON DUPLICATE KEY UPDATE
- `A_SYNCHRONIZED`=0
- ";
- }
- else {
- $sql = "insert into `_SYNC_TABLE_FILE_PERMS` (
- `TBL_NAME`,
- `TBL_ID`,
- `L_APPOITMENT_USER`,
- `A_ADM_COMPANY`,
- `A_CLASSIFIED`,
- `A_SYNCHRONIZED`
- )
- values (
- '{$tblName}'
- , '{$id}'
- , '{$sql_L_APPOITMENT_USER}'
- , '{$sql_A_ADM_COMPANY}'
- , '{$sql_A_CLASSIFIED}'
- , 0
- )
- ON DUPLICATE KEY UPDATE
- `A_SYNCHRONIZED`=0
- ";
- }
- $res = $mainDB->query($sql);
- if ($mainDB->has_errors()) {
- //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';
- //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>';
- throw new Exception("Nie udało się dodać zadania");
- }
- // TODO: this blocks browser ajax query
- //$limit = 3;
- //while ($limit--) {
- // sleep(10);
- // TODO: check if task is done
- //}
- $confTblName = "{$tblName}_COLUMN";
- $folderConfAll = FoldersConfig::getRawData();
- if (!FoldersConfig::hasConfig($confTblName)) {
- throw new Exception("Brak danych konfiguracyjnych ({$tblName})", 404);
- }
- $folderConf = FoldersConfig::getAll($confTblName);
- $uploader = new FileUploader($confTblName, $record);
- if (!$uploader->setConfig($folderConf)) {
- throw new Exception("Błąd danych konfiguracyjnych ({$tblName})", 404);
- }
- $uploader->findFolder();
- $mainFolder = $uploader->getDestFolder();
- $files = $uploader->getFilesFromFolder($mainFolder, false, true);
- $localPath = $uploader->getLocalPath();
- $folderWeb = $uploader->getFolderWeb();
- $jsonData = new stdClass();
- $jsonData->msg = 'Zadanie dodane';
- $jsonData->type = 'success';
- $jsonData->files = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
- return $jsonData;
- }
- private function sendAjaxFilesConnTblList($id, $args) {
- header("Content-type: application/json");
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- $dbID = $this->_acl->getDB();
- $db = DB::getDB($dbID);
- if (!$db) {
- header('HTTP/1.0 406 Not Acceptable');
- echo 'No DB (' . $dbID . ')';
- exit;
- }
- $record = $this->_acl->getItem($id);
- if (!$record) {
- header('HTTP/1.0 404 Not Found');
- echo 'No item ID(' . $rowID . ')';
- exit;
- }
- $connTblName = '';
- $connTblID = V::get('connTblID', 0, $_REQUEST, 'int');
- if ($connTblID <= 0) {
- header('HTTP/1.0 406 Not Acceptable');
- echo 'No conn Table ID';
- exit;
- }
- $connTblTypespecials = $this->getConnectedTblTypespecials($connTblID);
- if (empty($connTblTypespecials)) {
- header('HTTP/1.0 406 Not Acceptable');
- echo "No conn Table (ID={$connTblID})";
- exit;
- }
- 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>';}
- if(1) {
- header('HTTP/1.0 404 Not Found');
- echo 'TODO: ...';
- exit;
- }
- $tblName = $this->_acl->getName();
- $confTblName = "{$tblName}_COLUMN";
- $folderConfAll = FoldersConfig::getRawData();
- if (!FoldersConfig::hasConfig($confTblName)) {
- header('HTTP/1.0 404 Not Found');
- echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
- exit;
- }
- $folderConf = FoldersConfig::getAll($confTblName);
- $uploader = new FileUploader($confTblName, $record);
- if (!$uploader->setConfig($folderConf)) {
- header('HTTP/1.0 404 Not Found');
- echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
- exit;
- }
- $uploader->findFolder();
- $mainFolder = $uploader->getDestFolder();
- $files = $uploader->getFilesFromFolder($mainFolder, false, true);
- $localPath = $uploader->getLocalPath();
- $folderWeb = $uploader->getFolderWeb();
- $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
- echo json_encode($jsonFiles);
- exit;
- }
- public function convertFileListToJson($files, $folderWeb, $localPath, $mainFolder) {
- $jsonFiles = array();
- if (!is_array($files) || empty($files)) {
- return $jsonFiles;
- }
- sort($files);
- foreach ($files as $vFilePath) {
- $file = new stdClass();
- $file->name = str_replace("{$localPath}/{$mainFolder}/", '', $vFilePath);
- //$file->name = explode('/', $vFilePath);
- //$file->name = end($file->name);
- $file->size = filesize($vFilePath);
- $file->sizeStr = round($file->size, 2) . "B";
- if ($file->size > 1024 * 1024) {
- $file->sizeStr = round(($file->size / (1024 * 1024)), 2) . "M";
- } else if ($file->size > 1024) {
- $file->sizeStr = round(($file->size / 1024), 2) . "K";
- }
- $file->type = '';
- $file->created = date("Y-m-d H:i:s", filectime($vFilePath));
- $file->web = str_replace($localPath, $folderWeb, $vFilePath);
- $jsonFiles[] = $file;
- }
- return $jsonFiles;
- }
- private function getConnectedTables() {
- $connTbls = array();
- return $connTbls;// TODO: OFF - hardlinki tworzone w bash_sync_perms.php
- $fields = $this->_acl->getVisibleFieldList();
- if (!empty($fields)) {
- foreach ($fields as $vColID => $vCol) {
- $typeSpecial = Typespecial::getInstance($vColID);
- if ($typeSpecial) {
- $tsConnTbls = $typeSpecial->getTblAliasList();
- if (!empty($tsConnTbls)) {
- foreach ($tsConnTbls as $kID => $vName) {
- $connTbls[$kID] = $vName;
- }
- }
- }
- }
- }
- return $connTbls;
- }
- private function getConnectedTblTypespecials($connTblID) {
- $connTblTypespecials = array();
- $fields = $this->_acl->getVisibleFieldList();
- if (!empty($fields)) {
- foreach ($fields as $vColID => $vCol) {
- $typeSpecial = Typespecial::getInstance($vColID);
- if ($typeSpecial) {
- $tsConnTbls = $typeSpecial->getTblAliasList();
- if (array_key_exists($connTblID, $tsConnTbls)) {
- $connTblTypespecials[] = $typeSpecial;
- }
- }
- }
- }
- return $connTblTypespecials;
- }
- private function sendAjaxFiles($id, $args) {
- header("Content-type: text/plain");
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- $dbID = $this->_acl->getDB();
- $db = DB::getDB($dbID);
- if (!$db) {
- header('HTTP/1.0 406 Not Acceptable');
- exit;
- }
- $record = $this->_acl->getItem($id);
- if (!$record) {
- header('HTTP/1.0 404 Not Found');
- echo "404: No item ID({$rowID})";
- exit;
- }
- if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
- echo '<div class="alert alert-danger">';
- echo "Brak dostępu do rekordu";// TODO: more info - reason
- echo '</div>';
- return;
- }
- $tblName = $this->_acl->getName();
- $confTblName = "{$tblName}_COLUMN";
- $folderConfAll = FoldersConfig::getRawData();
- if (!FoldersConfig::hasConfig($confTblName)) {
- header('HTTP/1.0 404 Not Found');
- echo "Brak danych konfiguracyjnych";
- exit;
- }
- $folderConf = FoldersConfig::getAll($confTblName);
- //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$folderConf (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($folderConf);echo'</pre>';
- $uploader = new FileUploader($confTblName, $record);
- $errMsg = '';
- if (!$uploader->setConfig($folderConf, $errMsg)) {
- header('HTTP/1.0 404 Not Found');
- echo "Błąd danych konfiguracyjnych ({$tblName})";
- echo '<br>' . "\n" . $errMsg;
- exit;
- }
- $uploader->findFolder();
- 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>'; }
- $mainFolder = $uploader->getDestFolder();
- 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>'; }
- $files = $uploader->getFilesFromFolder($mainFolder, false, true);
- 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>'; }
- $sharePoint = V::get('share_point', null, $folderConf);
- if ($sharePoint) {
- $sharePoint = FoldersConfig::getNfsOsPath() . "{$sharePoint}/{$mainFolder}";
- }
- $localPath = $uploader->getLocalPath();
- $folderWeb = $uploader->getFolderWeb();
- $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
- 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>'; }
- $folderSkanyConf = FoldersConfig::getAll('SCANS_COLUMN');
- $skanyLocalPath = V::get('mount_point', null, $folderSkanyConf);
- $skanySharePoint = V::get('share_point', null, $folderSkanyConf);
- $skanyFolderWeb = V::get('www_share_point', null, $folderSkanyConf);
- $skanyFiles = $uploader->getFilesFromSkany($folderSkanyConf, false);
- sort($skanyFiles);
- $fileTypes = FoldersConfig::getAll('m_dist_files_types');
- $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('files', 'cp'), true);
- $fileIndexField = V::get('DEST_FILE_INDEX_FIELD', 'ID', $folderConf);
- $fileIndex = V::get($fileIndexField, $record->ID, $record);
- ?>
- <script src="stuff/jquery.form.js"></script>
- <div class="container">
- <h4 style="margin:20px 0 3px 0;">Pliki w katalogu
- <?php if ($sharePoint) : ?>
- <a href="<?php echo $sharePoint; ?>"><span class="glyphicon glyphicon-folder-open"></span><code><?php echo $mainFolder; ?></code></a>
- <?php else : ?>
- <code><?php echo $mainFolder; ?></code>
- <?php endif; ?>
- <span class="pull-right valign-btns-bottom">
- <span id="FILES_LIST_ACTIONS_<?php echo $this->_htmlID; ?>"></span>
- <?php echo $rowFunctionsOut; ?>
- </span>
- </h4>
- <div style="clear:both; max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">
- <table class="table table-bordered table-hover">
- <colgroup>
- <col style="">
- <col style="width:30px;">
- <?php if ($sharePoint) : ?>
- <col style="width:30px;">
- <?php endif; ?>
- <col style="width:80px;">
- <col style="width:140px;">
- </colgroup>
- <tbody id="FILES_LIST_<?php echo $this->_htmlID; ?>">
- <?php if (empty($mainFolder)) : ?>
- <tr>
- <td colspan="5">
- <div class="alert alert-warning">
- <h4>Brak folderu!</h4>
- Folder dla tego rekordu nie został utworzony.
- </div>
- </td>
- </tr>
- <?php elseif (empty($files)) : ?>
- <tr>
- <td colspan="5">
- <div class="alert alert-info">
- <h4>Brak plików</h4>
- </div>
- </td>
- </tr>
- <?php endif; ?>
- </tbody>
- </table>
- </div>
- <br>
- <br>
- <div id="FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>"></div>
- <form enctype="multipart/form-data" method="POST" action="" id="FILES_FRM_<?php echo $this->_htmlID; ?>" class="form-inline">
- <input type="hidden" name="M_DIST_UPLOAD_SOURCE" value="local">
- <ul id="FILES_TAB_<?php echo $this->_htmlID; ?>" class="nav nav-tabs" style="margin:0;">
- <li class="active"><a href="#local" data-toggle="local">Wybierz plik lokalny</a></li>
- <li><a href="#scan" data-toggle="scan">Wybierz plik ze skanów</a></li>
- </ul>
- <div id="myTabContent" class="tab-content">
- <div class="tab-pane fade in active" id="local" style="text-align: center;">
- <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'">
- </div>
- <div class="tab-pane fade" id="scan">
- <?php if (empty($skanyFiles)) : ?>
- <div class="alert alert-info">
- <h4>Brak plików</h4>
- <?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>"; ?>
- </div>
- <?php else : ?>
- <div style="max-height:150px; overflow:auto; border-bottom:1px solid #ddd;">
- <table class="table table-bordered table-hover">
- <colgroup>
- <col style="width:30px;">
- <col style="">
- <col style="width:30px;">
- <col style="width:80px;">
- <col style="width:140px;">
- </colgroup>
- <tbody>
- <?php foreach ($skanyFiles as $vFilePath) : ?>
- <tr>
- <?php
- $vFileName = explode('/', $vFilePath);
- $vFileName = end($vFileName);
- $vFileSize = filesize($vFilePath);
- $vFileSizeOut = round($vFileSize, 2) . "B";
- if ($vFileSize > 1024 * 1024) {
- $vFileSizeOut = round(($vFileSize / (1024 * 1024)), 2) . "M";
- } else if ($vFileSize > 1024) {
- $vFileSizeOut = round(($vFileSize / 1024), 0) . "K";
- }
- ?>
- <td><input style="margin:0;" type="radio" name="SCANS_COLUMN_ADD" value="<?php echo $vFileName; ?>"></td>
- <td><div style="overflow:hidden; white-space:nowrap;" title="<?php echo $vFileName; ?>"><?php echo $vFileName; ?></div></td>
- <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>
- <td style="white-space:nowrap;"><?php echo $vFileSizeOut; ?></td>
- <td style="white-space:nowrap;"><?php echo date("Y-m-d H:i:s", filectime($vFilePath)); ?></td>
- </tr>
- <?php endforeach; ?>
- </tbody>
- </table>
- </div>
- <?php endif; ?>
- </div>
- </div>
- <br>
- <h4>Ustal nazwę pliku zgodną z obiegiem dokumentów
- <?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> ?>
- </h4>
- <table style="width:100%" class="table table-bordered">
- <tr>
- <th>Nr</th>
- <th>Typ</th>
- <th style="width:40%;">Opis <i class="glyphicon glyphicon-question-sign" title="kogo dotyczy / czego / sprawa / nazwa_firmy itp"></i></th>
- <th style="width:16%">Data wersji</th>
- <th style="width:12%">Numer wersji</th>
- </tr>
- <tr>
- <td>
- <?php echo $fileIndex; ?>
- </td>
- <td>
- <select class="form-control" name="M_DIST_FILES_TYPE">
- <?php foreach ($fileTypes as $kType => $vLabel) : ?>
- <option value="<?php echo $kType; ?>"<?php if ($kType == 'TODO') { echo ' selected="selected"'; } ?> ><?php echo $vLabel; ?></option>
- <?php endforeach; ?>
- </select>
- <br>
- <label class="checkbox">
- <input type="checkbox" name="M_DIST_FILES_TYPE_AUTO">
- Wykrycie automatyczne typu z wysylanego pliku
- </label>
- <label class="checkbox">
- <input type="checkbox" name="M_DIST_FILES_TEMP">
- Plik tymczasowy / roboczy / nieoficjalny (_TEMP)
- </label>
- </td>
- <td>
- <input class="form-control" style="width:100%" type="text" name="M_DIST_FILES_DESCRIPTION" value="" maxlength="50">
- <br><label>jeśli nie zostanie podany to zostanie automatycznie wygenerowany na podstawie nazwy pliku wysyłanego</label>
- </td>
- <td>
- <div class="input-group">
- <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">
- <span class="glyphicon glyphicon-calendar"></span>
- </span>
- </div>
- <!--
- <input class="form-control" type="date" name="M_DIST_FILES_DATE" value="<?php echo date('Y-m-d');?>" maxlength="10">
- -->
- <br><label>jeśli nie zostanie podana to zostanie ustawiona na dzisiaj (<?php echo date('Y-m-d');?>)</label>
- </td>
- <td>
- <input class="form-control" style="width:100%" type="number" name="M_DIST_FILES_VERSION">
- <br>
- <label class="checkbox">
- <input type="checkbox" name="M_DIST_FILES_VERSION_AUTO">
- Automatycznie dodaj wersje
- </label>
- </td>
- </tr>
- <tr>
- <td colspan="5">
- <div id="FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>"></div>
- <p>
- <input type="submit" value="Wyślij" class="btn btn-primary"> wybrany plik do folderu:
- </p>
- <p>
- <code><b><?php echo $uploader->getDestPathShare(true); ?></b></code>
- <br><i style="color:#777">(Jeśli folder nie istnieje to zostanie utworzony automatycznie)</i>
- </p>
- </td>
- </tr>
- </table>
- </form>
- </div>
- <script>
- function fileListUpdateAjax<?php echo $this->_htmlID; ?>() {
- var postData = {};
- jQuery.ajax({
- 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; ?>',
- type: 'POST',
- //dataType: 'json',
- //contentType: "application/json; charset=utf-8",
- data: postData,
- async: true,
- success: function(data) {
- fileListUpdate<?php echo $this->_htmlID; ?>(data);
- },
- error: function(jhr, textStatus, errorThrown) {
- if (priv.options.debug) console.log('request error: ', errorThrown, ' textStatus: ', textStatus);
- }
- });
- }
- function fileListUpdate<?php echo $this->_htmlID; ?>(fileListJson) {
- var fileListNode = jQuery('#FILES_LIST_<?php echo $this->_htmlID; ?>');
- fileListNode.empty();
- fileListJson.map(function(file){
- var node = $('<tr></tr>');
- var fFun = $('<i class="glyphicon glyphicon-remove" style="cursor:pointer" data-filename="' + file.name + '"></i>');
- var fNameCell = $('<td style="overflow: hidden;"></td>');
- var fName = $('<div style="overflow:hidden; white-space:nowrap;" title="' + file.name + '"></div>');
- fName.append(fFun);
- fName.append(file.name);
- fName.appendTo(fNameCell);
- node.append(fNameCell);
- 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>');
- <?php if ($sharePoint) : ?>
- 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>');
- <?php endif; ?>
- node.append('<td style="overflow:hidden; white-space:nowrap; text-align:right;">' + file.sizeStr + '</td>');
- node.append('<td style="overflow:hidden; white-space:nowrap;">' + file.created + '</td>');
- node.appendTo(fileListNode);
- $(fFun).click(function(e){
- var n = $(e.target);
- var fname= n.data('filename');
- if (!fname) {
- return false;
- }
- if (confirm('Czy jesteś pewien, że chcesz usunąć plik o nazwie ' + fname + '?')) {
- var postData = {filename: fname};
- jQuery.ajax({
- 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; ?>',
- type: 'POST',
- //dataType: 'json',
- //contentType: "application/json; charset=utf-8",
- data: postData,
- async: true,
- success: function(data) {
- if (data && data.type) {
- if (data.type == 'SUCCESS') {
- n.parents('tr').remove();
- //console.log('TODO: SUCCESS msg: ', data.string);
- }
- else if (data.type == 'ERROR') {
- //console.log('TODO: ERROR msg: ', data.string);
- }
- } else {
- if (priv.options.debug) console.log('TODO: ??? data: ', data);
- }
- },
- error: function(jhr, textStatus, errorThrown) {
- if (priv.options.debug) console.log('rm error: ', errorThrown, ' textStatus: ', textStatus);
- }
- });
- }
- });
- });
- }
- function connTblListUpdateAjax<?php echo $this->_htmlID; ?>(connTblID) {
- var postData = {};
- // clear current file list
- jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list').empty();
- jQuery.ajax({
- 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,
- type: 'POST',
- //dataType: 'json',
- //contentType: "application/json; charset=utf-8",
- data: postData,
- async: true,
- success: function(data) {
- connTblListUpdate<?php echo $this->_htmlID; ?>(data);
- },
- error: function(jqXHR, textStatus, errorThrown) {
- var txt = jqXHR.responseText || 'Error';
- 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>');
- if (priv.options.debug) console.log('connTblListUpdateAjax error: ', errorThrown, ' textStatus: ', textStatus);
- }
- });
- }
- function connTblListUpdate<?php echo $this->_htmlID; ?>(fileListJson) {
- var fileListNode = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list');
- fileListNode.empty();
- fileListJson.map(function(file){
- var node = $('<tr></tr>');
- var fNameCell = $('<td style="overflow: hidden;"></td>');
- var fName = $('<div style="overflow:hidden; white-space:nowrap;" title="' + file.name + '"></div>');
- fName.append(file.name);
- fName.appendTo(fNameCell);
- node.append(fNameCell);
- 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>');
- node.append('<td style="overflow:hidden; white-space:nowrap; text-align:right;">' + file.sizeStr + '</td>');
- node.append('<td style="overflow:hidden; white-space:nowrap;">' + file.created + '</td>');
- node.appendTo(fileListNode);
- });
- }
- function fileListActions<?php echo $this->_htmlID; ?>() {
- var filePermsReload = jQuery('#FILES_LIST_ACTIONS_<?php echo $this->_htmlID; ?>');
- 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>');
- btnReload.on('click', function(e) {
- //console.log('TODO: click reload perms...');
- function notifyAjaxCallback(data) {
- var notify = {};
- notify.type = (data && data.type)? data.type : '';
- notify.msg = (data && data.msg)? data.msg : '';
- switch (notify.type) {
- case 'success':
- if (!notify.msg) notify.msg = 'OK';
- break;
- case 'info':
- if (!notify.msg) notify.msg = '';
- break;
- case 'error':
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- case 'warning':
- notify.type = 'warn';
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- default:
- notify.msg = 'Nieznany błąd';
- if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
- notify.type = '';
- }
- jQuery.notify(notify.msg, notify.type);
- }
- var reqData = {};
- jQuery.ajax({
- data: reqData,
- dataType: 'json',
- type: "GET",
- 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; ?>',
- })
- .done(function(data, textStatus, jqXHR){
- notifyAjaxCallback(data);
- if (data && data.files) {
- fileListUpdate<?php echo $this->_htmlID; ?>(data.files);
- }
- })
- .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
- if (jqXHR.responseJSON) {
- notifyAjaxCallback(jqXHR.responseJSON);
- }
- else {
- var txt = jqXHR.responseText || 'Wystąpiły błędy';
- if (jqXHR.status == 404) {
- jQuery.notify(jqXHR.responseText, 'error');
- } else {
- jQuery.notify(jqXHR.responseText, 'warn');
- }
- }
- });
- });
- filePermsReload.append(btnReload);
- }
- jQuery(document).ready(function(){
- $('#FILES_TAB_<?php echo $this->_htmlID; ?> a').click(function(e) {
- e.preventDefault();
- $(this).tab('show');
- })
- .on('shown.bs.tab', function(e) {
- var fileSource = $(e.target).data('toggle')
- , frm = jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>').get(0);
- if (frm['M_DIST_UPLOAD_SOURCE']) {
- frm['M_DIST_UPLOAD_SOURCE'].value = fileSource;
- }
- })
- jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>').ajaxForm({
- 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; ?>',
- beforeSubmit: function(args, $form, options) {
- //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit()...');
- var argsMap = [];
- args.map(function(v, k) {
- argsMap[v.name] = v.value;
- });
- // validate
- if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'local') {
- if (!argsMap['M_DIST_FILES_NAME']) {
- //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit() M_DIST_UPLOAD_SOURCE=local && !M_DIST_FILES_NAME');
- return false;
- }
- }
- else if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'scan') {
- if (!argsMap['SCANS_COLUMN_ADD']) {
- //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit() M_DIST_UPLOAD_SOURCE=scan && !SCANS_COLUMN_ADD');
- return false;
- }
- }
- else {
- return false;
- }
- var $out = $('#FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>');
- $out.html('Wysyłanie...');
- },
- success: function(data) {
- //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->success()...');
- var $out = $('#FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>');
- var btnClose = '<button type="button" class="close" data-dismiss="alert"><i class="glyphicon glyphicon-remove"></i></button>';
- if (typeof data == 'object') {
- if (data.type == 'ERROR') {
- $out.html('<div class="alert alert-danger">' + btnClose + data.string + '</div>');
- } else if (data.type == 'SUCCESS') {
- $out.html('<div class="alert alert-success">' + btnClose + data.string + '</div>');
- fileListUpdateAjax<?php echo $this->_htmlID; ?>();
- }
- } else {
- if (data.substr(0, 7) == 'WARNING') {
- data = data.substr(7);
- $out.html('<div class="alert alert-warning">' + btnClose + data + '</div>');
- } else if (data.substr(0, 5) == 'ERROR') {
- data = data.substr(5);
- $out.html('<div class="alert alert-danger">' + btnClose + data + '</div>');
- } else if (data.substr(0, 7) == 'SUCCESS') {
- data = data.substr(7);
- $out.html('<div class="alert alert-success">' + btnClose + data + '</div>');
- fileListUpdateAjax<?php echo $this->_htmlID; ?>();
- } else if (data.substr(0, 4) == 'INFO') {
- data = data.substr(4);
- $out.html('<div class="alert alert-info">' + btnClose + data + '</div>');
- }
- }
- }
- });
- fileListActions<?php echo $this->_htmlID; ?>();
- var fileList = <?php echo json_encode($jsonFiles); ?>;
- fileListUpdate<?php echo $this->_htmlID; ?>(fileList);
- var connTbls = <?php echo json_encode($this->getConnectedTables()); ?>;
- if (connTbls) {
- var connTblsOut = '';
- for(var key in connTbls) {
- connTblsOut += '<button class="btn btn-sm btn-default conn-tbl-load" data-zasobid="' + key + '">' + connTbls[key] + '</button>';
- };
- if (connTblsOut) {
- connTblsOut = 'Pliki w powiązanych tabelach: <div class="btn-group">' + connTblsOut + '</div>';
- connTblsOut += '<div style="max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">' +
- '<table class="table table-bordered table-hover">' +
- '<colgroup>' +
- '<col style="">' +
- '<col style="width:30px;">' +
- <?php if ($sharePoint) : ?>
- '<col style="width:30px;">' +
- <?php endif; ?>
- '<col style="width:80px;">' +
- '<col style="width:140px;">' +
- '</colgroup>' +
- '<tbody class="files-list">' +
- '</tbody>' +
- '</table>' +
- '</div>';
- var _connTblsWrap = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>');
- _connTblsWrap.css('marginBottom', '26px');
- _connTblsWrap.html(connTblsOut);
- _connTblsWrap.find('.conn-tbl-load').each(function(){
- jQuery(this).click(function(e){
- var tblID = jQuery(e.target).data('zasobid');
- if (tblID) {
- connTblListUpdateAjax<?php echo $this->_htmlID; ?>(tblID);
- }// TODO: else show error
- });
- });
- }
- }
- initDateTimePicker(jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>'));
- });
- </script>
- <?php
- exit;
- }
- private function sendTypeSpecial($fldID, $args) {
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- header("Content-type: application/json");
- $fldName = '';
- $fld = $this->_acl->getField($fldID);
- 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>';}
- if (!$fld) {
- // 404
- } else {
- $fldName = $fld['name'];
- }
- $jsonData = array();
- $typeSpecial = Typespecial::getInstance($fldID, $fldName);
- if ($typeSpecial) {
- $query = V::get('q', '', $_REQUEST);
- $rawRows = null;
- $rows = $typeSpecial->getValuesWithExports($query);
- 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>';}
- foreach ($rows as $kID => $vItem) {
- $itemJson = new stdClass();
- $itemJson->id = $vItem->id;
- $itemJson->name = $vItem->param_out;
- if (!empty($vItem->exports)) {
- $itemJson->exports = $vItem->exports;
- }
- $jsonData[] = $itemJson;
- }
- }
- /*
- MENU_INIT:VIEWTABLE_AJAX
- ZASOB_ID:1188
- _task:TYPESPECIAL
- fldID:3866
- Form Dataview sourceview URL encoded
- q:te
- */
- echo json_encode($jsonData);
- exit;
- }
- private function sendTypeSpecialCell($id, $fldName, $args) {
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- header("Content-type: application/json");
- $jsonData = new stdClass();
- $fldID = $this->_acl->getFieldIdByName($fldName);
- 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>';}
- $item = $this->_acl->getItem($id);
- if (!$this->_acl->isAllowed($fldID, 'R', $item)) {
- $jsonData->msg = 'Brak dostępu';
- echo json_encode($jsonData);
- exit;
- }
- if (!$fldID) {
- $jsonData->msg = 'Wrong field';
- echo json_encode($jsonData);
- exit;
- }
- $typeSpecial = Typespecial::getInstance($fldID, $fldName);
- if ($typeSpecial) {
- $jsonData->data = $typeSpecial->getReturnData($this->_zasobID, $id, $fldName, '');
- 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>';}
- }
- echo json_encode($jsonData);
- exit;
- }
- private function ajaxData($args) {
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- $pageSize = V::get('pageSize', $this->_pageSize, $args, 'int');
- $page = V::get('page', 0, $args, 'int');
- $currSortCol = V::get('currSortCol', '', $args);
- $currSortFlip = V::get('currSortFlip', '', $args);
- if ($page > 0) {
- $page -= 1;
- }
- else {
-
- }
- $params = array();
- $params['limit'] = $pageSize;
- $params['limitstart'] = $page * $params['limit'];
- $params['order_by'] = ($currSortCol)? $currSortCol : '';
- $params['order_dir'] = $currSortFlip;
- $filters = new stdClass();
- $filters->currSortCol = $currSortCol;
- $filters->currSortFlip = $currSortFlip;
- foreach ($args as $k => $v) {
- if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
- $params[$k] = $v;
- $filters->{$k} = $v;
- }
- else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
- $params[$k] = $v;
- $filters->{$k} = $v;
- }
- }
- $this->setFilters($filters);
- $vCols = $this->_acl->getVirtualFieldList();
- if (!empty($vCols)) {
- 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>';}
- }
- $visibleCols = $this->_acl->getVisibleFieldList();
- 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>';}
- $jsonData = new stdClass();
- $jsonData->page = $page + 1;
- $jsonData->pageSize = $pageSize;
- $jsonData->filters = $filters;
- $jsonData->cols = new stdClass();
- $jsonData->uniqueCol = $this->_acl->getPrimaryKeyField();
- $ind = 0;
- foreach ($visibleCols as $fieldID => $col) {
- $ind++;
- $columnConfig = (object)array('index'=>$ind);
- if (in_array($col, array('A_STATUS','A_STATUS_CURRENT','A_SERVICES_STATUS_CURRENT'))) {
- $columnConfig->format = '<div class="cell-A_STATUS-{0}">{0}</div>';
- }
- else if (in_array($col, array('Status'))) {
- // Ahmes problems Status colors
- $columnConfig->format = '<div class="cell-Status-{0}">{0}</div>';
- }
- else if ($this->_acl->isGeomField($col)) {
- $columnConfig->type = 'geom';
- }
- if ('' !== ($label = $this->_acl->getFieldLabel($fieldID))) {
- $columnConfig->friendly = $label;
- }
- $colType = $this->_acl->getFieldType($col);
- if ($colType) {// @see MarkTableAjaxFilterColType
- if ($colType['type'] == 'date') {
- //$columnConfig->type = 'date';// TODO: require datetimepicker
- }
- } else {// typespecial - no type
- $columnConfig->type = 'special';
- }
- $typeSpecial = Typespecial::getInstance($fieldID, $col);
- if ($typeSpecial) {
- 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>';}
- $columnConfig->_tsRetId = $typeSpecial->getReturnId();
- if ($columnConfig->_tsRetId == 0) {
- $tsParamOut = V::get('param_out', null, $typeSpecial);
- if ($tsParamOut) {
- $tsFormat = V::get('format', null, $tsParamOut);
- $tsValues = V::get('values', null, $tsParamOut);
- $tsAliases = V::get('alias', null, $tsParamOut);
- if (false !== strpos($tsFormat, '<a') && !empty($tsValues) && !empty($tsAliases)) {
- $tsAliasMap = array();
- /* [values] => Array([ID] => 1467), [alias] => Array([1467] => ID) */
- $bugTsColsNotVisible = array();
- foreach ($tsValues as $kVarName => $vIdZasob) {
- if (array_key_exists($vIdZasob, $tsAliases)) {
- $tsAliasMap[$kVarName] = $tsAliases[$vIdZasob];
- } else {
- $bugTsColsNotVisible[] = "noAliasFor {$vIdZasob}";
- }
- if (!array_key_exists($vIdZasob, $visibleCols)) {
- $bugTsColsNotVisible[] = $vIdZasob;
- }
- }
- if (empty($bugTsColsNotVisible)) {
- $tsSimpleLink = new stdClass();
- $tsSimpleLink->format = $tsFormat;
- $tsSimpleLink->aliasMap = $tsAliasMap;
- $columnConfig->_tsSimpleLink = $tsSimpleLink;
- $columnConfig->type = 'simpleLink';
- } else {
- $columnConfig->_tsSimpleLinkBug = $bugTsColsNotVisible;
- }
- }
- }
- }
- }
- // @see ajaxHiddenColsSave
- if (UserProfile::isHiddenColumn($this->_zasobID, $fieldID)) {
- $columnConfig->hidden = true;
- }
- $columnConfig->description = $this->_acl->getFieldOpis($fieldID);
- $jsonData->cols->{$col} = $columnConfig;
- }
- $jsonData->rows = array();
- $jsonData->total = $this->_acl->getTotal($params);
- 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>';}
- $items = $this->_acl->getItems($params);
- 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>';}
- // TODO: add virtual data by Typespecial
- if (!empty($vCols) && !empty($items)) {
- foreach ($vCols as $vColID => $vCol) {
- $colType = $this->_acl->getFieldTypeById($vColID);
- if ($colType) {
- continue;// pomin Typespecial dla realnych komorek w bazie danych
- }
- $typeSpecial = Typespecial::getInstance($vColID, $vCol);
- if ($typeSpecial) {
- $columnConfig = V::get($vCol, null, $jsonData->cols);
- if ($columnConfig && !empty($columnConfig->_tsSimpleLink)) {
- // pomin simple link values - mved to js render
- } else {
- 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>';}
- $ids = array_keys($items);
- $specialValues = $typeSpecial->getValuesByIds($this->_zasobID, $ids);
- 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>';}
- if (!empty($specialValues)) foreach ($specialValues as $kItemID => $vValues) {
- $tsValue = implode('<br>', $vValues);
- 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>';}
- if (!empty($items[$kItemID]->{$vCol}) && !empty($tsValue)) {
- $items[$kItemID]->{$vCol} .= ": {$tsValue}";
- } else {
- $items[$kItemID]->{$vCol} = $tsValue;
- }
- }
- }
- }
- }
- }
- foreach ($items as $vItem) {
- // TODO: hide items without 'R'
- foreach ($visibleCols as $kID => $vCol) {
- // TODO: ID default 'R'
- if (!$this->_acl->isAllowed($kID, 'R', $vItem)) {
- $vItem->{$vCol} = '*****';
- }
- // null => empty string
- if (!isset($vItem->{$vCol}) || (!$vItem->{$vCol} && $vItem->{$vCol} !== '0')) {
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">isEmptyString['.$vCol.'] (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vItem->{$vCol});echo'</pre>';}
- $vItem->{$vCol} = '';
- }
- }
- $jsonData->rows[] = $vItem;
- }
- return $jsonData;
- }
- private function fixEmptyValueFromUser($fieldID) {// TODO: moved to TableAcl->fixEmptyValueFromUser
- $value = '';
- $type = $this->_acl->getFieldTypeById($fieldID);
- if ($type) {
- if ($type['type'] == 'date') {
- $value = $type['default'];
- }
- // fix bug when field is unique and is null allowed: change empty string to null
- if ($type['null']) {
- $value = 'NULL';
- }
- // fix bug when field is enum and is set to '0': for php '0' is empty
- if (substr($type['type'], 0, 4) == 'enum') {// && $args["f{$fieldID}"] === '0') {
- if (false !== strpos($type['type'], "''")) {
- // enum('', '1','2')
- $value = '';
- } else if (false !== strpos($type['type'], "'0'")) {
- // enum('0', '1','2')
- $value = '0';
- } else {
- $value = $type['default'];
- }
- }
- }
- return $value;
- }
- /**
- * set hidden cols in $_SESSION['USER_PROFILE'][$this->_zasobID];
- * $_SESSION['USER_PROFILE'][$this->_zasobID][fld_id] => boolean
- */
- private function ajaxHiddenColsSave($args) {
- $response = new stdClass();
- if (empty($args)) {
- $response->type = 'info';
- return $response;
- }
- UserProfile::load();
- // clean up old, wrong values
- if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
- unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
- }
- $colVis = UserProfile::getHiddenCols($this->_zasobID);
- $fields = $this->_acl->getFields();
- foreach ($fields as $kFldId => $vFld) {
- $vFldName = $vFld['name'];
- if (isset($args[$vFldName])) {
- if ($args[$vFldName] == 'SHOW') {
- $colVis[$kFldId] = 1;
- } else if ($args[$vFldName] == 'HIDE') {
- $colVis[$kFldId] = 0;
- }
- }
- }
- UserProfile::setHiddenCols($this->_zasobID, $colVis);
- UserProfile::save();
- $response->type = 'success';
- return $response;
- }
- private function ajaxPageSizeSave($args) {
- $response = new stdClass();
- if (empty($args)) {
- $response->type = 'info';
- return $response;
- }
- $pageSize = V::get('pageSize', 0, $args, 'int');
- UserProfile::load();
- // clean up old, wrong values
- if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
- unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
- }
- $tableAjaxSettings = UserProfile::getTableAjaxSettings();
- $tableAjaxSettings['pageSize'] = $pageSize;
- UserProfile::setTableAjaxSettings($tableAjaxSettings);
- UserProfile::save();
- $response->type = 'success';
- return $response;
- }
- private function ajaxTheGeomSave($args) {
- $primaryKeyField = $this->_acl->getPrimaryKeyField();
- $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
- $polygon = V::get('polygon', 0, $args);
- $geomFieldName = 'the_geom';
- if ($primaryKey <= 0) {
- throw new HttpException("Wrong param ID", 404);
- }
- // 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)))
- $record = $this->_acl->getItem($primaryKey);
- if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
- throw new HttpException("Brak dostępu do rekordu", 403);
- }
- $theGeomFieldId = $this->_acl->getFieldIdByName($geomFieldName);
- if (!$this->_acl->isAllowed($theGeomFieldId, 'W', $record)) {
- throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
- }
- $itemPatch = array();
- $itemPatch[$geomFieldName] = "GeomFromText('{$polygon}')";
- $itemPatch[$primaryKeyField] = $primaryKey;
- $response = new stdClass();
- try {
- $affected = $this->_acl->updateItem($itemPatch);
- if ($affected > 0) {
- $response->type = 'success';
- $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
- } else if ($affected == 0) {
- $response->type = 'info';
- $response->msg = "Nie wprowadzono żadnych zmian";
- }
- $response->record = $this->_acl->getItem($primaryKey);
- }
- catch (Exception $e) {
- $response->type = 'error';
- $response->msg = $e->getMessage();
- }
- return $response;
- }
- private function sendAjaxResponseJson($method, $args) {
- try {
- $response = $this->{$method}($args);
- }
- catch (HttpException $e) {
- $response = new stdClass();
- $response->type = 'error';
- $response->msg = $e->getMessage();
- $response->errorCode = $e->getCode();
- Http::sendHeaderByCode($e->getCode());
- }
- catch (Exception $e) {
- $response = new stdClass();
- $response->type = 'error';
- $response->msg = $e->getMessage();
- $response->errorCode = $e->getCode();
- }
- header('Content-type: application/json');
- if (!$response) $response = new stdClass();
- echo json_encode($response);
- exit;
- }
- private function ajaxTheGeomRemove($args) {// ajax task 'THE_GEOM_REMOVE'
- $primaryKeyField = $this->_acl->getPrimaryKeyField();
- $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
- $geomFieldName = 'the_geom';
- $response = new stdClass();
- if ($primaryKey <= 0) {
- throw new HttpException("Wrong param ID", 404);
- }
- $record = $this->_acl->getItem($primaryKey);
- if (!$record) {
- throw new HttpException("Nie odnaleziono rekordu nr {$primaryKey}", 404);
- }
- if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
- throw new HttpException("Brak dostępu do rekordu nr {$primaryKey}", 403);
- }
- $theGeomFieldId = $this->_acl->getFieldIdByName($geomFieldName);
- if (!$this->_acl->isAllowed($theGeomFieldId, 'W', $record)) {
- throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
- }
- if (empty($record->{$geomFieldName})) {
- $response->type = 'info';
- $response->msg = "Rekord nie jest powiązany z żadnym obiektem na mapie";
- $response->record = $record;
- return $response;
- }
- $itemPatch = array();
- $itemPatch[$geomFieldName] = "NULL";
- $itemPatch[$primaryKeyField] = $primaryKey;
- $response = new stdClass();
- try {
- $affected = $this->_acl->updateItem($itemPatch);
- if ($affected > 0) {
- $response->type = 'success';
- $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
- } else if ($affected == 0) {
- $response->type = 'info';
- $response->msg = "Nie wprowadzono żadnych zmian";
- }
- $response->record = $this->_acl->getItem($primaryKey);
- }
- catch (Exception $e) {
- $response->type = 'error';
- $response->msg = $e->getMessage();
- }
- return $response;
- }
- private function ajaxProcesInitFiltr($args) {// ajax task 'PROCES_INIT_FILTR'
- $response = new stdClass();
- $pInitList = array();// [proces_init_id] => label (DESC)
- if (!$this->_showProcesInit) {
- $response->type = 'error';
- return $response;
- }
- $userAcl = User::getAcl();
- $pInitList = $userAcl->getTableProcesInitList($this->_zasobID);
- if (!empty($pInitList)) {
- $procesIds = array_keys($pInitList);
- $mapTree = ACL::getProcesInitMapTreeOnlyIds($procesIds);
- DBG::_('DBG_MAP', '1', "mapTree", $mapTree, __CLASS__, __FUNCTION__, __LINE__);
- DBG::_('DBG_MAP', '1', "pInitList", $pInitList, __CLASS__, __FUNCTION__, __LINE__);
- $pInitListSelected = $this->getProcesInitSelected();
- $response->pInitData = new stdClass();
- $response->pInitData->pInitList = $pInitList;
- $response->pInitData->mapTree = $mapTree;
- $response->pInitData->pInitListSelected = $pInitListSelected;
- }
- $response->type = 'success';
- return $response;
- }
- function ajaxMoreFunctionsCell($args) {// ajax task 'MORE_FUNCTIONS_CELL'
- $id = V::get('ID', 0, $args, 'int');
- if ($id <= 0) throw new HttpException("404", 404);
- $response = new stdClass();
- $response->type = 'success';
- $response->msg = 'Funkcje';
- $response->rowFunctions = [];
- $tableName = $this->_acl->getName();
- if(1){// TODO: fetch $totalMsgs from TableMsgs
- $msgs = Router::getRoute('Msgs');
- $msgsList = $msgs->getActiveMessagesForTableRecord($tableName, $id);
- $totalMsgs = count($msgsList);
- $rowFunc = new stdClass();
- $rowFunc->ico = 'glyphicon glyphicon-envelope';
- $rowFunc->href = 'index.php?_route=TableMsgs&_task=tableRow&idTable=' . $this->_zasobID . '&idRow=' . $id;
- $rowFunc->title = "Wiadomości <span class=\"badge\">{$totalMsgs}</span>";
- $response->rowFunctions[] = $rowFunc;
- }
- if ('CRM_PROCES' == $this->_acl->getName()) {// TODO: mv to table gui xml or php class
- $record = $this->_acl->getItem($id);
- // procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id=22001
- $rowFunc = new stdClass();
- $rowFunc->ico = 'glyphicon glyphicon-eye-open';
- $rowFunc->href = "procesy5.php?task=CRM_PROCES&filtr_id={$id}";
- $rowFunc->title = "Zobacz na drzewie procesów {{$id}}";
- $response->rowFunctions[] = $rowFunc;
- $wskazniki = ProcesHelper::get_wskazniki($id);
- $connectedZasobyTotal = count($wskazniki);
- $rowFunc = new stdClass();
- $rowFunc->ico = 'glyphicon glyphicon-random';
- $rowFunc->href = "index.php?MENU_INIT=PROCES_ADD_ZASOB&procesID={$id}";
- $rowFunc->title = "Powiązane zasoby <span class=\"badge\">{$connectedZasobyTotal}</span>";
- $response->rowFunctions[] = $rowFunc;
- }
- if ('CRM_LISTA_ZASOBOW' == $this->_acl->getName()) {// TODO: mv to table gui xml or php class
- $record = $this->_acl->getItem($id);
- // procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id=22001
- $rowFunc = new stdClass();
- $rowFunc->ico = 'glyphicon glyphicon-eye-open';
- $rowFunc->href = "procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id={$id}";
- $rowFunc->title = "Zobacz na drzewie zasobów [{$id}]";
- $response->rowFunctions[] = $rowFunc;
- // index.php?MENU_INIT=ZASOB_OBOWIAZKI&id_zasob=22001
- $rowFunc = new stdClass();
- $rowFunc->ico = 'glyphicon glyphicon-random';
- $rowFunc->href = "index.php?MENU_INIT=ZASOB_OBOWIAZKI&id_zasob={$id}";
- $rowFunc->title = "Powiązane procesy (OB)";
- $response->rowFunctions[] = $rowFunc;
- // index.php?MENU_INIT=ZASOB_EXTERNAL_IDS&id_zasob=22001
- $rowFunc = new stdClass();
- $rowFunc->ico = 'glyphicon glyphicon-random';
- $rowFunc->href = "index.php?MENU_INIT=ZASOB_EXTERNAL_IDS&id_zasob={$id}";
- $rowFunc->title = "Powiązane dane (IDS)";
- $response->rowFunctions[] = $rowFunc;
- $groupTypeList = array();
- $groupTypeList[] = 'STANOWISKO';
- $groupTypeList[] = 'PODMIOT';
- $groupTypeList[] = 'DZIAL';
- if (in_array($record->TYPE, $groupTypeList)) {
- $rowFunc = new stdClass();
- $rowFunc->ico = 'glyphicon glyphicon-retweet';
- $rowFunc->href = "index.php?_route=Users&_task=syncGroup&idGroup={$id}";
- $rowFunc->title = "Synchronizuj do LDAP";
- $response->rowFunctions[] = $rowFunc;
- }
- }
- if ('ADMIN_USERS' == $this->_acl->getName()) {// TODO: mv to table gui xml
- $record = $this->_acl->getItem($id);
- $isAllowedoReadUserLogin = false;
- if ($this->_acl->canReadRecord($record)) {
- $idFieldUserLogin = $this->_acl->getFieldIdByName('ADM_ACCOUNT');
- if ($idFieldUserLogin) {
- if ($this->_acl->isAllowed($idFieldUserLogin, 'R', $record)) {
- $isAllowedoReadUserLogin = true;
- }
- }
- }
- if ($isAllowedoReadUserLogin) {
- $rowFunc = new stdClass();
- $rowFunc->ico = 'glyphicon glyphicon-user';
- $rowFunc->href = 'index.php?_route=Users&_task=userGroups&usrLogin=' . $record->ADM_ACCOUNT;
- $rowFunc->title = "Ustal stanowisko";
- $response->rowFunctions[] = $rowFunc;
- $rowFunc = new stdClass();
- $rowFunc->ico = 'glyphicon glyphicon-retweet';
- $rowFunc->href = 'index.php?_route=Users&_task=syncUser&usrLogin=' . $record->ADM_ACCOUNT;
- $rowFunc->title = "Synchronizuj do LDAP";
- $response->rowFunctions[] = $rowFunc;
- $rowFunc = new stdClass();
- $rowFunc->ico = 'glyphicon glyphicon-minus';
- $rowFunc->href = 'index.php?MENU_INIT=USER_OCENA_PRACOWNIKA&usrLogin=' . $record->ADM_ACCOUNT;
- $rowFunc->title = "Ocena pracownika";
- $response->rowFunctions[] = $rowFunc;
- }
- }
- return $response;
- }
- }
|