attributedef.class.inc.php 161 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819
  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. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  4822. {
  4823. $sFrom = array("\r\n", $sTextQualifier);
  4824. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  4825. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  4826. return $sTextQualifier.$sEscaped.$sTextQualifier;
  4827. }
  4828. // Do not display friendly names in the history of change
  4829. public function DescribeChangeAsHTML($sOldValue, $sNewValue, $sLabel = null)
  4830. {
  4831. return '';
  4832. }
  4833. public function GetBasicFilterLooseOperator()
  4834. {
  4835. return "Contains";
  4836. }
  4837. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4838. {
  4839. $sQValue = CMDBSource::Quote($value);
  4840. switch ($sOpCode)
  4841. {
  4842. case '=':
  4843. case '!=':
  4844. return $this->GetSQLExpr()." $sOpCode $sQValue";
  4845. case 'Contains':
  4846. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
  4847. case 'NotLike':
  4848. return $this->GetSQLExpr()." NOT LIKE $sQValue";
  4849. case 'Like':
  4850. default:
  4851. return $this->GetSQLExpr()." LIKE $sQValue";
  4852. }
  4853. }
  4854. public function IsPartOfFingerprint() { return false; }
  4855. }
  4856. /**
  4857. * Holds the setting for the redundancy on a specific relation
  4858. * Its value is a string, containing either:
  4859. * - 'disabled'
  4860. * - 'n', where n is a positive integer value giving the minimum count of items upstream
  4861. * - 'n%', where n is a positive integer value, giving the minimum as a percentage of the total count of items upstream
  4862. *
  4863. * @package iTopORM
  4864. */
  4865. class AttributeRedundancySettings extends AttributeDBField
  4866. {
  4867. static public function ListExpectedParams()
  4868. {
  4869. return array('sql', 'relation_code', 'from_class', 'neighbour_id', 'enabled', 'enabled_mode', 'min_up', 'min_up_type', 'min_up_mode');
  4870. }
  4871. public function GetValuesDef() {return null;}
  4872. public function GetPrerequisiteAttributes() {return array();}
  4873. public function GetEditClass() {return "RedundancySetting";}
  4874. protected function GetSQLCol($bFullSpec = false)
  4875. {
  4876. return "VARCHAR(20)".($bFullSpec ? $this->GetSQLColSpec() : '');
  4877. }
  4878. public function GetValidationPattern()
  4879. {
  4880. return "^[0-9]{1,3}|[0-9]{1,2}%|disabled$";
  4881. }
  4882. public function GetMaxSize()
  4883. {
  4884. return 20;
  4885. }
  4886. public function GetDefaultValue($aArgs = array())
  4887. {
  4888. $sRet = 'disabled';
  4889. if ($this->Get('enabled'))
  4890. {
  4891. if ($this->Get('min_up_type') == 'count')
  4892. {
  4893. $sRet = (string) $this->Get('min_up');
  4894. }
  4895. else // percent
  4896. {
  4897. $sRet = $this->Get('min_up').'%';
  4898. }
  4899. }
  4900. return $sRet;
  4901. }
  4902. public function IsNullAllowed()
  4903. {
  4904. return false;
  4905. }
  4906. public function GetNullValue()
  4907. {
  4908. return '';
  4909. }
  4910. public function IsNull($proposedValue)
  4911. {
  4912. return ($proposedValue == '');
  4913. }
  4914. public function MakeRealValue($proposedValue, $oHostObj)
  4915. {
  4916. if (is_null($proposedValue)) return '';
  4917. return (string)$proposedValue;
  4918. }
  4919. public function ScalarToSQL($value)
  4920. {
  4921. if (!is_string($value))
  4922. {
  4923. throw new CoreException('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetHostClass(), 'attribute' => $this->GetCode()));
  4924. }
  4925. return $value;
  4926. }
  4927. public function GetRelationQueryData()
  4928. {
  4929. foreach (MetaModel::EnumRelationQueries($this->GetHostClass(), $this->Get('relation_code'), false) as $sDummy => $aQueryInfo)
  4930. {
  4931. if ($aQueryInfo['sFromClass'] == $this->Get('from_class'))
  4932. {
  4933. if ($aQueryInfo['sNeighbour'] == $this->Get('neighbour_id'))
  4934. {
  4935. return $aQueryInfo;
  4936. }
  4937. }
  4938. }
  4939. }
  4940. /**
  4941. * Find the user option label
  4942. * @param user option : disabled|cout|percent
  4943. */
  4944. public function GetUserOptionFormat($sUserOption, $sDefault = null)
  4945. {
  4946. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/'.$sUserOption, null, true /*user lang*/);
  4947. if (is_null($sLabel))
  4948. {
  4949. // If no default value is specified, let's define the most relevant one for developping purposes
  4950. if (is_null($sDefault))
  4951. {
  4952. $sDefault = str_replace('_', ' ', $this->m_sCode.':'.$sUserOption.'(%1$s)');
  4953. }
  4954. // Browse the hierarchy again, accepting default (english) translations
  4955. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/'.$sUserOption, $sDefault, false);
  4956. }
  4957. return $sLabel;
  4958. }
  4959. /**
  4960. * Override to display the value in the GUI
  4961. */
  4962. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  4963. {
  4964. $sCurrentOption = $this->GetCurrentOption($sValue);
  4965. $sClass = $oHostObject ? get_class($oHostObject) : $this->m_sHostClass;
  4966. return sprintf($this->GetUserOptionFormat($sCurrentOption), $this->GetMinUpValue($sValue), MetaModel::GetName($sClass));
  4967. }
  4968. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  4969. {
  4970. $sFrom = array("\r\n", $sTextQualifier);
  4971. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  4972. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  4973. return $sTextQualifier.$sEscaped.$sTextQualifier;
  4974. }
  4975. /**
  4976. * Helper to interpret the value, given the current settings and string representation of the attribute
  4977. */
  4978. public function IsEnabled($sValue)
  4979. {
  4980. if ($this->get('enabled_mode') == 'fixed')
  4981. {
  4982. $bRet = $this->get('enabled');
  4983. }
  4984. else
  4985. {
  4986. $bRet = ($sValue != 'disabled');
  4987. }
  4988. return $bRet;
  4989. }
  4990. /**
  4991. * Helper to interpret the value, given the current settings and string representation of the attribute
  4992. */
  4993. public function GetMinUpType($sValue)
  4994. {
  4995. if ($this->get('min_up_mode') == 'fixed')
  4996. {
  4997. $sRet = $this->get('min_up_type');
  4998. }
  4999. else
  5000. {
  5001. $sRet = 'count';
  5002. if (substr(trim($sValue), -1, 1) == '%')
  5003. {
  5004. $sRet = 'percent';
  5005. }
  5006. }
  5007. return $sRet;
  5008. }
  5009. /**
  5010. * Helper to interpret the value, given the current settings and string representation of the attribute
  5011. */
  5012. public function GetMinUpValue($sValue)
  5013. {
  5014. if ($this->get('min_up_mode') == 'fixed')
  5015. {
  5016. $iRet = (int) $this->Get('min_up');
  5017. }
  5018. else
  5019. {
  5020. $sRefValue = $sValue;
  5021. if (substr(trim($sValue), -1, 1) == '%')
  5022. {
  5023. $sRefValue = substr(trim($sValue), 0, -1);
  5024. }
  5025. $iRet = (int) trim($sRefValue);
  5026. }
  5027. return $iRet;
  5028. }
  5029. /**
  5030. * Helper to determine if the redundancy can be viewed/edited by the end-user
  5031. */
  5032. public function IsVisible()
  5033. {
  5034. $bRet = false;
  5035. if ($this->Get('enabled_mode') == 'fixed')
  5036. {
  5037. $bRet = $this->Get('enabled');
  5038. }
  5039. elseif ($this->Get('enabled_mode') == 'user')
  5040. {
  5041. $bRet = true;
  5042. }
  5043. return $bRet;
  5044. }
  5045. public function IsWritable()
  5046. {
  5047. if (($this->Get('enabled_mode') == 'fixed') && ($this->Get('min_up_mode') == 'fixed'))
  5048. {
  5049. return false;
  5050. }
  5051. return true;
  5052. }
  5053. /**
  5054. * Returns an HTML form that can be read by ReadValueFromPostedForm
  5055. */
  5056. public function GetDisplayForm($sCurrentValue, $oPage, $bEditMode = false, $sFormPrefix = '')
  5057. {
  5058. $sRet = '';
  5059. $aUserOptions = $this->GetUserOptions($sCurrentValue);
  5060. if (count($aUserOptions) < 2)
  5061. {
  5062. $bEditOption = false;
  5063. }
  5064. else
  5065. {
  5066. $bEditOption = $bEditMode;
  5067. }
  5068. $sCurrentOption = $this->GetCurrentOption($sCurrentValue);
  5069. foreach($aUserOptions as $sUserOption)
  5070. {
  5071. $bSelected = ($sUserOption == $sCurrentOption);
  5072. $sRet .= '<div>';
  5073. $sRet .= $this->GetDisplayOption($sCurrentValue, $oPage, $sFormPrefix, $bEditOption, $sUserOption, $bSelected);
  5074. $sRet .= '</div>';
  5075. }
  5076. return $sRet;
  5077. }
  5078. const USER_OPTION_DISABLED = 'disabled';
  5079. const USER_OPTION_ENABLED_COUNT = 'count';
  5080. const USER_OPTION_ENABLED_PERCENT = 'percent';
  5081. /**
  5082. * Depending on the xxx_mode parameters, build the list of options that are allowed to the end-user
  5083. */
  5084. protected function GetUserOptions($sValue)
  5085. {
  5086. $aRet = array();
  5087. if ($this->Get('enabled_mode') == 'user')
  5088. {
  5089. $aRet[] = self::USER_OPTION_DISABLED;
  5090. }
  5091. if ($this->Get('min_up_mode') == 'user')
  5092. {
  5093. $aRet[] = self::USER_OPTION_ENABLED_COUNT;
  5094. $aRet[] = self::USER_OPTION_ENABLED_PERCENT;
  5095. }
  5096. else
  5097. {
  5098. if ($this->GetMinUpType($sValue) == 'count')
  5099. {
  5100. $aRet[] = self::USER_OPTION_ENABLED_COUNT;
  5101. }
  5102. else
  5103. {
  5104. $aRet[] = self::USER_OPTION_ENABLED_PERCENT;
  5105. }
  5106. }
  5107. return $aRet;
  5108. }
  5109. /**
  5110. * Convert the string representation into one of the existing options
  5111. */
  5112. protected function GetCurrentOption($sValue)
  5113. {
  5114. $sRet = self::USER_OPTION_DISABLED;
  5115. if ($this->IsEnabled($sValue))
  5116. {
  5117. if ($this->GetMinUpType($sValue) == 'count')
  5118. {
  5119. $sRet = self::USER_OPTION_ENABLED_COUNT;
  5120. }
  5121. else
  5122. {
  5123. $sRet = self::USER_OPTION_ENABLED_PERCENT;
  5124. }
  5125. }
  5126. return $sRet;
  5127. }
  5128. /**
  5129. * Display an option (form, or current value)
  5130. */
  5131. protected function GetDisplayOption($sCurrentValue, $oPage, $sFormPrefix, $bEditMode, $sUserOption, $bSelected = true)
  5132. {
  5133. $sRet = '';
  5134. $iCurrentValue = $this->GetMinUpValue($sCurrentValue);
  5135. if ($bEditMode)
  5136. {
  5137. $sHtmlNamesPrefix = 'rddcy_'.$this->Get('relation_code').'_'.$this->Get('from_class').'_'.$this->Get('neighbour_id');
  5138. switch ($sUserOption)
  5139. {
  5140. case self::USER_OPTION_DISABLED:
  5141. $sValue = ''; // Empty placeholder
  5142. break;
  5143. case self::USER_OPTION_ENABLED_COUNT:
  5144. if ($bEditMode)
  5145. {
  5146. $sName = $sHtmlNamesPrefix.'_min_up_count';
  5147. $sEditValue = $bSelected ? $iCurrentValue : '';
  5148. $sValue = '<input class="redundancy-min-up-count" type="string" size="3" name="'.$sName.'" value="'.$sEditValue.'">';
  5149. // To fix an issue on Firefox: focus set to the option (because the input is within the label for the option)
  5150. $oPage->add_ready_script("\$('[name=\"$sName\"]').click(function(){var me=this; setTimeout(function(){\$(me).focus();}, 100);});");
  5151. }
  5152. else
  5153. {
  5154. $sValue = $iCurrentValue;
  5155. }
  5156. break;
  5157. case self::USER_OPTION_ENABLED_PERCENT:
  5158. if ($bEditMode)
  5159. {
  5160. $sName = $sHtmlNamesPrefix.'_min_up_percent';
  5161. $sEditValue = $bSelected ? $iCurrentValue : '';
  5162. $sValue = '<input class="redundancy-min-up-percent" type="string" size="3" name="'.$sName.'" value="'.$sEditValue.'">';
  5163. // To fix an issue on Firefox: focus set to the option (because the input is within the label for the option)
  5164. $oPage->add_ready_script("\$('[name=\"$sName\"]').click(function(){var me=this; setTimeout(function(){\$(me).focus();}, 100);});");
  5165. }
  5166. else
  5167. {
  5168. $sValue = $iCurrentValue;
  5169. }
  5170. break;
  5171. }
  5172. $sLabel = sprintf($this->GetUserOptionFormat($sUserOption), $sValue, MetaModel::GetName($this->GetHostClass()));
  5173. $sOptionName = $sHtmlNamesPrefix.'_user_option';
  5174. $sOptionId = $sOptionName.'_'.$sUserOption;
  5175. $sChecked = $bSelected ? 'checked' : '';
  5176. $sRet = '<input type="radio" name="'.$sOptionName.'" id="'.$sOptionId.'" value="'.$sUserOption.'"'.$sChecked.'> <label for="'.$sOptionId.'">'.$sLabel.'</label>';
  5177. }
  5178. else
  5179. {
  5180. // Read-only: display only the currently selected option
  5181. if ($bSelected)
  5182. {
  5183. $sRet = sprintf($this->GetUserOptionFormat($sUserOption), $iCurrentValue, MetaModel::GetName($this->GetHostClass()));
  5184. }
  5185. }
  5186. return $sRet;
  5187. }
  5188. /**
  5189. * Makes the string representation out of the values given by the form defined in GetDisplayForm
  5190. */
  5191. public function ReadValueFromPostedForm($sFormPrefix)
  5192. {
  5193. $sHtmlNamesPrefix = 'rddcy_'.$this->Get('relation_code').'_'.$this->Get('from_class').'_'.$this->Get('neighbour_id');
  5194. $iMinUpCount = (int) utils::ReadPostedParam($sHtmlNamesPrefix.'_min_up_count', null, 'raw_data');
  5195. $iMinUpPercent = (int) utils::ReadPostedParam($sHtmlNamesPrefix.'_min_up_percent', null, 'raw_data');
  5196. $sSelectedOption = utils::ReadPostedParam($sHtmlNamesPrefix.'_user_option', null, 'raw_data');
  5197. switch ($sSelectedOption)
  5198. {
  5199. case self::USER_OPTION_ENABLED_COUNT:
  5200. $sRet = $iMinUpCount;
  5201. break;
  5202. case self::USER_OPTION_ENABLED_PERCENT:
  5203. $sRet = $iMinUpPercent.'%';
  5204. break;
  5205. case self::USER_OPTION_DISABLED:
  5206. default:
  5207. $sRet = 'disabled';
  5208. break;
  5209. }
  5210. return $sRet;
  5211. }
  5212. }