TableAjax.php 201 KB

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