attributedef.class.inc.php 152 KB

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