TableAjax.php 218 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157
  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. sorts the data on the current sorting column
  1930. */
  1931. priv.sort = function() {
  1932. if (!_data.cols[_state.filters.currSortCol]) _state.filters.currSortCol = "";
  1933. if (!_state.filters.currSortCol) return;
  1934. publ.loadPage(0);
  1935. };
  1936. /*
  1937. helper that returns the underlying data by the unique value
  1938. */
  1939. priv.getRow = function(uniqueValue) {
  1940. var row;
  1941. $.each(_data.rowsOrg, function(i, r) {
  1942. if (r[_state.uniqueCol] == uniqueValue) {
  1943. row = r;
  1944. return false;
  1945. }
  1946. });
  1947. return row;
  1948. };
  1949. /*
  1950. when: typing a filter
  1951. what: triggers filtering on the value
  1952. */
  1953. priv.filterChanged = function(e) {
  1954. //clear old timer if we're typing fast enough
  1955. if (priv.options.debug) console.log('filterChanged L.<?php echo __LINE__; ?>');
  1956. if (_filterTimeout) {
  1957. clearTimeout(_filterTimeout);
  1958. if (priv.options.debug) console.log('filterChanged L.<?php echo __LINE__; ?> previous filtering cancelled');
  1959. }
  1960. var filter = this.value
  1961. , fltr = $(this)
  1962. , col = _data.cols[e.data.column]
  1963. , timeout = 300;
  1964. if (this.value) {
  1965. if (!fltr.hasClass('filter-active')) {
  1966. fltr.addClass('filter-active');
  1967. }
  1968. } else {
  1969. if (fltr.hasClass('filter-active')) {
  1970. fltr.removeClass('filter-active');
  1971. }
  1972. }
  1973. //boolean filters needs some special care
  1974. if (col.type == "bool" || col.type == "unique") {
  1975. timeout = 0;
  1976. var elem = $(this);
  1977. var cssClass = 'indeterminate';
  1978. if (elem.hasClass(cssClass)) {
  1979. e.preventDefault();
  1980. elem.removeClass(cssClass);
  1981. filter = true;
  1982. } else {
  1983. if (!elem.is(':checked')) {
  1984. filter = false;
  1985. } else {
  1986. elem.addClass(cssClass);
  1987. filter = '';
  1988. }
  1989. }
  1990. }
  1991. //add the filter to the filter array
  1992. _state.filters.filterCols[col.column] = {
  1993. filter: filter,
  1994. colName: col.column
  1995. };
  1996. //wait a few deciseconds before filtering
  1997. _filterTimeout = setTimeout(function(filterValue, colName) {
  1998. _state.filters.filterCols[colName] = {
  1999. filter: filterValue,
  2000. colName: colName
  2001. };
  2002. priv.filter();
  2003. }, timeout, filter, col.column);
  2004. };
  2005. priv.filtersClean = function(e) {
  2006. if (_filterTimeout) {
  2007. clearTimeout(_filterTimeout);
  2008. if (priv.options.debug) console.log('filtering cancelled - filtersClean');
  2009. }
  2010. var filtersActive = false;
  2011. $.map(_state.filters.filterCols, function(colProps, col) {
  2012. if (colProps.filter.length > 0) {
  2013. filtersActive = true;
  2014. colProps.filter = '';
  2015. }
  2016. });
  2017. if (filtersActive) {
  2018. // TODO: dont remove value from forceFilterInit fields - no field names in search fields?
  2019. /// TODO: rerender _head (thead.filter)
  2020. var elems = _uiNode$Table.find('thead').find('.filter').find('input');
  2021. elems.val('').prop('disabled', false);
  2022. elems.removeClass('filter-active');
  2023. priv.filter();
  2024. }
  2025. return false;
  2026. },
  2027. /**
  2028. * Filters the data.
  2029. */
  2030. priv.filter = function() {
  2031. if (!priv.options.filter) return;
  2032. if (Object.keys(_state.filters.filterCols).length == 0) return;
  2033. priv.loadPage(0);
  2034. };
  2035. /**
  2036. * Filters the data by specialFilter.
  2037. * when: click on special filter
  2038. * what: triggers filtering on the value
  2039. */
  2040. priv.specialFilterChanged = function(e) {
  2041. if (priv.options.debug) console.log('specialFilterChanged e.data:', e.data);
  2042. var state = {};
  2043. state.specialFilters = _state.specialFilters;
  2044. state.specialFilters[e.data.group] = e.data.value;
  2045. priv.setState(state);
  2046. publ.loadPage(0);
  2047. };
  2048. priv.longTextChanged = function(e) {
  2049. priv.options.longDesc = !priv.options.longDesc;
  2050. _bodyNode.find('td').each(function(ind, el){
  2051. var $el = jQuery(el);
  2052. if (!$el.attr('class') || $el.attr('class') == 'tbl-short-txt') {
  2053. //console.log(el.attr('class') + ': ' + el.text());
  2054. if (el.firstChild && el.firstChild.nodeName == 'SPAN') {
  2055. if (priv.options.longDesc) {
  2056. $el.addClass('tbl-short-txt');
  2057. var $elSpan = jQuery(el.firstChild);
  2058. $elSpan.tooltip({title: $elSpan.text(), placement: 'left'});
  2059. } else {
  2060. $el.removeClass('tbl-short-txt');
  2061. }
  2062. }
  2063. }
  2064. });
  2065. return false;
  2066. };
  2067. priv.mapEditorHide = function() {
  2068. priv.options.mapEditor = false;
  2069. if ('window' == priv.options.mapEditorContainer) {
  2070. //_mapEditorDialog.dialog("close");
  2071. _mapEditorDialog.dialog("destroy");
  2072. }
  2073. _mapEditorWrap.hide();
  2074. _mapEditor.hide();
  2075. };
  2076. priv.mapEditorShow = function() {
  2077. //console.log('TODO:mapEditorShow():', priv.options.mapEditorContainer, 'visible:', priv.options.mapEditor);
  2078. priv.options.mapEditor = true;
  2079. _mapEditor.show();
  2080. _mapEditorWrap.show();
  2081. _mapEditor.TableAjaxMap({
  2082. //debug: true,
  2083. wpsUrl: 'http://biuro.biall-net.pl/wps',
  2084. wfsUrl: 'http://biuro.biall-net.pl/wps',
  2085. showAddLayerWidget: <?php echo ($this->hasAdditionalLayers())? 'true' : 'false'; ?>,
  2086. zoomStrategyActivate: 14,
  2087. layerName: '<?php echo $this->getLabelHtml(); ?>',
  2088. addBtn: {
  2089. title: 'Przenieś mapę do okna',
  2090. displayClass: 'mapEditor-btnBackToWindow',
  2091. trigger: function() {
  2092. priv.mapEditorHide();
  2093. priv.options.mapEditorContainer = 'window';
  2094. priv.mapEditorShow();
  2095. priv.resizableMapDockNode('destroy');
  2096. }
  2097. },
  2098. onSaveFeature: function(selectedRecordId, selectedFeatureExtent) {
  2099. if (priv.options.debug) console.log('onSaveFeature (',selectedRecordId,'/',selectedFeatureExtent,') ', this);
  2100. if (!selectedRecordId) {
  2101. alert('Brak zaznaczonego rekordu - wybierz rekord z tabeli');
  2102. return;
  2103. }
  2104. function notifyAjaxCallback(data) {
  2105. var notify = {};
  2106. notify.type = (data && data.type)? data.type : '';
  2107. notify.msg = (data && data.msg)? data.msg : '';
  2108. switch (notify.type) {
  2109. case 'success':
  2110. if (!notify.msg) notify.msg = 'Aktualizacja danych dla rekordu ' + selectedRecordId;
  2111. break;
  2112. case 'info':
  2113. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  2114. break;
  2115. case 'error':
  2116. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  2117. break;
  2118. case 'warning':
  2119. notify.type = 'warn';
  2120. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  2121. break;
  2122. default:
  2123. notify.msg = 'Nieznany błąd';
  2124. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  2125. notify.type = '';
  2126. }
  2127. jQuery.notify(notify.msg, notify.type);
  2128. }
  2129. $.ajax({
  2130. data: {polygon: selectedFeatureExtent},
  2131. dataType: 'json',
  2132. type: "POST",
  2133. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=THE_GEOM_SAVE&ID=' + selectedRecordId
  2134. })
  2135. .done(function(data, textStatus, jqXHR){
  2136. notifyAjaxCallback(data);
  2137. //jQuery.notify('Aktualizacja danych dla rekordu ' + selectedRecordId, 'success');
  2138. publ.loadPage(0);// TODO: reload table data
  2139. })
  2140. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  2141. if (jqXHR.responseJSON) {
  2142. notifyAjaxCallback(jqXHR.responseJSON);
  2143. }
  2144. else {
  2145. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  2146. if (jqXHR.status == 404) {
  2147. jQuery.notify(jqXHR.responseText, 'error');
  2148. } else {
  2149. jQuery.notify(jqXHR.responseText, 'warn');
  2150. }
  2151. }
  2152. });
  2153. },
  2154. onSelectBox: function(bounds) {
  2155. if (undefined !== OpenLayers.Bounds && bounds instanceof OpenLayers.Bounds) {
  2156. var column = 'the_geom';
  2157. if (undefined !== _filterFields['the_geom']) {
  2158. var filter = 'BBOX:' + bounds.top + ',' + bounds.right + ',' + bounds.bottom + ',' + bounds.left;
  2159. _filterFields[column].val(filter);
  2160. _state.filters.filterCols[column] = {
  2161. filter: filter,
  2162. colName: column
  2163. };
  2164. priv.filter();
  2165. }
  2166. }
  2167. }
  2168. });
  2169. priv.mapEditorShowElement();
  2170. };
  2171. priv.mapEditorShowElement = function() {
  2172. if ('window' == priv.options.mapEditorContainer) {
  2173. var mapEditor = _mapEditorWrap.children('.mapEditor-map');
  2174. if (!mapEditor || !mapEditor.length) {
  2175. var tblCont = jQuery(_uiNodeCont).parent('.AjaxTableCont');
  2176. var mapEditor = tblCont.children('.AjaxTableCont-mapEditorContainer').children('.mapEditor-map');
  2177. if (!mapEditor || !mapEditor.length) {
  2178. // TODO: create new map
  2179. }
  2180. _mapEditorWrap.append(mapEditor);
  2181. }
  2182. _mapEditorWrap.css({padding:'5px'});
  2183. _mapEditorDialog = _mapEditorWrap.dialog({
  2184. width: 540,
  2185. minWidth: 400,
  2186. minHeight: 400,
  2187. open: function(e, ui) {
  2188. var n = jQuery(this),
  2189. mapWrap = n.children(":first"),
  2190. map = mapWrap.children(":first");
  2191. map.css({width: n.width() - 5, height: n.height() - 5});
  2192. _mapEditor.TableAjaxMapUpdateSize();
  2193. },
  2194. resizeStart: function(e, ui) {
  2195. jQuery(this).children(":first").children(":first").css({display:'none'});
  2196. },
  2197. resizeStop: function(e, ui){
  2198. var n = jQuery(this),
  2199. map = n.children(":first").children(":first");
  2200. n.css({width: n.parent().width()});
  2201. map.css({display: 'block', height: n.height(), width: n.width()});
  2202. _mapEditor.TableAjaxMapUpdateSize();
  2203. },
  2204. dragStop: function(e, ui){
  2205. _mapEditor.TableAjaxMapUpdateSize();// to prevent drag-zoom error
  2206. }
  2207. });
  2208. _mapEditorWrap.bind('dialogclose', function(e) {
  2209. priv.options.mapEditor = false;
  2210. });
  2211. var dialogTitleBar = _mapEditorDialog.parent().parent().find('.ui-dialog-titlebar');
  2212. var dialogTitleBarCloseBtn = dialogTitleBar.find('.ui-dialog-titlebar-close');
  2213. if (dialogTitleBarCloseBtn) {
  2214. 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>');
  2215. btnToggle.on('click', function(e) {
  2216. priv.options.mapEditorContainer = 'dock';
  2217. _mapEditorWrap.dialog('close');
  2218. priv.mapEditorShowElement();
  2219. });
  2220. btnToggle.insertBefore(dialogTitleBarCloseBtn);
  2221. }
  2222. }
  2223. else if ('dock' == priv.options.mapEditorContainer) {
  2224. priv.resizableMapDockNode('prepare');
  2225. _mapEditor.TableAjaxMapUpdateSize();
  2226. }
  2227. };
  2228. priv.resizableMapDockNode = function(task) {
  2229. if ('prepare' == task) {
  2230. var mapEditor = _mapEditorWrap.children('.mapEditor-map');
  2231. if (mapEditor && mapEditor.length) {// map is inside _mapEditorWrap (window)
  2232. var mapDockNode = jQuery('<div class="AjaxTableCont-mapEditorContainer"></div>');
  2233. var tblCont = jQuery(_uiNodeCont).parent('.AjaxTableCont');
  2234. tblCont.children('.AjaxTableCont-mapEditorContainer').remove();
  2235. var breadcrumb = tblCont.children('.breadcrumb');
  2236. if (!breadcrumb || !breadcrumb.length) {
  2237. tblCont.prepend(mapDockNode);
  2238. } else {
  2239. mapDockNode.insertAfter(breadcrumb);
  2240. }
  2241. mapDockNode.append(mapEditor);
  2242. }
  2243. var mapDockResizable = mapEditor.parent();
  2244. mapDockResizable.resizable({handles: 's', minHeight: 300, minWidth: 300});
  2245. var resizeLineHeigth = 6;
  2246. mapDockResizable.children(":first").css({height: 'auto'});
  2247. mapDockResizable.css({marginBottom: resizeLineHeigth+'px'});
  2248. mapEditor.css({marginBottom: resizeLineHeigth+'px'});
  2249. mapEditor.children(":first").css({width: mapEditor.width()});
  2250. mapDockResizable.find('.ui-resizable-s').css({height:resizeLineHeigth+'px', bottom: '-'+resizeLineHeigth+'px'});
  2251. mapDockResizable.on('resizestart', function(event, ui) {
  2252. ui.element.children(":first").children(":first").css({display:'none'})
  2253. });
  2254. mapDockResizable.on('resizestop', function(event, ui) {
  2255. ui.element.children(":first").children(":first").css({display:'block', height: ui.element.height()});
  2256. });
  2257. } else if ('destroy' == task) {
  2258. var mapDockResizable = jQuery(_uiNodeCont).parent('.AjaxTableCont').children('.AjaxTableCont-mapEditorContainer');
  2259. mapDockResizable.resizable('destroy');
  2260. mapDockResizable.remove();
  2261. }
  2262. };
  2263. priv.mapEditorChanged = function(e) {
  2264. if (priv.options.debug) console.log('mapEditorChanged option(',priv.options.mapEditor,')');
  2265. priv.options.mapEditor = !priv.options.mapEditor;
  2266. if (priv.options.mapEditor) {
  2267. priv.mapEditorShow();
  2268. }
  2269. else {
  2270. priv.mapEditorHide();
  2271. }
  2272. return false;
  2273. };
  2274. /*
  2275. when: changing page in pager
  2276. what: triggers table to be created with new page
  2277. */
  2278. priv.pageChanged = function(e) {
  2279. e.preventDefault();
  2280. var totalPages = Math.ceil(_data.total / _state.pageSize);
  2281. if (e.data.pageIndex < 1 || e.data.pageIndex > totalPages) return;
  2282. //set the new page
  2283. _state.page = e.data.pageIndex;
  2284. publ.loadPage(_state.page);
  2285. };
  2286. /*
  2287. when: changing pagesize in pagesize dropdown
  2288. what: triggers table to be created with new pagesize
  2289. */
  2290. priv.pageSizeChanged = function(e) {
  2291. e.preventDefault();
  2292. var val = $(this).text();
  2293. if (priv.options.debug) console.log('pagesize changed to:{0}'.f(val));
  2294. if (parseInt(val) == priv.options.pageSize) {
  2295. return false;
  2296. }
  2297. priv.options.pageSize = parseInt(val);
  2298. publ.loadPage(1, priv.options.pageSize);
  2299. jQuery(_uiNodeCont).trigger('TableAjax:render', ['body', 'foot_pagination']);
  2300. priv.saveProfilePageSize(priv.options.pageSize);
  2301. };
  2302. /*
  2303. when: clicking a column
  2304. what: triggers table to be sorted by the column
  2305. */
  2306. priv.columnClicked = function(e) {
  2307. e.preventDefault();
  2308. if (priv.options.debug) console.log('col:{0} clicked'.f(e.data.column));
  2309. //set the new sorting column
  2310. if (_state.filters.currSortCol == e.data.column) _state.filters.currSortFlip = !_state.filters.currSortFlip;
  2311. _state.filters.currSortCol = e.data.column;
  2312. /// TODO: var state = {}; state.currSortCol = ''; state.currSortFlip = ''; priv.setState(state);
  2313. _headSort = undefined;
  2314. _body = undefined;
  2315. priv.sort();
  2316. };
  2317. priv.saveProfilePageSize = function(pageSize) {
  2318. var reqData = {};
  2319. reqData.pageSize = pageSize;
  2320. $.ajax({
  2321. data: reqData,
  2322. type: "POST",
  2323. dataType: 'json',
  2324. // async: true,
  2325. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=PAGE_SIZE_SAVE'
  2326. })
  2327. .done(function(data, textStatus, jqXHR){
  2328. if (data && data.type && data.type == 'info') {
  2329. jQuery.notify('Nie wprowadzono żadnych zmian', 'info');
  2330. } else {
  2331. jQuery.notify('Zapisano ustawienia', 'success');
  2332. }
  2333. })
  2334. .fail(function(){
  2335. jQuery.notify('Wystąpił błąd podczas zapisywania ustawień', 'error');
  2336. });
  2337. };
  2338. priv.saveHiddenCols = function() {
  2339. var reqData = {};
  2340. $.each(_data.cols, function(col, props) {
  2341. if (props.type != "unique" && col != 'unique' && col != 'ID') {
  2342. reqData[col] = (props.hidden)? 'HIDE' : 'SHOW';
  2343. }
  2344. });
  2345. $.ajax({
  2346. data: reqData,
  2347. type: "POST",
  2348. dataType: 'json',
  2349. // async: true,
  2350. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=HIDDEN_COLS_SAVE'
  2351. })
  2352. .done(function(data, textStatus, jqXHR){
  2353. if (data && data.type && data.type == 'info') {
  2354. jQuery.notify('Nie wprowadzono żadnych zmian', 'info');
  2355. } else {
  2356. jQuery.notify('Zapisano ustawienia', 'success');
  2357. }
  2358. })
  2359. .fail(function(){
  2360. jQuery.notify('Wystąpił błąd podczas zapisywania ustawień', 'error');
  2361. });
  2362. };
  2363. /*
  2364. when: clicking a column in columnpicker
  2365. what: triggers table to show/hide the column
  2366. */
  2367. priv.columnPickerClicked = function(e) {
  2368. e.stopPropagation();
  2369. var column = $(this).val();
  2370. //toggle column visibility
  2371. priv.modelColFilter_toggleColumn(column);
  2372. priv.saveHiddenCols();
  2373. //_data.cols[column].index = new priv.ext.XDate();
  2374. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body']);
  2375. };
  2376. priv.modelColFilter_init = function() {
  2377. var isAllSelected = true;
  2378. if (undefined === _state._modelColFilter) {
  2379. var columnFilters = [];
  2380. {
  2381. var fltrAll = {'name': 'all', 'label': 'Wszystkie', visibleCols: []};
  2382. $.each(_data.cols, function(col, props) {
  2383. if ("unique" == props.type) return;
  2384. fltrAll.visibleCols.push(col);
  2385. if (_data.cols[col].hidden) isAllSelected = false;
  2386. });
  2387. columnFilters.push(fltrAll);
  2388. }
  2389. {
  2390. var fltrMostUsed = {'name': 'most_used', 'label': 'Najczęściej używane', visibleCols: []};
  2391. var fltrMostUsedLimit = 10;
  2392. $.each(_data.cols, function(col, props) {
  2393. if ("unique" == props.type) return;
  2394. if (fltrMostUsedLimit-- > 0) {
  2395. fltrMostUsed.visibleCols.push(col);
  2396. }
  2397. });
  2398. columnFilters.push(fltrMostUsed);
  2399. }
  2400. _state._modelColFilter = {
  2401. selected: (isAllSelected)? 'all' : null,
  2402. filters: columnFilters
  2403. };
  2404. }
  2405. };
  2406. priv.modelColFilter_getFilters = function() {
  2407. priv.modelColFilter_init();
  2408. return _state._modelColFilter.filters;
  2409. };
  2410. priv.modelColFilter_getSelected = function() {
  2411. priv.modelColFilter_init();
  2412. return _state._modelColFilter.selected;
  2413. };
  2414. priv.modelColFilter_setFilter = function(filterKey) {
  2415. priv.modelColFilter_init();
  2416. _state._modelColFilter.selected = filterKey;
  2417. priv.modelColFilter_uiUncheckAllColFilters();
  2418. priv.modelColFilter_uiCheckColFilter(filterKey);
  2419. };
  2420. priv.modelColFilter_toggleColumn = function(column, value) {
  2421. priv.modelColFilter_init();
  2422. _state._modelColFilter.selected = null;
  2423. if (!_data.cols[column] || !_data.cols[column]) return;
  2424. _data.cols[column].hidden = (undefined !== value)? value : !_data.cols[column].hidden;
  2425. priv.modelColFilter_uiUncheckAllColFilters();
  2426. {
  2427. var isAllSelected = true;
  2428. $.each(_data.cols, function(col, props) {
  2429. if ("unique" == props.type) return;
  2430. if (_data.cols[col].hidden) isAllSelected = false;
  2431. });
  2432. if (isAllSelected) {
  2433. _state._modelColFilter.selected = 'all';
  2434. priv.modelColFilter_uiCheckColFilter('all');
  2435. }
  2436. }
  2437. };
  2438. priv.modelColFilter_uiUncheckAllColFilters = function() {
  2439. var nodeClass = 'tblAjax__' + 'footer__toolbar__columnPicker',
  2440. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass)
  2441. ;
  2442. currentNode.find('input[type="radio"]').prop("checked", false);
  2443. };
  2444. priv.modelColFilter_uiCheckColFilter = function(filterKey) {
  2445. var nodeClass = 'tblAjax__' + 'footer__toolbar__columnPicker',
  2446. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass)
  2447. ;
  2448. currentNode.find('input[type="radio"]').each(function(idx, input) {
  2449. var input$ = jQuery(input);
  2450. if (filterKey == jQuery(input$).parent().data('col_filter')) {
  2451. input$.prop("checked", true);
  2452. } else {
  2453. input$.prop("checked", false);
  2454. }
  2455. });
  2456. };
  2457. priv.columnPickerLinkClicked = function(e) {
  2458. e.stopPropagation();
  2459. var input$ = $(this).find('input'),
  2460. col_filter = $(this).data('col_filter'),
  2461. columnFilters = priv.modelColFilter_getFilters()
  2462. ;
  2463. if (col_filter) {
  2464. var filter = null;
  2465. $.each(columnFilters, function(idx, colFltr) {
  2466. if (col_filter == colFltr.name) {
  2467. filter = colFltr;
  2468. }
  2469. });
  2470. if (!filter) return;
  2471. $.each(_data.cols, function(col, props) {
  2472. var isHidden = (-1 === filter.visibleCols.indexOf(col));
  2473. priv.modelColFilter_toggleColumn(col, isHidden);
  2474. });
  2475. priv.modelColFilter_setFilter(col_filter);
  2476. priv.saveHiddenCols();
  2477. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body', 'foot__columnPicker']);
  2478. } else {
  2479. e.preventDefault();
  2480. if (input$.length != 1) return;
  2481. var column = input$.val();
  2482. if (!column) return;
  2483. //toggle column visibility
  2484. priv.modelColFilter_toggleColumn(column);
  2485. input$.prop("checked", !input$.is(':checked'));// update view
  2486. priv.saveHiddenCols();
  2487. //_data.cols[column].index = new priv.ext.XDate();
  2488. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body']);
  2489. }
  2490. };
  2491. priv.columnHideClicked = function(e) {
  2492. e.stopPropagation();
  2493. var column;
  2494. if (e.data && e.data.column) {
  2495. column = e.data.column;
  2496. } else {
  2497. return;
  2498. }
  2499. //toggle column visibility
  2500. priv.modelColFilter_toggleColumn(column);
  2501. priv.saveHiddenCols();
  2502. //_data.cols[column].index = new priv.ext.XDate();
  2503. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body', 'foot__columnPicker']);
  2504. };
  2505. /*
  2506. when: clicking a row checkbox
  2507. what: toggles checked state on row, and add/removes it from checked array
  2508. */
  2509. priv.rowChecked = function(e) {
  2510. var elem = $(this);
  2511. //get the row's unique value
  2512. var unique = elem.closest('tr').data('unique');
  2513. if (priv.options.debug) console.log('row({0}) {1}'.f(unique, elem.is(':checked') ? 'checked' : 'unchecked'));
  2514. //store the row in checked array
  2515. if (elem.is(':checked')) _uniqueCols[unique] = priv.getRow(unique);
  2516. else delete _uniqueCols[unique];
  2517. };
  2518. /*
  2519. when: clicking anywhere on a row
  2520. what: row data and other info is returned to caller
  2521. */
  2522. // priv.rowClicked = function(e) {// TODO: not used
  2523. // if (!_state.uniqueCol) {
  2524. // if (priv.options.debug) console.log('no unique column specified');
  2525. // return;
  2526. // }
  2527. // //gather callback data
  2528. // var elem = $(this);
  2529. // var column = _data.cols[elem.data('column')];
  2530. // var unique = elem.closest('tr').data('unique');
  2531. // var row = priv.getRow(unique);
  2532. // var isChecked = elem.closest('tr').find('.unique').is(':checked');
  2533. // //trigger callback
  2534. // if (typeof priv.options.rowClicked == 'function') {
  2535. // priv.options.rowClicked.call(e.target, {
  2536. // event: e,
  2537. // row: row,
  2538. // column: column,
  2539. // checked: isChecked
  2540. // });
  2541. // }
  2542. // };
  2543. /**
  2544. * Inline edit.
  2545. */
  2546. priv.rowDblClicked = function(e) {
  2547. var inlineEditBox$Node = $(_uiNodeCont).parent().children('.tblAjax__inlineEditBox');
  2548. // hide popover for typespecial fld on click
  2549. if (_popoverCellCurrent) {
  2550. _popoverCellCurrent.popover('hide');
  2551. }
  2552. // e.clientX: 1002; e.clientY: 245
  2553. if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
  2554. inlineEditBox$Node.modal();
  2555. inlineEditBox$Node.show();
  2556. inlineEditBox$Node.on('shown.bs.modal', function(e) {
  2557. var dialogBox = jQuery(this).find('.modal-dialog'),
  2558. modalBody = dialogBox.find('.modal-body'),
  2559. boudingRect = dialogBox.get(0).getBoundingClientRect();
  2560. dialogBox.css({position: 'absolute', margin:0, top: boudingRect.top, left: boudingRect.left});
  2561. modalBody.css({overflow: 'scroll'});
  2562. dialogBox.resizable({minHeight: 300, minWidth: 300, alsoResize: modalBody});
  2563. dialogBox.draggable({handle: '.modal-header'});
  2564. });
  2565. inlineEditBox$Node.on('hidden.bs.modal', function(e) {
  2566. var dialogBox = jQuery(this).find('.modal-dialog'),
  2567. modalBody = dialogBox.find('.modal-body');
  2568. dialogBox.removeAttr('style');
  2569. modalBody.removeAttr('style');
  2570. modalBody.css({padding: '0'});
  2571. dialogBox.resizable();
  2572. dialogBox.draggable();
  2573. dialogBox.resizable('destroy');
  2574. dialogBox.draggable('destroy');
  2575. });
  2576. inlineEditBox$Node.find('input[name=ID]').val(e.data.id);
  2577. inlineEditBox$Node.find('input[name=col]').val(e.data.col);
  2578. inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
  2579. $.ajax({
  2580. 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,
  2581. type: 'GET',
  2582. dataType: 'text',
  2583. data: '',
  2584. async: true,
  2585. success: function(data) {
  2586. inlineEditBox$Node.find('.inlineEditBox-cnt').html(data);
  2587. inlineEditBox$Node.find('.btn-save').show();
  2588. initDateTimePicker(inlineEditBox$Node);
  2589. inlineEditBox$Node.find('textarea').autosize();
  2590. var fld = inlineEditBox$Node.find('input[id^="f"]');
  2591. if (fld && !fld.hasClass('se_type-date')) {
  2592. fld.focus();
  2593. fld.keydown(function(event) {
  2594. if (event.which == 13) {
  2595. event.preventDefault();
  2596. inlineEditBox$Node.find('form').submit();
  2597. }
  2598. });
  2599. }
  2600. },
  2601. error: function(err) {
  2602. if (priv.options.debug) console.log('err');
  2603. }
  2604. });
  2605. } else {
  2606. if (priv.options.debug) console.log('NO data');
  2607. return false;
  2608. }
  2609. };
  2610. priv.ajaxLoadTypeSpeciallCell = function(id, col) {
  2611. if (_popoverCellAjaxXhr) {
  2612. _popoverCellAjaxXhr.abort();
  2613. }
  2614. _popoverCellAjaxXhr = $.ajax({
  2615. type: 'GET',
  2616. 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,
  2617. dataType: 'json',
  2618. contentType: "application/json; charset=utf-8",
  2619. data: '',
  2620. success: function(req){
  2621. if (req.data && req.data.tbl_id > 0) {
  2622. var addHtml = '';
  2623. for(var i in req.data.items){
  2624. var url = 'index.php?MENU_INIT=VIEWTABLE_AJAX';
  2625. url += '&ZASOB_ID=' + req.data.tbl_id;
  2626. url += '&f_' + req.data.fld_name + '=' + req.data.items[i].id;
  2627. url += '&_hash=' + Math.random().toString(36).substring(2);
  2628. addHtml += '<a href="' + url + '">Wyszukaj ' + req.data.items[i].id + '</a>: ' + req.data.items[i].label;
  2629. addHtml += '<br>';
  2630. }
  2631. //_popoverCell.append(addHtml);// cache
  2632. if (_popoverCellCurrent) {
  2633. var popoverNodeId = _popoverCellCurrent.attr('aria-describedby');
  2634. if (popoverNodeId) {
  2635. jQuery('#' + popoverNodeId).find('.popoverCellContent').append(addHtml);
  2636. }
  2637. }
  2638. }
  2639. }
  2640. });
  2641. };
  2642. priv.popoverCellTypeSpecial = function(e) {
  2643. e.preventDefault();
  2644. e.stopPropagation();
  2645. if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
  2646. var lastId = _popoverCell.data('rowid'),
  2647. lastCol = _popoverCell.data('col'),
  2648. rowPK = e.data.id,
  2649. colName = e.data.col
  2650. ;
  2651. if (lastId == rowPK && lastCol == colName) {
  2652. //_popoverCellCurrent.popover('toggle');
  2653. }
  2654. else {
  2655. if (_popoverCellCurrent) {
  2656. _popoverCellCurrent.popover('destroy');
  2657. }
  2658. _popoverCell.data('rowid', rowPK);
  2659. _popoverCell.data('col', colName);
  2660. _popoverCell.html(e.data.value + '<div class="popoverCellContent loading" style="white-space:normal"></div>');
  2661. _popoverCellCurrent = jQuery(e.currentTarget);
  2662. // title : '<span class="text-info"><strong>title</strong></span> <button type="button" id="close" class="close">&times;</button>'
  2663. var opts = {
  2664. placement: 'left'
  2665. , trigger: 'click'
  2666. // , title: e.data.col + '<a href="#" class="glyphicon glyphicon-remove pull-right" onclick="return hidePopover();"></a>'
  2667. , 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>'
  2668. , html: true
  2669. , content: _popoverCell.html()
  2670. }
  2671. _popoverCellCurrent.popover(opts);
  2672. if (_data.cols[colName]) {
  2673. if (_data.cols[colName]._tsRetId > 0) {
  2674. _popoverCellCurrent.on('shown.bs.popover', function() {
  2675. priv.ajaxLoadTypeSpeciallCell(rowPK, colName);
  2676. });
  2677. }
  2678. }
  2679. _popoverCellCurrent.popover('show');
  2680. }
  2681. } else {
  2682. if (priv.options.debug) console.log('NO data');
  2683. return false;
  2684. }
  2685. return;
  2686. };
  2687. priv.routeChanged = function(e) {
  2688. hash = e.data.hash || '';
  2689. if (hash.length == 0) {
  2690. return;
  2691. }
  2692. if (hash.substring(0, 1) != '#') {
  2693. hash = '#' + hash;
  2694. }
  2695. location.hash = hash;
  2696. };
  2697. priv.refresh = function(e) {
  2698. e.preventDefault();
  2699. publ.loadPage(_state.page);
  2700. };
  2701. publ.init = function(options) {
  2702. if (priv.options.debug) console.log('TableAjax initialization...');
  2703. //merge supplied options with defaults
  2704. $.extend(priv.options, defaults, options);
  2705. priv.init();
  2706. return publ;
  2707. };
  2708. publ.refresh = function() {
  2709. publ.loadPage(_state.page);
  2710. };
  2711. publ.loadPage = function(page, pageSize) {
  2712. priv.loadPage(page, pageSize);
  2713. }
  2714. priv.loadPage = function(page, pageSize) {
  2715. var skipCols = true, // skipCols = true - prevent columns delete
  2716. resetChecked = false;
  2717. var reqData = {
  2718. page: page,
  2719. pageSize: (pageSize || priv.options.pageSize),
  2720. currSortCol: (_state.filters.currSortCol || ''),
  2721. currSortFlip: _state.filters.currSortFlip ? "desc" : "asc"
  2722. };
  2723. if (Object.keys(_state.filters.filterCols).length > 0) {
  2724. $.each(_state.filters.filterCols, function(col, colProps) {
  2725. if (colProps.filter && colProps.filter.length > 0) {
  2726. reqData['f_' + col] = colProps.filter;
  2727. }
  2728. });
  2729. skipCols = true;
  2730. }
  2731. // specialFilters
  2732. $.each(_state.specialFilters, function(groupName, btnValue) {
  2733. if (btnValue.length > 0) {
  2734. reqData['sf_' + groupName] = btnValue;
  2735. }
  2736. });
  2737. if (priv.options.forceFilterInit) {
  2738. $.map(priv.options.forceFilterInit, function(fltrProps, fltr) {
  2739. reqData['f_' + fltr] = fltrProps;
  2740. filtersInitSet = true;
  2741. });
  2742. }
  2743. _uiNode$Table.parent().parent().addClass('AjaxTable-loading');
  2744. $.ajax({
  2745. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>',
  2746. type: 'GET',
  2747. dataType: 'json',
  2748. contentType: "application/json; charset=utf-8",
  2749. data: reqData,
  2750. async: true,
  2751. success: function(data) {
  2752. state = {data: {}};
  2753. state.data.rows = data.rows || [];
  2754. state.data.total = data.total || 0;
  2755. state.page = data.page || 0;
  2756. state.pageSize = data.pageSize || priv.options.pageSize;
  2757. state.filters = data.filters || {};
  2758. priv.setState(state);
  2759. _uiNode$Table.parent().parent().removeClass('AjaxTable-loading');
  2760. },
  2761. error: function(err) {
  2762. if (priv.options.debug) console.log('request error: {0}'.f(JSON.stringify(err)));
  2763. }
  2764. });
  2765. };
  2766. publ.getCurrentPage = function() {
  2767. return _state.page;
  2768. };
  2769. publ.popoverCellRemove = function() {
  2770. if (_popoverCellCurrent) {
  2771. _popoverCellCurrent.popover('destroy');
  2772. }
  2773. _popoverCell.data('rowid', -1);
  2774. _popoverCell.data('col', -1);
  2775. _popoverCell.html('');
  2776. };
  2777. return publ;
  2778. }
  2779. $.fn.TableAjax = function(options) {
  2780. options = options || {};
  2781. return this.each(function() {
  2782. options.id = this;
  2783. $(this).data('TableAjax', new TableAjax().init(options));
  2784. });
  2785. };
  2786. $.fn.TableAjaxLoadPage = function(page, pageSize) {
  2787. return this.each(function() {
  2788. var tblAjax = jQuery(this).data('TableAjax');
  2789. var curPage = page || tblAjax.getCurrentPage();
  2790. if (tblAjax) tblAjax.loadPage(curPage, pageSize);
  2791. });
  2792. };
  2793. $.fn.TableAjaxRefresh = function(page, pageSize) {
  2794. return this.each(function() {
  2795. var tblAjax = jQuery(this).data('TableAjax');
  2796. if (tblAjax) tblAjax.refresh();
  2797. });
  2798. };
  2799. String.prototype.format = String.prototype.f = function() {
  2800. var s = this;
  2801. i = arguments.length;
  2802. while (i--) s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
  2803. return s;
  2804. };
  2805. })(jQuery);
  2806. </script>
  2807. <?php
  2808. $filterInit = $this->_filterInit;
  2809. $forceFilterInit = $this->_forceFilterInit;
  2810. $pageSizes = $this->_pageSizes;
  2811. $pageSize = $this->_pageSize;
  2812. $rowFunctions = $this->_rowFunctions;//$this->_showRowFunctionsJson();
  2813. $exportFields = $this->_showExportFieldsJson();
  2814. ?>
  2815. <script>
  2816. jQuery(document).ready(function(){
  2817. jQuery('#<?php echo $this->_htmlID; ?>').TableAjax({
  2818. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>',
  2819. columnPicker: true,
  2820. filter: true,
  2821. filterInit: <?php echo json_encode($filterInit); ?>,
  2822. forceFilterInit: <?php echo json_encode($forceFilterInit); ?>,
  2823. debug: false,
  2824. height: 400,
  2825. sorting: true,
  2826. paging: true,
  2827. pageSize: <?php echo $pageSize; ?>,
  2828. pageSizes: <?php echo json_encode($pageSizes); ?>,
  2829. tblFunctions: {
  2830. shortdesc: {
  2831. icon: 'align-left',
  2832. title: 'Long desc',
  2833. method: 'longTextChanged'
  2834. },
  2835. <?php if ($hasGeomFlds) : ?>
  2836. mapeditor: {
  2837. icon: 'map-marker',
  2838. title: 'Mapa',
  2839. method: 'mapEditorChanged'
  2840. },
  2841. <?php endif; ?>
  2842. create: {
  2843. href: '#CREATE',
  2844. icon: 'plus',
  2845. title: 'Dodaj nowy rekord'
  2846. },
  2847. refresh: {
  2848. icon: 'refresh',
  2849. title: 'Odśwież dane',
  2850. method: 'refresh'
  2851. }
  2852. },
  2853. rowFunctions: <?php echo json_encode($rowFunctions); ?>,
  2854. exportFields: <?php echo json_encode($exportFields); ?>,
  2855. specialFilterFunctions: <?php
  2856. $fltrs = $this->_acl->getSpecialFilters();
  2857. if (!empty($fltrs)) {
  2858. echo json_encode($fltrs);
  2859. } else {
  2860. echo 'false';
  2861. }
  2862. echo ',';
  2863. ?>
  2864. router: function() {
  2865. var routes = {
  2866. EDIT: function(args) {
  2867. var recordID = args;
  2868. if (typeof args == 'object') {
  2869. recordID = args.shift();
  2870. recordID = parseInt(recordID);
  2871. }
  2872. if (typeof recordID !== 'number' || recordID <= 0) {
  2873. // TODO: msg
  2874. return false;
  2875. }
  2876. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2877. cont.hide();
  2878. // remove previous task content
  2879. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  2880. taskCnt.parent().remove();
  2881. taskCnt.remove();
  2882. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  2883. jQuery('<ul class="breadcrumb">' +
  2884. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  2885. '<li class="active">Edytuj rekord</li>' +
  2886. '</ul>').appendTo(taskCont);
  2887. taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  2888. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  2889. jQuery.ajax({
  2890. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT&ID=' + recordID,
  2891. type: 'GET',
  2892. dataType: 'text',
  2893. data: '',
  2894. async: true,
  2895. success: function(data) {
  2896. taskCnt.removeClass('AjaxTable-loading');
  2897. jQuery(data).appendTo(taskCnt);
  2898. initDateTimePicker(taskCnt);
  2899. },
  2900. error: function(err) {
  2901. taskCnt.removeClass('AjaxTable-loading');
  2902. //console.log('request error: {0}'.f(err));
  2903. }
  2904. });
  2905. //return false;
  2906. },
  2907. HIST: function(args) {
  2908. var recordID = args;
  2909. if (typeof args == 'object') {
  2910. recordID = args.shift();
  2911. recordID = parseInt(recordID);
  2912. }
  2913. if (typeof recordID !== 'number' || recordID <= 0) {
  2914. // TODO: msg
  2915. return false;
  2916. }
  2917. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2918. cont.hide();
  2919. // remove previous task content
  2920. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  2921. taskCnt.parent().remove();
  2922. taskCnt.remove();
  2923. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  2924. jQuery('<ul class="breadcrumb">' +
  2925. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  2926. '<li class="active">Historia rekordu</li>' +
  2927. '</ul>').appendTo(taskCont);
  2928. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  2929. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  2930. jQuery.ajax({
  2931. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=HIST&ID=' + recordID,
  2932. type: 'GET',
  2933. dataType: 'text',
  2934. data: '',
  2935. async: true,
  2936. success: function(data) {
  2937. taskCnt.removeClass('AjaxTable-loading');
  2938. //console.log('request finished L.<?php echo __LINE__; ?>');
  2939. jQuery(data).appendTo(taskCnt);
  2940. },
  2941. error: function(err) {
  2942. taskCnt.removeClass('AjaxTable-loading');
  2943. //console.log('request error: {0}'.f(err));
  2944. }
  2945. });
  2946. //return false;
  2947. },
  2948. FILES: function tableAjaxFiles(args) {
  2949. var recordID = args;
  2950. if (typeof args == 'object') {
  2951. recordID = args.shift();
  2952. recordID = parseInt(recordID);
  2953. }
  2954. if (typeof recordID !== 'number' || recordID <= 0) {
  2955. // TODO: msg
  2956. return false;
  2957. }
  2958. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2959. cont.hide();
  2960. // remove previous task content
  2961. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  2962. taskCnt.parent().remove();
  2963. taskCnt.remove();
  2964. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  2965. jQuery('<ul class="breadcrumb">' +
  2966. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  2967. '<li class="active">Pliki</li>' +
  2968. '</ul>').appendTo(taskCont);
  2969. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTable-loading"></div>').appendTo(taskCont);
  2970. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  2971. jQuery.ajax({
  2972. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES&ID=' + recordID,
  2973. type: 'GET',
  2974. dataType: 'text',
  2975. data: '',
  2976. async: true,
  2977. success: function(data) {
  2978. taskCnt.removeClass('AjaxTable-loading');
  2979. //console.log('request finished L.<?php echo __LINE__; ?>', data);
  2980. jQuery(data).appendTo(taskCnt);
  2981. },
  2982. error: function(jqXHR, textStatus, errorThrown) {
  2983. //console.log('request error:', jqXHR.status, 'txt:', jqXHR.responseText, 'err:', jqXHR);
  2984. taskCnt.removeClass('AjaxTable-loading');
  2985. var txt = jqXHR.responseText || 'Error';
  2986. if (jqXHR.status == 404) {
  2987. jQuery('<div class="container"><div class="alert alert-danger">' + txt + '</div></div>').appendTo(taskCnt);
  2988. } else {
  2989. jQuery('<div class="container"><div class="alert alert-danger">' + txt + '</div></div>').appendTo(taskCnt);
  2990. }
  2991. }
  2992. });
  2993. //return false;
  2994. },
  2995. CREATE: function tableAjaxCreate() {
  2996. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2997. cont.hide();
  2998. // remove previous task content
  2999. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  3000. taskCnt.parent().remove();
  3001. taskCnt.remove();
  3002. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  3003. jQuery('<ul class="breadcrumb">' +
  3004. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  3005. '<li class="active">Dodaj nowy rekord</li>' +
  3006. '</ul>').appendTo(taskCont);
  3007. taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  3008. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  3009. var reqData = {};
  3010. var forceFilterInit = <?php echo json_encode($forceFilterInit);// TODO: read from TableAjax ?>;
  3011. if (forceFilterInit) {
  3012. $.map(forceFilterInit, function(fltrProps, fltr) {
  3013. reqData['ff_' + fltr] = fltrProps;
  3014. });
  3015. }
  3016. jQuery.ajax({
  3017. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE',
  3018. type: 'GET',
  3019. dataType: 'text',
  3020. data: reqData,
  3021. async: true,
  3022. success: function(data) {
  3023. taskCnt.removeClass('AjaxTable-loading');
  3024. //console.log('request finished L.<?php echo __LINE__; ?>');
  3025. jQuery(data).appendTo(taskCnt);
  3026. initDateTimePicker(taskCnt);
  3027. },
  3028. error: function(err) {
  3029. taskCnt.removeClass('AjaxTable-loading');
  3030. //console.log('request error: {0}'.f(err));
  3031. }
  3032. });
  3033. //return false;
  3034. }
  3035. };
  3036. var routePath = location.hash;
  3037. //console.log('location.hash: ' + routePath);
  3038. if (location.hash == '' || location.hash == '#') {
  3039. return false;
  3040. }
  3041. if (routePath.charAt(0) == '#') {
  3042. routePath = routePath.substr(1);
  3043. }
  3044. //console.log('routePath: ' + routePath);
  3045. var parts = routePath.split('/');
  3046. var task = parts.shift();
  3047. //console.log('task(' + task + ') parts:');
  3048. //console.log(parts);
  3049. if (task in routes && typeof routes[task] == 'function') {
  3050. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  3051. if (con) {
  3052. var tblAjax = con.data('TableAjax');
  3053. if (tblAjax) {
  3054. tblAjax.popoverCellRemove();
  3055. }
  3056. }
  3057. routes[task](parts);
  3058. } else {
  3059. return false;
  3060. }
  3061. },
  3062. filtersClean: true,
  3063. longDesc: true
  3064. });
  3065. });
  3066. function tableAjaxBackToTable() {
  3067. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  3068. cont.show();
  3069. var taskCont = jQuery('#<?php echo $this->_htmlID . '_task'; ?>').parent();
  3070. taskCont.remove();
  3071. // reload first page
  3072. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  3073. con.TableAjaxLoadPage();// TODO: load current page
  3074. }
  3075. function tableAjaxCopy(args) {
  3076. var recordID = args;
  3077. if (typeof args == 'object') {
  3078. recordID = args.shift();
  3079. recordID = parseInt(recordID);
  3080. }
  3081. if (typeof recordID !== 'number' || recordID <= 0) {
  3082. // TODO: msg
  3083. return false;
  3084. }
  3085. if (!confirm('Czy na pewno chcesz utworzyc nowy rekord na podstawie danych z rekordu ID = ' + recordID + '?')) {
  3086. return false;
  3087. }
  3088. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  3089. function notifyAjaxCallback(data) {
  3090. var notify = {};
  3091. notify.type = (data && data.type)? data.type : '';
  3092. notify.msg = (data && data.msg)? data.msg : '';
  3093. switch (notify.type) {
  3094. case 'success':
  3095. if (!notify.msg) notify.msg = 'OK';
  3096. break;
  3097. case 'info':
  3098. if (!notify.msg) notify.msg = '';
  3099. break;
  3100. case 'error':
  3101. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3102. break;
  3103. case 'warning':
  3104. notify.type = 'warn';
  3105. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3106. break;
  3107. default:
  3108. notify.msg = 'Nieznany błąd';
  3109. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  3110. notify.type = '';
  3111. }
  3112. jQuery.notify(notify.msg, notify.type);
  3113. }
  3114. var reqData = {};
  3115. jQuery.ajax({
  3116. data: reqData,
  3117. dataType: 'json',
  3118. type: "GET",
  3119. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=COPY&ID=' + recordID,
  3120. })
  3121. .done(function(data, textStatus, jqXHR){
  3122. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  3123. con.TableAjaxRefresh();
  3124. notifyAjaxCallback(data);
  3125. })
  3126. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  3127. if (jqXHR.responseJSON) {
  3128. notifyAjaxCallback(jqXHR.responseJSON);
  3129. }
  3130. else {
  3131. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  3132. if (jqXHR.status == 404) {
  3133. jQuery.notify(jqXHR.responseText, 'error');
  3134. } else {
  3135. jQuery.notify(jqXHR.responseText, 'warn');
  3136. }
  3137. }
  3138. });
  3139. return false;
  3140. }
  3141. function hidePopover() {
  3142. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  3143. if (con) {
  3144. var tblAjax = con.data('TableAjax');
  3145. if (tblAjax) {
  3146. tblAjax.popoverCellRemove();
  3147. }
  3148. }
  3149. return false;
  3150. }
  3151. function <?php echo $jsToogleFiltrProcesuFunctionName; ?>(n) {
  3152. var $n = jQuery(n);
  3153. var $ul = $n.next();
  3154. if ($n.data('fetched')) return false;
  3155. function parseProcesInitData(pInitData) {
  3156. var procesInitMapHtml = '';
  3157. if (!pInitData) {
  3158. return '<li><a href="#">' + "Brak danych" + '</a></li>';
  3159. } else {
  3160. function _viewProcesInitListItem(pInitId, gotoIds, pInitList) {
  3161. var label = pInitList[pInitId];
  3162. 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;";
  3163. 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 + '">';
  3164. out += ' <i class="glyphicon glyphicon-info-sign"';
  3165. out += ' onclick="' + jsInfo + '"';
  3166. out += ' style="color:#aaa;"';
  3167. out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
  3168. out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
  3169. out += " {" + pInitId + "} " + label;
  3170. out += '</a>';
  3171. return out;
  3172. }
  3173. function _viewProcesGotoAndRetListItem(gotoId, pInitList) {
  3174. var label = pInitList[gotoId];
  3175. 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;";
  3176. var out = '';
  3177. 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 + '">';
  3178. out += ' <span style="padding:10px;"></span>';
  3179. out += ' <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>';
  3180. out += ' <i class="glyphicon glyphicon-info-sign"';
  3181. out += ' onclick="' + jsInfo + '"';
  3182. out += ' style="color:#aaa;"';
  3183. out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
  3184. out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
  3185. out += " {" + gotoId + "} " + label;
  3186. out += '</a>';
  3187. return out;
  3188. }
  3189. function _viewProcesGotoAndRetLvl2ListItem(gotoLvl2Id, pInitList) {
  3190. var label = pInitList[gotoLvl2Id];
  3191. 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;";
  3192. var out = '';
  3193. 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 + '">';
  3194. out += ' <span style="padding:20px;"></span>';
  3195. out += ' <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>';
  3196. out += ' <i class="glyphicon glyphicon-info-sign"';
  3197. out += ' onclick="' + jsInfo + '"';
  3198. out += ' style="color:#aaa;"';
  3199. out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
  3200. out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
  3201. out += " {" + gotoLvl2Id + "} " + label;
  3202. out += '</a>';
  3203. return out;
  3204. }
  3205. var sel = '',
  3206. liStyle = "white-space:nowrap; overflow:hidden; max-width:500px; /* text-overflow:ellipsis; */";
  3207. $.map(pInitData.mapTree, function(gotoIds, vInitId) {
  3208. sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
  3209. procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
  3210. procesInitMapHtml += _viewProcesInitListItem(vInitId, gotoIds, pInitData.pInitList);
  3211. procesInitMapHtml += '</li>' + "\n";
  3212. $.map(gotoIds, function(gotoLvl2Ids, gotoId) {
  3213. sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
  3214. procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
  3215. procesInitMapHtml += _viewProcesGotoAndRetListItem(gotoId, pInitData.pInitList);
  3216. procesInitMapHtml += '</li>' + "\n";
  3217. $.map(gotoLvl2Ids, function(vBool, gotoLvl2Id) {
  3218. sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
  3219. procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
  3220. procesInitMapHtml += _viewProcesGotoAndRetLvl2ListItem(gotoLvl2Id, pInitData.pInitList);
  3221. procesInitMapHtml += '</li>' + "\n";
  3222. });
  3223. });
  3224. });
  3225. }
  3226. return procesInitMapHtml;
  3227. }
  3228. jQuery.ajax({
  3229. data: null,
  3230. dataType: 'json',
  3231. type: "GET",
  3232. async: true,
  3233. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=PROCES_INIT_FILTR',
  3234. })
  3235. .always(function(data, textStatus, jqXHR) {
  3236. var type = data.type || null,
  3237. msg = data.msg || "Error",
  3238. pInitData = data.pInitData || null;
  3239. if (type) {
  3240. if ('success' == type) {
  3241. $ul.html(parseProcesInitData(pInitData));
  3242. } else if ('error' == type) {
  3243. $ul.html('<li><a href="#">' + msg + '</a></li>');
  3244. } else {
  3245. $ul.html('<li><a href="#">Wystapił błąd podczas pobierania listy procesów</a></li>');
  3246. }
  3247. } else {
  3248. $ul.html('<li><a href="#">Wystapił błąd podczas pobierania listy procesów</a></li>');
  3249. }
  3250. $n.data('fetched', true);
  3251. });
  3252. return false;
  3253. }
  3254. </script>
  3255. <?php
  3256. $out = ob_get_contents();
  3257. ob_end_clean();
  3258. return $out;
  3259. }
  3260. public function _viewProcesInitListItem($vInitId, $gotoIds, $pInitList) {
  3261. $vLabel = $pInitList[$vInitId];
  3262. $kId = $vInitId;
  3263. ?>
  3264. <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}"); ?>">
  3265. <i class="glyphicon glyphicon-info-sign"
  3266. 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;"
  3267. style="color:#aaa;"
  3268. onmouseover="this.style.color='#337AB7'"
  3269. onmouseout="this.style.color='#aaa'"></i>
  3270. <?php echo "{{$kId}} {$vLabel}"; ?>
  3271. </a>
  3272. <?php
  3273. }
  3274. public function _viewProcesGotoAndRetListItem($vGotoId, $pInitList) {
  3275. $vLabel = $pInitList[$vGotoId];
  3276. $kId = $vGotoId;
  3277. // TODO:?: prevent to execute procedure
  3278. ?>
  3279. <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}"); ?>">
  3280. <span style="padding:10px;"></span>
  3281. <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>
  3282. <i class="glyphicon glyphicon-info-sign"
  3283. 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;"
  3284. style="color:#aaa;"
  3285. onmouseover="this.style.color='#337AB7'"
  3286. onmouseout="this.style.color='#aaa'"></i>
  3287. <?php echo "{{$kId}} {$vLabel}"; ?>
  3288. </a>
  3289. <?php
  3290. }
  3291. public function _viewProcesGotoAndRetLvl2ListItem($vGotoLvl2Id, $pInitList) {
  3292. $vLabel = $pInitList[$vGotoLvl2Id];
  3293. $kId = $vGotoLvl2Id;
  3294. // TODO:?: prevent to execute procedure
  3295. ?>
  3296. <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}"); ?>">
  3297. <span style="padding:20px;"></span>
  3298. <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>
  3299. <i class="glyphicon glyphicon-info-sign"
  3300. 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;"
  3301. style="color:#aaa;"
  3302. onmouseover="this.style.color='#337AB7'"
  3303. onmouseout="this.style.color='#aaa'"></i>
  3304. <?php echo "{{$kId}} {$vLabel}"; ?>
  3305. </a>
  3306. <?php
  3307. }
  3308. public function hasAdditionalLayers() {
  3309. $layers = TableAjaxMap::getAdditionalLayers($this->_zasobID);
  3310. return !empty($layers);
  3311. }
  3312. public function ajaxTask($task) {
  3313. switch ($task) {
  3314. case 'EDIT': {
  3315. $id = V::get('ID', 0, $_REQUEST, 'int');
  3316. if ($id > 0) {
  3317. $this->sendAjaxEdit($id, $_REQUEST);
  3318. } else {
  3319. echo '404';
  3320. }
  3321. break;
  3322. }
  3323. case 'EDIT_SAVE': {
  3324. $this->sendAjaxResponseJson('ajaxEditSave', $_REQUEST);
  3325. break;
  3326. }
  3327. case 'EDIT_INLINE': {
  3328. $id = V::get('ID', 0, $_REQUEST, 'int');
  3329. $col = V::get('col', '', $_REQUEST);
  3330. if ($id > 0 && !empty($col)) {
  3331. $this->sendAjaxEditInline($id, $col, $_REQUEST);
  3332. } else {
  3333. echo '404';
  3334. }
  3335. break;
  3336. }
  3337. case 'EDIT_INLINE_SAVE': {
  3338. $this->sendAjaxResponseJson('ajaxEditInlineSave', $_REQUEST);
  3339. break;
  3340. }
  3341. case 'COPY': {
  3342. $this->sendAjaxResponseJson('ajaxCopy', $_REQUEST);
  3343. break;
  3344. }
  3345. case 'CREATE': {
  3346. $this->sendAjaxCreate($_REQUEST);
  3347. break;
  3348. }
  3349. case 'CREATE_SAVE': {
  3350. $this->sendAjaxResponseJson('ajaxCreateSave', $_REQUEST);
  3351. break;
  3352. }
  3353. case 'HIST': {
  3354. $id = V::get('ID', 0, $_REQUEST, 'int');
  3355. if ($id > 0) {
  3356. $this->sendAjaxHistory($id, $_REQUEST);
  3357. } else {
  3358. echo '404';
  3359. }
  3360. break;
  3361. }
  3362. case 'FILES': {
  3363. $id = V::get('ID', 0, $_REQUEST, 'int');
  3364. if ($id > 0) {
  3365. $this->sendAjaxFiles($id, $_REQUEST);
  3366. } else {
  3367. echo '404';
  3368. }
  3369. break;
  3370. }
  3371. case 'FILES_UPLOAD': {
  3372. $id = V::get('ID', 0, $_REQUEST, 'int');
  3373. if ($id > 0) {
  3374. $this->sendAjaxFilesUpload($id, $_REQUEST);
  3375. } else {
  3376. echo '404';
  3377. }
  3378. break;
  3379. }
  3380. case 'FILES_LIST': {
  3381. $id = V::get('ID', 0, $_REQUEST, 'int');
  3382. if ($id > 0) {
  3383. $this->sendAjaxFilesList($id, $_REQUEST);
  3384. } else {
  3385. echo '404';
  3386. }
  3387. break;
  3388. }
  3389. case 'FILE_REMOVE': {
  3390. $id = V::get('ID', 0, $_REQUEST, 'int');
  3391. if ($id > 0) {
  3392. $this->sendAjaxFileRemove($id, $_REQUEST);
  3393. } else {
  3394. echo '404';
  3395. }
  3396. break;
  3397. }
  3398. case 'filePermsRefresh': {
  3399. $this->sendAjaxResponseJson('ajaxFilePermsRefresh', $_REQUEST);
  3400. break;
  3401. }
  3402. case 'FILES_CONN_TBL_LIST': {
  3403. $id = V::get('ID', 0, $_REQUEST, 'int');
  3404. if ($id > 0) {
  3405. $this->sendAjaxFilesConnTblList($id, $_REQUEST);
  3406. } else {
  3407. echo '404';
  3408. }
  3409. break;
  3410. }
  3411. case 'TYPESPECIAL': {
  3412. $fldID = V::get('fldID', 0, $_REQUEST, 'int');
  3413. if ($fldID > 0) {
  3414. $this->sendTypeSpecial($fldID, $_REQUEST);
  3415. } else {
  3416. echo '404';
  3417. }
  3418. break;
  3419. }
  3420. case 'TYPESPECIALL_CELL': {
  3421. $id = V::get('ID', 0, $_REQUEST, 'int');
  3422. $col = V::get('col', '', $_REQUEST);
  3423. if ($id > 0 && !empty($col)) {
  3424. $this->sendTypeSpecialCell($id, $col, $_REQUEST);
  3425. } else {
  3426. echo '404';
  3427. }
  3428. break;
  3429. }
  3430. case 'MORE_FUNCTIONS_CELL': {
  3431. $this->sendAjaxResponseJson('ajaxMoreFunctionsCell', $_REQUEST);
  3432. break;
  3433. }
  3434. case 'HIDDEN_COLS_SAVE': {
  3435. $this->sendAjaxResponseJson('ajaxHiddenColsSave', $_POST);
  3436. break;
  3437. }
  3438. case 'PAGE_SIZE_SAVE': {
  3439. $this->sendAjaxResponseJson('ajaxPageSizeSave', $_POST);
  3440. break;
  3441. }
  3442. case 'THE_GEOM_SAVE': {
  3443. $this->sendAjaxResponseJson('ajaxTheGeomSave', $_REQUEST);
  3444. break;
  3445. }
  3446. case 'THE_GEOM_REMOVE': {
  3447. $this->sendAjaxResponseJson('ajaxTheGeomRemove', $_REQUEST);
  3448. break;
  3449. }
  3450. case 'PROCES_INIT_FILTR': {
  3451. $this->sendAjaxResponseJson('ajaxProcesInitFiltr', $_REQUEST);
  3452. break;
  3453. }
  3454. default:
  3455. $this->sendAjaxResponseJson('ajaxData', $_REQUEST);
  3456. }
  3457. }
  3458. /**
  3459. * ajax url: &_task=EDIT_INLINE
  3460. * @param $rowID - $_GET['ID']
  3461. * @param $fieldName - $_GET['col']
  3462. */
  3463. private function sendAjaxEditInline($rowID, $fieldName, $args) {
  3464. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3465. header("Content-type: text/plain");
  3466. $fieldID = $this->_acl->getFieldIdByName($fieldName);
  3467. if (!$fieldID) {
  3468. echo "404: No field by name ({$fieldName})";
  3469. exit;
  3470. }
  3471. if ($DBG) echo "fieldID: {$fieldID}\n";
  3472. $row = $this->_acl->getItem($rowID);
  3473. if (!$row) {
  3474. echo "404: No item ID({$rowID})";
  3475. exit;
  3476. }
  3477. if (!$this->_acl->isAllowed($fieldID, 'R', $row)) {
  3478. if ($DBG) echo " R not allowed\n";
  3479. } else {
  3480. if ($DBG) echo " R allowed\n";
  3481. }
  3482. if (!$this->_acl->isAllowed($fieldID, 'W', $row)) {
  3483. if ($DBG) echo " W not allowed\n";
  3484. } else {
  3485. if ($DBG) echo " W allowed\n";
  3486. }
  3487. $fieldVal = '';
  3488. if ($this->_acl->isAllowed($fieldID, 'R', $row)) {
  3489. $fieldVal = V::get($fieldName, $fieldVal, $row);
  3490. } else {
  3491. $fieldVal = '*****';
  3492. }
  3493. $fieldVal = V::get("f{$fieldID}", $fieldVal, $_POST);
  3494. $vCol = $this->_acl->getField($fieldID);
  3495. $vCol['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
  3496. $tsValues = array();
  3497. $typeSpecial = Typespecial::getInstance($fieldID, $vCol['name']);
  3498. if ($typeSpecial) {
  3499. 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>';}
  3500. $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $row->ID, $fieldName, V::get($fieldName, $fieldVal, $row));
  3501. 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>';}
  3502. if (!empty($specialValues)) {
  3503. $tsValues[$row->ID] = implode('<br>', $specialValues);
  3504. }
  3505. }
  3506. ?>
  3507. <label for="<?php echo "f{$fieldID}"; ?>" class="AjaxTableEdit-label">
  3508. <strong title="<?php echo "[{$fieldID}] {$fieldName}"; ?>"><?php echo "{$vCol['label']}"; ?></strong>
  3509. <?php if (!empty($vCol['opis'])) : ?>
  3510. <em><?php echo $vCol['opis']; ?></em>
  3511. <?php $perms = $this->_acl->getFieldPerms($fieldID); SE_Layout::hotKeyDBG($perms); ?>
  3512. <?php endif; ?>
  3513. </label>
  3514. <?php
  3515. $fieldParams = array('widthClass'=>'inside-modal', 'maxGrid'=>6);
  3516. if (!empty($tsValues[$row->ID])) {
  3517. $fieldParams['typespecialValue'] = $tsValues[$row->ID];
  3518. }
  3519. $vDefault = $this->_acl->getColDefault($fieldName);
  3520. if (!empty($vDefault)) {
  3521. $fieldParams['default'] = $vDefault;
  3522. }
  3523. echo $this->_acl->showFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $row);
  3524. if ($typeSpecial
  3525. || $this->_acl->isDateField($fieldName)
  3526. || $this->_acl->isDateTimeField($fieldName)
  3527. ) {
  3528. echo '<p style="padding:120px 0;"></p>';
  3529. }
  3530. exit;
  3531. }
  3532. private function ajaxEditInlineSave($args) {
  3533. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  3534. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  3535. $fieldName = V::get('col', '', $_REQUEST);
  3536. if (empty($primaryKey) || empty($fieldName)) {
  3537. throw new HttpException("Wrong param id or col!", 400);
  3538. }
  3539. $fieldID = $this->_acl->getFieldIdByName($fieldName);
  3540. if (!$fieldID) {
  3541. throw new HttpException("Field not exists!", 404);
  3542. }
  3543. $item = $this->_acl->getItem($primaryKey);
  3544. if (!$item) {
  3545. throw new HttpException("Item not exists!", 404);
  3546. }
  3547. $itemFromUser = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  3548. if (!isset($itemFromUser[$fieldName])) {
  3549. throw new HttpException("Field not set!", 400);
  3550. }
  3551. $itemPatch = array();
  3552. $itemPatch[$fieldName] = V::get($fieldName, null, $itemFromUser);
  3553. $itemPatch[$primaryKeyField] = $primaryKey;
  3554. $response = new stdClass();
  3555. try {
  3556. $affected = $this->_acl->updateItem($itemPatch);
  3557. if ($affected > 0) {
  3558. $response->type = 'success';
  3559. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  3560. } else if ($affected == 0) {
  3561. $response->type = 'info';
  3562. $response->msg = "Nie wprowadzono żadnych zmian";
  3563. }
  3564. $response->record = $this->_acl->getItem($primaryKey);
  3565. }
  3566. catch (Exception $e) {
  3567. $response->type = 'error';
  3568. $response->msg = $e->getMessage();
  3569. }
  3570. return $response;
  3571. }
  3572. private function sendAjaxEdit($id, $args) {
  3573. header("Content-type: text/plain");
  3574. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3575. $cols = array();
  3576. $record = $this->_acl->getItem($id);
  3577. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  3578. echo '<div class="alert alert-danger">';
  3579. echo "Brak dostępu do rekordu";// TODO: more info - reason
  3580. echo '</div>';
  3581. return;
  3582. }
  3583. $fieldsList = $this->_acl->getFields();
  3584. foreach ($fieldsList as $kID => $vCol) {
  3585. if ($vCol['name'] == 'ID') {
  3586. unset($fieldsList[$kID]);
  3587. continue;
  3588. }
  3589. $cols[$kID] = '';
  3590. if ($this->_acl->isAllowed($kID, 'R', $record)) {
  3591. $cols[$kID] = V::get($vCol['name'], '', $record);
  3592. } else {
  3593. $cols[$kID] = '*****';
  3594. }
  3595. $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
  3596. $fieldsList[$kID]['label'] = (!empty($vCol['label']))? $vCol['label'] : str_replace('_', ' ', $vCol['name']);
  3597. }
  3598. $tsValues = array();
  3599. 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>';}
  3600. if (!empty($fieldsList)) {
  3601. foreach ($fieldsList as $vColID => $vCol) {
  3602. $typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
  3603. if ($typeSpecial) {
  3604. 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>';}
  3605. $colValue = V::get($vCol['name'], '', $record);
  3606. 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>';}
  3607. $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $record->ID, $vCol['name'], $colValue);
  3608. 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>';}
  3609. if (!empty($specialValues)) {
  3610. $tsValues[$vColID] = implode('<br>', $specialValues);
  3611. }
  3612. }
  3613. }
  3614. }
  3615. 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>';}
  3616. $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('edit', 'cp'), true);
  3617. ?>
  3618. <div class="container AjaxFrmHorizontalEdit" style="max-width:940px">
  3619. <form class="form-horizontal" action="" method="post" id="EDIT_FRM_<?php echo $this->_htmlID; ?>">
  3620. <fieldset>
  3621. <legend>Edycja rekordu Nr <?php echo $record->ID; ?><span class="pull-right valign-btns-bottom"><?php echo $rowFunctionsOut; ?></span></legend>
  3622. <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
  3623. <?php if ($this->_acl->isAllowed($kID, 'W', $record)) : ?>
  3624. <div class="form-group">
  3625. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  3626. <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>
  3627. <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
  3628. </label>
  3629. <div class="col-xs-12 col-sm-9 col-md-10">
  3630. <?php
  3631. $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
  3632. if (!empty($tsValues[$kID])) {
  3633. $fieldParams['typespecialValue'] = $tsValues[$kID];
  3634. }
  3635. echo $this->_acl->showFormItem('W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record);
  3636. ?>
  3637. </div>
  3638. </div>
  3639. <?php elseif ($this->_acl->isAllowed($kID, 'R', $record)) : ?>
  3640. <div class="form-group">
  3641. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  3642. <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>
  3643. <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
  3644. </label>
  3645. <div class="col-xs-12 col-sm-9 col-md-10">
  3646. <p style="margin-top:5px;">
  3647. <?php
  3648. //echo $this->_acl->showFormItem('R', $kID, "f{$kID}", $cols[$kID], array('appendBack'=>true), $record);
  3649. if (!empty($tsValues[$kID])) {
  3650. echo $tsValues[$kID];
  3651. } else if (!empty($record->{$vCol['name']})) {
  3652. echo $record->{$vCol['name']};
  3653. }
  3654. ?>
  3655. </p>
  3656. </div>
  3657. </div>
  3658. <?php endif; ?>
  3659. <?php endforeach; ?>
  3660. <div class="form-group">
  3661. <div class="col-xs-offset-0 col-xs-12 col-sm-offset-3 col-sm-9 col-md-offset-2 col-md-10">
  3662. <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Zapisz</button>
  3663. </div>
  3664. </div>
  3665. </fieldset>
  3666. </form>
  3667. <p style="padding:100px 0;"></p>
  3668. </div>
  3669. <script>
  3670. jQuery(document).ready(function(){
  3671. jQuery('textarea').autosize();
  3672. jQuery('.frm-help').popover({trigger:'hover'});
  3673. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
  3674. var data = jQuery(this).serialize();
  3675. // TODO: change Edit btn to return to edit record with fields -> show form
  3676. var taskCont = jQuery('#<?php echo $this->_htmlID; ?>_task').parent();
  3677. //taskCont.empty();
  3678. taskCont.children().fadeOut('slow');
  3679. var alertCntWrap = jQuery('<div class="AjaxTableAlert AjaxTable-loading"></div>').prependTo(taskCont)
  3680. , alertCnt = jQuery('<div class="container"></div>').prependTo(alertCntWrap);
  3681. 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);
  3682. function notifyAjaxCallback(data) {
  3683. var notify = {}, outMsg = '';
  3684. notify.type = (data && data.type)? data.type : '';
  3685. notify.msg = (data && data.msg)? data.msg : '';
  3686. switch (notify.type) {
  3687. case 'success':
  3688. if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
  3689. break;
  3690. case 'info':
  3691. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  3692. break;
  3693. case 'error':
  3694. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3695. break;
  3696. case 'warning':
  3697. notify.type = 'warn';
  3698. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3699. break;
  3700. default:
  3701. notify.msg = 'Nieznany błąd';
  3702. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  3703. notify.type = '';
  3704. }
  3705. jQuery.notify(notify.msg, notify.type);
  3706. var alertType = ('error' == notify.type) ? 'danger' : notify.type;
  3707. outMsg = '<div class="alert alert-' + alertType + '">' + notify.msg + '</div>';
  3708. return outMsg;
  3709. }
  3710. $.ajax({
  3711. data: data,
  3712. dataType: 'json',
  3713. type: "POST",
  3714. 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; ?>',
  3715. })
  3716. .done(function(data, textStatus, jqXHR){
  3717. var outMsg = notifyAjaxCallback(data);
  3718. alertCntWrap.removeClass('AjaxTable-loading');
  3719. //console.log('request finished L.<?php echo __LINE__; ?>');
  3720. alertCnt.empty();
  3721. var out = '';
  3722. out += outMsg;
  3723. out += '<div class="breadcrumb">' +
  3724. ' <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>' +
  3725. ' <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>' +
  3726. '</div>';
  3727. jQuery(out).appendTo(alertCnt);
  3728. })
  3729. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  3730. if (jqXHR.responseJSON) {
  3731. notifyAjaxCallback(jqXHR.responseJSON);
  3732. }
  3733. else {
  3734. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  3735. if (jqXHR.status == 404) {
  3736. jQuery.notify(jqXHR.responseText, 'error');
  3737. } else {
  3738. jQuery.notify(jqXHR.responseText, 'warn');
  3739. }
  3740. }
  3741. alertCntWrap.removeClass('AjaxTable-loading');
  3742. //console.log('Request Error: {0}: {1}'.f(textStatus, errorThrown));
  3743. alertCnt.empty();
  3744. jQuery(errorTxt).appendTo(alertCnt);
  3745. var errLinks = jQuery('<div class="breadcrumb"></div>').appendTo(alertCnt);
  3746. jQuery('<a href="#" onclick="return tableAjaxBackToTable();"> <i class="icon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>').appendTo(errLinks);
  3747. 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);
  3748. backToEditBtn.on('click', function(){
  3749. alertCnt.remove();
  3750. taskCont.children().fadeIn('slow');
  3751. return false;
  3752. });
  3753. });
  3754. return false;
  3755. });
  3756. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value input').on('input', function(e) {
  3757. var input, btn, btnIco;
  3758. input = jQuery(e.target);
  3759. btn = input.next('.button-appendBack');
  3760. btnIco = btn.find('.glyphicon');
  3761. //console.log('title',btn.attr('title'),'val',input.val(),'input', input, 'btn', btn);
  3762. if (btn.attr('title') != input.val()) {
  3763. btnIco.show();
  3764. } else {
  3765. btnIco.hide();
  3766. }
  3767. });
  3768. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value').find('.button-appendBack').on('click', function(e) {
  3769. var input, btn, btnIco;
  3770. btn = jQuery(this);
  3771. btnIco = btn.find('.glyphicon');
  3772. input = btn.prev();
  3773. //console.log('title',btn.attr('title'),'val',input.val(),'input', input, 'btn', btn);
  3774. if (input.is('input')) {
  3775. if (btn.attr('title') != input.val()) {
  3776. input.val(btn.attr('title'));
  3777. btnIco.hide();
  3778. }
  3779. }
  3780. });
  3781. });
  3782. </script>
  3783. <?php
  3784. exit;
  3785. }
  3786. private function ajaxEditSave($args) {
  3787. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  3788. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  3789. if (empty($primaryKey)) {
  3790. throw new HttpException("Wrong param id!", 400);
  3791. }
  3792. $item = $this->_acl->getItem($primaryKey);
  3793. if (!$item) {
  3794. throw new HttpException("Item not exists!", 404);
  3795. }
  3796. $itemFromUser = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  3797. $response = new stdClass();
  3798. try {
  3799. $itemFromUser[$primaryKeyField] = $primaryKey;
  3800. $affected = $this->_acl->updateItem($itemFromUser);
  3801. if ($affected > 0) {
  3802. $response->type = 'success';
  3803. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  3804. } else if ($affected == 0) {
  3805. $response->type = 'info';
  3806. $response->msg = "Nie wprowadzono żadnych zmian";
  3807. }
  3808. $response->record = $this->_acl->getItem($primaryKey);
  3809. }
  3810. catch (Exception $e) {
  3811. $response->type = 'error';
  3812. $response->msg = "Wystąpiły błędy!";
  3813. $response->msg .= $e->getMessage();
  3814. }
  3815. return $response;
  3816. }
  3817. private function sendAjaxCreate($args) {
  3818. header("Content-type: text/plain");
  3819. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3820. if (!$this->_acl->hasCreatePerms()) {
  3821. ?>
  3822. <div class="container">
  3823. <div class="alert alert-danger">
  3824. Brak uprawnień do utworzenia nowego rekordu.
  3825. </div>
  3826. </div>
  3827. <?php
  3828. return;
  3829. }
  3830. $cols = array();
  3831. $forceFilterInit = array();
  3832. $defaultAclGroup = User::getDefaultAclGroup();
  3833. if ($defaultAclGroup) {
  3834. $forceFilterInit['A_ADM_COMPANY'] = $defaultAclGroup;
  3835. $forceFilterInit['A_CLASSIFIED'] = $defaultAclGroup;
  3836. }
  3837. foreach ($_GET as $k => $v) {
  3838. if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  3839. $fldName = substr($k, 3);
  3840. $forceFilterInit[$fldName] = $v;
  3841. }
  3842. }
  3843. $fieldsList = $this->_acl->getFields();
  3844. foreach ($fieldsList as $kID => $vCol) {
  3845. $defaultValue = '';
  3846. if ($vCol['name'] == 'ID') {
  3847. unset($fieldsList[$kID]);
  3848. continue;
  3849. }
  3850. if (!empty($forceFilterInit[$vCol['name']])) {
  3851. $defaultValue = $forceFilterInit[$vCol['name']];
  3852. }
  3853. // TODO: read from session cache
  3854. $cols[$kID] = V::get("f{$kID}", $defaultValue, $_POST);
  3855. $fieldsList[$kID]['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
  3856. }
  3857. ?>
  3858. <div class="container AjaxFrmHorizontalEdit">
  3859. <form class="form-horizontal" action="" method="post" id="CREATE_FRM_<?php echo $this->_htmlID; ?>">
  3860. <fieldset>
  3861. <legend>Dodaj nowy rekord</legend>
  3862. <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
  3863. <?php if ($this->_acl->isAllowed($kID, 'C')) : ?>
  3864. <div class="form-group">
  3865. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  3866. <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>
  3867. <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
  3868. </label>
  3869. <div class="col-xs-12 col-sm-9 col-md-10">
  3870. <?php
  3871. $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
  3872. echo $this->_acl->showFormItem('C', $kID, "f{$kID}", $cols[$kID], $fieldParams);
  3873. ?>
  3874. </div>
  3875. </div>
  3876. <?php endif; ?>
  3877. <?php endforeach; ?>
  3878. <div class="form-group">
  3879. <div class="col-xs-offset-0 col-xs-12 col-sm-offset-3 col-sm-9 col-md-offset-2 col-md-10">
  3880. <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Dodaj rekord</button>
  3881. </div>
  3882. </div>
  3883. </fieldset>
  3884. </form>
  3885. </div>
  3886. <script>
  3887. jQuery(document).ready(function(){
  3888. jQuery('textarea').autosize();
  3889. jQuery('.frm-help').popover({trigger:'hover'});
  3890. jQuery('#CREATE_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
  3891. var data = jQuery(this).serialize();
  3892. var taskContLast = jQuery('#<?php echo $this->_htmlID; ?>_task'),
  3893. taskCont = taskContLast.parent();
  3894. taskContLast.fadeOut('slow');
  3895. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  3896. 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);
  3897. function notifyAjaxCallback(data) {
  3898. var notify = {};
  3899. notify.type = (data && data.type)? data.type : '';
  3900. notify.msg = (data && data.msg)? data.msg : '';
  3901. switch (notify.type) {
  3902. case 'success':
  3903. if (!notify.msg) notify.msg = 'OK';
  3904. break;
  3905. case 'info':
  3906. if (!notify.msg) notify.msg = '';
  3907. break;
  3908. case 'error':
  3909. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3910. break;
  3911. case 'warning':
  3912. notify.type = 'warn';
  3913. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3914. break;
  3915. default:
  3916. notify.msg = 'Nieznany błąd';
  3917. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  3918. notify.type = '';
  3919. }
  3920. jQuery.notify(notify.msg, notify.type);
  3921. }
  3922. $.ajax({
  3923. data: data,
  3924. dataType: 'json',
  3925. type: "POST",
  3926. async: true,
  3927. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE_SAVE'
  3928. })
  3929. .always(function(dataOrJqXHR){
  3930. var data;
  3931. if (dataOrJqXHR && 'readyState' in dataOrJqXHR && 'status' in dataOrJqXHR) {
  3932. if ('responseJSON' in dataOrJqXHR) {
  3933. data = dataOrJqXHR.responseJSON;
  3934. } else {
  3935. data = {};
  3936. data.msg = dataOrJqXHR.responseText || 'Nieznany błąd';
  3937. if (dataOrJqXHR.status == 404) {
  3938. data.type = 'error';
  3939. } else {
  3940. data.type = 'warning';
  3941. }
  3942. }
  3943. }
  3944. else {
  3945. data = dataOrJqXHR;
  3946. }
  3947. notifyAjaxCallback(data);
  3948. taskCnt.removeClass('AjaxTable-loading');
  3949. taskCnt.empty();
  3950. if (data.type == 'error' || data.type == 'warning') {
  3951. var out = '<div class="container">' +
  3952. '<div class="alert alert-danger">' +
  3953. '<h4>Wystąpiły błędy!</h4>' + data.msg +
  3954. (('errors' in data)? '<p>' + data.errors + '</p>' : '') +
  3955. '</div>';
  3956. out += '<div class="breadcrumb">' +
  3957. ' <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>' +
  3958. '</div>' +
  3959. '</div>';
  3960. jQuery(out).appendTo(taskCnt);
  3961. var taskContLastNode = taskContLast
  3962. , taskCntNode = taskCnt;
  3963. taskCnt.find('.create-fix').click(function(){
  3964. taskCntNode.remove();
  3965. taskContLastNode.fadeIn('slow');
  3966. return false;
  3967. });
  3968. }
  3969. else if (data.type == 'success') {
  3970. var msg = '';
  3971. if (data.id && data.id > 0) {
  3972. msg = 'Utworzono pomyślnie rekord: ID = ' + data.id;
  3973. } else if (data.msg) {
  3974. msg = data.msg;
  3975. } else {
  3976. msg = 'OK';
  3977. }
  3978. var out = '<div class="container">';
  3979. out += '<div class="alert alert-success">' + msg + '</div>';
  3980. out += '<div class="breadcrumb">' +
  3981. ' <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>' +
  3982. ' <a href="#EDIT/' + data.id + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-pencil"></i> Edytuj rekord ' + data.id + '</a>' +
  3983. ' <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>' +
  3984. '</div>';
  3985. out += '</div>';
  3986. jQuery(out).appendTo(taskCnt);
  3987. }
  3988. });
  3989. return false;
  3990. });
  3991. });
  3992. </script>
  3993. <?php
  3994. exit;
  3995. }
  3996. private function ajaxCreateSave($args) {
  3997. $response = new stdClass();
  3998. $createdId = null;
  3999. try {
  4000. $item = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  4001. $createdId = $this->_acl->addItem($item);
  4002. if ($createdId) {
  4003. $response->type = 'success';
  4004. $response->msg = "Utworzono pomyślnie rekord nr {$createdId}";
  4005. $response->id = $createdId;
  4006. $response->record = $this->_acl->getItem($createdId);
  4007. }
  4008. else {
  4009. $response->type = 'error';
  4010. $response->msg = "Nie udało się utworzyć nowego rekordu!";
  4011. }
  4012. }
  4013. catch (Exception $e) {
  4014. $response->type = 'error';
  4015. $response->msg = "Wystąpiły błędy!";
  4016. $response->msg = $e->getMessage();
  4017. }
  4018. return $response;
  4019. }
  4020. private function ajaxCopy($args) {
  4021. $id = V::get('ID', 0, $_REQUEST, 'int');
  4022. if ($id <= 0) {
  4023. throw new HttpException("Wrong param ID!", 404);
  4024. }
  4025. $item = $this->_acl->getItem($id);
  4026. if (!$item) {
  4027. throw new HttpException("Item '{$id}' not exists!", 404);
  4028. }
  4029. $response = new stdClass();
  4030. $itemCopy = $this->_acl->createItemCopy($item);
  4031. $createdId = null;
  4032. try {
  4033. $createdId = $this->_acl->addItem($itemCopy);
  4034. if ($createdId) {
  4035. $response->type = 'success';
  4036. $response->msg = "Rekord skopiowany pomyślnie - utworzono rekord nr {$createdId}";
  4037. $response->id = $createdId;
  4038. $response->record = $this->_acl->getItem($createdId);
  4039. }
  4040. else {
  4041. $response->type = 'error';
  4042. $response->msg = "Nie udało się skopiować rekordu!";
  4043. }
  4044. }
  4045. catch (Exception $e) {
  4046. $response->type = 'error';
  4047. $response->msg = "Wystąpiły błędy!";
  4048. $response->msg = $e->getMessage();
  4049. }
  4050. return $response;
  4051. }
  4052. private function sendAjaxHistory($id, $args) {
  4053. header("Content-type: text/plain");
  4054. $record = $this->_acl->getItem($id);
  4055. if (!$record) {
  4056. header('HTTP/1.0 404 Not Found');
  4057. echo "404: No item ID({$rowID})";
  4058. exit;
  4059. }
  4060. $visibleCols = $this->_acl->getRealFieldList();
  4061. $rowsHist = $this->_acl->getHistItems($id);
  4062. $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('hist', 'cp'), true);
  4063. $visibleColsWithIds = array();
  4064. $visibleColsLabels = array();
  4065. foreach ($visibleCols as $vColName) {
  4066. $fldId = $this->_acl->getFieldIdByName($vColName);
  4067. if ($fldId) {
  4068. $visibleColsWithIds[$fldId] = $vColName;
  4069. $label = $this->_acl->getFieldLabel($fldId);
  4070. $label = (!$label)? $vColName : '<span title="' . "[{$fldId}] {$vColName}" . '">' . $label . '</span>';
  4071. $visibleColsLabels[$fldId] = $label;
  4072. }
  4073. }
  4074. ?>
  4075. <fieldset>
  4076. <legend>Historia rekordu Nr <?php echo $id; ?>
  4077. <span class="pull-right valign-btns-bottom"><?php echo $rowFunctionsOut; ?></span>
  4078. </legend>
  4079. </fieldset>
  4080. <?php if (empty($rowsHist)) : ?>
  4081. <div class="alert alert-info">
  4082. <h4>Brak danych</h4>
  4083. </div>
  4084. <?php else: ?>
  4085. <table class="table table-striped table-hover table-bordered table-condensed AjaxTableHist">
  4086. <thead>
  4087. <tr>
  4088. <th>Data</th>
  4089. <th>User</th>
  4090. <th>Zmiany</th>
  4091. </tr>
  4092. </thead>
  4093. <tbody>
  4094. <?php foreach ($rowsHist as $row) : ?>
  4095. <tr>
  4096. <td style="white-space:nowrap"><?php echo $row->_created; ?></td>
  4097. <td><?php echo $row->_author; ?></td>
  4098. <td>
  4099. <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
  4100. <?php if (in_array($colName, array('ID', 'A_RECORD_UPDATE_DATE', 'A_RECORD_UPDATE_AUTHOR', 'A_RECORD_CREATE_DATE', 'A_RECORD_CREATE_AUTHOR'))) continue; ?>
  4101. <?php if ($row->$colName == 'N/S;') continue; ?>
  4102. <p><em><?php echo $visibleColsLabels[$fldId]; ?></em>:
  4103. <?php if ($this->_acl->isAllowed($fldId, 'R', $record)) : ?>
  4104. <?php echo $row->$colName; ?>
  4105. <?php else : ?>
  4106. <span title="Brak uprawnień do odczytu tego pola">*****</span>
  4107. <?php endif; ?>
  4108. </p>
  4109. <?php endforeach; ?>
  4110. </td>
  4111. </tr>
  4112. <?php endforeach; ?>
  4113. </tbody>
  4114. </table>
  4115. <div style="overflow-x:scroll; overflow-y:visible; padding-bottom:1px; margin:10px 0;">
  4116. <table class="table table-striped table-hover table-bordered table-condensed AjaxTableHist">
  4117. <thead>
  4118. <tr>
  4119. <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
  4120. <th><?php echo str_replace('_', ' ', $visibleColsLabels[$fldId]); ?></th>
  4121. <?php endforeach; ?>
  4122. </tr>
  4123. </thead>
  4124. <tbody>
  4125. <?php foreach ($rowsHist as $row) : ?>
  4126. <tr>
  4127. <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
  4128. <td>
  4129. <?php if ($row->$colName == 'N/S;') : ?>
  4130. <em>N/S;</em>
  4131. <?php elseif ($this->_acl->isAllowed($fldId, 'R', $record)) : ?>
  4132. <?php echo $row->$colName; ?>
  4133. <?php else : ?>
  4134. <span title="Brak uprawnień do odczytu tego pola">*****</span>
  4135. <?php endif; ?>
  4136. </td>
  4137. <?php endforeach; ?>
  4138. </tr>
  4139. <?php endforeach; ?>
  4140. </tbody>
  4141. </table>
  4142. </div>
  4143. <?php endif; ?>
  4144. <?php
  4145. exit;
  4146. }
  4147. /**
  4148. * Returns text/plain with type at first line: ERROR, WARNING, INFO, SUCCESS
  4149. */
  4150. private function sendAjaxFilesUpload($id, $args) {
  4151. // http://www.sitepoint.com/html5-ajax-file-upload/
  4152. //$ajaxFileName = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
  4153. //header("Content-type: text/plain");
  4154. header("Content-type: application/json");
  4155. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4156. $dbID = $this->_acl->getDB();
  4157. $db = DB::getDB($dbID);
  4158. if (!$db) {
  4159. header('HTTP/1.0 406 Not Acceptable');
  4160. echo '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
  4161. exit;
  4162. }
  4163. $record = $this->_acl->getItem($id);
  4164. if (!$record) {
  4165. header('HTTP/1.0 404 Not Found');
  4166. echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
  4167. exit;
  4168. }
  4169. $tblName = $this->_acl->getName();
  4170. $confTblName = "{$tblName}_COLUMN";
  4171. $folderConfAll = FoldersConfig::getRawData();
  4172. if (!FoldersConfig::hasConfig($confTblName)) {
  4173. header('HTTP/1.0 404 Not Found');
  4174. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych(' . $tblName . ')"}';
  4175. exit;
  4176. }
  4177. $folderConf = FoldersConfig::getAll($confTblName);
  4178. $uploader = new FileUploader($confTblName, $record);
  4179. $errMsg = '';
  4180. if (!$uploader->setConfig($folderConf, $errMsg)) {
  4181. header('HTTP/1.0 404 Not Found');
  4182. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych(' . $tblName . ') <br>' . $errMsg . '"}';
  4183. exit;
  4184. }
  4185. $uploader->findFolder();
  4186. $errorMsg = '';
  4187. if (!empty($_POST['SCANS_COLUMN_ADD'])) {
  4188. $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
  4189. }
  4190. else {
  4191. $uploaded = $uploader->tryUploadAjax($errorMsg);
  4192. }
  4193. if ($uploaded) {
  4194. $uploadedFileName = '';
  4195. $uploadedFile = $uploader->getLastUploadedFile();
  4196. if ($uploadedFile) {
  4197. $uploadedFileName = explode('/', $uploadedFile);
  4198. $uploadedFileName = end($uploadedFileName);
  4199. }
  4200. echo '{"type":"SUCCESS", "string": "Plik został poprawnie wgrany do odpowiedniego katalogu '.$uploadedFileName.'"}';
  4201. if (!empty($uploadedFileName)) {
  4202. $sqlObj = new stdClass();
  4203. $sqlObj->ID = $record->ID;
  4204. $sqlObj->M_DIST_FILES = "Wgrano plik {$uploadedFileName}";
  4205. $db->UPDATE_OBJ($this->_tbl, $sqlObj);
  4206. }
  4207. } else {
  4208. echo '{"type":"ERROR", "string": "' . $errorMsg . '"}';
  4209. }
  4210. exit;
  4211. }
  4212. private function sendAjaxFileRemove($id, $args) {
  4213. header("Content-type: application/json");
  4214. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4215. if (empty($_POST['filename'])) {
  4216. echo '{"type":"ERROR", "string": "Nie wybrano pliku do usunięcia"}';
  4217. exit;
  4218. }
  4219. $dbID = $this->_acl->getDB();
  4220. $db = DB::getDB($dbID);
  4221. if (!$db) {
  4222. header('HTTP/1.0 406 Not Acceptable');
  4223. echo '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
  4224. exit;
  4225. }
  4226. $record = $this->_acl->getItem($id);
  4227. if (!$record) {
  4228. header('HTTP/1.0 404 Not Found');
  4229. echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
  4230. exit;
  4231. }
  4232. $tblName = $this->_acl->getName();
  4233. $confTblName = "{$tblName}_COLUMN";
  4234. $folderConfAll = FoldersConfig::getRawData();
  4235. if (!FoldersConfig::hasConfig($confTblName)) {
  4236. header('HTTP/1.0 404 Not Found');
  4237. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
  4238. exit;
  4239. }
  4240. $folderConf = FoldersConfig::getAll($confTblName);
  4241. $uploader = new FileUploader($confTblName, $record);
  4242. if (!$uploader->setConfig($folderConf)) {
  4243. header('HTTP/1.0 404 Not Found');
  4244. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
  4245. exit;
  4246. }
  4247. $uploader->findFolder();
  4248. $errorMsg = '';
  4249. $removed = $uploader->tryRemoveFromAjax($_POST['filename'], $errorMsg);
  4250. if (!$removed) {
  4251. echo '{"type":"ERROR", "string": "{' . $errorMsg . '}"}';
  4252. } else {
  4253. echo '{"type":"SUCCESS","string":"Plik został poprawnie usunięty"}';
  4254. }
  4255. exit;
  4256. }
  4257. private function sendAjaxFilesList($id, $args) {
  4258. header("Content-type: application/json");
  4259. $dbID = $this->_acl->getDB();
  4260. $db = DB::getDB($dbID);
  4261. if (!$db) {
  4262. header('HTTP/1.0 406 Not Acceptable');
  4263. echo '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
  4264. exit;
  4265. }
  4266. $record = $this->_acl->getItem($id);
  4267. if (!$record) {
  4268. header('HTTP/1.0 404 Not Found');
  4269. echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
  4270. exit;
  4271. }
  4272. $tblName = $this->_acl->getName();
  4273. $confTblName = "{$tblName}_COLUMN";
  4274. $folderConfAll = FoldersConfig::getRawData();
  4275. if (!FoldersConfig::hasConfig($confTblName)) {
  4276. header('HTTP/1.0 404 Not Found');
  4277. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
  4278. exit;
  4279. }
  4280. $folderConf = FoldersConfig::getAll($confTblName);
  4281. $uploader = new FileUploader($confTblName, $record);
  4282. if (!$uploader->setConfig($folderConf)) {
  4283. header('HTTP/1.0 404 Not Found');
  4284. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
  4285. exit;
  4286. }
  4287. $uploader->findFolder();
  4288. $mainFolder = $uploader->getDestFolder();
  4289. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4290. $localPath = $uploader->getLocalPath();
  4291. $folderWeb = $uploader->getFolderWeb();
  4292. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4293. echo json_encode($jsonFiles);
  4294. exit;
  4295. }
  4296. private function ajaxFilePermsRefresh($args) {
  4297. header("Content-type: application/json");
  4298. $id = V::get('ID', 0, $args, 'int');
  4299. if ($id <= 0) throw new HttpException("Wrong param ID", 404);
  4300. $dbID = $this->_acl->getDB();
  4301. $db = DB::getDB($dbID);
  4302. if (!$db) throw new HttpException("No DB", 406);
  4303. $record = $this->_acl->getItem($id);
  4304. if (!$record) throw new Exception("No item ID({$rowID})", 404);
  4305. $tblName = $this->_acl->getName();
  4306. // TODO: SyncPermsCustomTables->getRecordTask($tbl, $id);
  4307. $sql_L_APPOITMENT_USER = V::get('L_APPOITMENT_USER', '', $record);
  4308. $sql_A_ADM_COMPANY = V::get('A_ADM_COMPANY', '', $record);
  4309. $sql_A_CLASSIFIED = V::get('A_CLASSIFIED', '', $record);
  4310. $mainDB = DB::getDB();
  4311. if ('IN7_MK_BAZA_DYSTRYBUCJI' == $tblName) {
  4312. $sql = "insert into `_SYNC_FILE_PERMS` (
  4313. `ID_PROJECT`,
  4314. `A_SYNCHRONIZED`
  4315. )
  4316. values (
  4317. '{$record->ID}'
  4318. , 0
  4319. )
  4320. ON DUPLICATE KEY UPDATE
  4321. `A_SYNCHRONIZED`=0
  4322. ";
  4323. }
  4324. else if ('IN7_DZIENNIK_KORESP' == $tblName) {
  4325. $sql = "insert into `_SYNC_FILE_PERMS` (
  4326. `ID_PROJECT`,
  4327. `A_SYNCHRONIZED`
  4328. )
  4329. values (
  4330. '{$record->ID_PROJECT}'
  4331. , 0
  4332. )
  4333. ON DUPLICATE KEY UPDATE
  4334. `A_SYNCHRONIZED`=0
  4335. ";
  4336. }
  4337. else {
  4338. $sql = "insert into `_SYNC_TABLE_FILE_PERMS` (
  4339. `TBL_NAME`,
  4340. `TBL_ID`,
  4341. `L_APPOITMENT_USER`,
  4342. `A_ADM_COMPANY`,
  4343. `A_CLASSIFIED`,
  4344. `A_SYNCHRONIZED`
  4345. )
  4346. values (
  4347. '{$tblName}'
  4348. , '{$id}'
  4349. , '{$sql_L_APPOITMENT_USER}'
  4350. , '{$sql_A_ADM_COMPANY}'
  4351. , '{$sql_A_CLASSIFIED}'
  4352. , 0
  4353. )
  4354. ON DUPLICATE KEY UPDATE
  4355. `A_SYNCHRONIZED`=0
  4356. ";
  4357. }
  4358. $res = $mainDB->query($sql);
  4359. if ($mainDB->has_errors()) {
  4360. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';
  4361. //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>';
  4362. throw new Exception("Nie udało się dodać zadania");
  4363. }
  4364. // TODO: this blocks browser ajax query
  4365. //$limit = 3;
  4366. //while ($limit--) {
  4367. // sleep(10);
  4368. // TODO: check if task is done
  4369. //}
  4370. $confTblName = "{$tblName}_COLUMN";
  4371. $folderConfAll = FoldersConfig::getRawData();
  4372. if (!FoldersConfig::hasConfig($confTblName)) {
  4373. throw new Exception("Brak danych konfiguracyjnych ({$tblName})", 404);
  4374. }
  4375. $folderConf = FoldersConfig::getAll($confTblName);
  4376. $uploader = new FileUploader($confTblName, $record);
  4377. if (!$uploader->setConfig($folderConf)) {
  4378. throw new Exception("Błąd danych konfiguracyjnych ({$tblName})", 404);
  4379. }
  4380. $uploader->findFolder();
  4381. $mainFolder = $uploader->getDestFolder();
  4382. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4383. $localPath = $uploader->getLocalPath();
  4384. $folderWeb = $uploader->getFolderWeb();
  4385. $jsonData = new stdClass();
  4386. $jsonData->msg = 'Zadanie dodane';
  4387. $jsonData->type = 'success';
  4388. $jsonData->files = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4389. return $jsonData;
  4390. }
  4391. private function sendAjaxFilesConnTblList($id, $args) {
  4392. header("Content-type: application/json");
  4393. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4394. $dbID = $this->_acl->getDB();
  4395. $db = DB::getDB($dbID);
  4396. if (!$db) {
  4397. header('HTTP/1.0 406 Not Acceptable');
  4398. echo 'No DB (' . $dbID . ')';
  4399. exit;
  4400. }
  4401. $record = $this->_acl->getItem($id);
  4402. if (!$record) {
  4403. header('HTTP/1.0 404 Not Found');
  4404. echo 'No item ID(' . $rowID . ')';
  4405. exit;
  4406. }
  4407. $connTblName = '';
  4408. $connTblID = V::get('connTblID', 0, $_REQUEST, 'int');
  4409. if ($connTblID <= 0) {
  4410. header('HTTP/1.0 406 Not Acceptable');
  4411. echo 'No conn Table ID';
  4412. exit;
  4413. }
  4414. $connTblTypespecials = $this->getConnectedTblTypespecials($connTblID);
  4415. if (empty($connTblTypespecials)) {
  4416. header('HTTP/1.0 406 Not Acceptable');
  4417. echo "No conn Table (ID={$connTblID})";
  4418. exit;
  4419. }
  4420. 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>';}
  4421. if(1) {
  4422. header('HTTP/1.0 404 Not Found');
  4423. echo 'TODO: ...';
  4424. exit;
  4425. }
  4426. $tblName = $this->_acl->getName();
  4427. $confTblName = "{$tblName}_COLUMN";
  4428. $folderConfAll = FoldersConfig::getRawData();
  4429. if (!FoldersConfig::hasConfig($confTblName)) {
  4430. header('HTTP/1.0 404 Not Found');
  4431. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
  4432. exit;
  4433. }
  4434. $folderConf = FoldersConfig::getAll($confTblName);
  4435. $uploader = new FileUploader($confTblName, $record);
  4436. if (!$uploader->setConfig($folderConf)) {
  4437. header('HTTP/1.0 404 Not Found');
  4438. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
  4439. exit;
  4440. }
  4441. $uploader->findFolder();
  4442. $mainFolder = $uploader->getDestFolder();
  4443. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4444. $localPath = $uploader->getLocalPath();
  4445. $folderWeb = $uploader->getFolderWeb();
  4446. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4447. echo json_encode($jsonFiles);
  4448. exit;
  4449. }
  4450. public function convertFileListToJson($files, $folderWeb, $localPath, $mainFolder) {
  4451. $jsonFiles = array();
  4452. if (!is_array($files) || empty($files)) {
  4453. return $jsonFiles;
  4454. }
  4455. sort($files);
  4456. foreach ($files as $vFilePath) {
  4457. $file = new stdClass();
  4458. $file->name = str_replace("{$localPath}/{$mainFolder}/", '', $vFilePath);
  4459. //$file->name = explode('/', $vFilePath);
  4460. //$file->name = end($file->name);
  4461. $file->size = filesize($vFilePath);
  4462. $file->sizeStr = round($file->size, 2) . "B";
  4463. if ($file->size > 1024 * 1024) {
  4464. $file->sizeStr = round(($file->size / (1024 * 1024)), 2) . "M";
  4465. } else if ($file->size > 1024) {
  4466. $file->sizeStr = round(($file->size / 1024), 2) . "K";
  4467. }
  4468. $file->type = '';
  4469. $file->created = date("Y-m-d H:i:s", filectime($vFilePath));
  4470. $file->web = str_replace($localPath, $folderWeb, $vFilePath);
  4471. $jsonFiles[] = $file;
  4472. }
  4473. return $jsonFiles;
  4474. }
  4475. private function getConnectedTables() {
  4476. $connTbls = array();
  4477. return $connTbls;// TODO: OFF - hardlinki tworzone w bash_sync_perms.php
  4478. $fields = $this->_acl->getVisibleFieldList();
  4479. if (!empty($fields)) {
  4480. foreach ($fields as $vColID => $vCol) {
  4481. $typeSpecial = Typespecial::getInstance($vColID);
  4482. if ($typeSpecial) {
  4483. $tsConnTbls = $typeSpecial->getTblAliasList();
  4484. if (!empty($tsConnTbls)) {
  4485. foreach ($tsConnTbls as $kID => $vName) {
  4486. $connTbls[$kID] = $vName;
  4487. }
  4488. }
  4489. }
  4490. }
  4491. }
  4492. return $connTbls;
  4493. }
  4494. private function getConnectedTblTypespecials($connTblID) {
  4495. $connTblTypespecials = array();
  4496. $fields = $this->_acl->getVisibleFieldList();
  4497. if (!empty($fields)) {
  4498. foreach ($fields as $vColID => $vCol) {
  4499. $typeSpecial = Typespecial::getInstance($vColID);
  4500. if ($typeSpecial) {
  4501. $tsConnTbls = $typeSpecial->getTblAliasList();
  4502. if (array_key_exists($connTblID, $tsConnTbls)) {
  4503. $connTblTypespecials[] = $typeSpecial;
  4504. }
  4505. }
  4506. }
  4507. }
  4508. return $connTblTypespecials;
  4509. }
  4510. private function sendAjaxFiles($id, $args) {
  4511. header("Content-type: text/plain");
  4512. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4513. $dbID = $this->_acl->getDB();
  4514. $db = DB::getDB($dbID);
  4515. if (!$db) {
  4516. header('HTTP/1.0 406 Not Acceptable');
  4517. exit;
  4518. }
  4519. $record = $this->_acl->getItem($id);
  4520. if (!$record) {
  4521. header('HTTP/1.0 404 Not Found');
  4522. echo "404: No item ID({$rowID})";
  4523. exit;
  4524. }
  4525. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  4526. echo '<div class="alert alert-danger">';
  4527. echo "Brak dostępu do rekordu";// TODO: more info - reason
  4528. echo '</div>';
  4529. return;
  4530. }
  4531. $tblName = $this->_acl->getName();
  4532. $confTblName = "{$tblName}_COLUMN";
  4533. $folderConfAll = FoldersConfig::getRawData();
  4534. if (!FoldersConfig::hasConfig($confTblName)) {
  4535. header('HTTP/1.0 404 Not Found');
  4536. echo "Brak danych konfiguracyjnych";
  4537. exit;
  4538. }
  4539. $folderConf = FoldersConfig::getAll($confTblName);
  4540. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$folderConf (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($folderConf);echo'</pre>';
  4541. $uploader = new FileUploader($confTblName, $record);
  4542. $errMsg = '';
  4543. if (!$uploader->setConfig($folderConf, $errMsg)) {
  4544. header('HTTP/1.0 404 Not Found');
  4545. echo "Błąd danych konfiguracyjnych ({$tblName})";
  4546. echo '<br>' . "\n" . $errMsg;
  4547. exit;
  4548. }
  4549. $uploader->findFolder();
  4550. 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>'; }
  4551. $mainFolder = $uploader->getDestFolder();
  4552. 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>'; }
  4553. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4554. 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>'; }
  4555. $sharePoint = V::get('share_point', null, $folderConf);
  4556. if ($sharePoint) {
  4557. $sharePoint = FoldersConfig::getNfsOsPath() . "{$sharePoint}/{$mainFolder}";
  4558. }
  4559. $localPath = $uploader->getLocalPath();
  4560. $folderWeb = $uploader->getFolderWeb();
  4561. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4562. 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>'; }
  4563. $folderSkanyConf = FoldersConfig::getAll('SCANS_COLUMN');
  4564. $skanyLocalPath = V::get('mount_point', null, $folderSkanyConf);
  4565. $skanySharePoint = V::get('share_point', null, $folderSkanyConf);
  4566. $skanyFolderWeb = V::get('www_share_point', null, $folderSkanyConf);
  4567. $skanyFiles = $uploader->getFilesFromSkany($folderSkanyConf, false);
  4568. sort($skanyFiles);
  4569. $fileTypes = FoldersConfig::getAll('m_dist_files_types');
  4570. $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('files', 'cp'), true);
  4571. $fileIndexField = V::get('DEST_FILE_INDEX_FIELD', 'ID', $folderConf);
  4572. $fileIndex = V::get($fileIndexField, $record->ID, $record);
  4573. ?>
  4574. <script src="stuff/jquery.form.js"></script>
  4575. <div class="container">
  4576. <h4 style="margin:20px 0 3px 0;">Pliki w katalogu
  4577. <?php if ($sharePoint) : ?>
  4578. <a href="<?php echo $sharePoint; ?>"><span class="glyphicon glyphicon-folder-open"></span><code><?php echo $mainFolder; ?></code></a>
  4579. <?php else : ?>
  4580. <code><?php echo $mainFolder; ?></code>
  4581. <?php endif; ?>
  4582. <span class="pull-right valign-btns-bottom">
  4583. <span id="FILES_LIST_ACTIONS_<?php echo $this->_htmlID; ?>"></span>
  4584. <?php echo $rowFunctionsOut; ?>
  4585. </span>
  4586. </h4>
  4587. <div style="clear:both; max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">
  4588. <table class="table table-bordered table-hover">
  4589. <colgroup>
  4590. <col style="">
  4591. <col style="width:30px;">
  4592. <?php if ($sharePoint) : ?>
  4593. <col style="width:30px;">
  4594. <?php endif; ?>
  4595. <col style="width:80px;">
  4596. <col style="width:140px;">
  4597. </colgroup>
  4598. <tbody id="FILES_LIST_<?php echo $this->_htmlID; ?>">
  4599. <?php if (empty($mainFolder)) : ?>
  4600. <tr>
  4601. <td colspan="5">
  4602. <div class="alert alert-warning">
  4603. <h4>Brak folderu!</h4>
  4604. Folder dla tego rekordu nie został utworzony.
  4605. </div>
  4606. </td>
  4607. </tr>
  4608. <?php elseif (empty($files)) : ?>
  4609. <tr>
  4610. <td colspan="5">
  4611. <div class="alert alert-info">
  4612. <h4>Brak plików</h4>
  4613. </div>
  4614. </td>
  4615. </tr>
  4616. <?php endif; ?>
  4617. </tbody>
  4618. </table>
  4619. </div>
  4620. <br>
  4621. <br>
  4622. <div id="FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>"></div>
  4623. <form enctype="multipart/form-data" method="POST" action="" id="FILES_FRM_<?php echo $this->_htmlID; ?>" class="form-inline">
  4624. <input type="hidden" name="M_DIST_UPLOAD_SOURCE" value="local">
  4625. <ul id="FILES_TAB_<?php echo $this->_htmlID; ?>" class="nav nav-tabs" style="margin:0;">
  4626. <li class="active"><a href="#local" data-toggle="local">Wybierz plik lokalny</a></li>
  4627. <li><a href="#scan" data-toggle="scan">Wybierz plik ze skanów</a></li>
  4628. </ul>
  4629. <div id="myTabContent" class="tab-content">
  4630. <div class="tab-pane fade in active" id="local" style="text-align: center;">
  4631. <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'">
  4632. </div>
  4633. <div class="tab-pane fade" id="scan">
  4634. <?php if (empty($skanyFiles)) : ?>
  4635. <div class="alert alert-info">
  4636. <h4>Brak plików</h4>
  4637. <?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>"; ?>
  4638. </div>
  4639. <?php else : ?>
  4640. <div style="max-height:150px; overflow:auto; border-bottom:1px solid #ddd;">
  4641. <table class="table table-bordered table-hover">
  4642. <colgroup>
  4643. <col style="width:30px;">
  4644. <col style="">
  4645. <col style="width:30px;">
  4646. <col style="width:80px;">
  4647. <col style="width:140px;">
  4648. </colgroup>
  4649. <tbody>
  4650. <?php foreach ($skanyFiles as $vFilePath) : ?>
  4651. <tr>
  4652. <?php
  4653. $vFileName = explode('/', $vFilePath);
  4654. $vFileName = end($vFileName);
  4655. $vFileSize = filesize($vFilePath);
  4656. $vFileSizeOut = round($vFileSize, 2) . "B";
  4657. if ($vFileSize > 1024 * 1024) {
  4658. $vFileSizeOut = round(($vFileSize / (1024 * 1024)), 2) . "M";
  4659. } else if ($vFileSize > 1024) {
  4660. $vFileSizeOut = round(($vFileSize / 1024), 0) . "K";
  4661. }
  4662. ?>
  4663. <td><input style="margin:0;" type="radio" name="SCANS_COLUMN_ADD" value="<?php echo $vFileName; ?>"></td>
  4664. <td><div style="overflow:hidden; white-space:nowrap;" title="<?php echo $vFileName; ?>"><?php echo $vFileName; ?></div></td>
  4665. <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>
  4666. <td style="white-space:nowrap;"><?php echo $vFileSizeOut; ?></td>
  4667. <td style="white-space:nowrap;"><?php echo date("Y-m-d H:i:s", filectime($vFilePath)); ?></td>
  4668. </tr>
  4669. <?php endforeach; ?>
  4670. </tbody>
  4671. </table>
  4672. </div>
  4673. <?php endif; ?>
  4674. </div>
  4675. </div>
  4676. <br>
  4677. <h4>Ustal nazwę pliku zgodną z obiegiem dokumentów
  4678. <?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> ?>
  4679. </h4>
  4680. <table style="width:100%" class="table table-bordered">
  4681. <tr>
  4682. <th>Nr</th>
  4683. <th>Typ</th>
  4684. <th style="width:40%;">Opis <i class="glyphicon glyphicon-question-sign" title="kogo dotyczy / czego / sprawa / nazwa_firmy itp"></i></th>
  4685. <th style="width:16%">Data wersji</th>
  4686. <th style="width:12%">Numer wersji</th>
  4687. </tr>
  4688. <tr>
  4689. <td>
  4690. <?php echo $fileIndex; ?>
  4691. </td>
  4692. <td>
  4693. <select class="form-control" name="M_DIST_FILES_TYPE">
  4694. <?php foreach ($fileTypes as $kType => $vLabel) : ?>
  4695. <option value="<?php echo $kType; ?>"<?php if ($kType == 'TODO') { echo ' selected="selected"'; } ?> ><?php echo $vLabel; ?></option>
  4696. <?php endforeach; ?>
  4697. </select>
  4698. <br>
  4699. <label class="checkbox">
  4700. <input type="checkbox" name="M_DIST_FILES_TYPE_AUTO">
  4701. Wykrycie automatyczne typu z wysylanego pliku
  4702. </label>
  4703. <label class="checkbox">
  4704. <input type="checkbox" name="M_DIST_FILES_TEMP">
  4705. Plik tymczasowy / roboczy / nieoficjalny (_TEMP)
  4706. </label>
  4707. </td>
  4708. <td>
  4709. <input class="form-control" style="width:100%" type="text" name="M_DIST_FILES_DESCRIPTION" value="" maxlength="50">
  4710. <br><label>jeśli nie zostanie podany to zostanie automatycznie wygenerowany na podstawie nazwy pliku wysyłanego</label>
  4711. </td>
  4712. <td>
  4713. <div class="input-group">
  4714. <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">
  4715. <span class="glyphicon glyphicon-calendar"></span>
  4716. </span>
  4717. </div>
  4718. <!--
  4719. <input class="form-control" type="date" name="M_DIST_FILES_DATE" value="<?php echo date('Y-m-d');?>" maxlength="10">
  4720. -->
  4721. <br><label>jeśli nie zostanie podana to zostanie ustawiona na dzisiaj (<?php echo date('Y-m-d');?>)</label>
  4722. </td>
  4723. <td>
  4724. <input class="form-control" style="width:100%" type="number" name="M_DIST_FILES_VERSION">
  4725. <br>
  4726. <label class="checkbox">
  4727. <input type="checkbox" name="M_DIST_FILES_VERSION_AUTO">
  4728. Automatycznie dodaj wersje
  4729. </label>
  4730. </td>
  4731. </tr>
  4732. <tr>
  4733. <td colspan="5">
  4734. <div id="FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>"></div>
  4735. <p>
  4736. <input type="submit" value="Wyślij" class="btn btn-primary"> wybrany plik do folderu:
  4737. </p>
  4738. <p>
  4739. <code><b><?php echo $uploader->getDestPathShare(true); ?></b></code>
  4740. <br><i style="color:#777">(Jeśli folder nie istnieje to zostanie utworzony automatycznie)</i>
  4741. </p>
  4742. </td>
  4743. </tr>
  4744. </table>
  4745. </form>
  4746. </div>
  4747. <script>
  4748. function fileListUpdateAjax<?php echo $this->_htmlID; ?>() {
  4749. var postData = {};
  4750. jQuery.ajax({
  4751. 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; ?>',
  4752. type: 'POST',
  4753. //dataType: 'json',
  4754. //contentType: "application/json; charset=utf-8",
  4755. data: postData,
  4756. async: true,
  4757. success: function(data) {
  4758. fileListUpdate<?php echo $this->_htmlID; ?>(data);
  4759. },
  4760. error: function(jhr, textStatus, errorThrown) {
  4761. if (priv.options.debug) console.log('request error: ', errorThrown, ' textStatus: ', textStatus);
  4762. }
  4763. });
  4764. }
  4765. function fileListUpdate<?php echo $this->_htmlID; ?>(fileListJson) {
  4766. var fileListNode = jQuery('#FILES_LIST_<?php echo $this->_htmlID; ?>');
  4767. fileListNode.empty();
  4768. fileListJson.map(function(file){
  4769. var node = $('<tr></tr>');
  4770. var fFun = $('<i class="glyphicon glyphicon-remove" style="cursor:pointer" data-filename="' + file.name + '"></i>');
  4771. var fNameCell = $('<td style="overflow: hidden;"></td>');
  4772. var fName = $('<div style="overflow:hidden; white-space:nowrap;" title="' + file.name + '"></div>');
  4773. fName.append(fFun);
  4774. fName.append(file.name);
  4775. fName.appendTo(fNameCell);
  4776. node.append(fNameCell);
  4777. 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>');
  4778. <?php if ($sharePoint) : ?>
  4779. 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>');
  4780. <?php endif; ?>
  4781. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:right;">' + file.sizeStr + '</td>');
  4782. node.append('<td style="overflow:hidden; white-space:nowrap;">' + file.created + '</td>');
  4783. node.appendTo(fileListNode);
  4784. $(fFun).click(function(e){
  4785. var n = $(e.target);
  4786. var fname= n.data('filename');
  4787. if (!fname) {
  4788. return false;
  4789. }
  4790. if (confirm('Czy jesteś pewien, że chcesz usunąć plik o nazwie ' + fname + '?')) {
  4791. var postData = {filename: fname};
  4792. jQuery.ajax({
  4793. 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; ?>',
  4794. type: 'POST',
  4795. //dataType: 'json',
  4796. //contentType: "application/json; charset=utf-8",
  4797. data: postData,
  4798. async: true,
  4799. success: function(data) {
  4800. if (data && data.type) {
  4801. if (data.type == 'SUCCESS') {
  4802. n.parents('tr').remove();
  4803. //console.log('TODO: SUCCESS msg: ', data.string);
  4804. }
  4805. else if (data.type == 'ERROR') {
  4806. //console.log('TODO: ERROR msg: ', data.string);
  4807. }
  4808. } else {
  4809. if (priv.options.debug) console.log('TODO: ??? data: ', data);
  4810. }
  4811. },
  4812. error: function(jhr, textStatus, errorThrown) {
  4813. if (priv.options.debug) console.log('rm error: ', errorThrown, ' textStatus: ', textStatus);
  4814. }
  4815. });
  4816. }
  4817. });
  4818. });
  4819. }
  4820. function connTblListUpdateAjax<?php echo $this->_htmlID; ?>(connTblID) {
  4821. var postData = {};
  4822. // clear current file list
  4823. jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list').empty();
  4824. jQuery.ajax({
  4825. 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,
  4826. type: 'POST',
  4827. //dataType: 'json',
  4828. //contentType: "application/json; charset=utf-8",
  4829. data: postData,
  4830. async: true,
  4831. success: function(data) {
  4832. connTblListUpdate<?php echo $this->_htmlID; ?>(data);
  4833. },
  4834. error: function(jqXHR, textStatus, errorThrown) {
  4835. var txt = jqXHR.responseText || 'Error';
  4836. 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>');
  4837. if (priv.options.debug) console.log('connTblListUpdateAjax error: ', errorThrown, ' textStatus: ', textStatus);
  4838. }
  4839. });
  4840. }
  4841. function connTblListUpdate<?php echo $this->_htmlID; ?>(fileListJson) {
  4842. var fileListNode = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list');
  4843. fileListNode.empty();
  4844. fileListJson.map(function(file){
  4845. var node = $('<tr></tr>');
  4846. var fNameCell = $('<td style="overflow: hidden;"></td>');
  4847. var fName = $('<div style="overflow:hidden; white-space:nowrap;" title="' + file.name + '"></div>');
  4848. fName.append(file.name);
  4849. fName.appendTo(fNameCell);
  4850. node.append(fNameCell);
  4851. 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>');
  4852. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:right;">' + file.sizeStr + '</td>');
  4853. node.append('<td style="overflow:hidden; white-space:nowrap;">' + file.created + '</td>');
  4854. node.appendTo(fileListNode);
  4855. });
  4856. }
  4857. function fileListActions<?php echo $this->_htmlID; ?>() {
  4858. var filePermsReload = jQuery('#FILES_LIST_ACTIONS_<?php echo $this->_htmlID; ?>');
  4859. 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>');
  4860. btnReload.on('click', function(e) {
  4861. //console.log('TODO: click reload perms...');
  4862. function notifyAjaxCallback(data) {
  4863. var notify = {};
  4864. notify.type = (data && data.type)? data.type : '';
  4865. notify.msg = (data && data.msg)? data.msg : '';
  4866. switch (notify.type) {
  4867. case 'success':
  4868. if (!notify.msg) notify.msg = 'OK';
  4869. break;
  4870. case 'info':
  4871. if (!notify.msg) notify.msg = '';
  4872. break;
  4873. case 'error':
  4874. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  4875. break;
  4876. case 'warning':
  4877. notify.type = 'warn';
  4878. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  4879. break;
  4880. default:
  4881. notify.msg = 'Nieznany błąd';
  4882. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  4883. notify.type = '';
  4884. }
  4885. jQuery.notify(notify.msg, notify.type);
  4886. }
  4887. var reqData = {};
  4888. jQuery.ajax({
  4889. data: reqData,
  4890. dataType: 'json',
  4891. type: "GET",
  4892. 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; ?>',
  4893. })
  4894. .done(function(data, textStatus, jqXHR){
  4895. notifyAjaxCallback(data);
  4896. if (data && data.files) {
  4897. fileListUpdate<?php echo $this->_htmlID; ?>(data.files);
  4898. }
  4899. })
  4900. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  4901. if (jqXHR.responseJSON) {
  4902. notifyAjaxCallback(jqXHR.responseJSON);
  4903. }
  4904. else {
  4905. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  4906. if (jqXHR.status == 404) {
  4907. jQuery.notify(jqXHR.responseText, 'error');
  4908. } else {
  4909. jQuery.notify(jqXHR.responseText, 'warn');
  4910. }
  4911. }
  4912. });
  4913. });
  4914. filePermsReload.append(btnReload);
  4915. }
  4916. jQuery(document).ready(function(){
  4917. $('#FILES_TAB_<?php echo $this->_htmlID; ?> a').click(function(e) {
  4918. e.preventDefault();
  4919. $(this).tab('show');
  4920. })
  4921. .on('shown.bs.tab', function(e) {
  4922. var fileSource = $(e.target).data('toggle')
  4923. , frm = jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>').get(0);
  4924. if (frm['M_DIST_UPLOAD_SOURCE']) {
  4925. frm['M_DIST_UPLOAD_SOURCE'].value = fileSource;
  4926. }
  4927. })
  4928. jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>').ajaxForm({
  4929. 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; ?>',
  4930. beforeSubmit: function(args, $form, options) {
  4931. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit()...');
  4932. var argsMap = [];
  4933. args.map(function(v, k) {
  4934. argsMap[v.name] = v.value;
  4935. });
  4936. // validate
  4937. if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'local') {
  4938. if (!argsMap['M_DIST_FILES_NAME']) {
  4939. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit() M_DIST_UPLOAD_SOURCE=local && !M_DIST_FILES_NAME');
  4940. return false;
  4941. }
  4942. }
  4943. else if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'scan') {
  4944. if (!argsMap['SCANS_COLUMN_ADD']) {
  4945. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit() M_DIST_UPLOAD_SOURCE=scan && !SCANS_COLUMN_ADD');
  4946. return false;
  4947. }
  4948. }
  4949. else {
  4950. return false;
  4951. }
  4952. var $out = $('#FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>');
  4953. $out.html('Wysyłanie...');
  4954. },
  4955. success: function(data) {
  4956. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->success()...');
  4957. var $out = $('#FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>');
  4958. var btnClose = '<button type="button" class="close" data-dismiss="alert"><i class="glyphicon glyphicon-remove"></i></button>';
  4959. if (typeof data == 'object') {
  4960. if (data.type == 'ERROR') {
  4961. $out.html('<div class="alert alert-danger">' + btnClose + data.string + '</div>');
  4962. } else if (data.type == 'SUCCESS') {
  4963. $out.html('<div class="alert alert-success">' + btnClose + data.string + '</div>');
  4964. fileListUpdateAjax<?php echo $this->_htmlID; ?>();
  4965. }
  4966. } else {
  4967. if (data.substr(0, 7) == 'WARNING') {
  4968. data = data.substr(7);
  4969. $out.html('<div class="alert alert-warning">' + btnClose + data + '</div>');
  4970. } else if (data.substr(0, 5) == 'ERROR') {
  4971. data = data.substr(5);
  4972. $out.html('<div class="alert alert-danger">' + btnClose + data + '</div>');
  4973. } else if (data.substr(0, 7) == 'SUCCESS') {
  4974. data = data.substr(7);
  4975. $out.html('<div class="alert alert-success">' + btnClose + data + '</div>');
  4976. fileListUpdateAjax<?php echo $this->_htmlID; ?>();
  4977. } else if (data.substr(0, 4) == 'INFO') {
  4978. data = data.substr(4);
  4979. $out.html('<div class="alert alert-info">' + btnClose + data + '</div>');
  4980. }
  4981. }
  4982. }
  4983. });
  4984. fileListActions<?php echo $this->_htmlID; ?>();
  4985. var fileList = <?php echo json_encode($jsonFiles); ?>;
  4986. fileListUpdate<?php echo $this->_htmlID; ?>(fileList);
  4987. var connTbls = <?php echo json_encode($this->getConnectedTables()); ?>;
  4988. if (connTbls) {
  4989. var connTblsOut = '';
  4990. for(var key in connTbls) {
  4991. connTblsOut += '<button class="btn btn-sm btn-default conn-tbl-load" data-zasobid="' + key + '">' + connTbls[key] + '</button>';
  4992. };
  4993. if (connTblsOut) {
  4994. connTblsOut = 'Pliki w powiązanych tabelach: <div class="btn-group">' + connTblsOut + '</div>';
  4995. connTblsOut += '<div style="max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">' +
  4996. '<table class="table table-bordered table-hover">' +
  4997. '<colgroup>' +
  4998. '<col style="">' +
  4999. '<col style="width:30px;">' +
  5000. <?php if ($sharePoint) : ?>
  5001. '<col style="width:30px;">' +
  5002. <?php endif; ?>
  5003. '<col style="width:80px;">' +
  5004. '<col style="width:140px;">' +
  5005. '</colgroup>' +
  5006. '<tbody class="files-list">' +
  5007. '</tbody>' +
  5008. '</table>' +
  5009. '</div>';
  5010. var _connTblsWrap = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>');
  5011. _connTblsWrap.css('marginBottom', '26px');
  5012. _connTblsWrap.html(connTblsOut);
  5013. _connTblsWrap.find('.conn-tbl-load').each(function(){
  5014. jQuery(this).click(function(e){
  5015. var tblID = jQuery(e.target).data('zasobid');
  5016. if (tblID) {
  5017. connTblListUpdateAjax<?php echo $this->_htmlID; ?>(tblID);
  5018. }// TODO: else show error
  5019. });
  5020. });
  5021. }
  5022. }
  5023. initDateTimePicker(jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>'));
  5024. });
  5025. </script>
  5026. <?php
  5027. exit;
  5028. }
  5029. private function sendTypeSpecial($fldID, $args) {
  5030. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  5031. header("Content-type: application/json");
  5032. $fldName = '';
  5033. $fld = $this->_acl->getField($fldID);
  5034. 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>';}
  5035. if (!$fld) {
  5036. // 404
  5037. } else {
  5038. $fldName = $fld['name'];
  5039. }
  5040. $jsonData = array();
  5041. $typeSpecial = Typespecial::getInstance($fldID, $fldName);
  5042. if ($typeSpecial) {
  5043. $query = V::get('q', '', $_REQUEST);
  5044. $rawRows = null;
  5045. $rows = $typeSpecial->getValuesWithExports($query);
  5046. 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>';}
  5047. foreach ($rows as $kID => $vItem) {
  5048. $itemJson = new stdClass();
  5049. $itemJson->id = $vItem->id;
  5050. $itemJson->name = $vItem->param_out;
  5051. if (!empty($vItem->exports)) {
  5052. $itemJson->exports = $vItem->exports;
  5053. }
  5054. $jsonData[] = $itemJson;
  5055. }
  5056. }
  5057. /*
  5058. MENU_INIT:VIEWTABLE_AJAX
  5059. ZASOB_ID:1188
  5060. _task:TYPESPECIAL
  5061. fldID:3866
  5062. Form Dataview sourceview URL encoded
  5063. q:te
  5064. */
  5065. echo json_encode($jsonData);
  5066. exit;
  5067. }
  5068. private function sendTypeSpecialCell($id, $fldName, $args) {
  5069. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  5070. header("Content-type: application/json");
  5071. $jsonData = new stdClass();
  5072. $fldID = $this->_acl->getFieldIdByName($fldName);
  5073. 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>';}
  5074. $item = $this->_acl->getItem($id);
  5075. if (!$this->_acl->isAllowed($fldID, 'R', $item)) {
  5076. $jsonData->msg = 'Brak dostępu';
  5077. echo json_encode($jsonData);
  5078. exit;
  5079. }
  5080. if (!$fldID) {
  5081. $jsonData->msg = 'Wrong field';
  5082. echo json_encode($jsonData);
  5083. exit;
  5084. }
  5085. $typeSpecial = Typespecial::getInstance($fldID, $fldName);
  5086. if ($typeSpecial) {
  5087. $jsonData->data = $typeSpecial->getReturnData($this->_zasobID, $id, $fldName, '');
  5088. 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>';}
  5089. }
  5090. echo json_encode($jsonData);
  5091. exit;
  5092. }
  5093. private function ajaxData($args) {
  5094. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  5095. $pageSize = V::get('pageSize', $this->_pageSize, $args, 'int');
  5096. $page = V::get('page', 0, $args, 'int');
  5097. $currSortCol = V::get('currSortCol', '', $args);
  5098. $currSortFlip = V::get('currSortFlip', '', $args);
  5099. if ($page > 0) {
  5100. $page -= 1;
  5101. }
  5102. else {
  5103. }
  5104. $params = array();
  5105. $params['limit'] = $pageSize;
  5106. $params['limitstart'] = $page * $params['limit'];
  5107. $params['order_by'] = ($currSortCol)? $currSortCol : '';
  5108. $params['order_dir'] = $currSortFlip;
  5109. $filters = new stdClass();
  5110. $filters->currSortCol = $currSortCol;
  5111. $filters->currSortFlip = $currSortFlip;
  5112. foreach ($args as $k => $v) {
  5113. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  5114. $params[$k] = $v;
  5115. $filters->{$k} = $v;
  5116. }
  5117. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  5118. $params[$k] = $v;
  5119. $filters->{$k} = $v;
  5120. }
  5121. }
  5122. $this->setFilters($filters);
  5123. $vCols = $this->_acl->getVirtualFieldList();
  5124. if (!empty($vCols)) {
  5125. 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>';}
  5126. }
  5127. $visibleCols = $this->_acl->getVisibleFieldList();
  5128. 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>';}
  5129. $jsonData = new stdClass();
  5130. $jsonData->page = $page + 1;
  5131. $jsonData->pageSize = $pageSize;
  5132. $jsonData->filters = $filters;
  5133. $jsonData->cols = new stdClass();
  5134. $jsonData->uniqueCol = $this->_acl->getPrimaryKeyField();
  5135. $ind = 0;
  5136. foreach ($visibleCols as $fieldID => $col) {
  5137. $ind++;
  5138. $columnConfig = (object)array('index'=>$ind);
  5139. if (in_array($col, array('A_STATUS','A_STATUS_CURRENT','A_SERVICES_STATUS_CURRENT'))) {
  5140. $columnConfig->format = '<div class="cell-A_STATUS-{0}">{0}</div>';
  5141. }
  5142. else if (in_array($col, array('Status'))) {
  5143. // Ahmes problems Status colors
  5144. $columnConfig->format = '<div class="cell-Status-{0}">{0}</div>';
  5145. }
  5146. else if ($this->_acl->isGeomField($col)) {
  5147. $columnConfig->type = 'geom';
  5148. }
  5149. if ('' !== ($label = $this->_acl->getFieldLabel($fieldID))) {
  5150. $columnConfig->friendly = $label;
  5151. }
  5152. $colType = $this->_acl->getFieldType($col);
  5153. if ($colType) {// @see MarkTableAjaxFilterColType
  5154. if ($colType['type'] == 'date') {
  5155. //$columnConfig->type = 'date';// TODO: require datetimepicker
  5156. }
  5157. } else {// typespecial - no type
  5158. $columnConfig->type = 'special';
  5159. }
  5160. $typeSpecial = Typespecial::getInstance($fieldID, $col);
  5161. if ($typeSpecial) {
  5162. 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>';}
  5163. $columnConfig->_tsRetId = $typeSpecial->getReturnId();
  5164. if ($columnConfig->_tsRetId == 0) {
  5165. $tsParamOut = V::get('param_out', null, $typeSpecial);
  5166. if ($tsParamOut) {
  5167. $tsFormat = V::get('format', null, $tsParamOut);
  5168. $tsValues = V::get('values', null, $tsParamOut);
  5169. $tsAliases = V::get('alias', null, $tsParamOut);
  5170. if (false !== strpos($tsFormat, '<a') && !empty($tsValues) && !empty($tsAliases)) {
  5171. $tsAliasMap = array();
  5172. /* [values] => Array([ID] => 1467), [alias] => Array([1467] => ID) */
  5173. $bugTsColsNotVisible = array();
  5174. foreach ($tsValues as $kVarName => $vIdZasob) {
  5175. if (array_key_exists($vIdZasob, $tsAliases)) {
  5176. $tsAliasMap[$kVarName] = $tsAliases[$vIdZasob];
  5177. } else {
  5178. $bugTsColsNotVisible[] = "noAliasFor {$vIdZasob}";
  5179. }
  5180. if (!array_key_exists($vIdZasob, $visibleCols)) {
  5181. $bugTsColsNotVisible[] = $vIdZasob;
  5182. }
  5183. }
  5184. if (empty($bugTsColsNotVisible)) {
  5185. $tsSimpleLink = new stdClass();
  5186. $tsSimpleLink->format = $tsFormat;
  5187. $tsSimpleLink->aliasMap = $tsAliasMap;
  5188. $columnConfig->_tsSimpleLink = $tsSimpleLink;
  5189. $columnConfig->type = 'simpleLink';
  5190. } else {
  5191. $columnConfig->_tsSimpleLinkBug = $bugTsColsNotVisible;
  5192. }
  5193. }
  5194. }
  5195. }
  5196. }
  5197. // @see ajaxHiddenColsSave
  5198. if (UserProfile::isHiddenColumn($this->_zasobID, $fieldID)) {
  5199. $columnConfig->hidden = true;
  5200. }
  5201. $columnConfig->description = $this->_acl->getFieldOpis($fieldID);
  5202. $jsonData->cols->{$col} = $columnConfig;
  5203. }
  5204. $jsonData->rows = array();
  5205. $jsonData->total = $this->_acl->getTotal($params);
  5206. 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>';}
  5207. $items = $this->_acl->getItems($params);
  5208. 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>';}
  5209. // TODO: add virtual data by Typespecial
  5210. if (!empty($vCols) && !empty($items)) {
  5211. foreach ($vCols as $vColID => $vCol) {
  5212. $colType = $this->_acl->getFieldTypeById($vColID);
  5213. if ($colType) {
  5214. continue;// pomin Typespecial dla realnych komorek w bazie danych
  5215. }
  5216. $typeSpecial = Typespecial::getInstance($vColID, $vCol);
  5217. if ($typeSpecial) {
  5218. $columnConfig = V::get($vCol, null, $jsonData->cols);
  5219. if ($columnConfig && !empty($columnConfig->_tsSimpleLink)) {
  5220. // pomin simple link values - mved to js render
  5221. } else {
  5222. 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>';}
  5223. $ids = array_keys($items);
  5224. $specialValues = $typeSpecial->getValuesByIds($this->_zasobID, $ids);
  5225. 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>';}
  5226. if (!empty($specialValues)) foreach ($specialValues as $kItemID => $vValues) {
  5227. $tsValue = implode('<br>', $vValues);
  5228. 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>';}
  5229. if (!empty($items[$kItemID]->{$vCol}) && !empty($tsValue)) {
  5230. $items[$kItemID]->{$vCol} .= ": {$tsValue}";
  5231. } else {
  5232. $items[$kItemID]->{$vCol} = $tsValue;
  5233. }
  5234. }
  5235. }
  5236. }
  5237. }
  5238. }
  5239. foreach ($items as $vItem) {
  5240. // TODO: hide items without 'R'
  5241. foreach ($visibleCols as $kID => $vCol) {
  5242. // TODO: ID default 'R'
  5243. if (!$this->_acl->isAllowed($kID, 'R', $vItem)) {
  5244. $vItem->{$vCol} = '*****';
  5245. }
  5246. // null => empty string
  5247. if (!isset($vItem->{$vCol}) || (!$vItem->{$vCol} && $vItem->{$vCol} !== '0')) {
  5248. 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>';}
  5249. $vItem->{$vCol} = '';
  5250. }
  5251. }
  5252. $jsonData->rows[] = $vItem;
  5253. }
  5254. return $jsonData;
  5255. }
  5256. private function fixEmptyValueFromUser($fieldID) {// TODO: moved to TableAcl->fixEmptyValueFromUser
  5257. $value = '';
  5258. $type = $this->_acl->getFieldTypeById($fieldID);
  5259. if ($type) {
  5260. if ($type['type'] == 'date') {
  5261. $value = $type['default'];
  5262. }
  5263. // fix bug when field is unique and is null allowed: change empty string to null
  5264. if ($type['null']) {
  5265. $value = 'NULL';
  5266. }
  5267. // fix bug when field is enum and is set to '0': for php '0' is empty
  5268. if (substr($type['type'], 0, 4) == 'enum') {// && $args["f{$fieldID}"] === '0') {
  5269. if (false !== strpos($type['type'], "''")) {
  5270. // enum('', '1','2')
  5271. $value = '';
  5272. } else if (false !== strpos($type['type'], "'0'")) {
  5273. // enum('0', '1','2')
  5274. $value = '0';
  5275. } else {
  5276. $value = $type['default'];
  5277. }
  5278. }
  5279. }
  5280. return $value;
  5281. }
  5282. /**
  5283. * set hidden cols in $_SESSION['USER_PROFILE'][$this->_zasobID];
  5284. * $_SESSION['USER_PROFILE'][$this->_zasobID][fld_id] => boolean
  5285. */
  5286. private function ajaxHiddenColsSave($args) {
  5287. $response = new stdClass();
  5288. if (empty($args)) {
  5289. $response->type = 'info';
  5290. return $response;
  5291. }
  5292. UserProfile::load();
  5293. // clean up old, wrong values
  5294. if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
  5295. unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
  5296. }
  5297. $colVis = UserProfile::getHiddenCols($this->_zasobID);
  5298. $fields = $this->_acl->getFields();
  5299. foreach ($fields as $kFldId => $vFld) {
  5300. $vFldName = $vFld['name'];
  5301. if (isset($args[$vFldName])) {
  5302. if ($args[$vFldName] == 'SHOW') {
  5303. $colVis[$kFldId] = 1;
  5304. } else if ($args[$vFldName] == 'HIDE') {
  5305. $colVis[$kFldId] = 0;
  5306. }
  5307. }
  5308. }
  5309. UserProfile::setHiddenCols($this->_zasobID, $colVis);
  5310. UserProfile::save();
  5311. $response->type = 'success';
  5312. return $response;
  5313. }
  5314. private function ajaxPageSizeSave($args) {
  5315. $response = new stdClass();
  5316. if (empty($args)) {
  5317. $response->type = 'info';
  5318. return $response;
  5319. }
  5320. $pageSize = V::get('pageSize', 0, $args, 'int');
  5321. UserProfile::load();
  5322. // clean up old, wrong values
  5323. if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
  5324. unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
  5325. }
  5326. $tableAjaxSettings = UserProfile::getTableAjaxSettings();
  5327. $tableAjaxSettings['pageSize'] = $pageSize;
  5328. UserProfile::setTableAjaxSettings($tableAjaxSettings);
  5329. UserProfile::save();
  5330. $response->type = 'success';
  5331. return $response;
  5332. }
  5333. private function ajaxTheGeomSave($args) {
  5334. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  5335. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  5336. $polygon = V::get('polygon', 0, $args);
  5337. $geomFieldName = 'the_geom';
  5338. if ($primaryKey <= 0) {
  5339. throw new HttpException("Wrong param ID", 404);
  5340. }
  5341. // 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)))
  5342. $record = $this->_acl->getItem($primaryKey);
  5343. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  5344. throw new HttpException("Brak dostępu do rekordu", 403);
  5345. }
  5346. $theGeomFieldId = $this->_acl->getFieldIdByName($geomFieldName);
  5347. if (!$this->_acl->isAllowed($theGeomFieldId, 'W', $record)) {
  5348. throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  5349. }
  5350. $itemPatch = array();
  5351. $itemPatch[$geomFieldName] = "GeomFromText('{$polygon}')";
  5352. $itemPatch[$primaryKeyField] = $primaryKey;
  5353. $response = new stdClass();
  5354. try {
  5355. $affected = $this->_acl->updateItem($itemPatch);
  5356. if ($affected > 0) {
  5357. $response->type = 'success';
  5358. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  5359. } else if ($affected == 0) {
  5360. $response->type = 'info';
  5361. $response->msg = "Nie wprowadzono żadnych zmian";
  5362. }
  5363. $response->record = $this->_acl->getItem($primaryKey);
  5364. }
  5365. catch (Exception $e) {
  5366. $response->type = 'error';
  5367. $response->msg = $e->getMessage();
  5368. }
  5369. return $response;
  5370. }
  5371. private function sendAjaxResponseJson($method, $args) {
  5372. try {
  5373. $response = $this->{$method}($args);
  5374. }
  5375. catch (HttpException $e) {
  5376. $response = new stdClass();
  5377. $response->type = 'error';
  5378. $response->msg = $e->getMessage();
  5379. $response->errorCode = $e->getCode();
  5380. Http::sendHeaderByCode($e->getCode());
  5381. }
  5382. catch (Exception $e) {
  5383. $response = new stdClass();
  5384. $response->type = 'error';
  5385. $response->msg = $e->getMessage();
  5386. $response->errorCode = $e->getCode();
  5387. }
  5388. header('Content-type: application/json');
  5389. if (!$response) $response = new stdClass();
  5390. echo json_encode($response);
  5391. exit;
  5392. }
  5393. private function ajaxTheGeomRemove($args) {// ajax task 'THE_GEOM_REMOVE'
  5394. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  5395. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  5396. $geomFieldName = 'the_geom';
  5397. $response = new stdClass();
  5398. if ($primaryKey <= 0) {
  5399. throw new HttpException("Wrong param ID", 404);
  5400. }
  5401. $record = $this->_acl->getItem($primaryKey);
  5402. if (!$record) {
  5403. throw new HttpException("Nie odnaleziono rekordu nr {$primaryKey}", 404);
  5404. }
  5405. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  5406. throw new HttpException("Brak dostępu do rekordu nr {$primaryKey}", 403);
  5407. }
  5408. $theGeomFieldId = $this->_acl->getFieldIdByName($geomFieldName);
  5409. if (!$this->_acl->isAllowed($theGeomFieldId, 'W', $record)) {
  5410. throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  5411. }
  5412. if (empty($record->{$geomFieldName})) {
  5413. $response->type = 'info';
  5414. $response->msg = "Rekord nie jest powiązany z żadnym obiektem na mapie";
  5415. $response->record = $record;
  5416. return $response;
  5417. }
  5418. $itemPatch = array();
  5419. $itemPatch[$geomFieldName] = "NULL";
  5420. $itemPatch[$primaryKeyField] = $primaryKey;
  5421. $response = new stdClass();
  5422. try {
  5423. $affected = $this->_acl->updateItem($itemPatch);
  5424. if ($affected > 0) {
  5425. $response->type = 'success';
  5426. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  5427. } else if ($affected == 0) {
  5428. $response->type = 'info';
  5429. $response->msg = "Nie wprowadzono żadnych zmian";
  5430. }
  5431. $response->record = $this->_acl->getItem($primaryKey);
  5432. }
  5433. catch (Exception $e) {
  5434. $response->type = 'error';
  5435. $response->msg = $e->getMessage();
  5436. }
  5437. return $response;
  5438. }
  5439. private function ajaxProcesInitFiltr($args) {// ajax task 'PROCES_INIT_FILTR'
  5440. $response = new stdClass();
  5441. $pInitList = array();// [proces_init_id] => label (DESC)
  5442. if (!$this->_showProcesInit) {
  5443. $response->type = 'error';
  5444. return $response;
  5445. }
  5446. $userAcl = User::getAcl();
  5447. $pInitList = $userAcl->getTableProcesInitList($this->_zasobID);
  5448. if (!empty($pInitList)) {
  5449. $procesIds = array_keys($pInitList);
  5450. $mapTree = ACL::getProcesInitMapTreeOnlyIds($procesIds);
  5451. DBG::_('DBG_MAP', '1', "mapTree", $mapTree, __CLASS__, __FUNCTION__, __LINE__);
  5452. DBG::_('DBG_MAP', '1', "pInitList", $pInitList, __CLASS__, __FUNCTION__, __LINE__);
  5453. $pInitListSelected = $this->getProcesInitSelected();
  5454. $response->pInitData = new stdClass();
  5455. $response->pInitData->pInitList = $pInitList;
  5456. $response->pInitData->mapTree = $mapTree;
  5457. $response->pInitData->pInitListSelected = $pInitListSelected;
  5458. }
  5459. $response->type = 'success';
  5460. return $response;
  5461. }
  5462. function ajaxMoreFunctionsCell($args) {// ajax task 'MORE_FUNCTIONS_CELL'
  5463. $id = V::get('ID', 0, $args, 'int');
  5464. if ($id <= 0) throw new HttpException("404", 404);
  5465. $response = new stdClass();
  5466. $response->type = 'success';
  5467. $response->msg = 'Funkcje';
  5468. $response->rowFunctions = [];
  5469. $tableName = $this->_acl->getName();
  5470. if(1){// TODO: fetch $totalMsgs from TableMsgs
  5471. $msgs = Router::getRoute('Msgs');
  5472. $msgsList = $msgs->getActiveMessagesForTableRecord($tableName, $id);
  5473. $totalMsgs = count($msgsList);
  5474. $rowFunc = new stdClass();
  5475. $rowFunc->id = 'msgs';
  5476. $rowFunc->ico = 'glyphicon glyphicon-envelope';
  5477. $rowFunc->href = 'index.php?_route=TableMsgs&_task=tableRow&idTable=' . $this->_zasobID . '&idRow=' . $id;
  5478. $rowFunc->title = "Wiadomości ({$totalMsgs})";
  5479. $rowFunc->label = "Wiadomości <span class=\"badge\">{$totalMsgs}</span>";
  5480. $response->rowFunctions[] = $rowFunc;
  5481. }
  5482. if ('CRM_PROCES' == $this->_acl->getName()) {// TODO: mv to table gui xml or php class
  5483. $record = $this->_acl->getItem($id);
  5484. // procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id=22001
  5485. $rowFunc = new stdClass();
  5486. $rowFunc->ico = 'glyphicon glyphicon-eye-open';
  5487. $rowFunc->href = "procesy5.php?task=CRM_PROCES&filtr_id={$id}";
  5488. $rowFunc->title = "Zobacz na drzewie procesów {{$id}}";
  5489. $response->rowFunctions[] = $rowFunc;
  5490. $wskazniki = ProcesHelper::get_wskazniki($id);
  5491. $connectedZasobyTotal = count($wskazniki);
  5492. $rowFunc = new stdClass();
  5493. $rowFunc->ico = 'glyphicon glyphicon-random';
  5494. $rowFunc->href = "index.php?MENU_INIT=PROCES_ADD_ZASOB&procesID={$id}";
  5495. $rowFunc->title = "Powiązane zasoby <span class=\"badge\">{$connectedZasobyTotal}</span>";
  5496. $response->rowFunctions[] = $rowFunc;
  5497. }
  5498. if ('CRM_LISTA_ZASOBOW' == $this->_acl->getName()) {// TODO: mv to table gui xml or php class
  5499. $record = $this->_acl->getItem($id);
  5500. // procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id=22001
  5501. $rowFunc = new stdClass();
  5502. $rowFunc->ico = 'glyphicon glyphicon-eye-open';
  5503. $rowFunc->href = "procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id={$id}";
  5504. $rowFunc->title = "Zobacz na drzewie zasobów [{$id}]";
  5505. $response->rowFunctions[] = $rowFunc;
  5506. // index.php?MENU_INIT=ZASOB_OBOWIAZKI&id_zasob=22001
  5507. $rowFunc = new stdClass();
  5508. $rowFunc->ico = 'glyphicon glyphicon-random';
  5509. $rowFunc->href = "index.php?MENU_INIT=ZASOB_OBOWIAZKI&id_zasob={$id}";
  5510. $rowFunc->title = "Powiązane procesy (OB)";
  5511. $response->rowFunctions[] = $rowFunc;
  5512. // index.php?MENU_INIT=ZASOB_EXTERNAL_IDS&id_zasob=22001
  5513. $rowFunc = new stdClass();
  5514. $rowFunc->ico = 'glyphicon glyphicon-random';
  5515. $rowFunc->href = "index.php?MENU_INIT=ZASOB_EXTERNAL_IDS&id_zasob={$id}";
  5516. $rowFunc->title = "Powiązane dane (IDS)";
  5517. $response->rowFunctions[] = $rowFunc;
  5518. $groupTypeList = array();
  5519. $groupTypeList[] = 'STANOWISKO';
  5520. $groupTypeList[] = 'PODMIOT';
  5521. $groupTypeList[] = 'DZIAL';
  5522. if (in_array($record->TYPE, $groupTypeList)) {
  5523. $rowFunc = new stdClass();
  5524. $rowFunc->ico = 'glyphicon glyphicon-retweet';
  5525. $rowFunc->href = "index.php?_route=Users&_task=syncGroup&idGroup={$id}";
  5526. $rowFunc->title = "Synchronizuj do LDAP";
  5527. $response->rowFunctions[] = $rowFunc;
  5528. }
  5529. }
  5530. if ('ADMIN_USERS' == $this->_acl->getName()) {// TODO: mv to table gui xml
  5531. $record = $this->_acl->getItem($id);
  5532. $isAllowedoReadUserLogin = false;
  5533. if ($this->_acl->canReadRecord($record)) {
  5534. $idFieldUserLogin = $this->_acl->getFieldIdByName('ADM_ACCOUNT');
  5535. if ($idFieldUserLogin) {
  5536. if ($this->_acl->isAllowed($idFieldUserLogin, 'R', $record)) {
  5537. $isAllowedoReadUserLogin = true;
  5538. }
  5539. }
  5540. }
  5541. if ($isAllowedoReadUserLogin) {
  5542. $rowFunc = new stdClass();
  5543. $rowFunc->ico = 'glyphicon glyphicon-user';
  5544. $rowFunc->href = 'index.php?_route=Users&_task=userGroups&usrLogin=' . $record->ADM_ACCOUNT;
  5545. $rowFunc->title = "Ustal stanowisko";
  5546. $response->rowFunctions[] = $rowFunc;
  5547. $rowFunc = new stdClass();
  5548. $rowFunc->ico = 'glyphicon glyphicon-retweet';
  5549. $rowFunc->href = 'index.php?_route=Users&_task=syncUser&usrLogin=' . $record->ADM_ACCOUNT;
  5550. $rowFunc->title = "Synchronizuj do LDAP";
  5551. $response->rowFunctions[] = $rowFunc;
  5552. $rowFunc = new stdClass();
  5553. $rowFunc->ico = 'glyphicon glyphicon-minus';
  5554. $rowFunc->href = 'index.php?MENU_INIT=USER_OCENA_PRACOWNIKA&usrLogin=' . $record->ADM_ACCOUNT;
  5555. $rowFunc->title = "Ocena pracownika";
  5556. $response->rowFunctions[] = $rowFunc;
  5557. }
  5558. }
  5559. return $response;
  5560. }
  5561. }