TableAjax.php 182 KB

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