attributedef.class.inc.php 160 KB

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