TableAjax.php 195 KB

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