TableAjax.php 182 KB

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