TableAjax.php 239 KB

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