TableAjax.php 196 KB

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