TableAjax.php 235 KB

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