TableAjax.php 229 KB

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