TableAjax.php 218 KB

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