TableAjax.php 183 KB

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