attributedef.class.inc.php 161 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826
  1. <?php
  2. // Copyright (C) 2010-2015 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Typology for the attributes
  20. *
  21. * @copyright Copyright (C) 2010-2015 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. require_once('MyHelpers.class.inc.php');
  25. require_once('ormdocument.class.inc.php');
  26. require_once('ormstopwatch.class.inc.php');
  27. require_once('ormpassword.class.inc.php');
  28. require_once('ormcaselog.class.inc.php');
  29. /**
  30. * MissingColumnException - sent if an attribute is being created but the column is missing in the row
  31. *
  32. * @package iTopORM
  33. */
  34. class MissingColumnException extends Exception
  35. {}
  36. /**
  37. * add some description here...
  38. *
  39. * @package iTopORM
  40. */
  41. define('EXTKEY_RELATIVE', 1);
  42. /**
  43. * add some description here...
  44. *
  45. * @package iTopORM
  46. */
  47. define('EXTKEY_ABSOLUTE', 2);
  48. /**
  49. * Propagation of the deletion through an external key - ask the user to delete the referencing object
  50. *
  51. * @package iTopORM
  52. */
  53. define('DEL_MANUAL', 1);
  54. /**
  55. * Propagation of the deletion through an external key - ask the user to delete the referencing object
  56. *
  57. * @package iTopORM
  58. */
  59. define('DEL_AUTO', 2);
  60. /**
  61. * Fully silent delete... not yet implemented
  62. */
  63. define('DEL_SILENT', 2);
  64. /**
  65. * For HierarchicalKeys only: move all the children up one level automatically
  66. */
  67. define('DEL_MOVEUP', 3);
  68. /**
  69. * For Link sets: tracking_level
  70. *
  71. * @package iTopORM
  72. */
  73. define('ATTRIBUTE_TRACKING_NONE', 0); // Do not track changes of the attribute
  74. define('ATTRIBUTE_TRACKING_ALL', 3); // Do track all changes of the attribute
  75. define('LINKSET_TRACKING_NONE', 0); // Do not track changes in the link set
  76. define('LINKSET_TRACKING_LIST', 1); // Do track added/removed items
  77. define('LINKSET_TRACKING_DETAILS', 2); // Do track modified items
  78. define('LINKSET_TRACKING_ALL', 3); // Do track added/removed/modified items
  79. define('LINKSET_EDITMODE_NONE', 0); // The linkset cannot be edited at all from inside this object
  80. define('LINKSET_EDITMODE_ADDONLY', 1); // The only possible action is to open a new window to create a new object
  81. define('LINKSET_EDITMODE_ACTIONS', 2); // Show the usual 'Actions' popup menu
  82. define('LINKSET_EDITMODE_INPLACE', 3); // The "linked" objects can be created/modified/deleted in place
  83. define('LINKSET_EDITMODE_ADDREMOVE', 4); // The "linked" objects can be added/removed in place
  84. /**
  85. * Attribute definition API, implemented in and many flavours (Int, String, Enum, etc.)
  86. *
  87. * @package iTopORM
  88. */
  89. abstract class AttributeDefinition
  90. {
  91. public function GetType()
  92. {
  93. return Dict::S('Core:'.get_class($this));
  94. }
  95. public function GetTypeDesc()
  96. {
  97. return Dict::S('Core:'.get_class($this).'+');
  98. }
  99. abstract public function GetEditClass();
  100. protected $m_sCode;
  101. private $m_aParams = array();
  102. protected $m_sHostClass = '!undefined!';
  103. public function Get($sParamName) {return $this->m_aParams[$sParamName];}
  104. protected function IsParam($sParamName) {return (array_key_exists($sParamName, $this->m_aParams));}
  105. protected function GetOptional($sParamName, $default)
  106. {
  107. if (array_key_exists($sParamName, $this->m_aParams))
  108. {
  109. return $this->m_aParams[$sParamName];
  110. }
  111. else
  112. {
  113. return $default;
  114. }
  115. }
  116. public function __construct($sCode, $aParams)
  117. {
  118. $this->m_sCode = $sCode;
  119. $this->m_aParams = $aParams;
  120. $this->ConsistencyCheck();
  121. }
  122. public function GetParams()
  123. {
  124. return $this->m_aParams;
  125. }
  126. public function SetHostClass($sHostClass)
  127. {
  128. $this->m_sHostClass = $sHostClass;
  129. }
  130. public function GetHostClass()
  131. {
  132. return $this->m_sHostClass;
  133. }
  134. public function ListSubItems()
  135. {
  136. $aSubItems = array();
  137. foreach(MetaModel::ListAttributeDefs($this->m_sHostClass) as $sAttCode => $oAttDef)
  138. {
  139. if ($oAttDef instanceof AttributeSubItem)
  140. {
  141. if ($oAttDef->Get('target_attcode') == $this->m_sCode)
  142. {
  143. $aSubItems[$sAttCode] = $oAttDef;
  144. }
  145. }
  146. }
  147. return $aSubItems;
  148. }
  149. // Note: I could factorize this code with the parameter management made for the AttributeDef class
  150. // to be overloaded
  151. static public function ListExpectedParams()
  152. {
  153. return array();
  154. }
  155. private function ConsistencyCheck()
  156. {
  157. // Check that any mandatory param has been specified
  158. //
  159. $aExpectedParams = $this->ListExpectedParams();
  160. foreach($aExpectedParams as $sParamName)
  161. {
  162. if (!array_key_exists($sParamName, $this->m_aParams))
  163. {
  164. $aBacktrace = debug_backtrace();
  165. $sTargetClass = $aBacktrace[2]["class"];
  166. $sCodeInfo = $aBacktrace[1]["file"]." - ".$aBacktrace[1]["line"];
  167. throw new Exception("ERROR missing parameter '$sParamName' in ".get_class($this)." declaration for class $sTargetClass ($sCodeInfo)");
  168. }
  169. }
  170. }
  171. // table, key field, name field
  172. public function ListDBJoins()
  173. {
  174. return "";
  175. // e.g: return array("Site", "infrid", "name");
  176. }
  177. public function GetFinalAttDef()
  178. {
  179. return $this;
  180. }
  181. public function IsDirectField() {return false;}
  182. public function IsScalar() {return false;}
  183. public function IsLinkSet() {return false;}
  184. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return false;}
  185. public function IsHierarchicalKey() {return false;}
  186. public function IsExternalField() {return false;}
  187. public function IsWritable() {return false;}
  188. public function LoadInObject() {return true;}
  189. public function AlwaysLoadInTables() {return $this->GetOptional('always_load_in_tables', false);}
  190. public function GetValue($oHostObject){return null;} // must return the value if LoadInObject returns false
  191. public function IsNullAllowed() {return true;}
  192. public function GetCode() {return $this->m_sCode;}
  193. public function GetMirrorLinkAttribute() {return null;}
  194. /**
  195. * Helper to browse the hierarchy of classes, searching for a label
  196. */
  197. protected function SearchLabel($sDictEntrySuffix, $sDefault, $bUserLanguageOnly)
  198. {
  199. $sLabel = Dict::S('Class:'.$this->m_sHostClass.$sDictEntrySuffix, '', $bUserLanguageOnly);
  200. if (strlen($sLabel) == 0)
  201. {
  202. // Nothing found: go higher in the hierarchy (if possible)
  203. //
  204. $sLabel = $sDefault;
  205. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  206. if ($sParentClass)
  207. {
  208. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  209. {
  210. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  211. $sLabel = $oAttDef->SearchLabel($sDictEntrySuffix, $sDefault, $bUserLanguageOnly);
  212. }
  213. }
  214. }
  215. return $sLabel;
  216. }
  217. public function GetLabel($sDefault = null)
  218. {
  219. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode, null, true /*user lang*/);
  220. if (is_null($sLabel))
  221. {
  222. // If no default value is specified, let's define the most relevant one for developping purposes
  223. if (is_null($sDefault))
  224. {
  225. $sDefault = str_replace('_', ' ', $this->m_sCode);
  226. }
  227. // Browse the hierarchy again, accepting default (english) translations
  228. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode, $sDefault, false);
  229. }
  230. return $sLabel;
  231. }
  232. /**
  233. * Get the label corresponding to the given value (in plain text)
  234. * To be overloaded for localized enums
  235. */
  236. public function GetValueLabel($sValue)
  237. {
  238. return $sValue;
  239. }
  240. /**
  241. * Get the value from a given string (plain text, CSV import)
  242. * Return null if no match could be found
  243. */
  244. public function MakeValueFromString($sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  245. {
  246. return $this->MakeRealValue($sProposedValue, null);
  247. }
  248. public function GetLabel_Obsolete()
  249. {
  250. // Written for compatibility with a data model written prior to version 0.9.1
  251. if (array_key_exists('label', $this->m_aParams))
  252. {
  253. return $this->m_aParams['label'];
  254. }
  255. else
  256. {
  257. return $this->GetLabel();
  258. }
  259. }
  260. public function GetDescription($sDefault = null)
  261. {
  262. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'+', null, true /*user lang*/);
  263. if (is_null($sLabel))
  264. {
  265. // If no default value is specified, let's define the most relevant one for developping purposes
  266. if (is_null($sDefault))
  267. {
  268. $sDefault = '';
  269. }
  270. // Browse the hierarchy again, accepting default (english) translations
  271. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'+', $sDefault, false);
  272. }
  273. return $sLabel;
  274. }
  275. public function GetHelpOnEdition($sDefault = null)
  276. {
  277. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'?', null, true /*user lang*/);
  278. if (is_null($sLabel))
  279. {
  280. // If no default value is specified, let's define the most relevant one for developping purposes
  281. if (is_null($sDefault))
  282. {
  283. $sDefault = '';
  284. }
  285. // Browse the hierarchy again, accepting default (english) translations
  286. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'?', $sDefault, false);
  287. }
  288. return $sLabel;
  289. }
  290. public function GetHelpOnSmartSearch()
  291. {
  292. $aParents = array_merge(array(get_class($this) => get_class($this)), class_parents($this));
  293. foreach ($aParents as $sClass)
  294. {
  295. $sHelp = Dict::S("Core:$sClass?SmartSearch", '-missing-');
  296. if ($sHelp != '-missing-')
  297. {
  298. return $sHelp;
  299. }
  300. }
  301. return '';
  302. }
  303. public function GetDescription_Obsolete()
  304. {
  305. // Written for compatibility with a data model written prior to version 0.9.1
  306. if (array_key_exists('description', $this->m_aParams))
  307. {
  308. return $this->m_aParams['description'];
  309. }
  310. else
  311. {
  312. return $this->GetDescription();
  313. }
  314. }
  315. public function GetTrackingLevel()
  316. {
  317. return $this->GetOptional('tracking_level', ATTRIBUTE_TRACKING_ALL);
  318. }
  319. public function GetValuesDef() {return null;}
  320. public function GetPrerequisiteAttributes() {return array();}
  321. public function GetNullValue() {return null;}
  322. public function IsNull($proposedValue) {return is_null($proposedValue);}
  323. public function MakeRealValue($proposedValue, $oHostObj) {return $proposedValue;} // force an allowed value (type conversion and possibly forces a value as mySQL would do upon writing!)
  324. public function Equals($val1, $val2) {return ($val1 == $val2);}
  325. public function GetSQLExpressions($sPrefix = '') {return array();} // returns suffix/expression pairs (1 in most of the cases), for READING (Select)
  326. public function FromSQLToValue($aCols, $sPrefix = '') {return null;} // returns a value out of suffix/value pairs, for SELECT result interpretation
  327. public function GetSQLColumns($bFullSpec = false) {return array();} // returns column/spec pairs (1 in most of the cases), for STRUCTURING (DB creation)
  328. public function GetSQLValues($value) {return array();} // returns column/value pairs (1 in most of the cases), for WRITING (Insert, Update)
  329. public function RequiresIndex() {return false;}
  330. public function GetOrderBySQLExpressions($sClassAlias)
  331. {
  332. // Note: This is the responsibility of this function to place backticks around column aliases
  333. return array('`'.$sClassAlias.$this->GetCode().'`');
  334. }
  335. public function GetOrderByHint()
  336. {
  337. return '';
  338. }
  339. // Import - differs slightly from SQL input, but identical in most cases
  340. //
  341. public function GetImportColumns() {return $this->GetSQLColumns();}
  342. public function FromImportToValue($aCols, $sPrefix = '')
  343. {
  344. $aValues = array();
  345. foreach ($this->GetSQLExpressions($sPrefix) as $sAlias => $sExpr)
  346. {
  347. // This is working, based on the assumption that importable fields
  348. // are not computed fields => the expression is the name of a column
  349. $aValues[$sPrefix.$sAlias] = $aCols[$sExpr];
  350. }
  351. return $this->FromSQLToValue($aValues, $sPrefix);
  352. }
  353. public function GetValidationPattern()
  354. {
  355. return '';
  356. }
  357. public function CheckFormat($value)
  358. {
  359. return true;
  360. }
  361. public function GetMaxSize()
  362. {
  363. return null;
  364. }
  365. public function MakeValue()
  366. {
  367. $sComputeFunc = $this->Get("compute_func");
  368. if (empty($sComputeFunc)) return null;
  369. return call_user_func($sComputeFunc);
  370. }
  371. abstract public function GetDefaultValue();
  372. //
  373. // To be overloaded in subclasses
  374. //
  375. abstract public function GetBasicFilterOperators(); // returns an array of "opCode"=>"description"
  376. abstract public function GetBasicFilterLooseOperator(); // returns an "opCode"
  377. //abstract protected GetBasicFilterHTMLInput();
  378. abstract public function GetBasicFilterSQLExpr($sOpCode, $value);
  379. public function GetFilterDefinitions()
  380. {
  381. return array();
  382. }
  383. public function GetEditValue($sValue, $oHostObj = null)
  384. {
  385. return (string)$sValue;
  386. }
  387. /**
  388. * Helper to get a value that will be JSON encoded
  389. * The operation is the opposite to FromJSONToValue
  390. */
  391. public function GetForJSON($value)
  392. {
  393. // In most of the cases, that will be the expected behavior...
  394. return $this->GetEditValue($value);
  395. }
  396. /**
  397. * Helper to form a value, given JSON decoded data
  398. * The operation is the opposite to GetForJSON
  399. */
  400. public function FromJSONToValue($json)
  401. {
  402. // Passthrough in most of the cases
  403. return $json;
  404. }
  405. /**
  406. * Override to display the value in the GUI
  407. */
  408. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  409. {
  410. return Str::pure2html((string)$sValue);
  411. }
  412. /**
  413. * Override to export the value in XML
  414. */
  415. public function GetAsXML($sValue, $oHostObject = null, $bLocalize = true)
  416. {
  417. return Str::pure2xml((string)$sValue);
  418. }
  419. /**
  420. * Override to escape the value when read by DBObject::GetAsCSV()
  421. */
  422. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  423. {
  424. return (string)$sValue;
  425. }
  426. /**
  427. * Override to differentiate a value displayed in the UI or in the history
  428. */
  429. public function GetAsHTMLForHistory($sValue, $oHostObject = null, $bLocalize = true)
  430. {
  431. return $this->GetAsHTML($sValue, $oHostObject, $bLocalize);
  432. }
  433. /**
  434. * Get various representations of the value, for insertion into a template (e.g. in Notifications)
  435. * @param $value mixed The current value of the field
  436. * @param $sVerb string The verb specifying the representation of the value
  437. * @param $oHostObject DBObject The object
  438. * @param $bLocalize bool Whether or not to localize the value
  439. */
  440. public function GetForTemplate($value, $sVerb, $oHostObject = null, $bLocalize = true)
  441. {
  442. if ($this->IsScalar())
  443. {
  444. switch ($sVerb)
  445. {
  446. case '':
  447. return $value;
  448. case 'html':
  449. return $this->GetAsHtml($value, $oHostObject, $bLocalize);
  450. case 'label':
  451. return $this->GetEditValue($value);
  452. default:
  453. throw new Exception("Unknown verb '$sVerb' for attribute ".$this->GetCode().' in class '.get_class($oHostObj));
  454. }
  455. }
  456. return null;
  457. }
  458. public function GetAllowedValues($aArgs = array(), $sContains = '')
  459. {
  460. $oValSetDef = $this->GetValuesDef();
  461. if (!$oValSetDef) return null;
  462. return $oValSetDef->GetValues($aArgs, $sContains);
  463. }
  464. /**
  465. * Explain the change of the attribute (history)
  466. */
  467. public function DescribeChangeAsHTML($sOldValue, $sNewValue, $sLabel = null)
  468. {
  469. if (is_null($sLabel))
  470. {
  471. $sLabel = $this->GetLabel();
  472. }
  473. $sNewValueHtml = $this->GetAsHTMLForHistory($sNewValue);
  474. $sOldValueHtml = $this->GetAsHTMLForHistory($sOldValue);
  475. if($this->IsExternalKey())
  476. {
  477. $sTargetClass = $this->GetTargetClass();
  478. $sOldValueHtml = (int)$sOldValue ? MetaModel::GetHyperLink($sTargetClass, (int)$sOldValue) : null;
  479. $sNewValueHtml = (int)$sNewValue ? MetaModel::GetHyperLink($sTargetClass, (int)$sNewValue) : null;
  480. }
  481. if ( (($this->GetType() == 'String') || ($this->GetType() == 'Text')) &&
  482. (strlen($sNewValue) > strlen($sOldValue)) )
  483. {
  484. // Check if some text was not appended to the field
  485. if (substr($sNewValue,0, strlen($sOldValue)) == $sOldValue) // Text added at the end
  486. {
  487. $sDelta = $this->GetAsHTML(substr($sNewValue, strlen($sOldValue)));
  488. $sResult = Dict::Format('Change:Text_AppendedTo_AttName', $sDelta, $sLabel);
  489. }
  490. else if (substr($sNewValue, -strlen($sOldValue)) == $sOldValue) // Text added at the beginning
  491. {
  492. $sDelta = $this->GetAsHTML(substr($sNewValue, 0, strlen($sNewValue) - strlen($sOldValue)));
  493. $sResult = Dict::Format('Change:Text_AppendedTo_AttName', $sDelta, $sLabel);
  494. }
  495. else
  496. {
  497. if (strlen($sOldValue) == 0)
  498. {
  499. $sResult = Dict::Format('Change:AttName_SetTo', $sLabel, $sNewValueHtml);
  500. }
  501. else
  502. {
  503. if (is_null($sNewValue))
  504. {
  505. $sNewValueHtml = Dict::S('UI:UndefinedObject');
  506. }
  507. $sResult = Dict::Format('Change:AttName_SetTo_NewValue_PreviousValue_OldValue', $sLabel, $sNewValueHtml, $sOldValueHtml);
  508. }
  509. }
  510. }
  511. else
  512. {
  513. if (strlen($sOldValue) == 0)
  514. {
  515. $sResult = Dict::Format('Change:AttName_SetTo', $sLabel, $sNewValueHtml);
  516. }
  517. else
  518. {
  519. if (is_null($sNewValue))
  520. {
  521. $sNewValueHtml = Dict::S('UI:UndefinedObject');
  522. }
  523. $sResult = Dict::Format('Change:AttName_SetTo_NewValue_PreviousValue_OldValue', $sLabel, $sNewValueHtml, $sOldValueHtml);
  524. }
  525. }
  526. return $sResult;
  527. }
  528. /**
  529. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  530. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  531. * does nothing special, and just calls the default (loose) operator
  532. * @param string $sSearchText The search string to analyze for smart patterns
  533. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  534. * @param Hash $aParams Values of the query parameters
  535. * @return Expression The search condition to be added (AND) to the current search
  536. */
  537. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  538. {
  539. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  540. $oRightExpr = new VariableExpression($sParamName);
  541. $sOperator = $this->GetBasicFilterLooseOperator();
  542. switch ($sOperator)
  543. {
  544. case 'Contains':
  545. $aParams[$sParamName] = "%$sSearchText%";
  546. $sSQLOperator = 'LIKE';
  547. break;
  548. default:
  549. $sSQLOperator = $sOperator;
  550. $aParams[$sParamName] = $sSearchText;
  551. }
  552. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  553. return $oNewCondition;
  554. }
  555. /**
  556. * Tells if an attribute is part of the unique fingerprint of the object (used for comparing two objects)
  557. * All attributes which value is not based on a value from the object itself (like ExternalFields or LinkedSet)
  558. * must be excluded from the object's signature
  559. * @return boolean
  560. */
  561. public function IsPartOfFingerprint()
  562. {
  563. return true;
  564. }
  565. /**
  566. * The part of the current attribute in the object's signature, for the supplied value
  567. * @param unknown $value The value of this attribute for the object
  568. * @return string The "signature" for this field/attribute
  569. */
  570. public function Fingerprint($value)
  571. {
  572. return (string)$value;
  573. }
  574. }
  575. /**
  576. * Set of objects directly linked to an object, and being part of its definition
  577. *
  578. * @package iTopORM
  579. */
  580. class AttributeLinkedSet extends AttributeDefinition
  581. {
  582. static public function ListExpectedParams()
  583. {
  584. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "linked_class", "ext_key_to_me", "count_min", "count_max"));
  585. }
  586. public function GetEditClass() {return "LinkedSet";}
  587. public function IsWritable() {return true;}
  588. public function IsLinkSet() {return true;}
  589. public function IsIndirect() {return false;}
  590. public function GetValuesDef() {return $this->Get("allowed_values");}
  591. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  592. public function GetDefaultValue($aArgs = array())
  593. {
  594. // Note: so far, this feature is a prototype,
  595. // later, the argument 'this' should always be present in the arguments
  596. //
  597. if (($this->IsParam('default_value')) && array_key_exists('this', $aArgs))
  598. {
  599. $aValues = $this->Get('default_value')->GetValues($aArgs);
  600. $oSet = DBObjectSet::FromArray($this->Get('linked_class'), $aValues);
  601. return $oSet;
  602. }
  603. else
  604. {
  605. return DBObjectSet::FromScratch($this->Get('linked_class'));
  606. }
  607. }
  608. public function GetTrackingLevel()
  609. {
  610. return $this->GetOptional('tracking_level', MetaModel::GetConfig()->Get('tracking_level_linked_set_default'));
  611. }
  612. public function GetEditMode()
  613. {
  614. return $this->GetOptional('edit_mode', LINKSET_EDITMODE_ACTIONS);
  615. }
  616. public function GetLinkedClass() {return $this->Get('linked_class');}
  617. public function GetExtKeyToMe() {return $this->Get('ext_key_to_me');}
  618. public function GetBasicFilterOperators() {return array();}
  619. public function GetBasicFilterLooseOperator() {return '';}
  620. public function GetBasicFilterSQLExpr($sOpCode, $value) {return '';}
  621. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  622. {
  623. if (is_object($sValue) && ($sValue instanceof DBObjectSet))
  624. {
  625. $sValue->Rewind();
  626. $aItems = array();
  627. while ($oObj = $sValue->Fetch())
  628. {
  629. // Show only relevant information (hide the external key to the current object)
  630. $aAttributes = array();
  631. foreach(MetaModel::ListAttributeDefs($this->GetLinkedClass()) as $sAttCode => $oAttDef)
  632. {
  633. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  634. if ($oAttDef->IsExternalField()) continue;
  635. $sAttValue = $oObj->GetAsHTML($sAttCode);
  636. if (strlen($sAttValue) > 0)
  637. {
  638. $aAttributes[] = $sAttValue;
  639. }
  640. }
  641. $sAttributes = implode(', ', $aAttributes);
  642. $aItems[] = $sAttributes;
  643. }
  644. return implode('<br/>', $aItems);
  645. }
  646. return null;
  647. }
  648. public function GetAsXML($sValue, $oHostObject = null, $bLocalize = true)
  649. {
  650. if (is_object($sValue) && ($sValue instanceof DBObjectSet))
  651. {
  652. $sValue->Rewind();
  653. $sRes = "<Set>\n";
  654. while ($oObj = $sValue->Fetch())
  655. {
  656. $sObjClass = get_class($oObj);
  657. $sRes .= "<$sObjClass id=\"".$oObj->GetKey()."\">\n";
  658. // Show only relevant information (hide the external key to the current object)
  659. $aAttributes = array();
  660. foreach(MetaModel::ListAttributeDefs($sObjClass) as $sAttCode => $oAttDef)
  661. {
  662. if ($sAttCode == 'finalclass')
  663. {
  664. if ($sObjClass == $this->GetLinkedClass())
  665. {
  666. // Simplify the output if the exact class could be determined implicitely
  667. continue;
  668. }
  669. }
  670. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  671. if ($oAttDef->IsExternalField() && ($oAttDef->GetKeyAttCode() == $this->GetExtKeyToMe())) continue;
  672. if (($oAttDef instanceof AttributeFriendlyName) && ($oAttDef->GetKeyAttCode() == $this->GetExtKeyToMe())) continue;
  673. if (($oAttDef instanceof AttributeFriendlyName) && ($oAttDef->GetKeyAttCode() == 'id')) continue;
  674. if (!$oAttDef->IsScalar()) continue;
  675. $sAttValue = $oObj->GetAsXML($sAttCode, $bLocalize);
  676. $sRes .= "<$sAttCode>$sAttValue</$sAttCode>\n";
  677. }
  678. $sRes .= "</$sObjClass>\n";
  679. }
  680. $sRes .= "</Set>\n";
  681. }
  682. else
  683. {
  684. $sRes = '';
  685. }
  686. return $sRes;
  687. }
  688. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  689. {
  690. $sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator');
  691. $sSepAttribute = MetaModel::GetConfig()->Get('link_set_attribute_separator');
  692. $sSepValue = MetaModel::GetConfig()->Get('link_set_value_separator');
  693. $sAttributeQualifier = MetaModel::GetConfig()->Get('link_set_attribute_qualifier');
  694. if (is_object($sValue) && ($sValue instanceof DBObjectSet))
  695. {
  696. $sValue->Rewind();
  697. $aItems = array();
  698. while ($oObj = $sValue->Fetch())
  699. {
  700. $sObjClass = get_class($oObj);
  701. // Show only relevant information (hide the external key to the current object)
  702. $aAttributes = array();
  703. foreach(MetaModel::ListAttributeDefs($sObjClass) as $sAttCode => $oAttDef)
  704. {
  705. if ($sAttCode == 'finalclass')
  706. {
  707. if ($sObjClass == $this->GetLinkedClass())
  708. {
  709. // Simplify the output if the exact class could be determined implicitely
  710. continue;
  711. }
  712. }
  713. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  714. if ($oAttDef->IsExternalField()) continue;
  715. if (!$oAttDef->IsDirectField()) continue;
  716. if (!$oAttDef->IsScalar()) continue;
  717. $sAttValue = $oObj->GetAsCSV($sAttCode, $sSepValue, '', $bLocalize);
  718. if (strlen($sAttValue) > 0)
  719. {
  720. $sAttributeData = str_replace($sAttributeQualifier, $sAttributeQualifier.$sAttributeQualifier, $sAttCode.$sSepValue.$sAttValue);
  721. $aAttributes[] = $sAttributeQualifier.$sAttributeData.$sAttributeQualifier;
  722. }
  723. }
  724. $sAttributes = implode($sSepAttribute, $aAttributes);
  725. $aItems[] = $sAttributes;
  726. }
  727. $sRes = implode($sSepItem, $aItems);
  728. }
  729. else
  730. {
  731. $sRes = '';
  732. }
  733. $sRes = str_replace($sTextQualifier, $sTextQualifier.$sTextQualifier, $sRes);
  734. $sRes = $sTextQualifier.$sRes.$sTextQualifier;
  735. return $sRes;
  736. }
  737. /**
  738. * Get various representations of the value, for insertion into a template (e.g. in Notifications)
  739. * @param $value mixed The current value of the field
  740. * @param $sVerb string The verb specifying the representation of the value
  741. * @param $oHostObject DBObject The object
  742. * @param $bLocalize bool Whether or not to localize the value
  743. */
  744. public function GetForTemplate($value, $sVerb, $oHostObject = null, $bLocalize = true)
  745. {
  746. $sRemoteName = $this->IsIndirect() ? $this->GetExtKeyToRemote().'_friendlyname' : 'friendlyname';
  747. $oLinkSet = clone $value; // Workaround/Safety net for Trac #887
  748. $iLimit = MetaModel::GetConfig()->Get('max_linkset_output');
  749. if ($iLimit > 0)
  750. {
  751. $oLinkSet->SetLimit($iLimit);
  752. }
  753. $aNames = $oLinkSet->GetColumnAsArray($sRemoteName);
  754. if ($iLimit > 0)
  755. {
  756. $iTotal = $oLinkSet->Count();
  757. if ($iTotal > count($aNames))
  758. {
  759. $aNames[] = '... '.Dict::Format('UI:TruncatedResults', count($aNames), $iTotal);
  760. }
  761. }
  762. switch($sVerb)
  763. {
  764. case '':
  765. return implode("\n", $aNames);
  766. case 'html':
  767. return '<ul><li>'.implode("</li><li>", $aNames).'</li></ul>';
  768. default:
  769. throw new Exception("Unknown verb '$sVerb' for attribute ".$this->GetCode().' in class '.get_class($oHostObj));
  770. }
  771. }
  772. public function DuplicatesAllowed() {return false;} // No duplicates for 1:n links, never
  773. public function GetImportColumns()
  774. {
  775. $aColumns = array();
  776. $aColumns[$this->GetCode()] = 'TEXT';
  777. return $aColumns;
  778. }
  779. public function MakeValueFromString($sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  780. {
  781. if (is_null($sSepItem) || empty($sSepItem))
  782. {
  783. $sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator');
  784. }
  785. if (is_null($sSepAttribute) || empty($sSepAttribute))
  786. {
  787. $sSepAttribute = MetaModel::GetConfig()->Get('link_set_attribute_separator');
  788. }
  789. if (is_null($sSepValue) || empty($sSepValue))
  790. {
  791. $sSepValue = MetaModel::GetConfig()->Get('link_set_value_separator');
  792. }
  793. if (is_null($sAttributeQualifier) || empty($sAttributeQualifier))
  794. {
  795. $sAttributeQualifier = MetaModel::GetConfig()->Get('link_set_attribute_qualifier');
  796. }
  797. $sTargetClass = $this->Get('linked_class');
  798. $sInput = str_replace($sSepItem, "\n", $sProposedValue);
  799. $oCSVParser = new CSVParser($sInput, $sSepAttribute, $sAttributeQualifier);
  800. $aInput = $oCSVParser->ToArray(0 /* do not skip lines */);
  801. $aLinks = array();
  802. foreach($aInput as $aRow)
  803. {
  804. // 1st - get the values, split the extkey->searchkey specs, and eventually get the finalclass value
  805. $aExtKeys = array();
  806. $aValues = array();
  807. foreach($aRow as $sCell)
  808. {
  809. $iSepPos = strpos($sCell, $sSepValue);
  810. if ($iSepPos === false)
  811. {
  812. // Houston...
  813. throw new CoreException('Wrong format for link attribute specification', array('value' => $sCell));
  814. }
  815. $sAttCode = trim(substr($sCell, 0, $iSepPos));
  816. $sValue = substr($sCell, $iSepPos + strlen($sSepValue));
  817. if (preg_match('/^(.+)->(.+)$/', $sAttCode, $aMatches))
  818. {
  819. $sKeyAttCode = $aMatches[1];
  820. $sRemoteAttCode = $aMatches[2];
  821. $aExtKeys[$sKeyAttCode][$sRemoteAttCode] = $sValue;
  822. if (!MetaModel::IsValidAttCode($sTargetClass, $sKeyAttCode))
  823. {
  824. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sTargetClass, 'attcode' => $sKeyAttCode));
  825. }
  826. $oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode);
  827. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  828. if (!MetaModel::IsValidAttCode($sRemoteClass, $sRemoteAttCode))
  829. {
  830. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sRemoteClass, 'attcode' => $sRemoteAttCode));
  831. }
  832. }
  833. else
  834. {
  835. if(!MetaModel::IsValidAttCode($sTargetClass, $sAttCode))
  836. {
  837. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sTargetClass, 'attcode' => $sAttCode));
  838. }
  839. $oAttDef = MetaModel::GetAttributeDef($sTargetClass, $sAttCode);
  840. $aValues[$sAttCode] = $oAttDef->MakeValueFromString($sValue, $bLocalizedValue, $sSepItem, $sSepAttribute, $sSepValue, $sAttributeQualifier);
  841. }
  842. }
  843. // 2nd - Instanciate the object and set the value
  844. if (isset($aValues['finalclass']))
  845. {
  846. $sLinkClass = $aValues['finalclass'];
  847. if (!is_subclass_of($sLinkClass, $sTargetClass))
  848. {
  849. throw new CoreException('Wrong class for link attribute specification', array('requested_class' => $sLinkClass, 'expected_class' => $sTargetClass));
  850. }
  851. }
  852. elseif (MetaModel::IsAbstract($sTargetClass))
  853. {
  854. throw new CoreException('Missing finalclass for link attribute specification');
  855. }
  856. else
  857. {
  858. $sLinkClass = $sTargetClass;
  859. }
  860. $oLink = MetaModel::NewObject($sLinkClass);
  861. foreach ($aValues as $sAttCode => $sValue)
  862. {
  863. $oLink->Set($sAttCode, $sValue);
  864. }
  865. // 3rd - Set external keys from search conditions
  866. foreach ($aExtKeys as $sKeyAttCode => $aReconciliation)
  867. {
  868. $oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode);
  869. $sKeyClass = $oKeyAttDef->GetTargetClass();
  870. $oExtKeyFilter = new DBObjectSearch($sKeyClass);
  871. $aReconciliationDesc = array();
  872. foreach($aReconciliation as $sRemoteAttCode => $sValue)
  873. {
  874. $oExtKeyFilter->AddCondition($sRemoteAttCode, $sValue, '=');
  875. $aReconciliationDesc[] = "$sRemoteAttCode=$sValue";
  876. }
  877. $oExtKeySet = new CMDBObjectSet($oExtKeyFilter);
  878. switch($oExtKeySet->Count())
  879. {
  880. case 0:
  881. $sReconciliationDesc = implode(', ', $aReconciliationDesc);
  882. throw new CoreException("Found no match", array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc));
  883. break;
  884. case 1:
  885. $oRemoteObj = $oExtKeySet->Fetch();
  886. $oLink->Set($sKeyAttCode, $oRemoteObj->GetKey());
  887. break;
  888. default:
  889. $sReconciliationDesc = implode(', ', $aReconciliationDesc);
  890. throw new CoreException("Found several matches", array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc));
  891. // Found several matches, ambiguous
  892. }
  893. }
  894. // Check (roughly) if such a link is valid
  895. $aErrors = array();
  896. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sAttCode => $oAttDef)
  897. {
  898. if ($oAttDef->IsExternalKey())
  899. {
  900. if (($oAttDef->GetTargetClass() == $this->GetHostClass()) || (is_subclass_of($this->GetHostClass(), $oAttDef->GetTargetClass())))
  901. {
  902. continue; // Don't check the key to self
  903. }
  904. }
  905. if ($oAttDef->IsWritable() && $oAttDef->IsNull($oLink->Get($sAttCode)) && !$oAttDef->IsNullAllowed())
  906. {
  907. $aErrors[] = $sAttCode;
  908. }
  909. }
  910. if (count($aErrors) > 0)
  911. {
  912. throw new CoreException("Missing value for mandatory attribute(s): ".implode(', ', $aErrors));
  913. }
  914. $aLinks[] = $oLink;
  915. }
  916. $oSet = DBObjectSet::FromArray($sTargetClass, $aLinks);
  917. return $oSet;
  918. }
  919. /**
  920. * Helper to get a value that will be JSON encoded
  921. * The operation is the opposite to FromJSONToValue
  922. */
  923. public function GetForJSON($value)
  924. {
  925. $aRet = array();
  926. if (is_object($value) && ($value instanceof DBObjectSet))
  927. {
  928. $value->Rewind();
  929. while ($oObj = $value->Fetch())
  930. {
  931. $sObjClass = get_class($oObj);
  932. // Show only relevant information (hide the external key to the current object)
  933. $aAttributes = array();
  934. foreach(MetaModel::ListAttributeDefs($sObjClass) as $sAttCode => $oAttDef)
  935. {
  936. if ($sAttCode == 'finalclass')
  937. {
  938. if ($sObjClass == $this->GetLinkedClass())
  939. {
  940. // Simplify the output if the exact class could be determined implicitely
  941. continue;
  942. }
  943. }
  944. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  945. if ($oAttDef->IsExternalField()) continue;
  946. if (!$oAttDef->IsDirectField()) continue;
  947. if (!$oAttDef->IsScalar()) continue;
  948. $attValue = $oObj->Get($sAttCode);
  949. $aAttributes[$sAttCode] = $oAttDef->GetForJSON($attValue);
  950. }
  951. $aRet[] = $aAttributes;
  952. }
  953. }
  954. return $aRet;
  955. }
  956. /**
  957. * Helper to form a value, given JSON decoded data
  958. * The operation is the opposite to GetForJSON
  959. */
  960. public function FromJSONToValue($json)
  961. {
  962. $sTargetClass = $this->Get('linked_class');
  963. $aLinks = array();
  964. foreach($json as $aValues)
  965. {
  966. if (isset($aValues['finalclass']))
  967. {
  968. $sLinkClass = $aValues['finalclass'];
  969. if (!is_subclass_of($sLinkClass, $sTargetClass))
  970. {
  971. throw new CoreException('Wrong class for link attribute specification', array('requested_class' => $sLinkClass, 'expected_class' => $sTargetClass));
  972. }
  973. }
  974. elseif (MetaModel::IsAbstract($sTargetClass))
  975. {
  976. throw new CoreException('Missing finalclass for link attribute specification');
  977. }
  978. else
  979. {
  980. $sLinkClass = $sTargetClass;
  981. }
  982. $oLink = MetaModel::NewObject($sLinkClass);
  983. foreach ($aValues as $sAttCode => $sValue)
  984. {
  985. $oLink->Set($sAttCode, $sValue);
  986. }
  987. // Check (roughly) if such a link is valid
  988. $aErrors = array();
  989. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sAttCode => $oAttDef)
  990. {
  991. if ($oAttDef->IsExternalKey())
  992. {
  993. if (($oAttDef->GetTargetClass() == $this->GetHostClass()) || (is_subclass_of($this->GetHostClass(), $oAttDef->GetTargetClass())))
  994. {
  995. continue; // Don't check the key to self
  996. }
  997. }
  998. if ($oAttDef->IsWritable() && $oAttDef->IsNull($oLink->Get($sAttCode)) && !$oAttDef->IsNullAllowed())
  999. {
  1000. $aErrors[] = $sAttCode;
  1001. }
  1002. }
  1003. if (count($aErrors) > 0)
  1004. {
  1005. throw new CoreException("Missing value for mandatory attribute(s): ".implode(', ', $aErrors));
  1006. }
  1007. $aLinks[] = $oLink;
  1008. }
  1009. $oSet = DBObjectSet::FromArray($sTargetClass, $aLinks);
  1010. return $oSet;
  1011. }
  1012. public function Equals($val1, $val2)
  1013. {
  1014. if ($val1 === $val2) return true;
  1015. if (is_object($val1) != is_object($val2))
  1016. {
  1017. return false;
  1018. }
  1019. if (!is_object($val1))
  1020. {
  1021. // string ?
  1022. // todo = implement this case ?
  1023. return false;
  1024. }
  1025. // Both values are Object sets
  1026. return $val1->HasSameContents($val2);
  1027. }
  1028. /**
  1029. * Find the corresponding "link" attribute on the target class
  1030. *
  1031. * @return string The attribute code on the target class, or null if none has been found
  1032. */
  1033. public function GetMirrorLinkAttribute()
  1034. {
  1035. $oRemoteAtt = MetaModel::GetAttributeDef($this->GetLinkedClass(), $this->GetExtKeyToMe());
  1036. return $oRemoteAtt;
  1037. }
  1038. public function IsPartOfFingerprint() { return false; }
  1039. }
  1040. /**
  1041. * Set of objects linked to an object (n-n), and being part of its definition
  1042. *
  1043. * @package iTopORM
  1044. */
  1045. class AttributeLinkedSetIndirect extends AttributeLinkedSet
  1046. {
  1047. static public function ListExpectedParams()
  1048. {
  1049. return array_merge(parent::ListExpectedParams(), array("ext_key_to_remote"));
  1050. }
  1051. public function IsIndirect() {return true;}
  1052. public function GetExtKeyToRemote() { return $this->Get('ext_key_to_remote'); }
  1053. public function GetEditClass() {return "LinkedSet";}
  1054. public function DuplicatesAllowed() {return $this->GetOptional("duplicates", false);} // The same object may be linked several times... or not...
  1055. public function GetTrackingLevel()
  1056. {
  1057. return $this->GetOptional('tracking_level', MetaModel::GetConfig()->Get('tracking_level_linked_set_indirect_default'));
  1058. }
  1059. /**
  1060. * Find the corresponding "link" attribute on the target class
  1061. *
  1062. * @return string The attribute code on the target class, or null if none has been found
  1063. */
  1064. public function GetMirrorLinkAttribute()
  1065. {
  1066. $oRet = null;
  1067. $oExtKeyToRemote = MetaModel::GetAttributeDef($this->GetLinkedClass(), $this->GetExtKeyToRemote());
  1068. $sRemoteClass = $oExtKeyToRemote->GetTargetClass();
  1069. foreach (MetaModel::ListAttributeDefs($sRemoteClass) as $sRemoteAttCode => $oRemoteAttDef)
  1070. {
  1071. if (!$oRemoteAttDef instanceof AttributeLinkedSetIndirect) continue;
  1072. if ($oRemoteAttDef->GetLinkedClass() != $this->GetLinkedClass()) continue;
  1073. if ($oRemoteAttDef->GetExtKeyToMe() != $this->GetExtKeyToRemote()) continue;
  1074. if ($oRemoteAttDef->GetExtKeyToRemote() != $this->GetExtKeyToMe()) continue;
  1075. $oRet = $oRemoteAttDef;
  1076. break;
  1077. }
  1078. return $oRet;
  1079. }
  1080. }
  1081. /**
  1082. * Abstract class implementing default filters for a DB column
  1083. *
  1084. * @package iTopORM
  1085. */
  1086. class AttributeDBFieldVoid extends AttributeDefinition
  1087. {
  1088. static public function ListExpectedParams()
  1089. {
  1090. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "sql"));
  1091. }
  1092. // To be overriden, used in GetSQLColumns
  1093. protected function GetSQLCol($bFullSpec = false)
  1094. {
  1095. return "VARCHAR(255)".($bFullSpec ? $this->GetSQLColSpec() : '');
  1096. }
  1097. protected function GetSQLColSpec()
  1098. {
  1099. $default = $this->ScalarToSQL($this->GetDefaultValue());
  1100. if (is_null($default))
  1101. {
  1102. $sRet = '';
  1103. }
  1104. else
  1105. {
  1106. if (is_numeric($default))
  1107. {
  1108. // Though it is a string in PHP, it will be considered as a numeric value in MySQL
  1109. // Then it must not be quoted here, to preserve the compatibility with the value returned by CMDBSource::GetFieldSpec
  1110. $sRet = " DEFAULT $default";
  1111. }
  1112. else
  1113. {
  1114. $sRet = " DEFAULT ".CMDBSource::Quote($default);
  1115. }
  1116. }
  1117. return $sRet;
  1118. }
  1119. public function GetEditClass() {return "String";}
  1120. public function GetValuesDef() {return $this->Get("allowed_values");}
  1121. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  1122. public function IsDirectField() {return true;}
  1123. public function IsScalar() {return true;}
  1124. public function IsWritable() {return true;}
  1125. public function GetSQLExpr() {return $this->Get("sql");}
  1126. public function GetDefaultValue() {return $this->MakeRealValue("", null);}
  1127. public function IsNullAllowed() {return false;}
  1128. //
  1129. protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  1130. public function GetSQLExpressions($sPrefix = '')
  1131. {
  1132. $aColumns = array();
  1133. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  1134. $aColumns[''] = $this->Get("sql");
  1135. return $aColumns;
  1136. }
  1137. public function FromSQLToValue($aCols, $sPrefix = '')
  1138. {
  1139. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  1140. return $value;
  1141. }
  1142. public function GetSQLValues($value)
  1143. {
  1144. $aValues = array();
  1145. $aValues[$this->Get("sql")] = $this->ScalarToSQL($value);
  1146. return $aValues;
  1147. }
  1148. public function GetSQLColumns($bFullSpec = false)
  1149. {
  1150. $aColumns = array();
  1151. $aColumns[$this->Get("sql")] = $this->GetSQLCol($bFullSpec);
  1152. return $aColumns;
  1153. }
  1154. public function GetFilterDefinitions()
  1155. {
  1156. return array($this->GetCode() => new FilterFromAttribute($this));
  1157. }
  1158. public function GetBasicFilterOperators()
  1159. {
  1160. return array("="=>"equals", "!="=>"differs from");
  1161. }
  1162. public function GetBasicFilterLooseOperator()
  1163. {
  1164. return "=";
  1165. }
  1166. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1167. {
  1168. $sQValue = CMDBSource::Quote($value);
  1169. switch ($sOpCode)
  1170. {
  1171. case '!=':
  1172. return $this->GetSQLExpr()." != $sQValue";
  1173. break;
  1174. case '=':
  1175. default:
  1176. return $this->GetSQLExpr()." = $sQValue";
  1177. }
  1178. }
  1179. }
  1180. /**
  1181. * Base class for all kind of DB attributes, with the exception of external keys
  1182. *
  1183. * @package iTopORM
  1184. */
  1185. class AttributeDBField extends AttributeDBFieldVoid
  1186. {
  1187. static public function ListExpectedParams()
  1188. {
  1189. return array_merge(parent::ListExpectedParams(), array("default_value", "is_null_allowed"));
  1190. }
  1191. public function GetDefaultValue() {return $this->MakeRealValue($this->Get("default_value"), null);}
  1192. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  1193. }
  1194. /**
  1195. * Map an integer column to an attribute
  1196. *
  1197. * @package iTopORM
  1198. */
  1199. class AttributeInteger extends AttributeDBField
  1200. {
  1201. static public function ListExpectedParams()
  1202. {
  1203. return parent::ListExpectedParams();
  1204. //return array_merge(parent::ListExpectedParams(), array());
  1205. }
  1206. public function GetEditClass() {return "String";}
  1207. protected function GetSQLCol($bFullSpec = false) {return "INT(11)".($bFullSpec ? $this->GetSQLColSpec() : '');}
  1208. public function GetValidationPattern()
  1209. {
  1210. return "^[0-9]+$";
  1211. }
  1212. public function GetBasicFilterOperators()
  1213. {
  1214. return array(
  1215. "!="=>"differs from",
  1216. "="=>"equals",
  1217. ">"=>"greater (strict) than",
  1218. ">="=>"greater than",
  1219. "<"=>"less (strict) than",
  1220. "<="=>"less than",
  1221. "in"=>"in"
  1222. );
  1223. }
  1224. public function GetBasicFilterLooseOperator()
  1225. {
  1226. // Unless we implement an "equals approximately..." or "same order of magnitude"
  1227. return "=";
  1228. }
  1229. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1230. {
  1231. $sQValue = CMDBSource::Quote($value);
  1232. switch ($sOpCode)
  1233. {
  1234. case '!=':
  1235. return $this->GetSQLExpr()." != $sQValue";
  1236. break;
  1237. case '>':
  1238. return $this->GetSQLExpr()." > $sQValue";
  1239. break;
  1240. case '>=':
  1241. return $this->GetSQLExpr()." >= $sQValue";
  1242. break;
  1243. case '<':
  1244. return $this->GetSQLExpr()." < $sQValue";
  1245. break;
  1246. case '<=':
  1247. return $this->GetSQLExpr()." <= $sQValue";
  1248. break;
  1249. case 'in':
  1250. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  1251. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  1252. break;
  1253. case '=':
  1254. default:
  1255. return $this->GetSQLExpr()." = \"$value\"";
  1256. }
  1257. }
  1258. public function GetNullValue()
  1259. {
  1260. return null;
  1261. }
  1262. public function IsNull($proposedValue)
  1263. {
  1264. return is_null($proposedValue);
  1265. }
  1266. public function MakeRealValue($proposedValue, $oHostObj)
  1267. {
  1268. if (is_null($proposedValue)) return null;
  1269. if ($proposedValue === '') return null; // 0 is transformed into '' !
  1270. return (int)$proposedValue;
  1271. }
  1272. public function ScalarToSQL($value)
  1273. {
  1274. assert(is_numeric($value) || is_null($value));
  1275. return $value; // supposed to be an int
  1276. }
  1277. }
  1278. /**
  1279. * An external key for which the class is defined as the value of another attribute
  1280. *
  1281. * @package iTopORM
  1282. */
  1283. class AttributeObjectKey extends AttributeDBFieldVoid
  1284. {
  1285. static public function ListExpectedParams()
  1286. {
  1287. return array_merge(parent::ListExpectedParams(), array('class_attcode', 'is_null_allowed'));
  1288. }
  1289. public function GetEditClass() {return "String";}
  1290. protected function GetSQLCol($bFullSpec = false) {return "INT(11)".($bFullSpec ? " DEFAULT 0" : "");}
  1291. public function GetDefaultValue() {return 0;}
  1292. public function IsNullAllowed()
  1293. {
  1294. return $this->Get("is_null_allowed");
  1295. }
  1296. public function GetBasicFilterOperators()
  1297. {
  1298. return parent::GetBasicFilterOperators();
  1299. }
  1300. public function GetBasicFilterLooseOperator()
  1301. {
  1302. return parent::GetBasicFilterLooseOperator();
  1303. }
  1304. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1305. {
  1306. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  1307. }
  1308. public function GetNullValue()
  1309. {
  1310. return 0;
  1311. }
  1312. public function IsNull($proposedValue)
  1313. {
  1314. return ($proposedValue == 0);
  1315. }
  1316. public function MakeRealValue($proposedValue, $oHostObj)
  1317. {
  1318. if (is_null($proposedValue)) return 0;
  1319. if ($proposedValue === '') return 0;
  1320. if (MetaModel::IsValidObject($proposedValue)) return $proposedValue->GetKey();
  1321. return (int)$proposedValue;
  1322. }
  1323. }
  1324. /**
  1325. * Display an integer between 0 and 100 as a percentage / horizontal bar graph
  1326. *
  1327. * @package iTopORM
  1328. */
  1329. class AttributePercentage extends AttributeInteger
  1330. {
  1331. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  1332. {
  1333. $iWidth = 5; // Total width of the percentage bar graph, in em...
  1334. $iValue = (int)$sValue;
  1335. if ($iValue > 100)
  1336. {
  1337. $iValue = 100;
  1338. }
  1339. else if ($iValue < 0)
  1340. {
  1341. $iValue = 0;
  1342. }
  1343. if ($iValue > 90)
  1344. {
  1345. $sColor = "#cc3300";
  1346. }
  1347. else if ($iValue > 50)
  1348. {
  1349. $sColor = "#cccc00";
  1350. }
  1351. else
  1352. {
  1353. $sColor = "#33cc00";
  1354. }
  1355. $iPercentWidth = ($iWidth * $iValue) / 100;
  1356. return "<div style=\"width:{$iWidth}em;-moz-border-radius: 3px;-webkit-border-radius: 3px;border-radius: 3px;display:inline-block;border: 1px #ccc solid;\"><div style=\"width:{$iPercentWidth}em; display:inline-block;background-color:$sColor;\">&nbsp;</div></div>&nbsp;$sValue %";
  1357. }
  1358. }
  1359. /**
  1360. * Map a decimal value column (suitable for financial computations) to an attribute
  1361. * internally in PHP such numbers are represented as string. Should you want to perform
  1362. * a calculation on them, it is recommended to use the BC Math functions in order to
  1363. * retain the precision
  1364. *
  1365. * @package iTopORM
  1366. */
  1367. class AttributeDecimal extends AttributeDBField
  1368. {
  1369. static public function ListExpectedParams()
  1370. {
  1371. return array_merge(parent::ListExpectedParams(), array('digits', 'decimals' /* including precision */));
  1372. }
  1373. public function GetEditClass() {return "String";}
  1374. protected function GetSQLCol($bFullSpec = false)
  1375. {
  1376. return "DECIMAL(".$this->Get('digits').",".$this->Get('decimals').")".($bFullSpec ? $this->GetSQLColSpec() : '');
  1377. }
  1378. public function GetValidationPattern()
  1379. {
  1380. $iNbDigits = $this->Get('digits');
  1381. $iPrecision = $this->Get('decimals');
  1382. $iNbIntegerDigits = $iNbDigits - $iPrecision - 1; // -1 because the first digit is treated separately in the pattern below
  1383. return "^[-+]?[0-9]\d{0,$iNbIntegerDigits}(\.\d{0,$iPrecision})?$";
  1384. }
  1385. public function GetBasicFilterOperators()
  1386. {
  1387. return array(
  1388. "!="=>"differs from",
  1389. "="=>"equals",
  1390. ">"=>"greater (strict) than",
  1391. ">="=>"greater than",
  1392. "<"=>"less (strict) than",
  1393. "<="=>"less than",
  1394. "in"=>"in"
  1395. );
  1396. }
  1397. public function GetBasicFilterLooseOperator()
  1398. {
  1399. // Unless we implement an "equals approximately..." or "same order of magnitude"
  1400. return "=";
  1401. }
  1402. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1403. {
  1404. $sQValue = CMDBSource::Quote($value);
  1405. switch ($sOpCode)
  1406. {
  1407. case '!=':
  1408. return $this->GetSQLExpr()." != $sQValue";
  1409. break;
  1410. case '>':
  1411. return $this->GetSQLExpr()." > $sQValue";
  1412. break;
  1413. case '>=':
  1414. return $this->GetSQLExpr()." >= $sQValue";
  1415. break;
  1416. case '<':
  1417. return $this->GetSQLExpr()." < $sQValue";
  1418. break;
  1419. case '<=':
  1420. return $this->GetSQLExpr()." <= $sQValue";
  1421. break;
  1422. case 'in':
  1423. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  1424. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  1425. break;
  1426. case '=':
  1427. default:
  1428. return $this->GetSQLExpr()." = \"$value\"";
  1429. }
  1430. }
  1431. public function GetNullValue()
  1432. {
  1433. return null;
  1434. }
  1435. public function IsNull($proposedValue)
  1436. {
  1437. return is_null($proposedValue);
  1438. }
  1439. public function MakeRealValue($proposedValue, $oHostObj)
  1440. {
  1441. if (is_null($proposedValue)) return null;
  1442. if ($proposedValue === '') return null;
  1443. return (string)$proposedValue;
  1444. }
  1445. public function ScalarToSQL($value)
  1446. {
  1447. assert(is_null($value) || preg_match('/'.$this->GetValidationPattern().'/', $value));
  1448. return $value; // null or string
  1449. }
  1450. }
  1451. /**
  1452. * Map a boolean column to an attribute
  1453. *
  1454. * @package iTopORM
  1455. */
  1456. class AttributeBoolean extends AttributeInteger
  1457. {
  1458. static public function ListExpectedParams()
  1459. {
  1460. return parent::ListExpectedParams();
  1461. //return array_merge(parent::ListExpectedParams(), array());
  1462. }
  1463. public function GetEditClass() {return "Integer";}
  1464. protected function GetSQLCol($bFullSpec = false) {return "TINYINT(1)".($bFullSpec ? $this->GetSQLColSpec() : '');}
  1465. public function MakeRealValue($proposedValue, $oHostObj)
  1466. {
  1467. if (is_null($proposedValue)) return null;
  1468. if ($proposedValue === '') return null;
  1469. if ((int)$proposedValue) return true;
  1470. return false;
  1471. }
  1472. public function ScalarToSQL($value)
  1473. {
  1474. if ($value) return 1;
  1475. return 0;
  1476. }
  1477. public function GetAsXML($sValue, $oHostObject = null, $bLocalize = true)
  1478. {
  1479. return $sValue ? '1' : '0';
  1480. }
  1481. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  1482. {
  1483. return $sValue ? '1' : '0';
  1484. }
  1485. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  1486. {
  1487. return $sValue ? '1' : '0';
  1488. }
  1489. /**
  1490. * Helper to get a value that will be JSON encoded
  1491. * The operation is the opposite to FromJSONToValue
  1492. */
  1493. public function GetForJSON($value)
  1494. {
  1495. return $value ? '1' : '0';
  1496. }
  1497. }
  1498. /**
  1499. * Map a varchar column (size < ?) to an attribute
  1500. *
  1501. * @package iTopORM
  1502. */
  1503. class AttributeString extends AttributeDBField
  1504. {
  1505. static public function ListExpectedParams()
  1506. {
  1507. return parent::ListExpectedParams();
  1508. //return array_merge(parent::ListExpectedParams(), array());
  1509. }
  1510. public function GetEditClass() {return "String";}
  1511. protected function GetSQLCol($bFullSpec = false) {return "VARCHAR(255)".($bFullSpec ? $this->GetSQLColSpec() : '');}
  1512. public function GetValidationPattern()
  1513. {
  1514. $sPattern = $this->GetOptional('validation_pattern', '');
  1515. if (empty($sPattern))
  1516. {
  1517. return parent::GetValidationPattern();
  1518. }
  1519. else
  1520. {
  1521. return $sPattern;
  1522. }
  1523. }
  1524. public function CheckFormat($value)
  1525. {
  1526. $sRegExp = $this->GetValidationPattern();
  1527. if (empty($sRegExp))
  1528. {
  1529. return true;
  1530. }
  1531. else
  1532. {
  1533. $sRegExp = str_replace('/', '\\/', $sRegExp);
  1534. return preg_match("/$sRegExp/", $value);
  1535. }
  1536. }
  1537. public function GetMaxSize()
  1538. {
  1539. return 255;
  1540. }
  1541. public function GetBasicFilterOperators()
  1542. {
  1543. return array(
  1544. "="=>"equals",
  1545. "!="=>"differs from",
  1546. "Like"=>"equals (no case)",
  1547. "NotLike"=>"differs from (no case)",
  1548. "Contains"=>"contains",
  1549. "Begins with"=>"begins with",
  1550. "Finishes with"=>"finishes with"
  1551. );
  1552. }
  1553. public function GetBasicFilterLooseOperator()
  1554. {
  1555. return "Contains";
  1556. }
  1557. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1558. {
  1559. $sQValue = CMDBSource::Quote($value);
  1560. switch ($sOpCode)
  1561. {
  1562. case '=':
  1563. case '!=':
  1564. return $this->GetSQLExpr()." $sOpCode $sQValue";
  1565. case 'Begins with':
  1566. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("$value%");
  1567. case 'Finishes with':
  1568. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value");
  1569. case 'Contains':
  1570. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
  1571. case 'NotLike':
  1572. return $this->GetSQLExpr()." NOT LIKE $sQValue";
  1573. case 'Like':
  1574. default:
  1575. return $this->GetSQLExpr()." LIKE $sQValue";
  1576. }
  1577. }
  1578. public function GetNullValue()
  1579. {
  1580. return '';
  1581. }
  1582. public function IsNull($proposedValue)
  1583. {
  1584. return ($proposedValue == '');
  1585. }
  1586. public function MakeRealValue($proposedValue, $oHostObj)
  1587. {
  1588. if (is_null($proposedValue)) return '';
  1589. return (string)$proposedValue;
  1590. }
  1591. public function ScalarToSQL($value)
  1592. {
  1593. if (!is_string($value) && !is_null($value))
  1594. {
  1595. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetHostClass(), 'attribute' => $this->GetCode()));
  1596. }
  1597. return $value;
  1598. }
  1599. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  1600. {
  1601. $sFrom = array("\r\n", $sTextQualifier);
  1602. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  1603. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  1604. return $sTextQualifier.$sEscaped.$sTextQualifier;
  1605. }
  1606. public function GetDisplayStyle()
  1607. {
  1608. return $this->GetOptional('display_style', 'select');
  1609. }
  1610. }
  1611. /**
  1612. * An attibute that matches an object class
  1613. *
  1614. * @package iTopORM
  1615. */
  1616. class AttributeClass extends AttributeString
  1617. {
  1618. static public function ListExpectedParams()
  1619. {
  1620. return array_merge(parent::ListExpectedParams(), array("class_category", "more_values"));
  1621. }
  1622. public function __construct($sCode, $aParams)
  1623. {
  1624. $this->m_sCode = $sCode;
  1625. $aParams["allowed_values"] = new ValueSetEnumClasses($aParams['class_category'], $aParams['more_values']);
  1626. parent::__construct($sCode, $aParams);
  1627. }
  1628. public function GetDefaultValue()
  1629. {
  1630. $sDefault = parent::GetDefaultValue();
  1631. if (!$this->IsNullAllowed() && $this->IsNull($sDefault))
  1632. {
  1633. // For this kind of attribute specifying null as default value
  1634. // is authorized even if null is not allowed
  1635. // Pick the first one...
  1636. $aClasses = $this->GetAllowedValues();
  1637. $sDefault = key($aClasses);
  1638. }
  1639. return $sDefault;
  1640. }
  1641. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  1642. {
  1643. if (empty($sValue)) return '';
  1644. return MetaModel::GetName($sValue);
  1645. }
  1646. public function RequiresIndex()
  1647. {
  1648. return true;
  1649. }
  1650. public function GetBasicFilterLooseOperator()
  1651. {
  1652. return '=';
  1653. }
  1654. }
  1655. /**
  1656. * An attibute that matches one of the language codes availables in the dictionnary
  1657. *
  1658. * @package iTopORM
  1659. */
  1660. class AttributeApplicationLanguage extends AttributeString
  1661. {
  1662. static public function ListExpectedParams()
  1663. {
  1664. return parent::ListExpectedParams();
  1665. }
  1666. public function __construct($sCode, $aParams)
  1667. {
  1668. $this->m_sCode = $sCode;
  1669. $aAvailableLanguages = Dict::GetLanguages();
  1670. $aLanguageCodes = array();
  1671. foreach($aAvailableLanguages as $sLangCode => $aInfo)
  1672. {
  1673. $aLanguageCodes[$sLangCode] = $aInfo['description'].' ('.$aInfo['localized_description'].')';
  1674. }
  1675. $aParams["allowed_values"] = new ValueSetEnum($aLanguageCodes);
  1676. parent::__construct($sCode, $aParams);
  1677. }
  1678. public function RequiresIndex()
  1679. {
  1680. return true;
  1681. }
  1682. public function GetBasicFilterLooseOperator()
  1683. {
  1684. return '=';
  1685. }
  1686. }
  1687. /**
  1688. * The attribute dedicated to the finalclass automatic attribute
  1689. *
  1690. * @package iTopORM
  1691. */
  1692. class AttributeFinalClass extends AttributeString
  1693. {
  1694. public function __construct($sCode, $aParams)
  1695. {
  1696. $this->m_sCode = $sCode;
  1697. $aParams["allowed_values"] = null;
  1698. parent::__construct($sCode, $aParams);
  1699. $this->m_sValue = $this->Get("default_value");
  1700. }
  1701. public function IsWritable()
  1702. {
  1703. return false;
  1704. }
  1705. public function RequiresIndex()
  1706. {
  1707. return true;
  1708. }
  1709. public function SetFixedValue($sValue)
  1710. {
  1711. $this->m_sValue = $sValue;
  1712. }
  1713. public function GetDefaultValue()
  1714. {
  1715. return $this->m_sValue;
  1716. }
  1717. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  1718. {
  1719. if (empty($sValue)) return '';
  1720. return MetaModel::GetName($sValue);
  1721. }
  1722. public function GetBasicFilterLooseOperator()
  1723. {
  1724. return '=';
  1725. }
  1726. public function GetValueLabel($sValue)
  1727. {
  1728. if (empty($sValue)) return '';
  1729. return MetaModel::GetName($sValue);
  1730. }
  1731. public function GetAllowedValues($aArgs = array(), $sContains = '')
  1732. {
  1733. $aRawValues = MetaModel::EnumChildClasses($this->GetHostClass(), ENUM_CHILD_CLASSES_ALL);
  1734. $aLocalizedValues = array();
  1735. foreach ($aRawValues as $sClass)
  1736. {
  1737. $aLocalizedValues[$sClass] = MetaModel::GetName($sClass);
  1738. }
  1739. return $aLocalizedValues;
  1740. }
  1741. }
  1742. /**
  1743. * Map a varchar column (size < ?) to an attribute that must never be shown to the user
  1744. *
  1745. * @package iTopORM
  1746. */
  1747. class AttributePassword extends AttributeString
  1748. {
  1749. static public function ListExpectedParams()
  1750. {
  1751. return parent::ListExpectedParams();
  1752. //return array_merge(parent::ListExpectedParams(), array());
  1753. }
  1754. public function GetEditClass() {return "Password";}
  1755. protected function GetSQLCol($bFullSpec = false) {return "VARCHAR(64)".($bFullSpec ? $this->GetSQLColSpec() : '');}
  1756. public function GetMaxSize()
  1757. {
  1758. return 64;
  1759. }
  1760. public function GetFilterDefinitions()
  1761. {
  1762. // Note: due to this, you will get an error if a password is being declared as a search criteria (see ZLists)
  1763. // not allowed to search on passwords!
  1764. return array();
  1765. }
  1766. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  1767. {
  1768. if (strlen($sValue) == 0)
  1769. {
  1770. return '';
  1771. }
  1772. else
  1773. {
  1774. return '******';
  1775. }
  1776. }
  1777. public function IsPartOfFingerprint() { return false; } // Cannot reliably compare two encrypted passwords since the same password will be encrypted in diffferent manners depending on the random 'salt'
  1778. }
  1779. /**
  1780. * Map a text column (size < 255) to an attribute that is encrypted in the database
  1781. * The encryption is based on a key set per iTop instance. Thus if you export your
  1782. * database (in SQL) to someone else without providing the key at the same time
  1783. * the encrypted fields will remain encrypted
  1784. *
  1785. * @package iTopORM
  1786. */
  1787. class AttributeEncryptedString extends AttributeString
  1788. {
  1789. static $sKey = null; // Encryption key used for all encrypted fields
  1790. public function __construct($sCode, $aParams)
  1791. {
  1792. parent::__construct($sCode, $aParams);
  1793. if (self::$sKey == null)
  1794. {
  1795. self::$sKey = MetaModel::GetConfig()->GetEncryptionKey();
  1796. }
  1797. }
  1798. /**
  1799. * When the attribute definitions are stored in APC cache:
  1800. * 1) The static class variable $sKey is NOT serialized
  1801. * 2) The object's constructor is NOT called upon wakeup
  1802. * 3) mcrypt may crash the server if passed an empty key !!
  1803. *
  1804. * So let's restore the key (if needed) when waking up
  1805. **/
  1806. public function __wakeup()
  1807. {
  1808. if (self::$sKey == null)
  1809. {
  1810. self::$sKey = MetaModel::GetConfig()->GetEncryptionKey();
  1811. }
  1812. }
  1813. protected function GetSQLCol($bFullSpec = false) {return "TINYBLOB";}
  1814. public function GetMaxSize()
  1815. {
  1816. return 255;
  1817. }
  1818. public function GetFilterDefinitions()
  1819. {
  1820. // Note: due to this, you will get an error if a an encrypted field is declared as a search criteria (see ZLists)
  1821. // not allowed to search on encrypted fields !
  1822. return array();
  1823. }
  1824. public function MakeRealValue($proposedValue, $oHostObj)
  1825. {
  1826. if (is_null($proposedValue)) return null;
  1827. return (string)$proposedValue;
  1828. }
  1829. /**
  1830. * Decrypt the value when reading from the database
  1831. */
  1832. public function FromSQLToValue($aCols, $sPrefix = '')
  1833. {
  1834. $oSimpleCrypt = new SimpleCrypt();
  1835. $sValue = $oSimpleCrypt->Decrypt(self::$sKey, $aCols[$sPrefix]);
  1836. return $sValue;
  1837. }
  1838. /**
  1839. * Encrypt the value before storing it in the database
  1840. */
  1841. public function GetSQLValues($value)
  1842. {
  1843. $oSimpleCrypt = new SimpleCrypt();
  1844. $encryptedValue = $oSimpleCrypt->Encrypt(self::$sKey, $value);
  1845. $aValues = array();
  1846. $aValues[$this->Get("sql")] = $encryptedValue;
  1847. return $aValues;
  1848. }
  1849. }
  1850. // Wiki formatting - experimental
  1851. //
  1852. // [[<objClass>:<objName>]]
  1853. // Example: [[Server:db1.tnut.com]]
  1854. define('WIKI_OBJECT_REGEXP', '/\[\[(.+):(.+)\]\]/U');
  1855. /**
  1856. * Map a text column (size > ?) to an attribute
  1857. *
  1858. * @package iTopORM
  1859. */
  1860. class AttributeText extends AttributeString
  1861. {
  1862. public function GetEditClass() {return "Text";}
  1863. protected function GetSQLCol($bFullSpec = false) {return "TEXT";}
  1864. public function GetMaxSize()
  1865. {
  1866. // Is there a way to know the current limitation for mysql?
  1867. // See mysql_field_len()
  1868. return 65535;
  1869. }
  1870. static public function RenderWikiHtml($sText)
  1871. {
  1872. $sPattern = '/'.str_replace('/', '\/', utils::GetConfig()->Get('url_validation_pattern')).'/i';
  1873. if (preg_match_all($sPattern, $sText, $aAllMatches, PREG_SET_ORDER /* important !*/ |PREG_OFFSET_CAPTURE /* important ! */))
  1874. {
  1875. $aUrls = array();
  1876. $i = count($aAllMatches);
  1877. // Replace the URLs by an actual hyperlink <a href="...">...</a>
  1878. // Let's do it backwards so that the initial positions are not modified by the replacement
  1879. // This works if the matches are captured: in the order they occur in the string AND
  1880. // with their offset (i.e. position) inside the string
  1881. while($i > 0)
  1882. {
  1883. $i--;
  1884. $sUrl = $aAllMatches[$i][0][0]; // String corresponding to the main pattern
  1885. $iPos = $aAllMatches[$i][0][1]; // Position of the main pattern
  1886. $sText = substr_replace($sText, "<a href=\"$sUrl\">$sUrl</a>", $iPos, strlen($sUrl));
  1887. }
  1888. }
  1889. if (preg_match_all(WIKI_OBJECT_REGEXP, $sText, $aAllMatches, PREG_SET_ORDER))
  1890. {
  1891. foreach($aAllMatches as $iPos => $aMatches)
  1892. {
  1893. $sClass = $aMatches[1];
  1894. $sName = $aMatches[2];
  1895. if (MetaModel::IsValidClass($sClass))
  1896. {
  1897. $oObj = MetaModel::GetObjectByName($sClass, $sName, false /* MustBeFound */);
  1898. if (is_object($oObj))
  1899. {
  1900. // Propose a std link to the object
  1901. $sText = str_replace($aMatches[0], $oObj->GetHyperlink(), $sText);
  1902. }
  1903. else
  1904. {
  1905. // Propose a std link to the object
  1906. $sClassLabel = MetaModel::GetName($sClass);
  1907. $sText = str_replace($aMatches[0], "<span class=\"wiki_broken_link\">$sClassLabel:$sName</span>", $sText);
  1908. // Later: propose a link to create a new object
  1909. // Anyhow... there is no easy way to suggest default values based on the given FRIENDLY name
  1910. //$sText = preg_replace('/\[\[(.+):(.+)\]\]/', '<a href="'.utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=new&class='.$sClass.'&default[att1]=xxx&default[att2]=yyy">'.$sName.'</a>', $sText);
  1911. }
  1912. }
  1913. }
  1914. }
  1915. return $sText;
  1916. }
  1917. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  1918. {
  1919. $sValue = parent::GetAsHTML($sValue, $oHostObject, $bLocalize);
  1920. $sValue = self::RenderWikiHtml($sValue);
  1921. $aStyles = array();
  1922. if ($this->GetWidth() != '')
  1923. {
  1924. $aStyles[] = 'width:'.$this->GetWidth();
  1925. }
  1926. if ($this->GetHeight() != '')
  1927. {
  1928. $aStyles[] = 'height:'.$this->GetHeight();
  1929. }
  1930. $sStyle = '';
  1931. if (count($aStyles) > 0)
  1932. {
  1933. $aStyles[] = 'overflow:auto';
  1934. $sStyle = 'style="'.implode(';', $aStyles).'"';
  1935. }
  1936. return "<div $sStyle>".str_replace("\n", "<br>\n", $sValue).'</div>';
  1937. }
  1938. public function GetEditValue($sValue, $oHostObj = null)
  1939. {
  1940. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  1941. {
  1942. foreach($aAllMatches as $iPos => $aMatches)
  1943. {
  1944. $sClass = $aMatches[1];
  1945. $sName = $aMatches[2];
  1946. if (MetaModel::IsValidClass($sClass))
  1947. {
  1948. $sClassLabel = MetaModel::GetName($sClass);
  1949. $sValue = str_replace($aMatches[0], "[[$sClassLabel:$sName]]", $sValue);
  1950. }
  1951. }
  1952. }
  1953. return $sValue;
  1954. }
  1955. public function MakeRealValue($proposedValue, $oHostObj)
  1956. {
  1957. $sValue = $proposedValue;
  1958. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  1959. {
  1960. foreach($aAllMatches as $iPos => $aMatches)
  1961. {
  1962. $sClassLabel = $aMatches[1];
  1963. $sName = $aMatches[2];
  1964. if (!MetaModel::IsValidClass($sClassLabel))
  1965. {
  1966. $sClass = MetaModel::GetClassFromLabel($sClassLabel);
  1967. if ($sClass)
  1968. {
  1969. $sValue = str_replace($aMatches[0], "[[$sClass:$sName]]", $sValue);
  1970. }
  1971. }
  1972. }
  1973. }
  1974. return $sValue;
  1975. }
  1976. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  1977. {
  1978. return Str::pure2xml($value);
  1979. }
  1980. public function GetWidth()
  1981. {
  1982. return $this->GetOptional('width', '');
  1983. }
  1984. public function GetHeight()
  1985. {
  1986. return $this->GetOptional('height', '');
  1987. }
  1988. }
  1989. /**
  1990. * Map a log to an attribute
  1991. *
  1992. * @package iTopORM
  1993. */
  1994. class AttributeLongText extends AttributeText
  1995. {
  1996. protected function GetSQLCol($bFullSpec = false) {return "LONGTEXT";}
  1997. public function GetMaxSize()
  1998. {
  1999. // Is there a way to know the current limitation for mysql?
  2000. // See mysql_field_len()
  2001. return 65535*1024; // Limited... still 64 Mb!
  2002. }
  2003. }
  2004. /**
  2005. * An attibute that stores a case log (i.e journal)
  2006. *
  2007. * @package iTopORM
  2008. */
  2009. class AttributeCaseLog extends AttributeLongText
  2010. {
  2011. public function GetNullValue()
  2012. {
  2013. return '';
  2014. }
  2015. public function IsNull($proposedValue)
  2016. {
  2017. if (!($proposedValue instanceof ormCaseLog))
  2018. {
  2019. return ($proposedValue == '');
  2020. }
  2021. return ($proposedValue->GetText() == '');
  2022. }
  2023. public function ScalarToSQL($value)
  2024. {
  2025. if (!is_string($value) && !is_null($value))
  2026. {
  2027. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetCode(), 'attribute' => $this->GetHostClass()));
  2028. }
  2029. return $value;
  2030. }
  2031. public function GetEditClass() {return "CaseLog";}
  2032. public function GetEditValue($sValue, $oHostObj = null)
  2033. {
  2034. if (!($sValue instanceOf ormCaseLog))
  2035. {
  2036. return '';
  2037. }
  2038. return $sValue->GetModifiedEntry();
  2039. }
  2040. public function GetDefaultValue() {return new ormCaseLog();}
  2041. public function Equals($val1, $val2) {return ($val1->GetText() == $val2->GetText());}
  2042. // Facilitate things: allow the user to Set the value from a string
  2043. public function MakeRealValue($proposedValue, $oHostObj)
  2044. {
  2045. if ($proposedValue instanceof ormCaseLog)
  2046. {
  2047. // Passthrough
  2048. $ret = $proposedValue;
  2049. }
  2050. else
  2051. {
  2052. // Append the new value if an instance of the object is supplied
  2053. //
  2054. $oPreviousLog = null;
  2055. if ($oHostObj != null)
  2056. {
  2057. $oPreviousLog = $oHostObj->Get($this->GetCode());
  2058. if (!is_object($oPreviousLog))
  2059. {
  2060. $oPreviousLog = $oHostObj->GetOriginal($this->GetCode());;
  2061. }
  2062. }
  2063. if (is_object($oPreviousLog))
  2064. {
  2065. $oCaseLog = clone($oPreviousLog);
  2066. }
  2067. else
  2068. {
  2069. $oCaseLog = new ormCaseLog();
  2070. }
  2071. if ($proposedValue instanceof stdClass)
  2072. {
  2073. $oCaseLog->AddLogEntryFromJSON($proposedValue);
  2074. }
  2075. else
  2076. {
  2077. if (strlen($proposedValue) > 0)
  2078. {
  2079. $oCaseLog->AddLogEntry(parent::MakeRealValue($proposedValue, $oHostObj));
  2080. }
  2081. }
  2082. $ret = $oCaseLog;
  2083. }
  2084. return $ret;
  2085. }
  2086. public function GetSQLExpressions($sPrefix = '')
  2087. {
  2088. if ($sPrefix == '')
  2089. {
  2090. $sPrefix = $this->GetCode();
  2091. }
  2092. $aColumns = array();
  2093. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  2094. $aColumns[''] = $sPrefix;
  2095. $aColumns['_index'] = $sPrefix.'_index';
  2096. return $aColumns;
  2097. }
  2098. public function FromSQLToValue($aCols, $sPrefix = '')
  2099. {
  2100. if (!array_key_exists($sPrefix, $aCols))
  2101. {
  2102. $sAvailable = implode(', ', array_keys($aCols));
  2103. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  2104. }
  2105. $sLog = $aCols[$sPrefix];
  2106. if (isset($aCols[$sPrefix.'_index']))
  2107. {
  2108. $sIndex = $aCols[$sPrefix.'_index'];
  2109. }
  2110. else
  2111. {
  2112. // For backward compatibility, allow the current state to be: 1 log, no index
  2113. $sIndex = '';
  2114. }
  2115. if (strlen($sIndex) > 0)
  2116. {
  2117. $aIndex = unserialize($sIndex);
  2118. $value = new ormCaseLog($sLog, $aIndex);
  2119. }
  2120. else
  2121. {
  2122. $value = new ormCaseLog($sLog);
  2123. }
  2124. return $value;
  2125. }
  2126. public function GetSQLValues($value)
  2127. {
  2128. if (!($value instanceOf ormCaseLog))
  2129. {
  2130. $value = new ormCaseLog('');
  2131. }
  2132. $aValues = array();
  2133. $aValues[$this->GetCode()] = $value->GetText();
  2134. $aValues[$this->GetCode().'_index'] = serialize($value->GetIndex());
  2135. return $aValues;
  2136. }
  2137. public function GetSQLColumns($bFullSpec = false)
  2138. {
  2139. $aColumns = array();
  2140. $aColumns[$this->GetCode()] = 'LONGTEXT'; // 2^32 (4 Gb)
  2141. $aColumns[$this->GetCode().'_index'] = 'BLOB';
  2142. return $aColumns;
  2143. }
  2144. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  2145. {
  2146. if ($value instanceOf ormCaseLog)
  2147. {
  2148. $sContent = $value->GetAsHTML(null, false, array(__class__, 'RenderWikiHtml'));
  2149. }
  2150. else
  2151. {
  2152. $sContent = '';
  2153. }
  2154. $aStyles = array();
  2155. if ($this->GetWidth() != '')
  2156. {
  2157. $aStyles[] = 'width:'.$this->GetWidth();
  2158. }
  2159. if ($this->GetHeight() != '')
  2160. {
  2161. $aStyles[] = 'height:'.$this->GetHeight();
  2162. }
  2163. $sStyle = '';
  2164. if (count($aStyles) > 0)
  2165. {
  2166. $sStyle = 'style="'.implode(';', $aStyles).'"';
  2167. }
  2168. return "<div class=\"caselog\" $sStyle>".$sContent.'</div>'; }
  2169. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  2170. {
  2171. if ($value instanceOf ormCaseLog)
  2172. {
  2173. return parent::GetAsCSV($value->GetText(), $sSeparator, $sTextQualifier, $oHostObject, $bLocalize);
  2174. }
  2175. else
  2176. {
  2177. return '';
  2178. }
  2179. }
  2180. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  2181. {
  2182. if ($value instanceOf ormCaseLog)
  2183. {
  2184. return parent::GetAsXML($value->GetText(), $oHostObject, $bLocalize);
  2185. }
  2186. else
  2187. {
  2188. return '';
  2189. }
  2190. }
  2191. /**
  2192. * Get various representations of the value, for insertion into a template (e.g. in Notifications)
  2193. * @param $value mixed The current value of the field
  2194. * @param $sVerb string The verb specifying the representation of the value
  2195. * @param $oHostObject DBObject The object
  2196. * @param $bLocalize bool Whether or not to localize the value
  2197. */
  2198. public function GetForTemplate($value, $sVerb, $oHostObject = null, $bLocalize = true)
  2199. {
  2200. switch($sVerb)
  2201. {
  2202. case '':
  2203. return $value->GetText();
  2204. case 'head':
  2205. return $value->GetLatestEntry();
  2206. case 'head_html':
  2207. return '<div class="caselog_entry">'.str_replace( array( "\r\n", "\n", "\r"), "<br/>", htmlentities($value->GetLatestEntry(), ENT_QUOTES, 'UTF-8')).'</div>';
  2208. case 'html':
  2209. return $value->GetAsEmailHtml();
  2210. default:
  2211. throw new Exception("Unknown verb '$sVerb' for attribute ".$this->GetCode().' in class '.get_class($oHostObj));
  2212. }
  2213. }
  2214. /**
  2215. * Helper to get a value that will be JSON encoded
  2216. * The operation is the opposite to FromJSONToValue
  2217. */
  2218. public function GetForJSON($value)
  2219. {
  2220. return $value->GetForJSON();
  2221. }
  2222. /**
  2223. * Helper to form a value, given JSON decoded data
  2224. * The operation is the opposite to GetForJSON
  2225. */
  2226. public function FromJSONToValue($json)
  2227. {
  2228. if (is_string($json))
  2229. {
  2230. // Will be correctly handled in MakeRealValue
  2231. $ret = $json;
  2232. }
  2233. else
  2234. {
  2235. if (isset($json->add_item))
  2236. {
  2237. // Will be correctly handled in MakeRealValue
  2238. $ret = $json->add_item;
  2239. if (!isset($ret->message))
  2240. {
  2241. throw new Exception("Missing mandatory entry: 'message'");
  2242. }
  2243. }
  2244. else
  2245. {
  2246. $ret = ormCaseLog::FromJSON($json);
  2247. }
  2248. }
  2249. return $ret;
  2250. }
  2251. public function Fingerprint($value)
  2252. {
  2253. $sFingerprint = '';
  2254. if ($value instanceOf ormCaseLog)
  2255. {
  2256. $sFingerprint = $value->GetText();
  2257. }
  2258. return $sFingerprint;
  2259. }
  2260. }
  2261. /**
  2262. * Map a text column (size > ?), containing HTML code, to an attribute
  2263. *
  2264. * @package iTopORM
  2265. */
  2266. class AttributeHTML extends AttributeLongText
  2267. {
  2268. public function GetEditClass() {return "HTML";}
  2269. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  2270. {
  2271. return $sValue;
  2272. }
  2273. }
  2274. /**
  2275. * Specialization of a string: email
  2276. *
  2277. * @package iTopORM
  2278. */
  2279. class AttributeEmailAddress extends AttributeString
  2280. {
  2281. public function GetValidationPattern()
  2282. {
  2283. return $this->GetOptional('validation_pattern', '^'.utils::GetConfig()->Get('email_validation_pattern').'$');
  2284. }
  2285. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  2286. {
  2287. if (empty($sValue)) return '';
  2288. return '<a class="mailto" href="mailto:'.$sValue.'">'.parent::GetAsHTML($sValue).'</a>';
  2289. }
  2290. }
  2291. /**
  2292. * Specialization of a string: IP address
  2293. *
  2294. * @package iTopORM
  2295. */
  2296. class AttributeIPAddress extends AttributeString
  2297. {
  2298. public function GetValidationPattern()
  2299. {
  2300. $sNum = '(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])';
  2301. return "^($sNum\\.$sNum\\.$sNum\\.$sNum)$";
  2302. }
  2303. public function GetOrderBySQLExpressions($sClassAlias)
  2304. {
  2305. // Note: This is the responsibility of this function to place backticks around column aliases
  2306. return array('INET_ATON(`'.$sClassAlias.$this->GetCode().'`)');
  2307. }
  2308. }
  2309. /**
  2310. * Specialization of a string: OQL expression
  2311. *
  2312. * @package iTopORM
  2313. */
  2314. class AttributeOQL extends AttributeText
  2315. {
  2316. public function GetEditClass() {return "OQLExpression";}
  2317. }
  2318. /**
  2319. * Specialization of a string: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  2320. *
  2321. * @package iTopORM
  2322. */
  2323. class AttributeTemplateString extends AttributeString
  2324. {
  2325. }
  2326. /**
  2327. * Specialization of a text: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  2328. *
  2329. * @package iTopORM
  2330. */
  2331. class AttributeTemplateText extends AttributeText
  2332. {
  2333. }
  2334. /**
  2335. * Specialization of a HTML: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  2336. *
  2337. * @package iTopORM
  2338. */
  2339. class AttributeTemplateHTML extends AttributeText
  2340. {
  2341. public function GetEditClass() {return "HTML";}
  2342. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  2343. {
  2344. return $sValue;
  2345. }
  2346. }
  2347. /**
  2348. * Map a enum column to an attribute
  2349. *
  2350. * @package iTopORM
  2351. */
  2352. class AttributeEnum extends AttributeString
  2353. {
  2354. static public function ListExpectedParams()
  2355. {
  2356. return parent::ListExpectedParams();
  2357. //return array_merge(parent::ListExpectedParams(), array());
  2358. }
  2359. public function GetEditClass() {return "String";}
  2360. protected function GetSQLCol($bFullSpec = false)
  2361. {
  2362. $oValDef = $this->GetValuesDef();
  2363. if ($oValDef)
  2364. {
  2365. $aValues = CMDBSource::Quote(array_keys($oValDef->GetValues(array(), "")), true);
  2366. }
  2367. else
  2368. {
  2369. $aValues = array();
  2370. }
  2371. if (count($aValues) > 0)
  2372. {
  2373. // The syntax used here do matters
  2374. // In particular, I had to remove unnecessary spaces to
  2375. // make sure that this string will match the field type returned by the DB
  2376. // (used to perform a comparison between the current DB format and the data model)
  2377. return "ENUM(".implode(",", $aValues).")".($bFullSpec ? $this->GetSQLColSpec() : '');
  2378. }
  2379. else
  2380. {
  2381. return "VARCHAR(255)".($bFullSpec ? " DEFAULT ''" : ""); // ENUM() is not an allowed syntax!
  2382. }
  2383. }
  2384. protected function GetSQLColSpec()
  2385. {
  2386. $default = $this->ScalarToSQL($this->GetDefaultValue());
  2387. if (is_null($default))
  2388. {
  2389. $sRet = '';
  2390. }
  2391. else
  2392. {
  2393. // ENUMs values are strings so the default value must be a string as well,
  2394. // otherwise MySQL interprets the number as the zero-based index of the value in the list (i.e. the nth value in the list)
  2395. $sRet = " DEFAULT ".CMDBSource::Quote($default);
  2396. }
  2397. return $sRet;
  2398. }
  2399. public function ScalarToSQL($value)
  2400. {
  2401. // Note: for strings, the null value is an empty string and it is recorded as such in the DB
  2402. // but that wasn't working for enums, because '' is NOT one of the allowed values
  2403. // that's why a null value must be forced to a real null
  2404. $value = parent::ScalarToSQL($value);
  2405. if ($this->IsNull($value))
  2406. {
  2407. return null;
  2408. }
  2409. else
  2410. {
  2411. return $value;
  2412. }
  2413. }
  2414. public function RequiresIndex()
  2415. {
  2416. return false;
  2417. }
  2418. public function GetBasicFilterOperators()
  2419. {
  2420. return parent::GetBasicFilterOperators();
  2421. }
  2422. public function GetBasicFilterLooseOperator()
  2423. {
  2424. return '=';
  2425. }
  2426. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2427. {
  2428. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  2429. }
  2430. public function GetValueLabel($sValue)
  2431. {
  2432. if (is_null($sValue))
  2433. {
  2434. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  2435. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, Dict::S('Enum:Undefined'));
  2436. }
  2437. else
  2438. {
  2439. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/Value:'.$sValue, null, true /*user lang*/);
  2440. if (is_null($sLabel))
  2441. {
  2442. $sDefault = str_replace('_', ' ', $sValue);
  2443. // Browse the hierarchy again, accepting default (english) translations
  2444. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/Value:'.$sValue, $sDefault, false);
  2445. }
  2446. }
  2447. return $sLabel;
  2448. }
  2449. public function GetValueDescription($sValue)
  2450. {
  2451. if (is_null($sValue))
  2452. {
  2453. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  2454. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', Dict::S('Enum:Undefined'));
  2455. }
  2456. else
  2457. {
  2458. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', '', true /* user language only */);
  2459. if (strlen($sDescription) == 0)
  2460. {
  2461. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  2462. if ($sParentClass)
  2463. {
  2464. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  2465. {
  2466. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  2467. $sDescription = $oAttDef->GetValueDescription($sValue);
  2468. }
  2469. }
  2470. }
  2471. }
  2472. return $sDescription;
  2473. }
  2474. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  2475. {
  2476. if ($bLocalize)
  2477. {
  2478. $sLabel = $this->GetValueLabel($sValue);
  2479. $sDescription = $this->GetValueDescription($sValue);
  2480. // later, we could imagine a detailed description in the title
  2481. $sRes = "<span title=\"$sDescription\">".parent::GetAsHtml($sLabel)."</span>";
  2482. }
  2483. else
  2484. {
  2485. $sRes = parent::GetAsHtml($sValue, $oHostObject, $bLocalize);
  2486. }
  2487. return $sRes;
  2488. }
  2489. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  2490. {
  2491. if (is_null($value))
  2492. {
  2493. $sFinalValue = '';
  2494. }
  2495. elseif ($bLocalize)
  2496. {
  2497. $sFinalValue = $this->GetValueLabel($value);
  2498. }
  2499. else
  2500. {
  2501. $sFinalValue = $value;
  2502. }
  2503. $sRes = parent::GetAsXML($sFinalValue, $oHostObject, $bLocalize);
  2504. return $sRes;
  2505. }
  2506. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  2507. {
  2508. if (is_null($sValue))
  2509. {
  2510. $sFinalValue = '';
  2511. }
  2512. elseif ($bLocalize)
  2513. {
  2514. $sFinalValue = $this->GetValueLabel($sValue);
  2515. }
  2516. else
  2517. {
  2518. $sFinalValue = $sValue;
  2519. }
  2520. $sRes = parent::GetAsCSV($sFinalValue, $sSeparator, $sTextQualifier, $oHostObject, $bLocalize);
  2521. return $sRes;
  2522. }
  2523. public function GetEditValue($sValue, $oHostObj = null)
  2524. {
  2525. if (is_null($sValue))
  2526. {
  2527. return '';
  2528. }
  2529. else
  2530. {
  2531. return $this->GetValueLabel($sValue);
  2532. }
  2533. }
  2534. /**
  2535. * Helper to get a value that will be JSON encoded
  2536. * The operation is the opposite to FromJSONToValue
  2537. */
  2538. public function GetForJSON($value)
  2539. {
  2540. return $value;
  2541. }
  2542. public function GetAllowedValues($aArgs = array(), $sContains = '')
  2543. {
  2544. $aRawValues = parent::GetAllowedValues($aArgs, $sContains);
  2545. if (is_null($aRawValues)) return null;
  2546. $aLocalizedValues = array();
  2547. foreach ($aRawValues as $sKey => $sValue)
  2548. {
  2549. $aLocalizedValues[$sKey] = Str::pure2html($this->GetValueLabel($sKey));
  2550. }
  2551. return $aLocalizedValues;
  2552. }
  2553. /**
  2554. * An enum can be localized
  2555. */
  2556. public function MakeValueFromString($sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  2557. {
  2558. if ($bLocalizedValue)
  2559. {
  2560. // Lookup for the value matching the input
  2561. //
  2562. $sFoundValue = null;
  2563. $aRawValues = parent::GetAllowedValues();
  2564. if (!is_null($aRawValues))
  2565. {
  2566. foreach ($aRawValues as $sKey => $sValue)
  2567. {
  2568. $sRefValue = $this->GetValueLabel($sKey);
  2569. if ($sProposedValue == $sRefValue)
  2570. {
  2571. $sFoundValue = $sKey;
  2572. break;
  2573. }
  2574. }
  2575. }
  2576. if (is_null($sFoundValue))
  2577. {
  2578. return null;
  2579. }
  2580. return $this->MakeRealValue($sFoundValue, null);
  2581. }
  2582. else
  2583. {
  2584. return parent::MakeValueFromString($sProposedValue, $bLocalizedValue, $sSepItem, $sSepAttribute, $sSepValue, $sAttributeQualifier);
  2585. }
  2586. }
  2587. /**
  2588. * Processes the input value to align it with the values supported
  2589. * by this type of attribute. In this case: turns empty strings into nulls
  2590. * @param mixed $proposedValue The value to be set for the attribute
  2591. * @return mixed The actual value that will be set
  2592. */
  2593. public function MakeRealValue($proposedValue, $oHostObj)
  2594. {
  2595. if ($proposedValue == '') return null;
  2596. return parent::MakeRealValue($proposedValue, $oHostObj);
  2597. }
  2598. public function GetOrderByHint()
  2599. {
  2600. $aValues = $this->GetAllowedValues();
  2601. return Dict::Format('UI:OrderByHint_Values', implode(', ', $aValues));
  2602. }
  2603. }
  2604. /**
  2605. * Map a date+time column to an attribute
  2606. *
  2607. * @package iTopORM
  2608. */
  2609. class AttributeDateTime extends AttributeDBField
  2610. {
  2611. static public function GetDateFormat()
  2612. {
  2613. return "Y-m-d H:i:s";
  2614. }
  2615. static public function ListExpectedParams()
  2616. {
  2617. return parent::ListExpectedParams();
  2618. //return array_merge(parent::ListExpectedParams(), array());
  2619. }
  2620. public function GetEditClass() {return "DateTime";}
  2621. protected function GetSQLCol($bFullSpec = false) {return "DATETIME";}
  2622. public static function GetAsUnixSeconds($value)
  2623. {
  2624. $oDeadlineDateTime = new DateTime($value);
  2625. $iUnixSeconds = $oDeadlineDateTime->format('U');
  2626. return $iUnixSeconds;
  2627. }
  2628. // This has been done at the time when itop was using TIMESTAMP columns,
  2629. // now that iTop is using DATETIME columns, it seems possible to have IsNullAllowed returning false... later when this is needed
  2630. public function IsNullAllowed() {return true;}
  2631. public function GetDefaultValue()
  2632. {
  2633. $default = parent::GetDefaultValue();
  2634. if (!parent::IsNullAllowed())
  2635. {
  2636. if (empty($default))
  2637. {
  2638. $default = date($this->GetDateFormat());
  2639. }
  2640. }
  2641. return $default;
  2642. }
  2643. // END OF THE WORKAROUND
  2644. ///////////////////////////////////////////////////////////////
  2645. public function GetValidationPattern()
  2646. {
  2647. return "^(([0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30))))( (0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])(:([0-5][0-9])){0,1}){0,1}|0000-00-00 00:00:00|0000-00-00)$";
  2648. }
  2649. public function GetBasicFilterOperators()
  2650. {
  2651. return array(
  2652. "="=>"equals",
  2653. "!="=>"differs from",
  2654. "<"=>"before",
  2655. "<="=>"before",
  2656. ">"=>"after (strictly)",
  2657. ">="=>"after",
  2658. "SameDay"=>"same day (strip time)",
  2659. "SameMonth"=>"same year/month",
  2660. "SameYear"=>"same year",
  2661. "Today"=>"today",
  2662. ">|"=>"after today + N days",
  2663. "<|"=>"before today + N days",
  2664. "=|"=>"equals today + N days",
  2665. );
  2666. }
  2667. public function GetBasicFilterLooseOperator()
  2668. {
  2669. // Unless we implement a "same xxx, depending on given precision" !
  2670. return "=";
  2671. }
  2672. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2673. {
  2674. $sQValue = CMDBSource::Quote($value);
  2675. switch ($sOpCode)
  2676. {
  2677. case '=':
  2678. case '!=':
  2679. case '<':
  2680. case '<=':
  2681. case '>':
  2682. case '>=':
  2683. return $this->GetSQLExpr()." $sOpCode $sQValue";
  2684. case 'SameDay':
  2685. return "DATE(".$this->GetSQLExpr().") = DATE($sQValue)";
  2686. case 'SameMonth':
  2687. return "DATE_FORMAT(".$this->GetSQLExpr().", '%Y-%m') = DATE_FORMAT($sQValue, '%Y-%m')";
  2688. case 'SameYear':
  2689. return "MONTH(".$this->GetSQLExpr().") = MONTH($sQValue)";
  2690. case 'Today':
  2691. return "DATE(".$this->GetSQLExpr().") = CURRENT_DATE()";
  2692. case '>|':
  2693. return "DATE(".$this->GetSQLExpr().") > DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  2694. case '<|':
  2695. return "DATE(".$this->GetSQLExpr().") < DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  2696. case '=|':
  2697. return "DATE(".$this->GetSQLExpr().") = DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  2698. default:
  2699. return $this->GetSQLExpr()." = $sQValue";
  2700. }
  2701. }
  2702. public function MakeRealValue($proposedValue, $oHostObj)
  2703. {
  2704. if (is_null($proposedValue))
  2705. {
  2706. return null;
  2707. }
  2708. if (is_string($proposedValue) && ($proposedValue == "") && $this->IsNullAllowed())
  2709. {
  2710. return null;
  2711. }
  2712. if (!is_numeric($proposedValue))
  2713. {
  2714. return $proposedValue;
  2715. }
  2716. return date(self::GetDateFormat(), $proposedValue);
  2717. }
  2718. public function ScalarToSQL($value)
  2719. {
  2720. if (is_null($value))
  2721. {
  2722. return null;
  2723. }
  2724. elseif (empty($value))
  2725. {
  2726. // Make a valid date for MySQL. TO DO: support NULL as a literal value for fields that can be null.
  2727. return '0000-00-00 00:00:00';
  2728. }
  2729. return $value;
  2730. }
  2731. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  2732. {
  2733. return Str::pure2html($value);
  2734. }
  2735. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  2736. {
  2737. return Str::pure2xml($value);
  2738. }
  2739. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  2740. {
  2741. $sFrom = array("\r\n", $sTextQualifier);
  2742. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  2743. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  2744. return $sTextQualifier.$sEscaped.$sTextQualifier;
  2745. }
  2746. /**
  2747. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  2748. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  2749. * does nothing special, and just calls the default (loose) operator
  2750. * @param string $sSearchText The search string to analyze for smart patterns
  2751. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  2752. * @param Hash $aParams Values of the query parameters
  2753. * @return Expression The search condition to be added (AND) to the current search
  2754. */
  2755. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  2756. {
  2757. // Possible smart patterns
  2758. $aPatterns = array(
  2759. 'between' => array('pattern' => '/^\[(.*),(.*)\]$/', 'operator' => 'n/a'),
  2760. 'greater than or equal' => array('pattern' => '/^>=(.*)$/', 'operator' => '>='),
  2761. 'greater than' => array('pattern' => '/^>(.*)$/', 'operator' => '>'),
  2762. 'less than or equal' => array('pattern' => '/^<=(.*)$/', 'operator' => '<='),
  2763. 'less than' => array('pattern' => '/^<(.*)$/', 'operator' => '<'),
  2764. );
  2765. $sPatternFound = '';
  2766. $aMatches = array();
  2767. foreach($aPatterns as $sPatName => $sPattern)
  2768. {
  2769. if (preg_match($sPattern['pattern'], $sSearchText, $aMatches))
  2770. {
  2771. $sPatternFound = $sPatName;
  2772. break;
  2773. }
  2774. }
  2775. switch($sPatternFound)
  2776. {
  2777. case 'between':
  2778. $sParamName1 = $oField->GetParent().'_'.$oField->GetName().'_1';
  2779. $oRightExpr = new VariableExpression($sParamName1);
  2780. $aParams[$sParamName1] = $aMatches[1];
  2781. $oCondition1 = new BinaryExpression($oField, '>=', $oRightExpr);
  2782. $sParamName2 = $oField->GetParent().'_'.$oField->GetName().'_2';
  2783. $oRightExpr = new VariableExpression($sParamName2);
  2784. $sOperator = $this->GetBasicFilterLooseOperator();
  2785. $aParams[$sParamName2] = $aMatches[2];
  2786. $oCondition2 = new BinaryExpression($oField, '<=', $oRightExpr);
  2787. $oNewCondition = new BinaryExpression($oCondition1, 'AND', $oCondition2);
  2788. break;
  2789. case 'greater than':
  2790. case 'greater than or equal':
  2791. case 'less than':
  2792. case 'less than or equal':
  2793. $sSQLOperator = $aPatterns[$sPatternFound]['operator'];
  2794. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  2795. $oRightExpr = new VariableExpression($sParamName);
  2796. $aParams[$sParamName] = $aMatches[1];
  2797. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  2798. break;
  2799. default:
  2800. $oNewCondition = parent::GetSmartConditionExpression($sSearchText, $oField, $aParams);
  2801. }
  2802. return $oNewCondition;
  2803. }
  2804. }
  2805. /**
  2806. * Store a duration as a number of seconds
  2807. *
  2808. * @package iTopORM
  2809. */
  2810. class AttributeDuration extends AttributeInteger
  2811. {
  2812. public function GetEditClass() {return "Duration";}
  2813. protected function GetSQLCol($bFullSpec = false) {return "INT(11) UNSIGNED";}
  2814. public function GetNullValue() {return '0';}
  2815. public function MakeRealValue($proposedValue, $oHostObj)
  2816. {
  2817. if (is_null($proposedValue)) return null;
  2818. if (!is_numeric($proposedValue)) return null;
  2819. if ( ((int)$proposedValue) < 0) return null;
  2820. return (int)$proposedValue;
  2821. }
  2822. public function ScalarToSQL($value)
  2823. {
  2824. if (is_null($value))
  2825. {
  2826. return null;
  2827. }
  2828. return $value;
  2829. }
  2830. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  2831. {
  2832. return Str::pure2html(self::FormatDuration($value));
  2833. }
  2834. public static function FormatDuration($duration)
  2835. {
  2836. $aDuration = self::SplitDuration($duration);
  2837. $sResult = '';
  2838. if ($duration < 60)
  2839. {
  2840. // Less than 1 min
  2841. $sResult = Dict::Format('Core:Duration_Seconds', $aDuration['seconds']);
  2842. }
  2843. else if ($duration < 3600)
  2844. {
  2845. // less than 1 hour, display it in minutes/seconds
  2846. $sResult = Dict::Format('Core:Duration_Minutes_Seconds', $aDuration['minutes'], $aDuration['seconds']);
  2847. }
  2848. else if ($duration < 86400)
  2849. {
  2850. // Less than 1 day, display it in hours/minutes/seconds
  2851. $sResult = Dict::Format('Core:Duration_Hours_Minutes_Seconds', $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  2852. }
  2853. else
  2854. {
  2855. // more than 1 day, display it in days/hours/minutes/seconds
  2856. $sResult = Dict::Format('Core:Duration_Days_Hours_Minutes_Seconds', $aDuration['days'], $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  2857. }
  2858. return $sResult;
  2859. }
  2860. static function SplitDuration($duration)
  2861. {
  2862. $duration = (int) $duration;
  2863. $days = floor($duration / 86400);
  2864. $hours = floor(($duration - (86400*$days)) / 3600);
  2865. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  2866. $seconds = ($duration % 60); // modulo
  2867. return array( 'days' => $days, 'hours' => $hours, 'minutes' => $minutes, 'seconds' => $seconds );
  2868. }
  2869. }
  2870. /**
  2871. * Map a date+time column to an attribute
  2872. *
  2873. * @package iTopORM
  2874. */
  2875. class AttributeDate extends AttributeDateTime
  2876. {
  2877. const MYDATEFORMAT = "Y-m-d";
  2878. static public function GetDateFormat()
  2879. {
  2880. return "Y-m-d";
  2881. }
  2882. static public function ListExpectedParams()
  2883. {
  2884. return parent::ListExpectedParams();
  2885. //return array_merge(parent::ListExpectedParams(), array());
  2886. }
  2887. public function GetEditClass() {return "Date";}
  2888. protected function GetSQLCol($bFullSpec = false) {return "DATE";}
  2889. public function GetValidationPattern()
  2890. {
  2891. return "^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$";
  2892. }
  2893. }
  2894. /**
  2895. * A dead line stored as a date & time
  2896. * The only difference with the DateTime attribute is the display:
  2897. * relative to the current time
  2898. */
  2899. class AttributeDeadline extends AttributeDateTime
  2900. {
  2901. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  2902. {
  2903. $sResult = self::FormatDeadline($value);
  2904. return $sResult;
  2905. }
  2906. public static function FormatDeadline($value)
  2907. {
  2908. $sResult = '';
  2909. if ($value !== null)
  2910. {
  2911. $iValue = AttributeDateTime::GetAsUnixSeconds($value);
  2912. $sDate = $value;
  2913. $difference = $iValue - time();
  2914. if ($difference >= 0)
  2915. {
  2916. $sDifference = self::FormatDuration($difference);
  2917. }
  2918. else
  2919. {
  2920. $sDifference = Dict::Format('UI:DeadlineMissedBy_duration', self::FormatDuration(-$difference));
  2921. }
  2922. $sFormat = MetaModel::GetConfig()->Get('deadline_format', '$difference$');
  2923. $sResult = str_replace(array('$date$', '$difference$'), array($sDate, $sDifference), $sFormat);
  2924. }
  2925. return $sResult;
  2926. }
  2927. static function FormatDuration($duration)
  2928. {
  2929. $days = floor($duration / 86400);
  2930. $hours = floor(($duration - (86400*$days)) / 3600);
  2931. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  2932. $sResult = '';
  2933. if ($duration < 60)
  2934. {
  2935. // Less than 1 min
  2936. $sResult =Dict::S('UI:Deadline_LessThan1Min');
  2937. }
  2938. else if ($duration < 3600)
  2939. {
  2940. // less than 1 hour, display it in minutes
  2941. $sResult =Dict::Format('UI:Deadline_Minutes', $minutes);
  2942. }
  2943. else if ($duration < 86400)
  2944. {
  2945. // Less that 1 day, display it in hours/minutes
  2946. $sResult =Dict::Format('UI:Deadline_Hours_Minutes', $hours, $minutes);
  2947. }
  2948. else
  2949. {
  2950. // Less that 1 day, display it in hours/minutes
  2951. $sResult =Dict::Format('UI:Deadline_Days_Hours_Minutes', $days, $hours, $minutes);
  2952. }
  2953. return $sResult;
  2954. }
  2955. }
  2956. /**
  2957. * Map a foreign key to an attribute
  2958. * AttributeExternalKey and AttributeExternalField may be an external key
  2959. * the difference is that AttributeExternalKey corresponds to a column into the defined table
  2960. * where an AttributeExternalField corresponds to a column into another table (class)
  2961. *
  2962. * @package iTopORM
  2963. */
  2964. class AttributeExternalKey extends AttributeDBFieldVoid
  2965. {
  2966. static public function ListExpectedParams()
  2967. {
  2968. return array_merge(parent::ListExpectedParams(), array("targetclass", "is_null_allowed", "on_target_delete"));
  2969. }
  2970. public function GetEditClass() {return "ExtKey";}
  2971. protected function GetSQLCol($bFullSpec = false) {return "INT(11)".($bFullSpec ? " DEFAULT 0" : "");}
  2972. public function RequiresIndex()
  2973. {
  2974. return true;
  2975. }
  2976. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return true;}
  2977. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->Get("targetclass");}
  2978. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  2979. public function GetKeyAttCode() {return $this->GetCode();}
  2980. public function GetDisplayStyle() { return $this->GetOptional('display_style', 'select'); }
  2981. public function GetDefaultValue() {return 0;}
  2982. public function IsNullAllowed()
  2983. {
  2984. if (MetaModel::GetConfig()->Get('disable_mandatory_ext_keys'))
  2985. {
  2986. return true;
  2987. }
  2988. return $this->Get("is_null_allowed");
  2989. }
  2990. public function GetBasicFilterOperators()
  2991. {
  2992. return parent::GetBasicFilterOperators();
  2993. }
  2994. public function GetBasicFilterLooseOperator()
  2995. {
  2996. return parent::GetBasicFilterLooseOperator();
  2997. }
  2998. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2999. {
  3000. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  3001. }
  3002. // overloaded here so that an ext key always have the answer to
  3003. // "what are your possible values?"
  3004. public function GetValuesDef()
  3005. {
  3006. $oValSetDef = $this->Get("allowed_values");
  3007. if (!$oValSetDef)
  3008. {
  3009. // Let's propose every existing value
  3010. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  3011. }
  3012. return $oValSetDef;
  3013. }
  3014. public function GetAllowedValues($aArgs = array(), $sContains = '')
  3015. {
  3016. //throw new Exception("GetAllowedValues on ext key has been deprecated");
  3017. try
  3018. {
  3019. return parent::GetAllowedValues($aArgs, $sContains);
  3020. }
  3021. catch (MissingQueryArgument $e)
  3022. {
  3023. // Some required arguments could not be found, enlarge to any existing value
  3024. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  3025. return $oValSetDef->GetValues($aArgs, $sContains);
  3026. }
  3027. }
  3028. public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '')
  3029. {
  3030. $oValSetDef = $this->GetValuesDef();
  3031. $oSet = $oValSetDef->ToObjectSet($aArgs, $sContains);
  3032. return $oSet;
  3033. }
  3034. public function GetDeletionPropagationOption()
  3035. {
  3036. return $this->Get("on_target_delete");
  3037. }
  3038. public function GetNullValue()
  3039. {
  3040. return 0;
  3041. }
  3042. public function IsNull($proposedValue)
  3043. {
  3044. return ($proposedValue == 0);
  3045. }
  3046. public function MakeRealValue($proposedValue, $oHostObj)
  3047. {
  3048. if (is_null($proposedValue)) return 0;
  3049. if ($proposedValue === '') return 0;
  3050. if (MetaModel::IsValidObject($proposedValue)) return $proposedValue->GetKey();
  3051. return (int)$proposedValue;
  3052. }
  3053. public function GetMaximumComboLength()
  3054. {
  3055. return $this->GetOptional('max_combo_length', MetaModel::GetConfig()->Get('max_combo_length'));
  3056. }
  3057. public function GetMinAutoCompleteChars()
  3058. {
  3059. return $this->GetOptional('min_autocomplete_chars', MetaModel::GetConfig()->Get('min_autocomplete_chars'));
  3060. }
  3061. public function AllowTargetCreation()
  3062. {
  3063. return $this->GetOptional('allow_target_creation', MetaModel::GetConfig()->Get('allow_target_creation'));
  3064. }
  3065. /**
  3066. * Find the corresponding "link" attribute on the target class
  3067. *
  3068. * @return string The attribute code on the target class, or null if none has been found
  3069. */
  3070. public function GetMirrorLinkAttribute()
  3071. {
  3072. $oRet = null;
  3073. $sRemoteClass = $this->GetTargetClass();
  3074. foreach (MetaModel::ListAttributeDefs($sRemoteClass) as $sRemoteAttCode => $oRemoteAttDef)
  3075. {
  3076. if (!$oRemoteAttDef->IsLinkSet()) continue;
  3077. if (!is_subclass_of($this->GetHostClass(), $oRemoteAttDef->GetLinkedClass()) && $oRemoteAttDef->GetLinkedClass() != $this->GetHostClass()) continue;
  3078. if ($oRemoteAttDef->GetExtKeyToMe() != $this->GetCode()) continue;
  3079. $oRet = $oRemoteAttDef;
  3080. break;
  3081. }
  3082. return $oRet;
  3083. }
  3084. }
  3085. /**
  3086. * Special kind of External Key to manage a hierarchy of objects
  3087. */
  3088. class AttributeHierarchicalKey extends AttributeExternalKey
  3089. {
  3090. protected $m_sTargetClass;
  3091. static public function ListExpectedParams()
  3092. {
  3093. $aParams = parent::ListExpectedParams();
  3094. $idx = array_search('targetclass', $aParams);
  3095. unset($aParams[$idx]);
  3096. $idx = array_search('jointype', $aParams);
  3097. unset($aParams[$idx]);
  3098. return $aParams; // TODO: mettre les bons parametres ici !!
  3099. }
  3100. public function GetEditClass() {return "ExtKey";}
  3101. public function RequiresIndex()
  3102. {
  3103. return true;
  3104. }
  3105. /*
  3106. * The target class is the class for which the attribute has been defined first
  3107. */
  3108. public function SetHostClass($sHostClass)
  3109. {
  3110. if (!isset($this->m_sTargetClass))
  3111. {
  3112. $this->m_sTargetClass = $sHostClass;
  3113. }
  3114. parent::SetHostClass($sHostClass);
  3115. }
  3116. public function IsHierarchicalKey() {return true;}
  3117. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->m_sTargetClass;}
  3118. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  3119. public function GetKeyAttCode() {return $this->GetCode();}
  3120. public function GetBasicFilterOperators()
  3121. {
  3122. return parent::GetBasicFilterOperators();
  3123. }
  3124. public function GetBasicFilterLooseOperator()
  3125. {
  3126. return parent::GetBasicFilterLooseOperator();
  3127. }
  3128. public function GetSQLColumns($bFullSpec = false)
  3129. {
  3130. $aColumns = array();
  3131. $aColumns[$this->GetCode()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
  3132. $aColumns[$this->GetSQLLeft()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
  3133. $aColumns[$this->GetSQLRight()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
  3134. return $aColumns;
  3135. }
  3136. public function GetSQLRight()
  3137. {
  3138. return $this->GetCode().'_right';
  3139. }
  3140. public function GetSQLLeft()
  3141. {
  3142. return $this->GetCode().'_left';
  3143. }
  3144. public function GetSQLValues($value)
  3145. {
  3146. if (!is_array($value))
  3147. {
  3148. $aValues[$this->GetCode()] = $value;
  3149. }
  3150. else
  3151. {
  3152. $aValues = array();
  3153. $aValues[$this->GetCode()] = $value[$this->GetCode()];
  3154. $aValues[$this->GetSQLRight()] = $value[$this->GetSQLRight()];
  3155. $aValues[$this->GetSQLLeft()] = $value[$this->GetSQLLeft()];
  3156. }
  3157. return $aValues;
  3158. }
  3159. public function GetAllowedValues($aArgs = array(), $sContains = '')
  3160. {
  3161. if (array_key_exists('this', $aArgs))
  3162. {
  3163. // Hierarchical keys have one more constraint: the "parent value" cannot be
  3164. // "under" themselves
  3165. $iRootId = $aArgs['this']->GetKey();
  3166. if ($iRootId > 0) // ignore objects that do no exist in the database...
  3167. {
  3168. $oValSetDef = $this->GetValuesDef();
  3169. $sClass = $this->m_sTargetClass;
  3170. $oFilter = DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
  3171. $oValSetDef->AddCondition($oFilter);
  3172. }
  3173. }
  3174. else
  3175. {
  3176. return parent::GetAllowedValues($aArgs, $sContains);
  3177. }
  3178. }
  3179. public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '')
  3180. {
  3181. $oValSetDef = $this->GetValuesDef();
  3182. if (array_key_exists('this', $aArgs))
  3183. {
  3184. // Hierarchical keys have one more constraint: the "parent value" cannot be
  3185. // "under" themselves
  3186. $iRootId = $aArgs['this']->GetKey();
  3187. if ($iRootId > 0) // ignore objects that do no exist in the database...
  3188. {
  3189. $aValuesSetDef = $this->GetValuesDef();
  3190. $sClass = $this->m_sTargetClass;
  3191. $oFilter = DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
  3192. $oValSetDef->AddCondition($oFilter);
  3193. }
  3194. }
  3195. $oSet = $oValSetDef->ToObjectSet($aArgs, $sContains);
  3196. return $oSet;
  3197. }
  3198. /**
  3199. * Find the corresponding "link" attribute on the target class
  3200. *
  3201. * @return string The attribute code on the target class, or null if none has been found
  3202. */
  3203. public function GetMirrorLinkAttribute()
  3204. {
  3205. return null;
  3206. }
  3207. }
  3208. /**
  3209. * An attribute which corresponds to an external key (direct or indirect)
  3210. *
  3211. * @package iTopORM
  3212. */
  3213. class AttributeExternalField extends AttributeDefinition
  3214. {
  3215. static public function ListExpectedParams()
  3216. {
  3217. return array_merge(parent::ListExpectedParams(), array("extkey_attcode", "target_attcode"));
  3218. }
  3219. public function GetEditClass() {return "ExtField";}
  3220. public function GetFinalAttDef()
  3221. {
  3222. $oExtAttDef = $this->GetExtAttDef();
  3223. return $oExtAttDef->GetFinalAttDef();
  3224. }
  3225. protected function GetSQLCol($bFullSpec = false)
  3226. {
  3227. // throw new CoreException("external attribute: does it make any sense to request its type ?");
  3228. $oExtAttDef = $this->GetExtAttDef();
  3229. return $oExtAttDef->GetSQLCol($bFullSpec);
  3230. }
  3231. public function GetSQLExpressions($sPrefix = '')
  3232. {
  3233. if ($sPrefix == '')
  3234. {
  3235. return array('' => $this->GetCode());
  3236. }
  3237. else
  3238. {
  3239. return $sPrefix;
  3240. }
  3241. }
  3242. public function GetLabel($sDefault = null)
  3243. {
  3244. $sLabel = parent::GetLabel('');
  3245. if (strlen($sLabel) == 0)
  3246. {
  3247. $oRemoteAtt = $this->GetExtAttDef();
  3248. $sLabel = $oRemoteAtt->GetLabel($this->m_sCode);
  3249. }
  3250. return $sLabel;
  3251. }
  3252. public function GetDescription($sDefault = null)
  3253. {
  3254. $sLabel = parent::GetDescription('');
  3255. if (strlen($sLabel) == 0)
  3256. {
  3257. $oRemoteAtt = $this->GetExtAttDef();
  3258. $sLabel = $oRemoteAtt->GetDescription('');
  3259. }
  3260. return $sLabel;
  3261. }
  3262. public function GetHelpOnEdition($sDefault = null)
  3263. {
  3264. $sLabel = parent::GetHelpOnEdition('');
  3265. if (strlen($sLabel) == 0)
  3266. {
  3267. $oRemoteAtt = $this->GetExtAttDef();
  3268. $sLabel = $oRemoteAtt->GetHelpOnEdition('');
  3269. }
  3270. return $sLabel;
  3271. }
  3272. public function IsExternalKey($iType = EXTKEY_RELATIVE)
  3273. {
  3274. switch($iType)
  3275. {
  3276. case EXTKEY_ABSOLUTE:
  3277. // see further
  3278. $oRemoteAtt = $this->GetExtAttDef();
  3279. return $oRemoteAtt->IsExternalKey($iType);
  3280. case EXTKEY_RELATIVE:
  3281. return false;
  3282. default:
  3283. throw new CoreException("Unexpected value for argument iType: '$iType'");
  3284. }
  3285. }
  3286. public function GetTargetClass($iType = EXTKEY_RELATIVE)
  3287. {
  3288. return $this->GetKeyAttDef($iType)->GetTargetClass();
  3289. }
  3290. public function IsExternalField() {return true;}
  3291. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  3292. public function GetExtAttCode() {return $this->Get("target_attcode");}
  3293. public function GetKeyAttDef($iType = EXTKEY_RELATIVE)
  3294. {
  3295. switch($iType)
  3296. {
  3297. case EXTKEY_ABSOLUTE:
  3298. // see further
  3299. $oRemoteAtt = $this->GetExtAttDef();
  3300. if ($oRemoteAtt->IsExternalField())
  3301. {
  3302. return $oRemoteAtt->GetKeyAttDef(EXTKEY_ABSOLUTE);
  3303. }
  3304. else if ($oRemoteAtt->IsExternalKey())
  3305. {
  3306. return $oRemoteAtt;
  3307. }
  3308. return $this->GetKeyAttDef(EXTKEY_RELATIVE); // which corresponds to the code hereafter !
  3309. case EXTKEY_RELATIVE:
  3310. return MetaModel::GetAttributeDef($this->GetHostClass(), $this->Get("extkey_attcode"));
  3311. default:
  3312. throw new CoreException("Unexpected value for argument iType: '$iType'");
  3313. }
  3314. }
  3315. public function GetPrerequisiteAttributes()
  3316. {
  3317. return array($this->Get("extkey_attcode"));
  3318. }
  3319. public function GetExtAttDef()
  3320. {
  3321. $oKeyAttDef = $this->GetKeyAttDef();
  3322. $oExtAttDef = MetaModel::GetAttributeDef($oKeyAttDef->GetTargetClass(), $this->Get("target_attcode"));
  3323. if (!is_object($oExtAttDef)) throw new CoreException("Invalid external field ".$this->GetCode()." in class ".$this->GetHostClass().". The class ".$oKeyAttDef->GetTargetClass()." has no attribute ".$this->Get("target_attcode"));
  3324. return $oExtAttDef;
  3325. }
  3326. public function GetSQLExpr()
  3327. {
  3328. $oExtAttDef = $this->GetExtAttDef();
  3329. return $oExtAttDef->GetSQLExpr();
  3330. }
  3331. public function GetDefaultValue()
  3332. {
  3333. $oExtAttDef = $this->GetExtAttDef();
  3334. return $oExtAttDef->GetDefaultValue();
  3335. }
  3336. public function IsNullAllowed()
  3337. {
  3338. $oExtAttDef = $this->GetExtAttDef();
  3339. return $oExtAttDef->IsNullAllowed();
  3340. }
  3341. public function IsScalar()
  3342. {
  3343. $oExtAttDef = $this->GetExtAttDef();
  3344. return $oExtAttDef->IsScalar();
  3345. }
  3346. public function GetFilterDefinitions()
  3347. {
  3348. return array($this->GetCode() => new FilterFromAttribute($this));
  3349. }
  3350. public function GetBasicFilterOperators()
  3351. {
  3352. $oExtAttDef = $this->GetExtAttDef();
  3353. return $oExtAttDef->GetBasicFilterOperators();
  3354. }
  3355. public function GetBasicFilterLooseOperator()
  3356. {
  3357. $oExtAttDef = $this->GetExtAttDef();
  3358. return $oExtAttDef->GetBasicFilterLooseOperator();
  3359. }
  3360. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3361. {
  3362. $oExtAttDef = $this->GetExtAttDef();
  3363. return $oExtAttDef->GetBasicFilterSQLExpr($sOpCode, $value);
  3364. }
  3365. public function GetNullValue()
  3366. {
  3367. $oExtAttDef = $this->GetExtAttDef();
  3368. return $oExtAttDef->GetNullValue();
  3369. }
  3370. public function IsNull($proposedValue)
  3371. {
  3372. $oExtAttDef = $this->GetExtAttDef();
  3373. return $oExtAttDef->IsNull($proposedValue);
  3374. }
  3375. public function MakeRealValue($proposedValue, $oHostObj)
  3376. {
  3377. $oExtAttDef = $this->GetExtAttDef();
  3378. return $oExtAttDef->MakeRealValue($proposedValue, $oHostObj);
  3379. }
  3380. public function ScalarToSQL($value)
  3381. {
  3382. // This one could be used in case of filtering only
  3383. $oExtAttDef = $this->GetExtAttDef();
  3384. return $oExtAttDef->ScalarToSQL($value);
  3385. }
  3386. // Do not overload GetSQLExpression here because this is handled in the joins
  3387. //public function GetSQLExpressions($sPrefix = '') {return array();}
  3388. // Here, we get the data...
  3389. public function FromSQLToValue($aCols, $sPrefix = '')
  3390. {
  3391. $oExtAttDef = $this->GetExtAttDef();
  3392. return $oExtAttDef->FromSQLToValue($aCols, $sPrefix);
  3393. }
  3394. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  3395. {
  3396. $oExtAttDef = $this->GetExtAttDef();
  3397. return $oExtAttDef->GetAsHTML($value, null, $bLocalize);
  3398. }
  3399. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  3400. {
  3401. $oExtAttDef = $this->GetExtAttDef();
  3402. return $oExtAttDef->GetAsXML($value, null, $bLocalize);
  3403. }
  3404. public function GetAsCSV($value, $sSeparator = ',', $sTestQualifier = '"', $oHostObject = null, $bLocalize = true)
  3405. {
  3406. $oExtAttDef = $this->GetExtAttDef();
  3407. return $oExtAttDef->GetAsCSV($value, $sSeparator, $sTestQualifier, null, $bLocalize);
  3408. }
  3409. public function IsPartOfFingerprint() { return false; }
  3410. }
  3411. /**
  3412. * Map a varchar column to an URL (formats the ouput in HMTL)
  3413. *
  3414. * @package iTopORM
  3415. */
  3416. class AttributeURL extends AttributeString
  3417. {
  3418. static public function ListExpectedParams()
  3419. {
  3420. //return parent::ListExpectedParams();
  3421. return array_merge(parent::ListExpectedParams(), array("target"));
  3422. }
  3423. public function GetEditClass() {return "String";}
  3424. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  3425. {
  3426. $sTarget = $this->Get("target");
  3427. if (empty($sTarget)) $sTarget = "_blank";
  3428. $sLabel = Str::pure2html($sValue);
  3429. if (strlen($sLabel) > 255)
  3430. {
  3431. // Truncate the length to 128 characters, by removing the middle
  3432. $sLabel = substr($sLabel, 0, 100).'.....'.substr($sLabel, -20);
  3433. }
  3434. return "<a target=\"$sTarget\" href=\"$sValue\">$sLabel</a>";
  3435. }
  3436. public function GetValidationPattern()
  3437. {
  3438. return $this->GetOptional('validation_pattern', '^'.utils::GetConfig()->Get('url_validation_pattern').'$');
  3439. }
  3440. }
  3441. /**
  3442. * A blob is an ormDocument, it is stored as several columns in the database
  3443. *
  3444. * @package iTopORM
  3445. */
  3446. class AttributeBlob extends AttributeDefinition
  3447. {
  3448. static public function ListExpectedParams()
  3449. {
  3450. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  3451. }
  3452. public function GetEditClass() {return "Document";}
  3453. public function IsDirectField() {return true;}
  3454. public function IsScalar() {return true;}
  3455. public function IsWritable() {return true;}
  3456. public function GetDefaultValue() {return "";}
  3457. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  3458. public function GetEditValue($sValue, $oHostObj = null)
  3459. {
  3460. return '';
  3461. }
  3462. // Facilitate things: allow administrators to upload a document
  3463. // from a CSV by specifying its path/URL
  3464. public function MakeRealValue($proposedValue, $oHostObj)
  3465. {
  3466. if (!is_object($proposedValue))
  3467. {
  3468. if (file_exists($proposedValue) && UserRights::IsAdministrator())
  3469. {
  3470. $sContent = file_get_contents($proposedValue);
  3471. $sExtension = strtolower(pathinfo($proposedValue, PATHINFO_EXTENSION));
  3472. $sMimeType = "application/x-octet-stream";
  3473. $aKnownExtensions = array(
  3474. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  3475. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  3476. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  3477. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  3478. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  3479. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  3480. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  3481. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  3482. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  3483. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12.xlsx',
  3484. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  3485. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  3486. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  3487. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  3488. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  3489. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  3490. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  3491. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  3492. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  3493. 'jpg' => 'image/jpeg',
  3494. 'jpeg' => 'image/jpeg',
  3495. 'gif' => 'image/gif',
  3496. 'png' => 'image/png',
  3497. 'pdf' => 'application/pdf',
  3498. 'doc' => 'application/msword',
  3499. 'dot' => 'application/msword',
  3500. 'xls' => 'application/vnd.ms-excel',
  3501. 'ppt' => 'application/vnd.ms-powerpoint',
  3502. 'vsd' => 'application/x-visio',
  3503. 'vdx' => 'application/visio.drawing',
  3504. 'odt' => 'application/vnd.oasis.opendocument.text',
  3505. 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  3506. 'odp' => 'application/vnd.oasis.opendocument.presentation',
  3507. 'zip' => 'application/zip',
  3508. 'txt' => 'text/plain',
  3509. 'htm' => 'text/html',
  3510. 'html' => 'text/html',
  3511. 'exe' => 'application/octet-stream'
  3512. );
  3513. if (!array_key_exists($sExtension, $aKnownExtensions) && extension_loaded('fileinfo'))
  3514. {
  3515. $finfo = new finfo(FILEINFO_MIME);
  3516. $sMimeType = $finfo->file($proposedValue);
  3517. }
  3518. return new ormDocument($sContent, $sMimeType);
  3519. }
  3520. else
  3521. {
  3522. return new ormDocument($proposedValue, 'text/plain');
  3523. }
  3524. }
  3525. return $proposedValue;
  3526. }
  3527. public function GetSQLExpressions($sPrefix = '')
  3528. {
  3529. if ($sPrefix == '')
  3530. {
  3531. $sPrefix = $this->GetCode();
  3532. }
  3533. $aColumns = array();
  3534. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  3535. $aColumns[''] = $sPrefix.'_mimetype';
  3536. $aColumns['_data'] = $sPrefix.'_data';
  3537. $aColumns['_filename'] = $sPrefix.'_filename';
  3538. return $aColumns;
  3539. }
  3540. public function FromSQLToValue($aCols, $sPrefix = '')
  3541. {
  3542. if (!array_key_exists($sPrefix, $aCols))
  3543. {
  3544. $sAvailable = implode(', ', array_keys($aCols));
  3545. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  3546. }
  3547. $sMimeType = isset($aCols[$sPrefix]) ? $aCols[$sPrefix] : '';
  3548. if (!array_key_exists($sPrefix.'_data', $aCols))
  3549. {
  3550. $sAvailable = implode(', ', array_keys($aCols));
  3551. throw new MissingColumnException("Missing column '".$sPrefix."_data' from {$sAvailable}");
  3552. }
  3553. $data = isset($aCols[$sPrefix.'_data']) ? $aCols[$sPrefix.'_data'] : null;
  3554. if (!array_key_exists($sPrefix.'_filename', $aCols))
  3555. {
  3556. $sAvailable = implode(', ', array_keys($aCols));
  3557. throw new MissingColumnException("Missing column '".$sPrefix."_filename' from {$sAvailable}");
  3558. }
  3559. $sFileName = isset($aCols[$sPrefix.'_filename']) ? $aCols[$sPrefix.'_filename'] : '';
  3560. $value = new ormDocument($data, $sMimeType, $sFileName);
  3561. return $value;
  3562. }
  3563. public function GetSQLValues($value)
  3564. {
  3565. // #@# Optimization: do not load blobs anytime
  3566. // As per mySQL doc, selecting blob columns will prevent mySQL from
  3567. // using memory in case a temporary table has to be created
  3568. // (temporary tables created on disk)
  3569. // We will have to remove the blobs from the list of attributes when doing the select
  3570. // then the use of Get() should finalize the load
  3571. if ($value instanceOf ormDocument)
  3572. {
  3573. $aValues = array();
  3574. $aValues[$this->GetCode().'_data'] = $value->GetData();
  3575. $aValues[$this->GetCode().'_mimetype'] = $value->GetMimeType();
  3576. $aValues[$this->GetCode().'_filename'] = $value->GetFileName();
  3577. }
  3578. else
  3579. {
  3580. $aValues = array();
  3581. $aValues[$this->GetCode().'_data'] = '';
  3582. $aValues[$this->GetCode().'_mimetype'] = '';
  3583. $aValues[$this->GetCode().'_filename'] = '';
  3584. }
  3585. return $aValues;
  3586. }
  3587. public function GetSQLColumns($bFullSpec = false)
  3588. {
  3589. $aColumns = array();
  3590. $aColumns[$this->GetCode().'_data'] = 'LONGBLOB'; // 2^32 (4 Gb)
  3591. $aColumns[$this->GetCode().'_mimetype'] = 'VARCHAR(255)';
  3592. $aColumns[$this->GetCode().'_filename'] = 'VARCHAR(255)';
  3593. return $aColumns;
  3594. }
  3595. public function GetFilterDefinitions()
  3596. {
  3597. return array();
  3598. // still not working... see later...
  3599. return array(
  3600. $this->GetCode().'->filename' => new FilterFromAttribute($this, '_filename'),
  3601. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype'),
  3602. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype')
  3603. );
  3604. }
  3605. public function GetBasicFilterOperators()
  3606. {
  3607. return array();
  3608. }
  3609. public function GetBasicFilterLooseOperator()
  3610. {
  3611. return '=';
  3612. }
  3613. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3614. {
  3615. return 'true';
  3616. }
  3617. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  3618. {
  3619. if (is_object($value))
  3620. {
  3621. return $value->GetAsHTML();
  3622. }
  3623. }
  3624. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  3625. {
  3626. return ''; // Not exportable in CSV !
  3627. }
  3628. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  3629. {
  3630. return ''; // Not exportable in XML, or as CDATA + some subtags ??
  3631. }
  3632. /**
  3633. * Helper to get a value that will be JSON encoded
  3634. * The operation is the opposite to FromJSONToValue
  3635. */
  3636. public function GetForJSON($value)
  3637. {
  3638. if ($value instanceOf ormDocument)
  3639. {
  3640. $aValues = array();
  3641. $aValues['data'] = base64_encode($value->GetData());
  3642. $aValues['mimetype'] = $value->GetMimeType();
  3643. $aValues['filename'] = $value->GetFileName();
  3644. }
  3645. else
  3646. {
  3647. $aValues = null;
  3648. }
  3649. return $aValues;
  3650. }
  3651. /**
  3652. * Helper to form a value, given JSON decoded data
  3653. * The operation is the opposite to GetForJSON
  3654. */
  3655. public function FromJSONToValue($json)
  3656. {
  3657. if (isset($json->data))
  3658. {
  3659. $data = base64_decode($json->data);
  3660. $value = new ormDocument($data, $json->mimetype, $json->filename);
  3661. }
  3662. else
  3663. {
  3664. $value = null;
  3665. }
  3666. return $value;
  3667. }
  3668. public function Fingerprint($value)
  3669. {
  3670. $sFingerprint = '';
  3671. if ($value instanceOf ormDocument)
  3672. {
  3673. $sFingerprint = md5($value->GetData());
  3674. }
  3675. return $sFingerprint;
  3676. }
  3677. }
  3678. /**
  3679. * A stop watch is an ormStopWatch object, it is stored as several columns in the database
  3680. *
  3681. * @package iTopORM
  3682. */
  3683. class AttributeStopWatch extends AttributeDefinition
  3684. {
  3685. static public function ListExpectedParams()
  3686. {
  3687. // The list of thresholds must be an array of iPercent => array of 'option' => value
  3688. return array_merge(parent::ListExpectedParams(), array("states", "goal_computing", "working_time_computing", "thresholds"));
  3689. }
  3690. public function GetEditClass() {return "StopWatch";}
  3691. public function IsDirectField() {return true;}
  3692. public function IsScalar() {return true;}
  3693. public function IsWritable() {return false;}
  3694. public function GetDefaultValue() {return $this->NewStopWatch();}
  3695. public function GetEditValue($value, $oHostObj = null)
  3696. {
  3697. return $value->GetTimeSpent();
  3698. }
  3699. public function GetStates()
  3700. {
  3701. return $this->Get('states');
  3702. }
  3703. public function AlwaysLoadInTables()
  3704. {
  3705. // Each and every stop watch is accessed for computing the highlight code (DBObject::GetHighlightCode())
  3706. return true;
  3707. }
  3708. /**
  3709. * Construct a brand new (but configured) stop watch
  3710. */
  3711. public function NewStopWatch()
  3712. {
  3713. $oSW = new ormStopWatch();
  3714. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3715. {
  3716. $oSW->DefineThreshold($iThreshold);
  3717. }
  3718. return $oSW;
  3719. }
  3720. // Facilitate things: allow the user to Set the value from a string
  3721. public function MakeRealValue($proposedValue, $oHostObj)
  3722. {
  3723. if (!$proposedValue instanceof ormStopWatch)
  3724. {
  3725. return $this->NewStopWatch();
  3726. }
  3727. return $proposedValue;
  3728. }
  3729. public function GetSQLExpressions($sPrefix = '')
  3730. {
  3731. if ($sPrefix == '')
  3732. {
  3733. $sPrefix = $this->GetCode();
  3734. }
  3735. $aColumns = array();
  3736. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  3737. $aColumns[''] = $sPrefix.'_timespent';
  3738. $aColumns['_started'] = $sPrefix.'_started';
  3739. $aColumns['_laststart'] = $sPrefix.'_laststart';
  3740. $aColumns['_stopped'] = $sPrefix.'_stopped';
  3741. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3742. {
  3743. $sThPrefix = '_'.$iThreshold;
  3744. $aColumns[$sThPrefix.'_deadline'] = $sPrefix.$sThPrefix.'_deadline';
  3745. $aColumns[$sThPrefix.'_passed'] = $sPrefix.$sThPrefix.'_passed';
  3746. $aColumns[$sThPrefix.'_triggered'] = $sPrefix.$sThPrefix.'_triggered';
  3747. $aColumns[$sThPrefix.'_overrun'] = $sPrefix.$sThPrefix.'_overrun';
  3748. }
  3749. return $aColumns;
  3750. }
  3751. public static function DateToSeconds($sDate)
  3752. {
  3753. if (is_null($sDate))
  3754. {
  3755. return null;
  3756. }
  3757. $oDateTime = new DateTime($sDate);
  3758. $iSeconds = $oDateTime->format('U');
  3759. return $iSeconds;
  3760. }
  3761. public static function SecondsToDate($iSeconds)
  3762. {
  3763. if (is_null($iSeconds))
  3764. {
  3765. return null;
  3766. }
  3767. return date("Y-m-d H:i:s", $iSeconds);
  3768. }
  3769. public function FromSQLToValue($aCols, $sPrefix = '')
  3770. {
  3771. $aExpectedCols = array($sPrefix, $sPrefix.'_started', $sPrefix.'_laststart', $sPrefix.'_stopped');
  3772. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3773. {
  3774. $sThPrefix = '_'.$iThreshold;
  3775. $aExpectedCols[] = $sPrefix.$sThPrefix.'_deadline';
  3776. $aExpectedCols[] = $sPrefix.$sThPrefix.'_passed';
  3777. $aExpectedCols[] = $sPrefix.$sThPrefix.'_triggered';
  3778. $aExpectedCols[] = $sPrefix.$sThPrefix.'_overrun';
  3779. }
  3780. foreach ($aExpectedCols as $sExpectedCol)
  3781. {
  3782. if (!array_key_exists($sExpectedCol, $aCols))
  3783. {
  3784. $sAvailable = implode(', ', array_keys($aCols));
  3785. throw new MissingColumnException("Missing column '$sExpectedCol' from {$sAvailable}");
  3786. }
  3787. }
  3788. $value = new ormStopWatch(
  3789. $aCols[$sPrefix],
  3790. self::DateToSeconds($aCols[$sPrefix.'_started']),
  3791. self::DateToSeconds($aCols[$sPrefix.'_laststart']),
  3792. self::DateToSeconds($aCols[$sPrefix.'_stopped'])
  3793. );
  3794. $aThresholds = array();
  3795. foreach ($this->ListThresholds() as $iThreshold => $aDefinition)
  3796. {
  3797. $sThPrefix = '_'.$iThreshold;
  3798. $value->DefineThreshold(
  3799. $iThreshold,
  3800. self::DateToSeconds($aCols[$sPrefix.$sThPrefix.'_deadline']),
  3801. (bool)($aCols[$sPrefix.$sThPrefix.'_passed'] == 1),
  3802. (bool)($aCols[$sPrefix.$sThPrefix.'_triggered'] == 1),
  3803. $aCols[$sPrefix.$sThPrefix.'_overrun'],
  3804. array_key_exists('highlight', $aDefinition) ? $aDefinition['highlight'] : null
  3805. );
  3806. }
  3807. return $value;
  3808. }
  3809. public function GetSQLValues($value)
  3810. {
  3811. if ($value instanceOf ormStopWatch)
  3812. {
  3813. $aValues = array();
  3814. $aValues[$this->GetCode().'_timespent'] = $value->GetTimeSpent();
  3815. $aValues[$this->GetCode().'_started'] = self::SecondsToDate($value->GetStartDate());
  3816. $aValues[$this->GetCode().'_laststart'] = self::SecondsToDate($value->GetLastStartDate());
  3817. $aValues[$this->GetCode().'_stopped'] = self::SecondsToDate($value->GetStopDate());
  3818. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3819. {
  3820. $sPrefix = $this->GetCode().'_'.$iThreshold;
  3821. $aValues[$sPrefix.'_deadline'] = self::SecondsToDate($value->GetThresholdDate($iThreshold));
  3822. $aValues[$sPrefix.'_passed'] = $value->IsThresholdPassed($iThreshold) ? '1' : '0';
  3823. $aValues[$sPrefix.'_triggered'] = $value->IsThresholdTriggered($iThreshold) ? '1' : '0';
  3824. $aValues[$sPrefix.'_overrun'] = $value->GetOverrun($iThreshold);
  3825. }
  3826. }
  3827. else
  3828. {
  3829. $aValues = array();
  3830. $aValues[$this->GetCode().'_timespent'] = '';
  3831. $aValues[$this->GetCode().'_started'] = '';
  3832. $aValues[$this->GetCode().'_laststart'] = '';
  3833. $aValues[$this->GetCode().'_stopped'] = '';
  3834. }
  3835. return $aValues;
  3836. }
  3837. public function GetSQLColumns($bFullSpec = false)
  3838. {
  3839. $aColumns = array();
  3840. $aColumns[$this->GetCode().'_timespent'] = 'INT(11) UNSIGNED';
  3841. $aColumns[$this->GetCode().'_started'] = 'DATETIME';
  3842. $aColumns[$this->GetCode().'_laststart'] = 'DATETIME';
  3843. $aColumns[$this->GetCode().'_stopped'] = 'DATETIME';
  3844. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3845. {
  3846. $sPrefix = $this->GetCode().'_'.$iThreshold;
  3847. $aColumns[$sPrefix.'_deadline'] = 'DATETIME';
  3848. $aColumns[$sPrefix.'_passed'] = 'TINYINT(1) UNSIGNED';
  3849. $aColumns[$sPrefix.'_triggered'] = 'TINYINT(1)';
  3850. $aColumns[$sPrefix.'_overrun'] = 'INT(11) UNSIGNED';
  3851. }
  3852. return $aColumns;
  3853. }
  3854. public function GetFilterDefinitions()
  3855. {
  3856. $aRes = array(
  3857. $this->GetCode() => new FilterFromAttribute($this),
  3858. $this->GetCode().'_started' => new FilterFromAttribute($this, '_started'),
  3859. $this->GetCode().'_laststart' => new FilterFromAttribute($this, '_laststart'),
  3860. $this->GetCode().'_stopped' => new FilterFromAttribute($this, '_stopped')
  3861. );
  3862. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3863. {
  3864. $sPrefix = $this->GetCode().'_'.$iThreshold;
  3865. $aRes[$sPrefix.'_deadline'] = new FilterFromAttribute($this, '_deadline');
  3866. $aRes[$sPrefix.'_passed'] = new FilterFromAttribute($this, '_passed');
  3867. $aRes[$sPrefix.'_triggered'] = new FilterFromAttribute($this, '_triggered');
  3868. $aRes[$sPrefix.'_overrun'] = new FilterFromAttribute($this, '_overrun');
  3869. }
  3870. return $aRes;
  3871. }
  3872. public function GetBasicFilterOperators()
  3873. {
  3874. return array();
  3875. }
  3876. public function GetBasicFilterLooseOperator()
  3877. {
  3878. return '=';
  3879. }
  3880. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3881. {
  3882. return 'true';
  3883. }
  3884. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  3885. {
  3886. if (is_object($value))
  3887. {
  3888. return $value->GetAsHTML($this, $oHostObject);
  3889. }
  3890. }
  3891. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  3892. {
  3893. return $value->GetTimeSpent();
  3894. }
  3895. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  3896. {
  3897. return $value->GetTimeSpent();
  3898. }
  3899. public function ListThresholds()
  3900. {
  3901. return $this->Get('thresholds');
  3902. }
  3903. public function Fingerprint($value)
  3904. {
  3905. $sFingerprint = '';
  3906. if (is_object($value))
  3907. {
  3908. $sFingerprint = $value->GetAsHTML($this);
  3909. }
  3910. return $sFingerprint;
  3911. }
  3912. /**
  3913. * To expose internal values: Declare an attribute AttributeSubItem
  3914. * and implement the GetSubItemXXXX verbs
  3915. */
  3916. public function GetSubItemSQLExpression($sItemCode)
  3917. {
  3918. $sPrefix = $this->GetCode();
  3919. switch($sItemCode)
  3920. {
  3921. case 'timespent':
  3922. return array('' => $sPrefix.'_timespent');
  3923. case 'started':
  3924. return array('' => $sPrefix.'_started');
  3925. case 'laststart':
  3926. return array('' => $sPrefix.'_laststart');
  3927. case 'stopped':
  3928. return array('' => $sPrefix.'_stopped');
  3929. }
  3930. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3931. {
  3932. $sThPrefix = $iThreshold.'_';
  3933. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  3934. {
  3935. // The current threshold is concerned
  3936. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  3937. switch($sThresholdCode)
  3938. {
  3939. case 'deadline':
  3940. return array('' => $sPrefix.'_'.$iThreshold.'_deadline');
  3941. case 'passed':
  3942. return array('' => $sPrefix.'_'.$iThreshold.'_passed');
  3943. case 'triggered':
  3944. return array('' => $sPrefix.'_'.$iThreshold.'_triggered');
  3945. case 'overrun':
  3946. return array('' => $sPrefix.'_'.$iThreshold.'_overrun');
  3947. }
  3948. }
  3949. }
  3950. throw new CoreException("Unknown item code '$sItemCode' for attribute ".$this->GetHostClass().'::'.$this->GetCode());
  3951. }
  3952. public function GetSubItemValue($sItemCode, $value, $oHostObject = null)
  3953. {
  3954. $oStopWatch = $value;
  3955. switch($sItemCode)
  3956. {
  3957. case 'timespent':
  3958. return $oStopWatch->GetTimeSpent();
  3959. case 'started':
  3960. return $oStopWatch->GetStartDate();
  3961. case 'laststart':
  3962. return $oStopWatch->GetLastStartDate();
  3963. case 'stopped':
  3964. return $oStopWatch->GetStopDate();
  3965. }
  3966. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3967. {
  3968. $sThPrefix = $iThreshold.'_';
  3969. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  3970. {
  3971. // The current threshold is concerned
  3972. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  3973. switch($sThresholdCode)
  3974. {
  3975. case 'deadline':
  3976. return $oStopWatch->GetThresholdDate($iThreshold);
  3977. case 'passed':
  3978. return $oStopWatch->IsThresholdPassed($iThreshold);
  3979. case 'triggered':
  3980. return $oStopWatch->IsThresholdTriggered($iThreshold);
  3981. case 'overrun':
  3982. return $oStopWatch->GetOverrun($iThreshold);
  3983. }
  3984. }
  3985. }
  3986. throw new CoreException("Unknown item code '$sItemCode' for attribute ".$this->GetHostClass().'::'.$this->GetCode());
  3987. }
  3988. protected function GetBooleanLabel($bValue)
  3989. {
  3990. $sDictKey = $bValue ? 'yes' : 'no';
  3991. return Dict::S('BooleanLabel:'.$sDictKey, 'def:'.$sDictKey);
  3992. }
  3993. public function GetSubItemAsHTMLForHistory($sItemCode, $sValue)
  3994. {
  3995. switch($sItemCode)
  3996. {
  3997. case 'timespent':
  3998. $sHtml = (int)$sValue ? Str::pure2html(AttributeDuration::FormatDuration($sValue)) : null;
  3999. break;
  4000. case 'started':
  4001. case 'laststart':
  4002. case 'stopped':
  4003. $sHtml = (int)$sValue ? date(self::GetDateFormat(), (int)$sValue) : null;
  4004. break;
  4005. default:
  4006. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4007. {
  4008. $sThPrefix = $iThreshold.'_';
  4009. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4010. {
  4011. // The current threshold is concerned
  4012. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4013. switch($sThresholdCode)
  4014. {
  4015. case 'deadline':
  4016. $sHtml = (int)$sValue ? date(self::GetDateFormat(true /*full*/), (int)$sValue) : null;
  4017. break;
  4018. case 'passed':
  4019. $sHtml = $this->GetBooleanLabel((int)$sValue);
  4020. break;
  4021. case 'triggered':
  4022. $sHtml = $this->GetBooleanLabel((int)$sValue);
  4023. break;
  4024. case 'overrun':
  4025. $sHtml = (int)$sValue > 0 ? Str::pure2html(AttributeDuration::FormatDuration((int)$sValue)) : '';
  4026. }
  4027. }
  4028. }
  4029. }
  4030. return $sHtml;
  4031. }
  4032. static protected function GetDateFormat($bFull = false)
  4033. {
  4034. if ($bFull)
  4035. {
  4036. return "Y-m-d H:i:s";
  4037. }
  4038. else
  4039. {
  4040. return "Y-m-d H:i";
  4041. }
  4042. }
  4043. public function GetSubItemAsHTML($sItemCode, $value)
  4044. {
  4045. $sHtml = $value;
  4046. switch($sItemCode)
  4047. {
  4048. case 'timespent':
  4049. $sHtml = Str::pure2html(AttributeDuration::FormatDuration($value));
  4050. break;
  4051. case 'started':
  4052. case 'laststart':
  4053. case 'stopped':
  4054. if (is_null($value))
  4055. {
  4056. $sHtml = ''; // Undefined
  4057. }
  4058. else
  4059. {
  4060. $sHtml = date(self::GetDateFormat(), $value);
  4061. }
  4062. break;
  4063. default:
  4064. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4065. {
  4066. $sThPrefix = $iThreshold.'_';
  4067. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4068. {
  4069. // The current threshold is concerned
  4070. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4071. switch($sThresholdCode)
  4072. {
  4073. case 'deadline':
  4074. if ($value)
  4075. {
  4076. $sDate = date(self::GetDateFormat(true /*full*/), $value);
  4077. $sHtml = Str::pure2html(AttributeDeadline::FormatDeadline($sDate));
  4078. }
  4079. else
  4080. {
  4081. $sHtml = '';
  4082. }
  4083. break;
  4084. case 'passed':
  4085. case 'triggered':
  4086. $sHtml = $this->GetBooleanLabel($value);
  4087. break;
  4088. case 'overrun':
  4089. $sHtml = Str::pure2html(AttributeDuration::FormatDuration($value));
  4090. break;
  4091. }
  4092. }
  4093. }
  4094. }
  4095. return $sHtml;
  4096. }
  4097. public function GetSubItemAsCSV($sItemCode, $value, $sSeparator = ',', $sTextQualifier = '"')
  4098. {
  4099. $sFrom = array("\r\n", $sTextQualifier);
  4100. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  4101. $sEscaped = str_replace($sFrom, $sTo, (string)$value);
  4102. $sRet = $sTextQualifier.$sEscaped.$sTextQualifier;
  4103. switch($sItemCode)
  4104. {
  4105. case 'timespent':
  4106. case 'started':
  4107. case 'laststart':
  4108. case 'stopped':
  4109. break;
  4110. default:
  4111. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4112. {
  4113. $sThPrefix = $iThreshold.'_';
  4114. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4115. {
  4116. // The current threshold is concerned
  4117. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4118. switch($sThresholdCode)
  4119. {
  4120. case 'deadline':
  4121. if ($value != '')
  4122. {
  4123. $sRet = $sTextQualifier.date(self::GetDateFormat(true /*full*/), $value).$sTextQualifier;
  4124. }
  4125. break;
  4126. case 'passed':
  4127. case 'triggered':
  4128. $sRet = $sTextQualifier.$this->GetBooleanLabel($value).$sTextQualifier;
  4129. break;
  4130. case 'overrun':
  4131. break;
  4132. }
  4133. }
  4134. }
  4135. }
  4136. return $sRet;
  4137. }
  4138. public function GetSubItemAsXML($sItemCode, $value)
  4139. {
  4140. $sRet = Str::pure2xml((string)$value);
  4141. switch($sItemCode)
  4142. {
  4143. case 'timespent':
  4144. case 'started':
  4145. case 'laststart':
  4146. case 'stopped':
  4147. break;
  4148. default:
  4149. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4150. {
  4151. $sThPrefix = $iThreshold.'_';
  4152. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4153. {
  4154. // The current threshold is concerned
  4155. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4156. switch($sThresholdCode)
  4157. {
  4158. case 'deadline':
  4159. break;
  4160. case 'passed':
  4161. case 'triggered':
  4162. $sRet = $this->GetBooleanLabel($value);
  4163. break;
  4164. case 'overrun':
  4165. break;
  4166. }
  4167. }
  4168. }
  4169. }
  4170. return $sRet;
  4171. }
  4172. /**
  4173. * Implemented for the HTML spreadsheet format!
  4174. */
  4175. public function GetSubItemAsEditValue($sItemCode, $value)
  4176. {
  4177. $sRet = $value;
  4178. switch($sItemCode)
  4179. {
  4180. case 'timespent':
  4181. break;
  4182. case 'started':
  4183. case 'laststart':
  4184. case 'stopped':
  4185. if (is_null($value))
  4186. {
  4187. $sRet = ''; // Undefined
  4188. }
  4189. else
  4190. {
  4191. $sRet = date(self::GetDateFormat(), $value);
  4192. }
  4193. break;
  4194. default:
  4195. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4196. {
  4197. $sThPrefix = $iThreshold.'_';
  4198. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4199. {
  4200. // The current threshold is concerned
  4201. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4202. switch($sThresholdCode)
  4203. {
  4204. case 'deadline':
  4205. if ($value)
  4206. {
  4207. $sRet = date(self::GetDateFormat(true /*full*/), $value);
  4208. }
  4209. else
  4210. {
  4211. $sRet = '';
  4212. }
  4213. break;
  4214. case 'passed':
  4215. case 'triggered':
  4216. $sRet = $this->GetBooleanLabel($value);
  4217. break;
  4218. case 'overrun':
  4219. break;
  4220. }
  4221. }
  4222. }
  4223. }
  4224. return $sRet;
  4225. }
  4226. }
  4227. /**
  4228. * View of a subvalue of another attribute
  4229. * If an attribute implements the verbs GetSubItem.... then it can expose
  4230. * internal values, each of them being an attribute and therefore they
  4231. * can be displayed at different times in the object lifecycle, and used for
  4232. * reporting (as a condition in OQL, or as an additional column in an export)
  4233. * Known usages: Stop Watches can expose threshold statuses
  4234. */
  4235. class AttributeSubItem extends AttributeDefinition
  4236. {
  4237. static public function ListExpectedParams()
  4238. {
  4239. return array_merge(parent::ListExpectedParams(), array('target_attcode', 'item_code'));
  4240. }
  4241. public function GetParentAttCode() {return $this->Get("target_attcode");}
  4242. /**
  4243. * Helper : get the attribute definition to which the execution will be forwarded
  4244. */
  4245. public function GetTargetAttDef()
  4246. {
  4247. $sClass = $this->GetHostClass();
  4248. $oParentAttDef = MetaModel::GetAttributeDef($sClass, $this->Get('target_attcode'));
  4249. return $oParentAttDef;
  4250. }
  4251. public function GetEditClass() {return "";}
  4252. public function GetValuesDef() {return null;}
  4253. //public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  4254. public function IsDirectField() {return true;}
  4255. public function IsScalar() {return true;}
  4256. public function IsWritable() {return false;}
  4257. public function GetDefaultValue() {return null;}
  4258. // public function IsNullAllowed() {return false;}
  4259. public function LoadInObject() {return false;} // if this verb returns true, then GetValue must be implemented
  4260. //
  4261. // protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  4262. public function FromSQLToValue($aCols, $sPrefix = '')
  4263. {
  4264. }
  4265. public function GetSQLColumns($bFullSpec = false)
  4266. {
  4267. return array();
  4268. }
  4269. public function GetFilterDefinitions()
  4270. {
  4271. return array($this->GetCode() => new FilterFromAttribute($this));
  4272. }
  4273. public function GetBasicFilterOperators()
  4274. {
  4275. return array();
  4276. }
  4277. public function GetBasicFilterLooseOperator()
  4278. {
  4279. return "=";
  4280. }
  4281. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4282. {
  4283. $sQValue = CMDBSource::Quote($value);
  4284. switch ($sOpCode)
  4285. {
  4286. case '!=':
  4287. return $this->GetSQLExpr()." != $sQValue";
  4288. break;
  4289. case '=':
  4290. default:
  4291. return $this->GetSQLExpr()." = $sQValue";
  4292. }
  4293. }
  4294. public function GetSQLExpressions($sPrefix = '')
  4295. {
  4296. $oParent = $this->GetTargetAttDef();
  4297. $res = $oParent->GetSubItemSQLExpression($this->Get('item_code'));
  4298. return $res;
  4299. }
  4300. /**
  4301. * Used by DBOBject::Get()
  4302. */
  4303. public function GetValue($parentValue, $oHostObject = null)
  4304. {
  4305. $oParent = $this->GetTargetAttDef();
  4306. $res = $oParent->GetSubItemValue($this->Get('item_code'), $parentValue, $oHostObject);
  4307. return $res;
  4308. }
  4309. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4310. {
  4311. $oParent = $this->GetTargetAttDef();
  4312. $res = $oParent->GetSubItemAsHTML($this->Get('item_code'), $value);
  4313. return $res;
  4314. }
  4315. public function GetAsHTMLForHistory($value, $oHostObject = null, $bLocalize = true)
  4316. {
  4317. $oParent = $this->GetTargetAttDef();
  4318. $res = $oParent->GetSubItemAsHTMLForHistory($this->Get('item_code'), $value);
  4319. return $res;
  4320. }
  4321. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  4322. {
  4323. $oParent = $this->GetTargetAttDef();
  4324. $res = $oParent->GetSubItemAsCSV($this->Get('item_code'), $value, $sSeparator, $sTextQualifier);
  4325. return $res;
  4326. }
  4327. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4328. {
  4329. $oParent = $this->GetTargetAttDef();
  4330. $res = $oParent->GetSubItemAsXML($this->Get('item_code'), $value);
  4331. return $res;
  4332. }
  4333. /**
  4334. * As of now, this function must be implemented to have the value in spreadsheet format
  4335. */
  4336. public function GetEditValue($value, $oHostObj = null)
  4337. {
  4338. $oParent = $this->GetTargetAttDef();
  4339. $res = $oParent->GetSubItemAsEditValue($this->Get('item_code'), $value);
  4340. return $res;
  4341. }
  4342. public function IsPartOfFingerprint() { return false; }
  4343. }
  4344. /**
  4345. * One way encrypted (hashed) password
  4346. */
  4347. class AttributeOneWayPassword extends AttributeDefinition
  4348. {
  4349. static public function ListExpectedParams()
  4350. {
  4351. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  4352. }
  4353. public function GetEditClass() {return "One Way Password";}
  4354. public function IsDirectField() {return true;}
  4355. public function IsScalar() {return true;}
  4356. public function IsWritable() {return true;}
  4357. public function GetDefaultValue() {return "";}
  4358. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  4359. // Facilitate things: allow the user to Set the value from a string or from an ormPassword (already encrypted)
  4360. public function MakeRealValue($proposedValue, $oHostObj)
  4361. {
  4362. $oPassword = $proposedValue;
  4363. if (!is_object($oPassword))
  4364. {
  4365. $oPassword = new ormPassword('', '');
  4366. $oPassword->SetPassword($proposedValue);
  4367. }
  4368. return $oPassword;
  4369. }
  4370. public function GetSQLExpressions($sPrefix = '')
  4371. {
  4372. if ($sPrefix == '')
  4373. {
  4374. $sPrefix = $this->GetCode();
  4375. }
  4376. $aColumns = array();
  4377. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  4378. $aColumns[''] = $sPrefix.'_hash';
  4379. $aColumns['_salt'] = $sPrefix.'_salt';
  4380. return $aColumns;
  4381. }
  4382. public function FromSQLToValue($aCols, $sPrefix = '')
  4383. {
  4384. if (!array_key_exists($sPrefix, $aCols))
  4385. {
  4386. $sAvailable = implode(', ', array_keys($aCols));
  4387. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  4388. }
  4389. $hashed = isset($aCols[$sPrefix]) ? $aCols[$sPrefix] : '';
  4390. if (!array_key_exists($sPrefix.'_salt', $aCols))
  4391. {
  4392. $sAvailable = implode(', ', array_keys($aCols));
  4393. throw new MissingColumnException("Missing column '".$sPrefix."_salt' from {$sAvailable}");
  4394. }
  4395. $sSalt = isset($aCols[$sPrefix.'_salt']) ? $aCols[$sPrefix.'_salt'] : '';
  4396. $value = new ormPassword($hashed, $sSalt);
  4397. return $value;
  4398. }
  4399. public function GetSQLValues($value)
  4400. {
  4401. // #@# Optimization: do not load blobs anytime
  4402. // As per mySQL doc, selecting blob columns will prevent mySQL from
  4403. // using memory in case a temporary table has to be created
  4404. // (temporary tables created on disk)
  4405. // We will have to remove the blobs from the list of attributes when doing the select
  4406. // then the use of Get() should finalize the load
  4407. if ($value instanceOf ormPassword)
  4408. {
  4409. $aValues = array();
  4410. $aValues[$this->GetCode().'_hash'] = $value->GetHash();
  4411. $aValues[$this->GetCode().'_salt'] = $value->GetSalt();
  4412. }
  4413. else
  4414. {
  4415. $aValues = array();
  4416. $aValues[$this->GetCode().'_hash'] = '';
  4417. $aValues[$this->GetCode().'_salt'] = '';
  4418. }
  4419. return $aValues;
  4420. }
  4421. public function GetSQLColumns($bFullSpec = false)
  4422. {
  4423. $aColumns = array();
  4424. $aColumns[$this->GetCode().'_hash'] = 'TINYBLOB';
  4425. $aColumns[$this->GetCode().'_salt'] = 'TINYBLOB';
  4426. return $aColumns;
  4427. }
  4428. public function GetImportColumns()
  4429. {
  4430. $aColumns = array();
  4431. $aColumns[$this->GetCode()] = 'TINYTEXT';
  4432. return $aColumns;
  4433. }
  4434. public function FromImportToValue($aCols, $sPrefix = '')
  4435. {
  4436. if (!isset($aCols[$sPrefix]))
  4437. {
  4438. $sAvailable = implode(', ', array_keys($aCols));
  4439. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  4440. }
  4441. $sClearPwd = $aCols[$sPrefix];
  4442. $oPassword = new ormPassword('', '');
  4443. $oPassword->SetPassword($sClearPwd);
  4444. return $oPassword;
  4445. }
  4446. public function GetFilterDefinitions()
  4447. {
  4448. return array();
  4449. // still not working... see later...
  4450. }
  4451. public function GetBasicFilterOperators()
  4452. {
  4453. return array();
  4454. }
  4455. public function GetBasicFilterLooseOperator()
  4456. {
  4457. return '=';
  4458. }
  4459. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4460. {
  4461. return 'true';
  4462. }
  4463. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4464. {
  4465. if (is_object($value))
  4466. {
  4467. return $value->GetAsHTML();
  4468. }
  4469. }
  4470. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  4471. {
  4472. return ''; // Not exportable in CSV
  4473. }
  4474. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4475. {
  4476. return ''; // Not exportable in XML
  4477. }
  4478. }
  4479. // Indexed array having two dimensions
  4480. class AttributeTable extends AttributeDBField
  4481. {
  4482. public function GetEditClass() {return "Table";}
  4483. protected function GetSQLCol($bFullSpec = false) {return "LONGTEXT";}
  4484. public function GetMaxSize()
  4485. {
  4486. return null;
  4487. }
  4488. public function GetNullValue()
  4489. {
  4490. return array();
  4491. }
  4492. public function IsNull($proposedValue)
  4493. {
  4494. return (count($proposedValue) == 0);
  4495. }
  4496. public function GetEditValue($sValue, $oHostObj = null)
  4497. {
  4498. return '';
  4499. }
  4500. // Facilitate things: allow the user to Set the value from a string
  4501. public function MakeRealValue($proposedValue, $oHostObj)
  4502. {
  4503. if (is_null($proposedValue))
  4504. {
  4505. return array();
  4506. }
  4507. else if (!is_array($proposedValue))
  4508. {
  4509. return array(0 => array(0 => $proposedValue));
  4510. }
  4511. return $proposedValue;
  4512. }
  4513. public function FromSQLToValue($aCols, $sPrefix = '')
  4514. {
  4515. try
  4516. {
  4517. $value = @unserialize($aCols[$sPrefix.'']);
  4518. if ($value === false)
  4519. {
  4520. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  4521. }
  4522. }
  4523. catch(Exception $e)
  4524. {
  4525. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  4526. }
  4527. return $value;
  4528. }
  4529. public function GetSQLValues($value)
  4530. {
  4531. $aValues = array();
  4532. $aValues[$this->Get("sql")] = serialize($value);
  4533. return $aValues;
  4534. }
  4535. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4536. {
  4537. if (!is_array($value))
  4538. {
  4539. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  4540. }
  4541. if (count($value) == 0)
  4542. {
  4543. return "";
  4544. }
  4545. $sRes = "<TABLE class=\"listResults\">";
  4546. $sRes .= "<TBODY>";
  4547. foreach($value as $iRow => $aRawData)
  4548. {
  4549. $sRes .= "<TR>";
  4550. foreach ($aRawData as $iCol => $cell)
  4551. {
  4552. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$cell));
  4553. $sRes .= "<TD>$sCell</TD>";
  4554. }
  4555. $sRes .= "</TR>";
  4556. }
  4557. $sRes .= "</TBODY>";
  4558. $sRes .= "</TABLE>";
  4559. return $sRes;
  4560. }
  4561. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  4562. {
  4563. // Not implemented
  4564. return '';
  4565. }
  4566. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4567. {
  4568. if (count($value) == 0)
  4569. {
  4570. return "";
  4571. }
  4572. $sRes = "";
  4573. foreach($value as $iRow => $aRawData)
  4574. {
  4575. $sRes .= "<row>";
  4576. foreach ($aRawData as $iCol => $cell)
  4577. {
  4578. $sCell = Str::pure2xml((string)$cell);
  4579. $sRes .= "<cell icol=\"$iCol\">$sCell</cell>";
  4580. }
  4581. $sRes .= "</row>";
  4582. }
  4583. return $sRes;
  4584. }
  4585. }
  4586. // The PHP value is a hash array, it is stored as a TEXT column
  4587. class AttributePropertySet extends AttributeTable
  4588. {
  4589. public function GetEditClass() {return "PropertySet";}
  4590. // Facilitate things: allow the user to Set the value from a string
  4591. public function MakeRealValue($proposedValue, $oHostObj)
  4592. {
  4593. if (!is_array($proposedValue))
  4594. {
  4595. return array('?' => (string)$proposedValue);
  4596. }
  4597. return $proposedValue;
  4598. }
  4599. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4600. {
  4601. if (!is_array($value))
  4602. {
  4603. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  4604. }
  4605. if (count($value) == 0)
  4606. {
  4607. return "";
  4608. }
  4609. $sRes = "<TABLE class=\"listResults\">";
  4610. $sRes .= "<TBODY>";
  4611. foreach($value as $sProperty => $sValue)
  4612. {
  4613. if ($sProperty == 'auth_pwd')
  4614. {
  4615. $sValue = '*****';
  4616. }
  4617. $sRes .= "<TR>";
  4618. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$sValue));
  4619. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  4620. $sRes .= "</TR>";
  4621. }
  4622. $sRes .= "</TBODY>";
  4623. $sRes .= "</TABLE>";
  4624. return $sRes;
  4625. }
  4626. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  4627. {
  4628. if (count($value) == 0)
  4629. {
  4630. return "";
  4631. }
  4632. $aRes = array();
  4633. foreach($value as $sProperty => $sValue)
  4634. {
  4635. if ($sProperty == 'auth_pwd')
  4636. {
  4637. $sValue = '*****';
  4638. }
  4639. $sFrom = array(',', '=');
  4640. $sTo = array('\,', '\=');
  4641. $aRes[] = $sProperty.'='.str_replace($sFrom, $sTo, (string)$sValue);
  4642. }
  4643. $sRaw = implode(',', $aRes);
  4644. $sFrom = array("\r\n", $sTextQualifier);
  4645. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  4646. $sEscaped = str_replace($sFrom, $sTo, $sRaw);
  4647. return $sTextQualifier.$sEscaped.$sTextQualifier;
  4648. }
  4649. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4650. {
  4651. if (count($value) == 0)
  4652. {
  4653. return "";
  4654. }
  4655. $sRes = "";
  4656. foreach($value as $sProperty => $sValue)
  4657. {
  4658. if ($sProperty == 'auth_pwd')
  4659. {
  4660. $sValue = '*****';
  4661. }
  4662. $sRes .= "<property id=\"$sProperty\">";
  4663. $sRes .= Str::pure2xml((string)$sValue);
  4664. $sRes .= "</property>";
  4665. }
  4666. return $sRes;
  4667. }
  4668. }
  4669. /**
  4670. * The attribute dedicated to the friendly name automatic attribute (not written)
  4671. *
  4672. * @package iTopORM
  4673. */
  4674. class AttributeComputedFieldVoid extends AttributeDefinition
  4675. {
  4676. static public function ListExpectedParams()
  4677. {
  4678. return array_merge(parent::ListExpectedParams(), array());
  4679. }
  4680. public function GetEditClass() {return "";}
  4681. public function GetValuesDef() {return null;}
  4682. public function GetPrerequisiteAttributes() {return $this->GetOptional("depends_on", array());}
  4683. public function IsDirectField() {return true;}
  4684. public function IsScalar() {return true;}
  4685. public function IsWritable() {return false;}
  4686. public function GetSQLExpr() {return null;}
  4687. public function GetDefaultValue() {return $this->MakeRealValue("", null);}
  4688. public function IsNullAllowed() {return false;}
  4689. //
  4690. // protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  4691. public function GetSQLExpressions($sPrefix = '')
  4692. {
  4693. if ($sPrefix == '')
  4694. {
  4695. $sPrefix = $this->GetCode();
  4696. }
  4697. return array('' => $sPrefix);
  4698. }
  4699. public function FromSQLToValue($aCols, $sPrefix = '')
  4700. {
  4701. return null;
  4702. }
  4703. public function GetSQLValues($value)
  4704. {
  4705. return array();
  4706. }
  4707. public function GetSQLColumns($bFullSpec = false)
  4708. {
  4709. return array();
  4710. }
  4711. public function GetFilterDefinitions()
  4712. {
  4713. return array($this->GetCode() => new FilterFromAttribute($this));
  4714. }
  4715. public function GetBasicFilterOperators()
  4716. {
  4717. return array("="=>"equals", "!="=>"differs from");
  4718. }
  4719. public function GetBasicFilterLooseOperator()
  4720. {
  4721. return "=";
  4722. }
  4723. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4724. {
  4725. $sQValue = CMDBSource::Quote($value);
  4726. switch ($sOpCode)
  4727. {
  4728. case '!=':
  4729. return $this->GetSQLExpr()." != $sQValue";
  4730. break;
  4731. case '=':
  4732. default:
  4733. return $this->GetSQLExpr()." = $sQValue";
  4734. }
  4735. }
  4736. public function IsPartOfFingerprint() { return false; }
  4737. }
  4738. /**
  4739. * The attribute dedicated to the friendly name automatic attribute (not written)
  4740. *
  4741. * @package iTopORM
  4742. */
  4743. class AttributeFriendlyName extends AttributeComputedFieldVoid
  4744. {
  4745. public function __construct($sCode, $sExtKeyAttCode)
  4746. {
  4747. $this->m_sCode = $sCode;
  4748. $aParams = array();
  4749. // $aParams["is_null_allowed"] = false,
  4750. $aParams["default_value"] = '';
  4751. $aParams["extkey_attcode"] = $sExtKeyAttCode;
  4752. parent::__construct($sCode, $aParams);
  4753. $this->m_sValue = $this->Get("default_value");
  4754. }
  4755. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  4756. public function GetExtAttCode() {return 'friendlyname';}
  4757. public function GetLabel($sDefault = null)
  4758. {
  4759. $sLabel = parent::GetLabel('');
  4760. if (strlen($sLabel) == 0)
  4761. {
  4762. $sKeyAttCode = $this->Get("extkey_attcode");
  4763. if ($sKeyAttCode == 'id')
  4764. {
  4765. return Dict::S('Core:FriendlyName-Label');
  4766. }
  4767. else
  4768. {
  4769. $oExtKeyAttDef = MetaModel::GetAttributeDef($this->GetHostClass(), $sKeyAttCode);
  4770. $sLabel = $oExtKeyAttDef->GetLabel($this->m_sCode);
  4771. }
  4772. }
  4773. return $sLabel;
  4774. }
  4775. public function GetDescription($sDefault = null)
  4776. {
  4777. $sLabel = parent::GetDescription('');
  4778. if (strlen($sLabel) == 0)
  4779. {
  4780. $sKeyAttCode = $this->Get("extkey_attcode");
  4781. if ($sKeyAttCode == 'id')
  4782. {
  4783. return Dict::S('Core:FriendlyName-Description');
  4784. }
  4785. else
  4786. {
  4787. $oExtKeyAttDef = MetaModel::GetAttributeDef($this->GetHostClass(), $sKeyAttCode);
  4788. $sLabel = $oExtKeyAttDef->GetDescription('');
  4789. }
  4790. }
  4791. return $sLabel;
  4792. }
  4793. // n/a, the friendly name is made of a complex expression (see GetNameSpec)
  4794. protected function GetSQLCol($bFullSpec = false) {return "";}
  4795. public function FromSQLToValue($aCols, $sPrefix = '')
  4796. {
  4797. $sValue = $aCols[$sPrefix];
  4798. return $sValue;
  4799. }
  4800. /**
  4801. * Encrypt the value before storing it in the database
  4802. */
  4803. public function GetSQLValues($value)
  4804. {
  4805. return array();
  4806. }
  4807. public function IsWritable()
  4808. {
  4809. return false;
  4810. }
  4811. public function IsDirectField()
  4812. {
  4813. return false;
  4814. }
  4815. public function SetFixedValue($sValue)
  4816. {
  4817. $this->m_sValue = $sValue;
  4818. }
  4819. public function GetDefaultValue()
  4820. {
  4821. return $this->m_sValue;
  4822. }
  4823. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  4824. {
  4825. return Str::pure2html((string)$sValue);
  4826. }
  4827. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  4828. {
  4829. $sFrom = array("\r\n", $sTextQualifier);
  4830. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  4831. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  4832. return $sTextQualifier.$sEscaped.$sTextQualifier;
  4833. }
  4834. // Do not display friendly names in the history of change
  4835. public function DescribeChangeAsHTML($sOldValue, $sNewValue, $sLabel = null)
  4836. {
  4837. return '';
  4838. }
  4839. public function GetBasicFilterLooseOperator()
  4840. {
  4841. return "Contains";
  4842. }
  4843. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4844. {
  4845. $sQValue = CMDBSource::Quote($value);
  4846. switch ($sOpCode)
  4847. {
  4848. case '=':
  4849. case '!=':
  4850. return $this->GetSQLExpr()." $sOpCode $sQValue";
  4851. case 'Contains':
  4852. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
  4853. case 'NotLike':
  4854. return $this->GetSQLExpr()." NOT LIKE $sQValue";
  4855. case 'Like':
  4856. default:
  4857. return $this->GetSQLExpr()." LIKE $sQValue";
  4858. }
  4859. }
  4860. public function IsPartOfFingerprint() { return false; }
  4861. }
  4862. /**
  4863. * Holds the setting for the redundancy on a specific relation
  4864. * Its value is a string, containing either:
  4865. * - 'disabled'
  4866. * - 'n', where n is a positive integer value giving the minimum count of items upstream
  4867. * - 'n%', where n is a positive integer value, giving the minimum as a percentage of the total count of items upstream
  4868. *
  4869. * @package iTopORM
  4870. */
  4871. class AttributeRedundancySettings extends AttributeDBField
  4872. {
  4873. static public function ListExpectedParams()
  4874. {
  4875. return array('sql', 'relation_code', 'from_class', 'neighbour_id', 'enabled', 'enabled_mode', 'min_up', 'min_up_type', 'min_up_mode');
  4876. }
  4877. public function GetValuesDef() {return null;}
  4878. public function GetPrerequisiteAttributes() {return array();}
  4879. public function GetEditClass() {return "RedundancySetting";}
  4880. protected function GetSQLCol($bFullSpec = false)
  4881. {
  4882. return "VARCHAR(20)".($bFullSpec ? $this->GetSQLColSpec() : '');
  4883. }
  4884. public function GetValidationPattern()
  4885. {
  4886. return "^[0-9]{1,3}|[0-9]{1,2}%|disabled$";
  4887. }
  4888. public function GetMaxSize()
  4889. {
  4890. return 20;
  4891. }
  4892. public function GetDefaultValue($aArgs = array())
  4893. {
  4894. $sRet = 'disabled';
  4895. if ($this->Get('enabled'))
  4896. {
  4897. if ($this->Get('min_up_type') == 'count')
  4898. {
  4899. $sRet = (string) $this->Get('min_up');
  4900. }
  4901. else // percent
  4902. {
  4903. $sRet = $this->Get('min_up').'%';
  4904. }
  4905. }
  4906. return $sRet;
  4907. }
  4908. public function IsNullAllowed()
  4909. {
  4910. return false;
  4911. }
  4912. public function GetNullValue()
  4913. {
  4914. return '';
  4915. }
  4916. public function IsNull($proposedValue)
  4917. {
  4918. return ($proposedValue == '');
  4919. }
  4920. public function MakeRealValue($proposedValue, $oHostObj)
  4921. {
  4922. if (is_null($proposedValue)) return '';
  4923. return (string)$proposedValue;
  4924. }
  4925. public function ScalarToSQL($value)
  4926. {
  4927. if (!is_string($value))
  4928. {
  4929. throw new CoreException('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetHostClass(), 'attribute' => $this->GetCode()));
  4930. }
  4931. return $value;
  4932. }
  4933. public function GetRelationQueryData()
  4934. {
  4935. foreach (MetaModel::EnumRelationQueries($this->GetHostClass(), $this->Get('relation_code'), false) as $sDummy => $aQueryInfo)
  4936. {
  4937. if ($aQueryInfo['sFromClass'] == $this->Get('from_class'))
  4938. {
  4939. if ($aQueryInfo['sNeighbour'] == $this->Get('neighbour_id'))
  4940. {
  4941. return $aQueryInfo;
  4942. }
  4943. }
  4944. }
  4945. }
  4946. /**
  4947. * Find the user option label
  4948. * @param user option : disabled|cout|percent
  4949. */
  4950. public function GetUserOptionFormat($sUserOption, $sDefault = null)
  4951. {
  4952. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/'.$sUserOption, null, true /*user lang*/);
  4953. if (is_null($sLabel))
  4954. {
  4955. // If no default value is specified, let's define the most relevant one for developping purposes
  4956. if (is_null($sDefault))
  4957. {
  4958. $sDefault = str_replace('_', ' ', $this->m_sCode.':'.$sUserOption.'(%1$s)');
  4959. }
  4960. // Browse the hierarchy again, accepting default (english) translations
  4961. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/'.$sUserOption, $sDefault, false);
  4962. }
  4963. return $sLabel;
  4964. }
  4965. /**
  4966. * Override to display the value in the GUI
  4967. */
  4968. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  4969. {
  4970. $sCurrentOption = $this->GetCurrentOption($sValue);
  4971. $sClass = $oHostObject ? get_class($oHostObject) : $this->m_sHostClass;
  4972. return sprintf($this->GetUserOptionFormat($sCurrentOption), $this->GetMinUpValue($sValue), MetaModel::GetName($sClass));
  4973. }
  4974. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  4975. {
  4976. $sFrom = array("\r\n", $sTextQualifier);
  4977. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  4978. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  4979. return $sTextQualifier.$sEscaped.$sTextQualifier;
  4980. }
  4981. /**
  4982. * Helper to interpret the value, given the current settings and string representation of the attribute
  4983. */
  4984. public function IsEnabled($sValue)
  4985. {
  4986. if ($this->get('enabled_mode') == 'fixed')
  4987. {
  4988. $bRet = $this->get('enabled');
  4989. }
  4990. else
  4991. {
  4992. $bRet = ($sValue != 'disabled');
  4993. }
  4994. return $bRet;
  4995. }
  4996. /**
  4997. * Helper to interpret the value, given the current settings and string representation of the attribute
  4998. */
  4999. public function GetMinUpType($sValue)
  5000. {
  5001. if ($this->get('min_up_mode') == 'fixed')
  5002. {
  5003. $sRet = $this->get('min_up_type');
  5004. }
  5005. else
  5006. {
  5007. $sRet = 'count';
  5008. if (substr(trim($sValue), -1, 1) == '%')
  5009. {
  5010. $sRet = 'percent';
  5011. }
  5012. }
  5013. return $sRet;
  5014. }
  5015. /**
  5016. * Helper to interpret the value, given the current settings and string representation of the attribute
  5017. */
  5018. public function GetMinUpValue($sValue)
  5019. {
  5020. if ($this->get('min_up_mode') == 'fixed')
  5021. {
  5022. $iRet = (int) $this->Get('min_up');
  5023. }
  5024. else
  5025. {
  5026. $sRefValue = $sValue;
  5027. if (substr(trim($sValue), -1, 1) == '%')
  5028. {
  5029. $sRefValue = substr(trim($sValue), 0, -1);
  5030. }
  5031. $iRet = (int) trim($sRefValue);
  5032. }
  5033. return $iRet;
  5034. }
  5035. /**
  5036. * Helper to determine if the redundancy can be viewed/edited by the end-user
  5037. */
  5038. public function IsVisible()
  5039. {
  5040. $bRet = false;
  5041. if ($this->Get('enabled_mode') == 'fixed')
  5042. {
  5043. $bRet = $this->Get('enabled');
  5044. }
  5045. elseif ($this->Get('enabled_mode') == 'user')
  5046. {
  5047. $bRet = true;
  5048. }
  5049. return $bRet;
  5050. }
  5051. public function IsWritable()
  5052. {
  5053. if (($this->Get('enabled_mode') == 'fixed') && ($this->Get('min_up_mode') == 'fixed'))
  5054. {
  5055. return false;
  5056. }
  5057. return true;
  5058. }
  5059. /**
  5060. * Returns an HTML form that can be read by ReadValueFromPostedForm
  5061. */
  5062. public function GetDisplayForm($sCurrentValue, $oPage, $bEditMode = false, $sFormPrefix = '')
  5063. {
  5064. $sRet = '';
  5065. $aUserOptions = $this->GetUserOptions($sCurrentValue);
  5066. if (count($aUserOptions) < 2)
  5067. {
  5068. $bEditOption = false;
  5069. }
  5070. else
  5071. {
  5072. $bEditOption = $bEditMode;
  5073. }
  5074. $sCurrentOption = $this->GetCurrentOption($sCurrentValue);
  5075. foreach($aUserOptions as $sUserOption)
  5076. {
  5077. $bSelected = ($sUserOption == $sCurrentOption);
  5078. $sRet .= '<div>';
  5079. $sRet .= $this->GetDisplayOption($sCurrentValue, $oPage, $sFormPrefix, $bEditOption, $sUserOption, $bSelected);
  5080. $sRet .= '</div>';
  5081. }
  5082. return $sRet;
  5083. }
  5084. const USER_OPTION_DISABLED = 'disabled';
  5085. const USER_OPTION_ENABLED_COUNT = 'count';
  5086. const USER_OPTION_ENABLED_PERCENT = 'percent';
  5087. /**
  5088. * Depending on the xxx_mode parameters, build the list of options that are allowed to the end-user
  5089. */
  5090. protected function GetUserOptions($sValue)
  5091. {
  5092. $aRet = array();
  5093. if ($this->Get('enabled_mode') == 'user')
  5094. {
  5095. $aRet[] = self::USER_OPTION_DISABLED;
  5096. }
  5097. if ($this->Get('min_up_mode') == 'user')
  5098. {
  5099. $aRet[] = self::USER_OPTION_ENABLED_COUNT;
  5100. $aRet[] = self::USER_OPTION_ENABLED_PERCENT;
  5101. }
  5102. else
  5103. {
  5104. if ($this->GetMinUpType($sValue) == 'count')
  5105. {
  5106. $aRet[] = self::USER_OPTION_ENABLED_COUNT;
  5107. }
  5108. else
  5109. {
  5110. $aRet[] = self::USER_OPTION_ENABLED_PERCENT;
  5111. }
  5112. }
  5113. return $aRet;
  5114. }
  5115. /**
  5116. * Convert the string representation into one of the existing options
  5117. */
  5118. protected function GetCurrentOption($sValue)
  5119. {
  5120. $sRet = self::USER_OPTION_DISABLED;
  5121. if ($this->IsEnabled($sValue))
  5122. {
  5123. if ($this->GetMinUpType($sValue) == 'count')
  5124. {
  5125. $sRet = self::USER_OPTION_ENABLED_COUNT;
  5126. }
  5127. else
  5128. {
  5129. $sRet = self::USER_OPTION_ENABLED_PERCENT;
  5130. }
  5131. }
  5132. return $sRet;
  5133. }
  5134. /**
  5135. * Display an option (form, or current value)
  5136. */
  5137. protected function GetDisplayOption($sCurrentValue, $oPage, $sFormPrefix, $bEditMode, $sUserOption, $bSelected = true)
  5138. {
  5139. $sRet = '';
  5140. $iCurrentValue = $this->GetMinUpValue($sCurrentValue);
  5141. if ($bEditMode)
  5142. {
  5143. $sHtmlNamesPrefix = 'rddcy_'.$this->Get('relation_code').'_'.$this->Get('from_class').'_'.$this->Get('neighbour_id');
  5144. switch ($sUserOption)
  5145. {
  5146. case self::USER_OPTION_DISABLED:
  5147. $sValue = ''; // Empty placeholder
  5148. break;
  5149. case self::USER_OPTION_ENABLED_COUNT:
  5150. if ($bEditMode)
  5151. {
  5152. $sName = $sHtmlNamesPrefix.'_min_up_count';
  5153. $sEditValue = $bSelected ? $iCurrentValue : '';
  5154. $sValue = '<input class="redundancy-min-up-count" type="string" size="3" name="'.$sName.'" value="'.$sEditValue.'">';
  5155. // To fix an issue on Firefox: focus set to the option (because the input is within the label for the option)
  5156. $oPage->add_ready_script("\$('[name=\"$sName\"]').click(function(){var me=this; setTimeout(function(){\$(me).focus();}, 100);});");
  5157. }
  5158. else
  5159. {
  5160. $sValue = $iCurrentValue;
  5161. }
  5162. break;
  5163. case self::USER_OPTION_ENABLED_PERCENT:
  5164. if ($bEditMode)
  5165. {
  5166. $sName = $sHtmlNamesPrefix.'_min_up_percent';
  5167. $sEditValue = $bSelected ? $iCurrentValue : '';
  5168. $sValue = '<input class="redundancy-min-up-percent" type="string" size="3" name="'.$sName.'" value="'.$sEditValue.'">';
  5169. // To fix an issue on Firefox: focus set to the option (because the input is within the label for the option)
  5170. $oPage->add_ready_script("\$('[name=\"$sName\"]').click(function(){var me=this; setTimeout(function(){\$(me).focus();}, 100);});");
  5171. }
  5172. else
  5173. {
  5174. $sValue = $iCurrentValue;
  5175. }
  5176. break;
  5177. }
  5178. $sLabel = sprintf($this->GetUserOptionFormat($sUserOption), $sValue, MetaModel::GetName($this->GetHostClass()));
  5179. $sOptionName = $sHtmlNamesPrefix.'_user_option';
  5180. $sOptionId = $sOptionName.'_'.$sUserOption;
  5181. $sChecked = $bSelected ? 'checked' : '';
  5182. $sRet = '<input type="radio" name="'.$sOptionName.'" id="'.$sOptionId.'" value="'.$sUserOption.'"'.$sChecked.'> <label for="'.$sOptionId.'">'.$sLabel.'</label>';
  5183. }
  5184. else
  5185. {
  5186. // Read-only: display only the currently selected option
  5187. if ($bSelected)
  5188. {
  5189. $sRet = sprintf($this->GetUserOptionFormat($sUserOption), $iCurrentValue, MetaModel::GetName($this->GetHostClass()));
  5190. }
  5191. }
  5192. return $sRet;
  5193. }
  5194. /**
  5195. * Makes the string representation out of the values given by the form defined in GetDisplayForm
  5196. */
  5197. public function ReadValueFromPostedForm($sFormPrefix)
  5198. {
  5199. $sHtmlNamesPrefix = 'rddcy_'.$this->Get('relation_code').'_'.$this->Get('from_class').'_'.$this->Get('neighbour_id');
  5200. $iMinUpCount = (int) utils::ReadPostedParam($sHtmlNamesPrefix.'_min_up_count', null, 'raw_data');
  5201. $iMinUpPercent = (int) utils::ReadPostedParam($sHtmlNamesPrefix.'_min_up_percent', null, 'raw_data');
  5202. $sSelectedOption = utils::ReadPostedParam($sHtmlNamesPrefix.'_user_option', null, 'raw_data');
  5203. switch ($sSelectedOption)
  5204. {
  5205. case self::USER_OPTION_ENABLED_COUNT:
  5206. $sRet = $iMinUpCount;
  5207. break;
  5208. case self::USER_OPTION_ENABLED_PERCENT:
  5209. $sRet = $iMinUpPercent.'%';
  5210. break;
  5211. case self::USER_OPTION_DISABLED:
  5212. default:
  5213. $sRet = 'disabled';
  5214. break;
  5215. }
  5216. return $sRet;
  5217. }
  5218. }