TableAjax.php 181 KB

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