TableAjax.php 183 KB

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