TableAjax.php 227 KB

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