TableAjax.php 202 KB

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