TableAjax.php 200 KB

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