TableAjax.php 248 KB

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