metamodel.class.php 173 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225
  1. <?php
  2. // Copyright (C) 2010-2017 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. require_once(APPROOT.'core/modulehandler.class.inc.php');
  19. require_once(APPROOT.'core/querybuildercontext.class.inc.php');
  20. require_once(APPROOT.'core/querymodifier.class.inc.php');
  21. require_once(APPROOT.'core/metamodelmodifier.inc.php');
  22. require_once(APPROOT.'core/computing.inc.php');
  23. require_once(APPROOT.'core/relationgraph.class.inc.php');
  24. require_once(APPROOT.'core/apc-compat.php');
  25. /**
  26. * Metamodel
  27. *
  28. * @copyright Copyright (C) 2010-2017 Combodo SARL
  29. * @license http://opensource.org/licenses/AGPL-3.0
  30. */
  31. /**
  32. * @package iTopORM
  33. */
  34. define('ENUM_PARENT_CLASSES_EXCLUDELEAF', 1);
  35. /**
  36. * @package iTopORM
  37. */
  38. define('ENUM_PARENT_CLASSES_ALL', 2);
  39. /**
  40. * Specifies that this attribute is visible/editable.... normal (default config)
  41. *
  42. * @package iTopORM
  43. */
  44. define('OPT_ATT_NORMAL', 0);
  45. /**
  46. * Specifies that this attribute is hidden in that state
  47. *
  48. * @package iTopORM
  49. */
  50. define('OPT_ATT_HIDDEN', 1);
  51. /**
  52. * Specifies that this attribute is not editable in that state
  53. *
  54. * @package iTopORM
  55. */
  56. define('OPT_ATT_READONLY', 2);
  57. /**
  58. * Specifieds that the attribute must be set (different than default value?) when arriving into that state
  59. *
  60. * @package iTopORM
  61. */
  62. define('OPT_ATT_MANDATORY', 4);
  63. /**
  64. * Specifies that the attribute must change when arriving into that state
  65. *
  66. * @package iTopORM
  67. */
  68. define('OPT_ATT_MUSTCHANGE', 8);
  69. /**
  70. * Specifies that the attribute must be proposed when arriving into that state
  71. *
  72. * @package iTopORM
  73. */
  74. define('OPT_ATT_MUSTPROMPT', 16);
  75. /**
  76. * Specifies that the attribute is in 'slave' mode compared to one data exchange task:
  77. * it should not be edited inside iTop anymore
  78. *
  79. * @package iTopORM
  80. */
  81. define('OPT_ATT_SLAVE', 32);
  82. /**
  83. * DB Engine -should be moved into CMDBSource
  84. *
  85. * @package iTopORM
  86. */
  87. define('MYSQL_ENGINE', 'innodb');
  88. //define('MYSQL_ENGINE', 'myisam');
  89. /**
  90. * (API) The objects definitions as well as their mapping to the database
  91. *
  92. * @package iTopORM
  93. */
  94. abstract class MetaModel
  95. {
  96. ///////////////////////////////////////////////////////////////////////////
  97. //
  98. // STATIC Members
  99. //
  100. ///////////////////////////////////////////////////////////////////////////
  101. private static $m_bTraceSourceFiles = false;
  102. private static $m_aClassToFile = array();
  103. protected static $m_sEnvironment = 'production';
  104. public static function GetClassFiles()
  105. {
  106. return self::$m_aClassToFile;
  107. }
  108. // Purpose: workaround the following limitation = PHP5 does not allow to know the class (derived from the current one)
  109. // from which a static function is called (__CLASS__ and self are interpreted during parsing)
  110. private static function GetCallersPHPClass($sExpectedFunctionName = null, $bRecordSourceFile = false)
  111. {
  112. //var_dump(debug_backtrace());
  113. $aBacktrace = debug_backtrace();
  114. // $aBacktrace[0] is where we are
  115. // $aBacktrace[1] is the caller of GetCallersPHPClass
  116. // $aBacktrace[1] is the info we want
  117. if (!empty($sExpectedFunctionName))
  118. {
  119. assert('$aBacktrace[2]["function"] == $sExpectedFunctionName');
  120. }
  121. if ($bRecordSourceFile)
  122. {
  123. self::$m_aClassToFile[$aBacktrace[2]["class"]] = $aBacktrace[1]["file"];
  124. }
  125. return $aBacktrace[2]["class"];
  126. }
  127. // Static init -why and how it works
  128. //
  129. // We found the following limitations:
  130. //- it is not possible to define non scalar constants
  131. //- it is not possible to declare a static variable as '= new myclass()'
  132. // Then we had do propose this model, in which a derived (non abstract)
  133. // class should implement Init(), to call InheritAttributes or AddAttribute.
  134. private static function _check_subclass($sClass)
  135. {
  136. // See also IsValidClass()... ???? #@#
  137. // class is mandatory
  138. // (it is not possible to guess it when called as myderived::...)
  139. if (!array_key_exists($sClass, self::$m_aClassParams))
  140. {
  141. throw new CoreException("Unknown class '$sClass'");
  142. }
  143. }
  144. public static function static_var_dump()
  145. {
  146. var_dump(get_class_vars(__CLASS__));
  147. }
  148. private static $m_oConfig = null;
  149. protected static $m_aModulesParameters = array();
  150. private static $m_bSkipCheckToWrite = false;
  151. private static $m_bSkipCheckExtKeys = false;
  152. private static $m_bUseAPCCache = false;
  153. private static $m_bLogIssue = false;
  154. private static $m_bLogNotification = false;
  155. private static $m_bLogWebService = false;
  156. public static function SkipCheckToWrite()
  157. {
  158. return self::$m_bSkipCheckToWrite;
  159. }
  160. public static function SkipCheckExtKeys()
  161. {
  162. return self::$m_bSkipCheckExtKeys;
  163. }
  164. public static function IsLogEnabledIssue()
  165. {
  166. return self::$m_bLogIssue;
  167. }
  168. public static function IsLogEnabledNotification()
  169. {
  170. return self::$m_bLogNotification;
  171. }
  172. public static function IsLogEnabledWebService()
  173. {
  174. return self::$m_bLogWebService;
  175. }
  176. private static $m_sDBName = "";
  177. private static $m_sTablePrefix = ""; // table prefix for the current application instance (allow several applications on the same DB)
  178. private static $m_Category2Class = array();
  179. private static $m_aRootClasses = array(); // array of "classname" => "rootclass"
  180. private static $m_aParentClasses = array(); // array of ("classname" => array of "parentclass")
  181. private static $m_aChildClasses = array(); // array of ("classname" => array of "childclass")
  182. private static $m_aClassParams = array(); // array of ("classname" => array of class information)
  183. private static $m_aHighlightScales = array(); // array of ("classname" => array of highlightscale information)
  184. static public function GetParentPersistentClass($sRefClass)
  185. {
  186. $sClass = get_parent_class($sRefClass);
  187. if (!$sClass) return '';
  188. if ($sClass == 'DBObject') return ''; // Warning: __CLASS__ is lower case in my version of PHP
  189. // Note: the UI/business model may implement pure PHP classes (intermediate layers)
  190. if (array_key_exists($sClass, self::$m_aClassParams))
  191. {
  192. return $sClass;
  193. }
  194. return self::GetParentPersistentClass($sClass);
  195. }
  196. final static public function GetName($sClass)
  197. {
  198. self::_check_subclass($sClass);
  199. $sStringCode = 'Class:'.$sClass;
  200. return Dict::S($sStringCode, str_replace('_', ' ', $sClass));
  201. }
  202. final static public function GetName_Obsolete($sClass)
  203. {
  204. // Written for compatibility with a data model written prior to version 0.9.1
  205. self::_check_subclass($sClass);
  206. if (array_key_exists('name', self::$m_aClassParams[$sClass]))
  207. {
  208. return self::$m_aClassParams[$sClass]['name'];
  209. }
  210. else
  211. {
  212. return self::GetName($sClass);
  213. }
  214. }
  215. final static public function GetClassFromLabel($sClassLabel, $bCaseSensitive = true)
  216. {
  217. foreach(self::GetClasses() as $sClass)
  218. {
  219. if ($bCaseSensitive)
  220. {
  221. if (self::GetName($sClass) == $sClassLabel)
  222. {
  223. return $sClass;
  224. }
  225. }
  226. else
  227. {
  228. if (strcasecmp(self::GetName($sClass), $sClassLabel) == 0)
  229. {
  230. return $sClass;
  231. }
  232. }
  233. }
  234. return null;
  235. }
  236. final static public function GetCategory($sClass)
  237. {
  238. self::_check_subclass($sClass);
  239. return self::$m_aClassParams[$sClass]["category"];
  240. }
  241. final static public function HasCategory($sClass, $sCategory)
  242. {
  243. self::_check_subclass($sClass);
  244. return (strpos(self::$m_aClassParams[$sClass]["category"], $sCategory) !== false);
  245. }
  246. final static public function GetClassDescription($sClass)
  247. {
  248. self::_check_subclass($sClass);
  249. $sStringCode = 'Class:'.$sClass.'+';
  250. return Dict::S($sStringCode, '');
  251. }
  252. final static public function GetClassDescription_Obsolete($sClass)
  253. {
  254. // Written for compatibility with a data model written prior to version 0.9.1
  255. self::_check_subclass($sClass);
  256. if (array_key_exists('description', self::$m_aClassParams[$sClass]))
  257. {
  258. return self::$m_aClassParams[$sClass]['description'];
  259. }
  260. else
  261. {
  262. return self::GetClassDescription($sClass);
  263. }
  264. }
  265. final static public function GetClassIcon($sClass, $bImgTag = true, $sMoreStyles = '')
  266. {
  267. self::_check_subclass($sClass);
  268. $sIcon = '';
  269. if (array_key_exists('icon', self::$m_aClassParams[$sClass]))
  270. {
  271. $sIcon = self::$m_aClassParams[$sClass]['icon'];
  272. }
  273. if (strlen($sIcon) == 0)
  274. {
  275. $sParentClass = self::GetParentPersistentClass($sClass);
  276. if (strlen($sParentClass) > 0)
  277. {
  278. return self::GetClassIcon($sParentClass, $bImgTag, $sMoreStyles);
  279. }
  280. }
  281. $sIcon = str_replace('/modules/', '/env-'.self::$m_sEnvironment.'/', $sIcon); // Support of pre-2.0 modules
  282. if ($bImgTag && ($sIcon != ''))
  283. {
  284. $sIcon = "<img src=\"$sIcon\" style=\"vertical-align:middle;$sMoreStyles\"/>";
  285. }
  286. return $sIcon;
  287. }
  288. final static public function IsAutoIncrementKey($sClass)
  289. {
  290. self::_check_subclass($sClass);
  291. return (self::$m_aClassParams[$sClass]["key_type"] == "autoincrement");
  292. }
  293. final static public function IsArchivable($sClass)
  294. {
  295. self::_check_subclass($sClass);
  296. return self::$m_aClassParams[$sClass]["archive"];
  297. }
  298. final static public function GetNameSpec($sClass)
  299. {
  300. self::_check_subclass($sClass);
  301. $nameRawSpec = self::$m_aClassParams[$sClass]["name_attcode"];
  302. if (is_array($nameRawSpec))
  303. {
  304. $sFormat = Dict::S("Class:$sClass/Name", '');
  305. if (strlen($sFormat) == 0)
  306. {
  307. // Default to "%1$s %2$s..."
  308. for($i = 1 ; $i <= count($nameRawSpec) ; $i++)
  309. {
  310. if (empty($sFormat))
  311. {
  312. $sFormat .= '%'.$i.'$s';
  313. }
  314. else
  315. {
  316. $sFormat .= ' %'.$i.'$s';
  317. }
  318. }
  319. }
  320. return array($sFormat, $nameRawSpec);
  321. }
  322. elseif (empty($nameRawSpec))
  323. {
  324. //return array($sClass.' %s', array('id'));
  325. return array($sClass, array());
  326. }
  327. else
  328. {
  329. // string -> attcode
  330. return array('%1$s', array($nameRawSpec));
  331. }
  332. }
  333. /**
  334. * Get the friendly name expression for a given class
  335. */
  336. final static public function GetNameExpression($sClass)
  337. {
  338. $aNameSpec = self::GetNameSpec($sClass);
  339. $sFormat = $aNameSpec[0];
  340. $aAttributes = $aNameSpec[1];
  341. $aPieces = preg_split('/%([0-9])\\$s/', $sFormat, -1, PREG_SPLIT_DELIM_CAPTURE);
  342. $aExpressions = array();
  343. foreach($aPieces as $i => $sPiece)
  344. {
  345. if ($i & 1)
  346. {
  347. // $i is ODD - sPiece is a delimiter
  348. //
  349. $iReplacement = (int)$sPiece - 1;
  350. if (isset($aAttributes[$iReplacement]))
  351. {
  352. $sAttCode = $aAttributes[$iReplacement];
  353. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  354. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  355. {
  356. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  357. $sClassOfAttribute = self::GetAttributeOrigin($sClass, $sKeyAttCode);
  358. }
  359. else
  360. {
  361. $sClassOfAttribute = self::GetAttributeOrigin($sClass, $sAttCode);
  362. }
  363. $aExpressions[] = new FieldExpression($sAttCode, $sClassOfAttribute);
  364. }
  365. }
  366. else
  367. {
  368. // $i is EVEN - sPiece is a literal
  369. //
  370. if (strlen($sPiece) > 0)
  371. {
  372. $aExpressions[] = new ScalarExpression($sPiece);
  373. }
  374. }
  375. }
  376. $oNameExpr = new CharConcatExpression($aExpressions);
  377. return $oNameExpr;
  378. }
  379. /**
  380. * Returns the friendly name IIF it is equivalent to a single attribute
  381. */
  382. final static public function GetFriendlyNameAttributeCode($sClass)
  383. {
  384. $aNameSpec = self::GetNameSpec($sClass);
  385. $sFormat = trim($aNameSpec[0]);
  386. $aAttributes = $aNameSpec[1];
  387. if (($sFormat != '') && ($sFormat != '%1$s'))
  388. {
  389. return null;
  390. }
  391. if (count($aAttributes) > 1)
  392. {
  393. return null;
  394. }
  395. return reset($aAttributes);
  396. }
  397. final static public function GetStateAttributeCode($sClass)
  398. {
  399. self::_check_subclass($sClass);
  400. return self::$m_aClassParams[$sClass]["state_attcode"];
  401. }
  402. final static public function GetDefaultState($sClass)
  403. {
  404. $sDefaultState = '';
  405. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  406. if (!empty($sStateAttrCode))
  407. {
  408. $oStateAttrDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  409. $sDefaultState = $oStateAttrDef->GetDefaultValue();
  410. }
  411. return $sDefaultState;
  412. }
  413. final static public function GetReconcKeys($sClass)
  414. {
  415. self::_check_subclass($sClass);
  416. return self::$m_aClassParams[$sClass]["reconc_keys"];
  417. }
  418. final static public function GetDisplayTemplate($sClass)
  419. {
  420. self::_check_subclass($sClass);
  421. return array_key_exists("display_template", self::$m_aClassParams[$sClass]) ? self::$m_aClassParams[$sClass]["display_template"]: '';
  422. }
  423. final static public function GetOrderByDefault($sClass, $bOnlyDeclared = false)
  424. {
  425. self::_check_subclass($sClass);
  426. $aOrderBy = array_key_exists("order_by_default", self::$m_aClassParams[$sClass]) ? self::$m_aClassParams[$sClass]["order_by_default"]: array();
  427. if ($bOnlyDeclared)
  428. {
  429. // Used to reverse engineer the declaration of the data model
  430. return $aOrderBy;
  431. }
  432. else
  433. {
  434. if (count($aOrderBy) == 0)
  435. {
  436. $aOrderBy['friendlyname'] = true;
  437. }
  438. return $aOrderBy;
  439. }
  440. }
  441. final static public function GetAttributeOrigin($sClass, $sAttCode)
  442. {
  443. self::_check_subclass($sClass);
  444. return self::$m_aAttribOrigins[$sClass][$sAttCode];
  445. }
  446. final static public function GetPrerequisiteAttributes($sClass, $sAttCode)
  447. {
  448. self::_check_subclass($sClass);
  449. $oAtt = self::GetAttributeDef($sClass, $sAttCode);
  450. // Temporary implementation: later, we might be able to compute
  451. // the dependencies, based on the attributes definition
  452. // (allowed values and default values)
  453. // Even non-writable attributes (like ExternalFields) can now have Prerequisites
  454. return $oAtt->GetPrerequisiteAttributes();
  455. }
  456. /**
  457. * Find all attributes that depend on the specified one (reverse of GetPrerequisiteAttributes)
  458. * @param string $sClass Name of the class
  459. * @param string $sAttCode Code of the attributes
  460. * @return Array List of attribute codes that depend on the given attribute, empty array if none.
  461. */
  462. final static public function GetDependentAttributes($sClass, $sAttCode)
  463. {
  464. $aResults = array();
  465. self::_check_subclass($sClass);
  466. foreach (self::ListAttributeDefs($sClass) as $sDependentAttCode=>$void)
  467. {
  468. $aPrerequisites = self::GetPrerequisiteAttributes($sClass, $sDependentAttCode);
  469. if (in_array($sAttCode, $aPrerequisites))
  470. {
  471. $aResults[] = $sDependentAttCode;
  472. }
  473. }
  474. return $aResults;
  475. }
  476. // #@# restore to private ?
  477. final static public function DBGetTable($sClass, $sAttCode = null)
  478. {
  479. self::_check_subclass($sClass);
  480. if (empty($sAttCode) || ($sAttCode == "id"))
  481. {
  482. $sTableRaw = self::$m_aClassParams[$sClass]["db_table"];
  483. if (empty($sTableRaw))
  484. {
  485. // return an empty string whenever the table is undefined, meaning that there is no table associated to this 'abstract' class
  486. return '';
  487. }
  488. else
  489. {
  490. // If the format changes here, do not forget to update the setup index page (detection of installed modules)
  491. return self::$m_sTablePrefix.$sTableRaw;
  492. }
  493. }
  494. // This attribute has been inherited (compound objects)
  495. return self::DBGetTable(self::$m_aAttribOrigins[$sClass][$sAttCode]);
  496. }
  497. final static public function DBGetView($sClass)
  498. {
  499. return self::$m_sTablePrefix."view_".$sClass;
  500. }
  501. final static public function DBEnumTables()
  502. {
  503. // This API does not rely on our capability to query the DB and retrieve
  504. // the list of existing tables
  505. // Rather, it uses the list of expected tables, corresponding to the data model
  506. $aTables = array();
  507. foreach (self::GetClasses() as $sClass)
  508. {
  509. if (!self::HasTable($sClass)) continue;
  510. $sTable = self::DBGetTable($sClass);
  511. // Could be completed later with all the classes that are using a given table
  512. if (!array_key_exists($sTable, $aTables))
  513. {
  514. $aTables[$sTable] = array();
  515. }
  516. $aTables[$sTable][] = $sClass;
  517. }
  518. return $aTables;
  519. }
  520. final static public function DBGetIndexes($sClass)
  521. {
  522. self::_check_subclass($sClass);
  523. if (isset(self::$m_aClassParams[$sClass]['indexes']))
  524. {
  525. $aRet = self::$m_aClassParams[$sClass]['indexes'];
  526. }
  527. else
  528. {
  529. $aRet = array();
  530. }
  531. return $aRet;
  532. }
  533. final static public function DBGetKey($sClass)
  534. {
  535. self::_check_subclass($sClass);
  536. return self::$m_aClassParams[$sClass]["db_key_field"];
  537. }
  538. final static public function DBGetClassField($sClass)
  539. {
  540. self::_check_subclass($sClass);
  541. return self::$m_aClassParams[$sClass]["db_finalclass_field"];
  542. }
  543. final static public function IsStandaloneClass($sClass)
  544. {
  545. self::_check_subclass($sClass);
  546. if (count(self::$m_aChildClasses[$sClass]) == 0)
  547. {
  548. if (count(self::$m_aParentClasses[$sClass]) == 0)
  549. {
  550. return true;
  551. }
  552. }
  553. return false;
  554. }
  555. final static public function IsParentClass($sParentClass, $sChildClass)
  556. {
  557. self::_check_subclass($sChildClass);
  558. self::_check_subclass($sParentClass);
  559. if (in_array($sParentClass, self::$m_aParentClasses[$sChildClass])) return true;
  560. if ($sChildClass == $sParentClass) return true;
  561. return false;
  562. }
  563. final static public function IsSameFamilyBranch($sClassA, $sClassB)
  564. {
  565. self::_check_subclass($sClassA);
  566. self::_check_subclass($sClassB);
  567. if (in_array($sClassA, self::$m_aParentClasses[$sClassB])) return true;
  568. if (in_array($sClassB, self::$m_aParentClasses[$sClassA])) return true;
  569. if ($sClassA == $sClassB) return true;
  570. return false;
  571. }
  572. final static public function IsSameFamily($sClassA, $sClassB)
  573. {
  574. self::_check_subclass($sClassA);
  575. self::_check_subclass($sClassB);
  576. return (self::GetRootClass($sClassA) == self::GetRootClass($sClassB));
  577. }
  578. // Attributes of a given class may contain attributes defined in a parent class
  579. // - Some attributes are a copy of the definition
  580. // - Some attributes correspond to the upper class table definition (compound objects)
  581. // (see also filters definition)
  582. private static $m_aAttribDefs = array(); // array of ("classname" => array of attributes)
  583. private static $m_aAttribOrigins = array(); // array of ("classname" => array of ("attcode"=>"sourceclass"))
  584. private static $m_aExtKeyFriends = array(); // array of ("classname" => array of ("indirect ext key attcode"=> array of ("relative ext field")))
  585. private static $m_aIgnoredAttributes = array(); //array of ("classname" => array of ("attcode"))
  586. private static $m_aEnumToMeta = array(); // array of ("classname" => array of ("attcode" => array of ("metaattcode" => oMetaAttDef))
  587. final static public function ListAttributeDefs($sClass)
  588. {
  589. self::_check_subclass($sClass);
  590. return self::$m_aAttribDefs[$sClass];
  591. }
  592. final public static function GetAttributesList($sClass)
  593. {
  594. self::_check_subclass($sClass);
  595. return array_keys(self::$m_aAttribDefs[$sClass]);
  596. }
  597. final public static function GetFiltersList($sClass)
  598. {
  599. self::_check_subclass($sClass);
  600. return array_keys(self::$m_aFilterDefs[$sClass]);
  601. }
  602. final public static function GetKeysList($sClass)
  603. {
  604. self::_check_subclass($sClass);
  605. $aExtKeys = array();
  606. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
  607. {
  608. if ($oAttDef->IsExternalKey())
  609. {
  610. $aExtKeys[] = $sAttCode;
  611. }
  612. }
  613. return $aExtKeys;
  614. }
  615. final static public function IsValidKeyAttCode($sClass, $sAttCode)
  616. {
  617. if (!array_key_exists($sClass, self::$m_aAttribDefs)) return false;
  618. if (!array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass])) return false;
  619. return (self::$m_aAttribDefs[$sClass][$sAttCode]->IsExternalKey());
  620. }
  621. final static public function IsValidAttCode($sClass, $sAttCode, $bExtended = false)
  622. {
  623. if (!array_key_exists($sClass, self::$m_aAttribDefs)) return false;
  624. if ($bExtended)
  625. {
  626. if (($iPos = strpos($sAttCode, '->')) === false)
  627. {
  628. $bRes = array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass]);
  629. }
  630. else
  631. {
  632. $sExtKeyAttCode = substr($sAttCode, 0, $iPos);
  633. $sRemoteAttCode = substr($sAttCode, $iPos + 2);
  634. if (MetaModel::IsValidAttCode($sClass, $sExtKeyAttCode))
  635. {
  636. $oKeyAttDef = MetaModel::GetAttributeDef($sClass, $sExtKeyAttCode);
  637. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  638. $bRes = MetaModel::IsValidAttCode($sRemoteClass, $sRemoteAttCode, true);
  639. }
  640. else
  641. {
  642. $bRes = false;
  643. }
  644. }
  645. }
  646. else
  647. {
  648. $bRes = array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass]);
  649. }
  650. return $bRes;
  651. }
  652. final static public function IsAttributeOrigin($sClass, $sAttCode)
  653. {
  654. return (self::$m_aAttribOrigins[$sClass][$sAttCode] == $sClass);
  655. }
  656. final static public function IsValidFilterCode($sClass, $sFilterCode)
  657. {
  658. if (!array_key_exists($sClass, self::$m_aFilterDefs)) return false;
  659. return (array_key_exists($sFilterCode, self::$m_aFilterDefs[$sClass]));
  660. }
  661. public static function IsValidClass($sClass)
  662. {
  663. return (array_key_exists($sClass, self::$m_aAttribDefs));
  664. }
  665. public static function IsValidObject($oObject)
  666. {
  667. if (!is_object($oObject)) return false;
  668. return (self::IsValidClass(get_class($oObject)));
  669. }
  670. public static function IsReconcKey($sClass, $sAttCode)
  671. {
  672. return (in_array($sAttCode, self::GetReconcKeys($sClass)));
  673. }
  674. final static public function GetAttributeDef($sClass, $sAttCode)
  675. {
  676. self::_check_subclass($sClass);
  677. if (isset(self::$m_aAttribDefs[$sClass][$sAttCode]))
  678. {
  679. return self::$m_aAttribDefs[$sClass][$sAttCode];
  680. }
  681. elseif (($iPos = strpos($sAttCode, '->')) !== false)
  682. {
  683. $sExtKeyAttCode = substr($sAttCode, 0, $iPos);
  684. $sRemoteAttCode = substr($sAttCode, $iPos + 2);
  685. $oKeyAttDef = self::GetAttributeDef($sClass, $sExtKeyAttCode);
  686. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  687. return self::GetAttributeDef($sRemoteClass, $sRemoteAttCode);
  688. }
  689. else
  690. {
  691. throw new Exception("Unknown attribute $sAttCode from class $sClass");
  692. }
  693. }
  694. final static public function GetExternalKeys($sClass)
  695. {
  696. $aExtKeys = array();
  697. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  698. {
  699. if ($oAtt->IsExternalKey())
  700. {
  701. $aExtKeys[$sAttCode] = $oAtt;
  702. }
  703. }
  704. return $aExtKeys;
  705. }
  706. final static public function GetLinkedSets($sClass)
  707. {
  708. $aLinkedSets = array();
  709. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  710. {
  711. if (is_subclass_of($oAtt, 'AttributeLinkedSet'))
  712. {
  713. $aLinkedSets[$sAttCode] = $oAtt;
  714. }
  715. }
  716. return $aLinkedSets;
  717. }
  718. final static public function GetExternalFields($sClass, $sKeyAttCode)
  719. {
  720. static $aExtFields = array();
  721. if (!isset($aExtFields[$sClass][$sKeyAttCode]))
  722. {
  723. $aExtFields[$sClass][$sKeyAttCode] = array();
  724. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  725. {
  726. if ($oAtt->IsExternalField() && ($oAtt->GetKeyAttCode() == $sKeyAttCode))
  727. {
  728. $aExtFields[$sClass][$sKeyAttCode][$oAtt->GetExtAttCode()] = $oAtt;
  729. }
  730. }
  731. }
  732. return $aExtFields[$sClass][$sKeyAttCode];
  733. }
  734. final static public function FindExternalField($sClass, $sKeyAttCode, $sRemoteAttCode)
  735. {
  736. $aExtFields = self::GetExternalFields($sClass, $sKeyAttCode);
  737. if (isset($aExtFields[$sRemoteAttCode]))
  738. {
  739. return $aExtFields[$sRemoteAttCode];
  740. }
  741. else
  742. {
  743. return null;
  744. }
  745. }
  746. final static public function GetExtKeyFriends($sClass, $sExtKeyAttCode)
  747. {
  748. if (array_key_exists($sExtKeyAttCode, self::$m_aExtKeyFriends[$sClass]))
  749. {
  750. return self::$m_aExtKeyFriends[$sClass][$sExtKeyAttCode];
  751. }
  752. else
  753. {
  754. return array();
  755. }
  756. }
  757. protected static $m_aTrackForwardCache = array();
  758. /**
  759. * List external keys for which there is a LinkSet (direct or indirect) on the other end
  760. * For those external keys, a change will have a special meaning on the other end
  761. * in term of change tracking
  762. */
  763. final static public function GetTrackForwardExternalKeys($sClass)
  764. {
  765. if (!isset(self::$m_aTrackForwardCache[$sClass]))
  766. {
  767. $aRes = array();
  768. foreach (MetaModel::GetExternalKeys($sClass) as $sAttCode => $oAttDef)
  769. {
  770. $sRemoteClass = $oAttDef->GetTargetClass();
  771. foreach (MetaModel::ListAttributeDefs($sRemoteClass) as $sRemoteAttCode => $oRemoteAttDef)
  772. {
  773. if (!$oRemoteAttDef->IsLinkSet()) continue;
  774. if (!is_subclass_of($sClass, $oRemoteAttDef->GetLinkedClass()) && $oRemoteAttDef->GetLinkedClass() != $sClass) continue;
  775. if ($oRemoteAttDef->GetExtKeyToMe() != $sAttCode) continue;
  776. $aRes[$sAttCode] = $oRemoteAttDef;
  777. }
  778. }
  779. self::$m_aTrackForwardCache[$sClass] = $aRes;
  780. }
  781. return self::$m_aTrackForwardCache[$sClass];
  782. }
  783. final static public function ListMetaAttributes($sClass, $sAttCode)
  784. {
  785. if (isset(self::$m_aEnumToMeta[$sClass][$sAttCode]))
  786. {
  787. $aRet = self::$m_aEnumToMeta[$sClass][$sAttCode];
  788. }
  789. else
  790. {
  791. $aRet = array();
  792. }
  793. return $aRet;
  794. }
  795. /**
  796. * Get the attribute label
  797. * @param string sClass Persistent class
  798. * @param string sAttCodeEx Extended attribute code: attcode[->attcode]
  799. * @param bool $bShowMandatory If true, add a star character (at the end or before the ->) to show that the field is mandatory
  800. * @return string A user friendly format of the string: AttributeName or AttributeName->ExtAttributeName
  801. */
  802. public static function GetLabel($sClass, $sAttCodeEx, $bShowMandatory = false)
  803. {
  804. $sLabel = '';
  805. if (($iPos = strpos($sAttCodeEx, '->')) === false)
  806. {
  807. if ($sAttCodeEx == 'id')
  808. {
  809. $sLabel = Dict::S('UI:CSVImport:idField');
  810. }
  811. else
  812. {
  813. $oAttDef = self::GetAttributeDef($sClass, $sAttCodeEx);
  814. $sMandatory = ($bShowMandatory && !$oAttDef->IsNullAllowed()) ? '*' : '';
  815. $sLabel = $oAttDef->GetLabel().$sMandatory;
  816. }
  817. }
  818. else
  819. {
  820. $sExtKeyAttCode = substr($sAttCodeEx, 0, $iPos);
  821. $sRemoteAttCode = substr($sAttCodeEx, $iPos + 2);
  822. $oKeyAttDef = MetaModel::GetAttributeDef($sClass, $sExtKeyAttCode);
  823. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  824. // Recurse
  825. $sLabel = self::GetLabel($sClass, $sExtKeyAttCode).'->'.self::GetLabel($sRemoteClass, $sRemoteAttCode);
  826. }
  827. return $sLabel;
  828. }
  829. public static function GetDescription($sClass, $sAttCode)
  830. {
  831. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  832. if ($oAttDef) return $oAttDef->GetDescription();
  833. return "";
  834. }
  835. // Filters of a given class may contain filters defined in a parent class
  836. // - Some filters are a copy of the definition
  837. // - Some filters correspond to the upper class table definition (compound objects)
  838. // (see also attributes definition)
  839. private static $m_aFilterDefs = array(); // array of ("classname" => array filterdef)
  840. private static $m_aFilterOrigins = array(); // array of ("classname" => array of ("attcode"=>"sourceclass"))
  841. public static function GetClassFilterDefs($sClass)
  842. {
  843. self::_check_subclass($sClass);
  844. return self::$m_aFilterDefs[$sClass];
  845. }
  846. final static public function GetClassFilterDef($sClass, $sFilterCode)
  847. {
  848. self::_check_subclass($sClass);
  849. if (!array_key_exists($sFilterCode, self::$m_aFilterDefs[$sClass]))
  850. {
  851. throw new CoreException("Unknown filter code '$sFilterCode' for class '$sClass'");
  852. }
  853. return self::$m_aFilterDefs[$sClass][$sFilterCode];
  854. }
  855. public static function GetFilterLabel($sClass, $sFilterCode)
  856. {
  857. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  858. if ($oFilter) return $oFilter->GetLabel();
  859. return "";
  860. }
  861. public static function GetFilterDescription($sClass, $sFilterCode)
  862. {
  863. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  864. if ($oFilter) return $oFilter->GetDescription();
  865. return "";
  866. }
  867. // returns an array of opcode=>oplabel (e.g. "differs from")
  868. public static function GetFilterOperators($sClass, $sFilterCode)
  869. {
  870. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  871. if ($oFilter) return $oFilter->GetOperators();
  872. return array();
  873. }
  874. // returns an opcode
  875. public static function GetFilterLooseOperator($sClass, $sFilterCode)
  876. {
  877. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  878. if ($oFilter) return $oFilter->GetLooseOperator();
  879. return array();
  880. }
  881. public static function GetFilterOpDescription($sClass, $sFilterCode, $sOpCode)
  882. {
  883. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  884. if ($oFilter) return $oFilter->GetOpDescription($sOpCode);
  885. return "";
  886. }
  887. public static function GetFilterHTMLInput($sFilterCode)
  888. {
  889. return "<INPUT name=\"$sFilterCode\">";
  890. }
  891. // Lists of attributes/search filters
  892. //
  893. private static $m_aListInfos = array(); // array of ("listcode" => various info on the list, common to every classes)
  894. private static $m_aListData = array(); // array of ("classname" => array of "listcode" => list)
  895. // list may be an array of attcode / fltcode
  896. // list may be an array of "groupname" => (array of attcode / fltcode)
  897. public static function EnumZLists()
  898. {
  899. return array_keys(self::$m_aListInfos);
  900. }
  901. final static public function GetZListInfo($sListCode)
  902. {
  903. return self::$m_aListInfos[$sListCode];
  904. }
  905. public static function GetZListItems($sClass, $sListCode)
  906. {
  907. if (array_key_exists($sClass, self::$m_aListData))
  908. {
  909. if (array_key_exists($sListCode, self::$m_aListData[$sClass]))
  910. {
  911. return self::$m_aListData[$sClass][$sListCode];
  912. }
  913. }
  914. $sParentClass = self::GetParentPersistentClass($sClass);
  915. if (empty($sParentClass)) return array(); // nothing for the mother of all classes
  916. // Dig recursively
  917. return self::GetZListItems($sParentClass, $sListCode);
  918. }
  919. public static function IsAttributeInZList($sClass, $sListCode, $sAttCodeOrFltCode, $sGroup = null)
  920. {
  921. $aZList = self::FlattenZlist(self::GetZListItems($sClass, $sListCode));
  922. if (!$sGroup)
  923. {
  924. return (in_array($sAttCodeOrFltCode, $aZList));
  925. }
  926. return (in_array($sAttCodeOrFltCode, $aZList[$sGroup]));
  927. }
  928. //
  929. // Relations
  930. //
  931. private static $m_aRelationInfos = array(); // array of ("relcode" => various info on the list, common to every classes)
  932. /**
  933. * TO BE DEPRECATED: use EnumRelationsEx instead
  934. * @param string $sClass
  935. * @return multitype:string unknown |Ambigous <string, multitype:>
  936. */
  937. public static function EnumRelations($sClass = '')
  938. {
  939. $aResult = array_keys(self::$m_aRelationInfos);
  940. if (!empty($sClass))
  941. {
  942. // Return only the relations that have a meaning (i.e. for which at least one query is defined)
  943. // for the specified class
  944. $aClassRelations = array();
  945. foreach($aResult as $sRelCode)
  946. {
  947. $aQueriesDown = self::EnumRelationQueries($sClass, $sRelCode);
  948. if (count($aQueriesDown) > 0)
  949. {
  950. $aClassRelations[] = $sRelCode;
  951. }
  952. // Temporary patch: until the impact analysis GUI gets rewritten,
  953. // let's consider that "depends on" is equivalent to "impacts/up"
  954. // The current patch has been implemented in DBObject and MetaModel
  955. if ($sRelCode == 'impacts')
  956. {
  957. $aQueriesUp = self::EnumRelationQueries($sClass, 'impacts', false);
  958. if (count($aQueriesUp) > 0)
  959. {
  960. $aClassRelations[] = 'depends on';
  961. }
  962. }
  963. }
  964. return $aClassRelations;
  965. }
  966. // Temporary patch: until the impact analysis GUI gets rewritten,
  967. // let's consider that "depends on" is equivalent to "impacts/up"
  968. // The current patch has been implemented in DBObject and MetaModel
  969. if (in_array('impacts', $aResult))
  970. {
  971. $aResult[] = 'depends on';
  972. }
  973. return $aResult;
  974. }
  975. public static function EnumRelationsEx($sClass)
  976. {
  977. $aRelationInfo = array_keys(self::$m_aRelationInfos);
  978. // Return only the relations that have a meaning (i.e. for which at least one query is defined)
  979. // for the specified class
  980. $aClassRelations = array();
  981. foreach($aRelationInfo as $sRelCode)
  982. {
  983. $aQueriesDown = self::EnumRelationQueries($sClass, $sRelCode, true /* Down */);
  984. if (count($aQueriesDown) > 0)
  985. {
  986. $aClassRelations[$sRelCode]['down'] = self::GetRelationLabel($sRelCode, true);
  987. }
  988. $aQueriesUp = self::EnumRelationQueries($sClass, $sRelCode, false /* Up */);
  989. if (count($aQueriesUp) > 0)
  990. {
  991. $aClassRelations[$sRelCode]['up'] = self::GetRelationLabel($sRelCode, false);
  992. }
  993. }
  994. return $aClassRelations;
  995. }
  996. final static public function GetRelationDescription($sRelCode)
  997. {
  998. return Dict::S("Relation:$sRelCode/Description");
  999. }
  1000. final static public function GetRelationLabel($sRelCode, $bDown = true)
  1001. {
  1002. if ($bDown)
  1003. {
  1004. // The legacy convention is confusing with regard to the way we have conceptualized the relations:
  1005. // In the former representation, the main stream was named after "up"
  1006. // Now, the relation from A to B says that something is transmitted from A to B, thus going DOWNstream as described in a petri net.
  1007. $sKey = "Relation:$sRelCode/DownStream";
  1008. $sLegacy = Dict::S("Relation:$sRelCode/VerbUp", $sKey);
  1009. }
  1010. else
  1011. {
  1012. $sKey = "Relation:$sRelCode/UpStream";
  1013. $sLegacy = Dict::S("Relation:$sRelCode/VerbDown", $sKey);
  1014. }
  1015. $sRet = Dict::S($sKey, $sLegacy);
  1016. return $sRet;
  1017. }
  1018. protected static function ComputeRelationQueries($sRelCode)
  1019. {
  1020. $bHasLegacy = false;
  1021. $aQueries = array();
  1022. foreach (self::GetClasses() as $sClass)
  1023. {
  1024. $aQueries[$sClass]['down'] = array();
  1025. if (!array_key_exists('up', $aQueries[$sClass]))
  1026. {
  1027. $aQueries[$sClass]['up'] = array();
  1028. }
  1029. $aNeighboursDown = call_user_func_array(array($sClass, 'GetRelationQueriesEx'), array($sRelCode));
  1030. // Translate attributes into queries (new style of spec only)
  1031. foreach($aNeighboursDown as $sNeighbourId => $aNeighbourData)
  1032. {
  1033. $aNeighbourData['sFromClass'] = $aNeighbourData['sDefinedInClass'];
  1034. try
  1035. {
  1036. if (strlen($aNeighbourData['sQueryDown']) == 0)
  1037. {
  1038. $oAttDef = self::GetAttributeDef($sClass, $aNeighbourData['sAttribute']);
  1039. if ($oAttDef instanceof AttributeExternalKey)
  1040. {
  1041. $sTargetClass = $oAttDef->GetTargetClass();
  1042. $aNeighbourData['sToClass'] = $sTargetClass;
  1043. $aNeighbourData['sQueryDown'] = 'SELECT '.$sTargetClass.' AS o WHERE o.id = :this->'.$aNeighbourData['sAttribute'];
  1044. $aNeighbourData['sQueryUp'] = 'SELECT '.$aNeighbourData['sFromClass'].' AS o WHERE o.'.$aNeighbourData['sAttribute'].' = :this->id';
  1045. }
  1046. elseif ($oAttDef instanceof AttributeLinkedSet)
  1047. {
  1048. $sLinkedClass = $oAttDef->GetLinkedClass();
  1049. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  1050. if ($oAttDef->IsIndirect())
  1051. {
  1052. $sExtKeyToRemote = $oAttDef->GetExtKeyToRemote();
  1053. $oRemoteAttDef = self::GetAttributeDef($sLinkedClass, $sExtKeyToRemote);
  1054. $sRemoteClass = $oRemoteAttDef->GetTargetClass();
  1055. $aNeighbourData['sToClass'] = $sRemoteClass;
  1056. $aNeighbourData['sQueryDown'] = "SELECT $sRemoteClass AS o JOIN $sLinkedClass AS lnk ON lnk.$sExtKeyToRemote = o.id WHERE lnk.$sExtKeyToMe = :this->id";
  1057. $aNeighbourData['sQueryUp'] = "SELECT ".$aNeighbourData['sFromClass']." AS o JOIN $sLinkedClass AS lnk ON lnk.$sExtKeyToMe = o.id WHERE lnk.$sExtKeyToRemote = :this->id";
  1058. }
  1059. else
  1060. {
  1061. $aNeighbourData['sToClass'] = $sLinkedClass;
  1062. $aNeighbourData['sQueryDown'] = "SELECT $sLinkedClass AS o WHERE o.$sExtKeyToMe = :this->id";
  1063. $aNeighbourData['sQueryUp'] = "SELECT ".$aNeighbourData['sFromClass']." AS o WHERE o.id = :this->$sExtKeyToMe";
  1064. }
  1065. }
  1066. else
  1067. {
  1068. throw new Exception("Unexpected attribute type for '{$aNeighbourData['sAttribute']}'. Expecting a link set or external key.");
  1069. }
  1070. }
  1071. else
  1072. {
  1073. $oSearch = DBObjectSearch::FromOQL($aNeighbourData['sQueryDown']);
  1074. $aNeighbourData['sToClass'] = $oSearch->GetClass();
  1075. }
  1076. }
  1077. catch (Exception $e)
  1078. {
  1079. throw new Exception("Wrong definition for the relation $sRelCode/{$aNeighbourData['sDefinedInClass']}/{$aNeighbourData['sNeighbour']}: ".$e->getMessage());
  1080. }
  1081. if ($aNeighbourData['sDirection'] == 'down')
  1082. {
  1083. $aNeighbourData['sQueryUp'] = null;
  1084. }
  1085. $sArrowId = $aNeighbourData['sDefinedInClass'].'_'.$sNeighbourId;
  1086. $aQueries[$sClass]['down'][$sArrowId] = $aNeighbourData;
  1087. // Compute the reverse index
  1088. if ($aNeighbourData['sDefinedInClass'] == $sClass)
  1089. {
  1090. if ($aNeighbourData['sDirection'] == 'both')
  1091. {
  1092. $sFromClass = $aNeighbourData['sFromClass'];
  1093. $sToClass = $aNeighbourData['sToClass'];
  1094. foreach (self::EnumChildClasses($sToClass, ENUM_CHILD_CLASSES_ALL) as $sSubClass)
  1095. {
  1096. $aQueries[$sSubClass]['up'][$sArrowId] = $aNeighbourData;
  1097. }
  1098. }
  1099. }
  1100. }
  1101. // Read legacy definitions
  1102. // The up/down queries have to be reconcilied, which can only be done later when all the classes have been browsed
  1103. //
  1104. // The keys used to store a query (up or down) into the array are built differently between the modern and legacy made data:
  1105. // Modern way: aQueries[sClass]['up'|'down'][sArrowId], where sArrowId is made of the source class + neighbour id (XML def)
  1106. // Legacy way: aQueries[sClass]['up'|'down'][sRemoteClass]
  1107. // The modern way does allow for several arrows between two classes
  1108. // The legacy way aims at simplifying the transformation (reconciliation between up and down)
  1109. if ($sRelCode == 'impacts')
  1110. {
  1111. $sRevertCode = 'depends on';
  1112. $aLegacy = call_user_func_array(array($sClass, 'GetRelationQueries'), array($sRelCode));
  1113. foreach($aLegacy as $sId => $aLegacyEntry)
  1114. {
  1115. $bHasLegacy = true;
  1116. $oFilter = DBObjectSearch::FromOQL($aLegacyEntry['sQuery']);
  1117. $sRemoteClass = $oFilter->GetClass();
  1118. // Determine wether the query is inherited from a parent or not
  1119. $bInherited = false;
  1120. foreach (self::EnumParentClasses($sClass) as $sParent)
  1121. {
  1122. if (!isset($aQueries[$sParent]['down'][$sRemoteClass])) continue;
  1123. if ($aLegacyEntry['sQuery'] == $aQueries[$sParent]['down'][$sRemoteClass]['sQueryDown'])
  1124. {
  1125. $bInherited = true;
  1126. $aQueries[$sClass]['down'][$sRemoteClass] = $aQueries[$sParent]['down'][$sRemoteClass];
  1127. break;
  1128. }
  1129. }
  1130. if (!$bInherited)
  1131. {
  1132. $aQueries[$sClass]['down'][$sRemoteClass] = array(
  1133. '_legacy_' => true,
  1134. 'sDefinedInClass' => $sClass,
  1135. 'sFromClass' => $sClass,
  1136. 'sToClass' => $sRemoteClass,
  1137. 'sDirection' => 'down',
  1138. 'sQueryDown' => $aLegacyEntry['sQuery'],
  1139. 'sQueryUp' => null,
  1140. 'sNeighbour' => $sRemoteClass // Normalize the neighbour id
  1141. );
  1142. }
  1143. }
  1144. $aLegacy = call_user_func_array(array($sClass, 'GetRelationQueries'), array($sRevertCode));
  1145. foreach($aLegacy as $sId => $aLegacyEntry)
  1146. {
  1147. $bHasLegacy = true;
  1148. $oFilter = DBObjectSearch::FromOQL($aLegacyEntry['sQuery']);
  1149. $sRemoteClass = $oFilter->GetClass();
  1150. // Determine wether the query is inherited from a parent or not
  1151. $bInherited = false;
  1152. foreach (self::EnumParentClasses($sClass) as $sParent)
  1153. {
  1154. if (!isset($aQueries[$sParent]['up'][$sRemoteClass])) continue;
  1155. if ($aLegacyEntry['sQuery'] == $aQueries[$sParent]['up'][$sRemoteClass]['sQueryUp'])
  1156. {
  1157. $bInherited = true;
  1158. $aQueries[$sClass]['up'][$sRemoteClass] = $aQueries[$sParent]['up'][$sRemoteClass];
  1159. break;
  1160. }
  1161. }
  1162. if (!$bInherited)
  1163. {
  1164. $aQueries[$sClass]['up'][$sRemoteClass] = array(
  1165. '_legacy_' => true,
  1166. 'sDefinedInClass' => $sRemoteClass,
  1167. 'sFromClass' => $sRemoteClass,
  1168. 'sToClass' => $sClass,
  1169. 'sDirection' => 'both',
  1170. 'sQueryDown' => null,
  1171. 'sQueryUp' => $aLegacyEntry['sQuery'],
  1172. 'sNeighbour' => $sClass// Normalize the neighbour id
  1173. );
  1174. }
  1175. }
  1176. }
  1177. else
  1178. {
  1179. // Cannot take the legacy system into account... simply ignore it
  1180. }
  1181. } // foreach class
  1182. // Perform the up/down reconciliation for the legacy definitions
  1183. if ($bHasLegacy)
  1184. {
  1185. foreach (self::GetClasses() as $sClass)
  1186. {
  1187. // Foreach "up" legacy query, update its "down" counterpart
  1188. if (isset($aQueries[$sClass]['up']))
  1189. {
  1190. foreach ($aQueries[$sClass]['up'] as $sNeighbourId => $aNeighbourData)
  1191. {
  1192. if (!array_key_exists('_legacy_', $aNeighbourData))
  1193. {
  1194. continue;
  1195. }
  1196. if (!$aNeighbourData['_legacy_']) continue; // Skip modern definitions
  1197. $sLocalClass = $aNeighbourData['sToClass'];
  1198. foreach (self::EnumChildClasses($aNeighbourData['sFromClass'], ENUM_CHILD_CLASSES_ALL) as $sRemoteClass)
  1199. {
  1200. if (isset($aQueries[$sRemoteClass]['down'][$sLocalClass]))
  1201. {
  1202. $aQueries[$sRemoteClass]['down'][$sLocalClass]['sQueryUp'] = $aNeighbourData['sQueryUp'];
  1203. $aQueries[$sRemoteClass]['down'][$sLocalClass]['sDirection'] = 'both';
  1204. }
  1205. // Be silent in order to transparently support legacy data models where the counterpart query does not always exist
  1206. //else
  1207. //{
  1208. // throw new Exception("Legacy definition of the relation '$sRelCode/$sRevertCode', defined on $sLocalClass (relation: $sRevertCode, inherited to $sClass), missing the counterpart query on class $sRemoteClass ($sRelCode)");
  1209. //}
  1210. }
  1211. }
  1212. }
  1213. // Foreach "down" legacy query, update its "up" counterpart (if any)
  1214. foreach ($aQueries[$sClass]['down'] as $sNeighbourId => $aNeighbourData)
  1215. {
  1216. if (!$aNeighbourData['_legacy_']) continue; // Skip modern definitions
  1217. $sLocalClass = $aNeighbourData['sFromClass'];
  1218. foreach (self::EnumChildClasses($aNeighbourData['sToClass'], ENUM_CHILD_CLASSES_ALL) as $sRemoteClass)
  1219. {
  1220. if (isset($aQueries[$sRemoteClass]['up'][$sLocalClass]))
  1221. {
  1222. $aQueries[$sRemoteClass]['up'][$sLocalClass]['sQueryDown'] = $aNeighbourData['sQueryDown'];
  1223. }
  1224. }
  1225. }
  1226. }
  1227. }
  1228. return $aQueries;
  1229. }
  1230. public static function EnumRelationQueries($sClass, $sRelCode, $bDown = true)
  1231. {
  1232. static $aQueries = array();
  1233. if (!isset($aQueries[$sRelCode]))
  1234. {
  1235. $aQueries[$sRelCode] = self::ComputeRelationQueries($sRelCode);
  1236. }
  1237. $sDirection = $bDown ? 'down' : 'up';
  1238. if (isset($aQueries[$sRelCode][$sClass][$sDirection]))
  1239. {
  1240. return $aQueries[$sRelCode][$sClass][$sDirection];
  1241. }
  1242. else
  1243. {
  1244. return array();
  1245. }
  1246. }
  1247. /**
  1248. * Compute the "RelatedObjects" for a whole set of DBObjects
  1249. *
  1250. * @param string $sRelCode The code of the relation to use for the computation
  1251. * @param array $asourceObjects The objects to start with
  1252. * @param int $iMaxDepth
  1253. * @param boolean $bEnableReduncancy
  1254. * @param array $aUnreachable Array of objects to be considered as 'unreachable'
  1255. *
  1256. * @return RelationGraph The graph of all the related objects
  1257. */
  1258. static public function GetRelatedObjectsDown($sRelCode, $aSourceObjects, $iMaxDepth = 99, $bEnableRedundancy = true, $aUnreachable = array(), $aContexts = array())
  1259. {
  1260. $oGraph = new RelationGraph();
  1261. foreach ($aSourceObjects as $oObject)
  1262. {
  1263. $oGraph->AddSourceObject($oObject);
  1264. }
  1265. foreach($aContexts as $key => $sOQL)
  1266. {
  1267. $oGraph->AddContextQuery($key, $sOQL);
  1268. }
  1269. $oGraph->ComputeRelatedObjectsDown($sRelCode, $iMaxDepth, $bEnableRedundancy, $aUnreachable);
  1270. return $oGraph;
  1271. }
  1272. /**
  1273. * Compute the "RelatedObjects" in the reverse way
  1274. *
  1275. * @param string $sRelCode The code of the relation to use for the computation
  1276. * @param array $asourceObjects The objects to start with
  1277. * @param int $iMaxDepth
  1278. * @param boolean $bEnableReduncancy
  1279. *
  1280. * @return RelationGraph The graph of all the related objects
  1281. */
  1282. static public function GetRelatedObjectsUp($sRelCode, $aSourceObjects, $iMaxDepth = 99, $bEnableRedundancy = true, $aContexts = array())
  1283. {
  1284. $oGraph = new RelationGraph();
  1285. foreach ($aSourceObjects as $oObject)
  1286. {
  1287. $oGraph->AddSinkObject($oObject);
  1288. }
  1289. foreach($aContexts as $key => $sOQL)
  1290. {
  1291. $oGraph->AddContextQuery($key, $sOQL);
  1292. }
  1293. $oGraph->ComputeRelatedObjectsUp($sRelCode, $iMaxDepth, $bEnableRedundancy);
  1294. return $oGraph;
  1295. }
  1296. //
  1297. // Object lifecycle model
  1298. //
  1299. private static $m_aStates = array(); // array of ("classname" => array of "statecode"=>array('label'=>..., attribute_inherit=> attribute_list=>...))
  1300. private static $m_aStimuli = array(); // array of ("classname" => array of ("stimuluscode"=>array('label'=>...)))
  1301. private static $m_aTransitions = array(); // array of ("classname" => array of ("statcode_from"=>array of ("stimuluscode" => array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD)))
  1302. public static function EnumStates($sClass)
  1303. {
  1304. if (array_key_exists($sClass, self::$m_aStates))
  1305. {
  1306. return self::$m_aStates[$sClass];
  1307. }
  1308. else
  1309. {
  1310. return array();
  1311. }
  1312. }
  1313. /*
  1314. * Enumerate all possible initial states, including the default one
  1315. */
  1316. public static function EnumInitialStates($sClass)
  1317. {
  1318. if (array_key_exists($sClass, self::$m_aStates))
  1319. {
  1320. $aRet = array();
  1321. // Add the states for which the flag 'is_initial_state' is set to <true>
  1322. foreach(self::$m_aStates[$sClass] as $aStateCode => $aProps)
  1323. {
  1324. if (isset($aProps['initial_state_path']))
  1325. {
  1326. $aRet[$aStateCode] = $aProps['initial_state_path'];
  1327. }
  1328. }
  1329. // Add the default initial state
  1330. $sMainInitialState = self::GetDefaultState($sClass);
  1331. if (!isset($aRet[$sMainInitialState]))
  1332. {
  1333. $aRet[$sMainInitialState] = array();
  1334. }
  1335. return $aRet;
  1336. }
  1337. else
  1338. {
  1339. return array();
  1340. }
  1341. }
  1342. public static function EnumStimuli($sClass)
  1343. {
  1344. if (array_key_exists($sClass, self::$m_aStimuli))
  1345. {
  1346. return self::$m_aStimuli[$sClass];
  1347. }
  1348. else
  1349. {
  1350. return array();
  1351. }
  1352. }
  1353. public static function GetStateLabel($sClass, $sStateValue)
  1354. {
  1355. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  1356. $oAttDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  1357. return $oAttDef->GetValueLabel($sStateValue);
  1358. }
  1359. public static function GetStateDescription($sClass, $sStateValue)
  1360. {
  1361. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  1362. $oAttDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  1363. return $oAttDef->GetValueDescription($sStateValue);
  1364. }
  1365. public static function EnumTransitions($sClass, $sStateCode)
  1366. {
  1367. if (array_key_exists($sClass, self::$m_aTransitions))
  1368. {
  1369. if (array_key_exists($sStateCode, self::$m_aTransitions[$sClass]))
  1370. {
  1371. return self::$m_aTransitions[$sClass][$sStateCode];
  1372. }
  1373. }
  1374. return array();
  1375. }
  1376. public static function GetAttributeFlags($sClass, $sState, $sAttCode)
  1377. {
  1378. $iFlags = 0; // By default (if no life cycle) no flag at all
  1379. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1380. if (!empty($sStateAttCode))
  1381. {
  1382. $aStates = MetaModel::EnumStates($sClass);
  1383. if (!array_key_exists($sState, $aStates))
  1384. {
  1385. throw new CoreException("Invalid state '$sState' for class '$sClass', expecting a value in {".implode(', ', array_keys($aStates))."}");
  1386. }
  1387. $aCurrentState = $aStates[$sState];
  1388. if ( (array_key_exists('attribute_list', $aCurrentState)) && (array_key_exists($sAttCode, $aCurrentState['attribute_list'])) )
  1389. {
  1390. $iFlags = $aCurrentState['attribute_list'][$sAttCode];
  1391. }
  1392. }
  1393. return $iFlags;
  1394. }
  1395. /**
  1396. * Returns the $sAttCode flags when $sStimulus is applied on an object of $sClass in the $sState state.
  1397. * Note: This does NOT combine flags from the target state.
  1398. *
  1399. * @param $sClass string
  1400. * @param $sState string
  1401. * @param $sStimulus string
  1402. * @param $sAttCode string
  1403. * @return int
  1404. * @throws CoreException
  1405. */
  1406. public static function GetTransitionFlags($sClass, $sState, $sStimulus, $sAttCode)
  1407. {
  1408. $iFlags = 0; // By default (if no lifecycle) no flag at all
  1409. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1410. if (!empty($sStateAttCode))
  1411. {
  1412. $aTransitions = MetaModel::EnumTransitions($sClass, $sState);
  1413. if(!array_key_exists($sStimulus, $aTransitions))
  1414. {
  1415. throw new CoreException("Invalid transition '$sStimulus' for class '$sClass', expecting a value in {".implode(', ', array_keys($aTransitions))."}");
  1416. }
  1417. $aCurrentTransition = $aTransitions[$sStimulus];
  1418. if( (array_key_exists('attribute_list', $aCurrentTransition)) && (array_key_exists($sAttCode, $aCurrentTransition['attribute_list'])) )
  1419. {
  1420. $iFlags = $aCurrentTransition['attribute_list'][$sAttCode];
  1421. }
  1422. }
  1423. return $iFlags;
  1424. }
  1425. /**
  1426. * Returns an array of attribute codes (with their flags) when $sStimulus is applied on an object of $sClass in the $sOriginState state.
  1427. * Note: Attributes (and flags) from the target state and the transition are combined.
  1428. *
  1429. * @param $sClass string Object class
  1430. * @param $sStimulus string Stimulus code applied
  1431. * @param $sOriginState string State the stimulus comes from
  1432. * @return array
  1433. */
  1434. public static function GetTransitionAttributes($sClass, $sStimulus, $sOriginState)
  1435. {
  1436. $aAttributes = array();
  1437. // Retrieving target state
  1438. $aTransitions = MetaModel::EnumTransitions($sClass, $sOriginState);
  1439. $aTransition = $aTransitions[$sStimulus];
  1440. $sTargetState = $aTransition['target_state'];
  1441. // Retrieving attributes from state
  1442. $aStates = MetaModel::EnumStates($sClass);
  1443. $aTargetState = $aStates[$sTargetState];
  1444. $aTargetStateAttributes = $aTargetState['attribute_list'];
  1445. // - Merging with results
  1446. $aAttributes = $aTargetStateAttributes;
  1447. // Retrieving attributes from transition
  1448. $aTransitionAttributes = $aTransition['attribute_list'];
  1449. // - Merging with results
  1450. foreach($aTransitionAttributes as $sAttCode => $iAttributeFlags)
  1451. {
  1452. if(array_key_exists($sAttCode, $aAttributes))
  1453. {
  1454. $aAttributes[$sAttCode] = $aAttributes[$sAttCode] | $iAttributeFlags;
  1455. }
  1456. else
  1457. {
  1458. $aAttributes[$sAttCode] = $iAttributeFlags;
  1459. }
  1460. }
  1461. return $aAttributes;
  1462. }
  1463. /**
  1464. * Combines the flags from the all states that compose the initial_state_path
  1465. */
  1466. public static function GetInitialStateAttributeFlags($sClass, $sState, $sAttCode)
  1467. {
  1468. $iFlags = self::GetAttributeFlags($sClass, $sState, $sAttCode); // Be default set the same flags as the 'target' state
  1469. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1470. if (!empty($sStateAttCode))
  1471. {
  1472. $aStates = MetaModel::EnumInitialStates($sClass);
  1473. if (array_key_exists($sState, $aStates))
  1474. {
  1475. $bReadOnly = (($iFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY);
  1476. $bHidden = (($iFlags & OPT_ATT_HIDDEN) == OPT_ATT_HIDDEN);
  1477. foreach($aStates[$sState] as $sPrevState)
  1478. {
  1479. $iPrevFlags = self::GetAttributeFlags($sClass, $sPrevState, $sAttCode);
  1480. if (($iPrevFlags & OPT_ATT_HIDDEN) != OPT_ATT_HIDDEN)
  1481. {
  1482. $bReadOnly = $bReadOnly && (($iPrevFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY); // if it is/was not readonly => then it's not
  1483. }
  1484. $bHidden = $bHidden && (($iPrevFlags & OPT_ATT_HIDDEN) == OPT_ATT_HIDDEN); // if it is/was not hidden => then it's not
  1485. }
  1486. if ($bReadOnly)
  1487. {
  1488. $iFlags = $iFlags | OPT_ATT_READONLY;
  1489. }
  1490. else
  1491. {
  1492. $iFlags = $iFlags & ~OPT_ATT_READONLY;
  1493. }
  1494. if ($bHidden)
  1495. {
  1496. $iFlags = $iFlags | OPT_ATT_HIDDEN;
  1497. }
  1498. else
  1499. {
  1500. $iFlags = $iFlags & ~OPT_ATT_HIDDEN;
  1501. }
  1502. }
  1503. }
  1504. return $iFlags;
  1505. }
  1506. //
  1507. // Allowed values
  1508. //
  1509. public static function GetAllowedValues_att($sClass, $sAttCode, $aArgs = array(), $sContains = '')
  1510. {
  1511. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  1512. return $oAttDef->GetAllowedValues($aArgs, $sContains);
  1513. }
  1514. public static function GetAllowedValues_flt($sClass, $sFltCode, $aArgs = array(), $sContains = '')
  1515. {
  1516. $oFltDef = self::GetClassFilterDef($sClass, $sFltCode);
  1517. return $oFltDef->GetAllowedValues($aArgs, $sContains);
  1518. }
  1519. public static function GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs = array(), $sContains = '', $iAdditionalValue = null)
  1520. {
  1521. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  1522. return $oAttDef->GetAllowedValuesAsObjectSet($aArgs, $sContains, $iAdditionalValue);
  1523. }
  1524. //
  1525. // Businezz model declaration verbs (should be static)
  1526. //
  1527. public static function RegisterZList($sListCode, $aListInfo)
  1528. {
  1529. // Check mandatory params
  1530. $aMandatParams = array(
  1531. "description" => "detailed (though one line) description of the list",
  1532. "type" => "attributes | filters",
  1533. );
  1534. foreach($aMandatParams as $sParamName=>$sParamDesc)
  1535. {
  1536. if (!array_key_exists($sParamName, $aListInfo))
  1537. {
  1538. throw new CoreException("Declaration of list $sListCode - missing parameter $sParamName");
  1539. }
  1540. }
  1541. self::$m_aListInfos[$sListCode] = $aListInfo;
  1542. }
  1543. public static function RegisterRelation($sRelCode)
  1544. {
  1545. // Each item used to be an array of properties...
  1546. self::$m_aRelationInfos[$sRelCode] = $sRelCode;
  1547. }
  1548. /*
  1549. * Helper to correctly add a magic attribute (called from InitClasses)
  1550. */
  1551. private static function AddMagicAttribute(AttributeDefinition $oAttribute, $sTargetClass, $sOriginClass = null)
  1552. {
  1553. $sCode = $oAttribute->GetCode();
  1554. if (is_null($sOriginClass))
  1555. {
  1556. $sOriginClass = $sTargetClass;
  1557. }
  1558. $oAttribute->SetHostClass($sTargetClass);
  1559. self::$m_aAttribDefs[$sTargetClass][$sCode] = $oAttribute;
  1560. self::$m_aAttribOrigins[$sTargetClass][$sCode] = $sOriginClass;
  1561. $oFlt = new FilterFromAttribute($oAttribute);
  1562. self::$m_aFilterDefs[$sTargetClass][$sCode] = $oFlt;
  1563. self::$m_aFilterOrigins[$sTargetClass][$sCode] = $sOriginClass;
  1564. }
  1565. // Must be called once and only once...
  1566. public static function InitClasses($sTablePrefix)
  1567. {
  1568. if (count(self::GetClasses()) > 0)
  1569. {
  1570. throw new CoreException("InitClasses should not be called more than once -skipped");
  1571. return;
  1572. }
  1573. self::$m_sTablePrefix = $sTablePrefix;
  1574. // Build the list of available extensions
  1575. //
  1576. $aInterfaces = array('iApplicationUIExtension', 'iApplicationObjectExtension', 'iQueryModifier', 'iOnClassInitialization', 'iPopupMenuExtension', 'iPageUIExtension');
  1577. foreach($aInterfaces as $sInterface)
  1578. {
  1579. self::$m_aExtensionClasses[$sInterface] = array();
  1580. }
  1581. foreach(get_declared_classes() as $sPHPClass)
  1582. {
  1583. $oRefClass = new ReflectionClass($sPHPClass);
  1584. $oExtensionInstance = null;
  1585. foreach($aInterfaces as $sInterface)
  1586. {
  1587. if ($oRefClass->implementsInterface($sInterface) && $oRefClass->isInstantiable())
  1588. {
  1589. if (is_null($oExtensionInstance))
  1590. {
  1591. $oExtensionInstance = new $sPHPClass;
  1592. }
  1593. self::$m_aExtensionClasses[$sInterface][$sPHPClass] = $oExtensionInstance;
  1594. }
  1595. }
  1596. }
  1597. // Initialize the classes (declared attributes, etc.)
  1598. //
  1599. foreach(get_declared_classes() as $sPHPClass)
  1600. {
  1601. if (is_subclass_of($sPHPClass, 'DBObject'))
  1602. {
  1603. $sParent = get_parent_class($sPHPClass);
  1604. if (array_key_exists($sParent, self::$m_aIgnoredAttributes))
  1605. {
  1606. // Inherit info about attributes to ignore
  1607. self::$m_aIgnoredAttributes[$sPHPClass] = self::$m_aIgnoredAttributes[$sParent];
  1608. }
  1609. try
  1610. {
  1611. $oMethod = new ReflectionMethod($sPHPClass, 'Init');
  1612. if ($oMethod->getDeclaringClass()->name == $sPHPClass)
  1613. {
  1614. call_user_func(array($sPHPClass, 'Init'));
  1615. // Inherit archive flag
  1616. $bParentArchivable = isset(self::$m_aClassParams[$sParent]['archive']) ? self::$m_aClassParams[$sParent]['archive'] : false;
  1617. $bArchivable = isset(self::$m_aClassParams[$sPHPClass]['archive']) ? self::$m_aClassParams[$sPHPClass]['archive'] : null;
  1618. if (!$bParentArchivable && $bArchivable && !self::IsRootClass($sPHPClass))
  1619. {
  1620. throw new Exception("Archivability must be declared on top of the class hierarchy above $sPHPClass (consistency throughout the whole class tree is a must)");
  1621. }
  1622. if ($bParentArchivable && ($bArchivable === false))
  1623. {
  1624. throw new Exception("$sPHPClass must be archivable (consistency throughout the whole class tree is a must)");
  1625. }
  1626. $bReallyArchivable = $bParentArchivable || $bArchivable;
  1627. self::$m_aClassParams[$sPHPClass]['archive'] = $bReallyArchivable;
  1628. $bArchiveRoot = $bReallyArchivable && !$bParentArchivable;
  1629. self::$m_aClassParams[$sPHPClass]['archive_root'] = $bArchiveRoot;
  1630. if ($bReallyArchivable)
  1631. {
  1632. self::$m_aClassParams[$sPHPClass]['archive_root_class'] = $bArchiveRoot ? $sPHPClass : self::$m_aClassParams[$sParent]['archive_root_class'];
  1633. }
  1634. foreach (MetaModel::EnumPlugins('iOnClassInitialization') as $sPluginClass => $oClassInit)
  1635. {
  1636. $oClassInit->OnAfterClassInitialization($sPHPClass);
  1637. }
  1638. }
  1639. }
  1640. catch (ReflectionException $e)
  1641. {
  1642. // This class is only implementing methods, ignore it from the MetaModel perspective
  1643. }
  1644. }
  1645. }
  1646. // Add a 'class' attribute/filter to the root classes and their children
  1647. //
  1648. foreach(self::EnumRootClasses() as $sRootClass)
  1649. {
  1650. if (self::IsStandaloneClass($sRootClass)) continue;
  1651. $sDbFinalClassField = self::DBGetClassField($sRootClass);
  1652. if (strlen($sDbFinalClassField) == 0)
  1653. {
  1654. $sDbFinalClassField = 'finalclass';
  1655. self::$m_aClassParams[$sRootClass]["db_finalclass_field"] = 'finalclass';
  1656. }
  1657. $oClassAtt = new AttributeFinalClass('finalclass', array(
  1658. "sql"=>$sDbFinalClassField,
  1659. "default_value"=>$sRootClass,
  1660. "is_null_allowed"=>false,
  1661. "depends_on"=>array()
  1662. ));
  1663. self::AddMagicAttribute($oClassAtt, $sRootClass);
  1664. foreach(self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_EXCLUDETOP) as $sChildClass)
  1665. {
  1666. if (array_key_exists('finalclass', self::$m_aAttribDefs[$sChildClass]))
  1667. {
  1668. throw new CoreException("Class $sChildClass, 'finalclass' is a reserved keyword, it cannot be used as an attribute code");
  1669. }
  1670. if (array_key_exists('finalclass', self::$m_aFilterDefs[$sChildClass]))
  1671. {
  1672. throw new CoreException("Class $sChildClass, 'finalclass' is a reserved keyword, it cannot be used as a filter code");
  1673. }
  1674. $oCloned = clone $oClassAtt;
  1675. $oCloned->SetFixedValue($sChildClass);
  1676. self::AddMagicAttribute($oCloned, $sChildClass, $sRootClass);
  1677. }
  1678. }
  1679. // Prepare external fields and filters
  1680. // Add final class to external keys
  1681. //
  1682. foreach (self::GetClasses() as $sClass)
  1683. {
  1684. // Create the friendly name attribute
  1685. $sFriendlyNameAttCode = 'friendlyname';
  1686. $oFriendlyName = new AttributeFriendlyName($sFriendlyNameAttCode, 'id');
  1687. self::AddMagicAttribute($oFriendlyName, $sClass);
  1688. if (self::$m_aClassParams[$sClass]["archive_root"])
  1689. {
  1690. // Create archive attributes on top the archivable hierarchy
  1691. $oArchiveFlag = new AttributeArchiveFlag('archive_flag');
  1692. self::AddMagicAttribute($oArchiveFlag, $sClass);
  1693. $oArchiveDate = new AttributeDate('archive_date', array('magic' => true, "allowed_values"=>null, "sql"=>'archive_date', "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array()));
  1694. self::AddMagicAttribute($oArchiveDate, $sClass);
  1695. }
  1696. elseif (self::$m_aClassParams[$sClass]["archive"])
  1697. {
  1698. $sArchiveRoot = self::$m_aClassParams[$sClass]['archive_root_class'];
  1699. // Inherit archive attributes
  1700. $oArchiveFlag = clone self::$m_aAttribDefs[$sArchiveRoot]['archive_flag'];
  1701. $oArchiveFlag->SetHostClass($sArchiveRoot);
  1702. self::$m_aAttribDefs[$sClass]['archive_flag'] = $oArchiveFlag;
  1703. self::$m_aAttribOrigins[$sClass]['archive_flag'] = $sArchiveRoot;
  1704. $oArchiveDate = clone self::$m_aAttribDefs[$sArchiveRoot]['archive_date'];
  1705. $oArchiveDate->SetHostClass($sArchiveRoot);
  1706. self::$m_aAttribDefs[$sClass]['archive_date'] = $oArchiveDate;
  1707. self::$m_aAttribOrigins[$sClass]['archive_date'] = $sArchiveRoot;
  1708. }
  1709. self::$m_aExtKeyFriends[$sClass] = array();
  1710. foreach (self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
  1711. {
  1712. // Compute the filter codes
  1713. //
  1714. foreach ($oAttDef->GetFilterDefinitions() as $sFilterCode => $oFilterDef)
  1715. {
  1716. self::$m_aFilterDefs[$sClass][$sFilterCode] = $oFilterDef;
  1717. if ($oAttDef->IsExternalField())
  1718. {
  1719. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1720. $oKeyDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  1721. self::$m_aFilterOrigins[$sClass][$sFilterCode] = $oKeyDef->GetTargetClass();
  1722. }
  1723. else
  1724. {
  1725. self::$m_aFilterOrigins[$sClass][$sFilterCode] = self::$m_aAttribOrigins[$sClass][$sAttCode];
  1726. }
  1727. }
  1728. // Compute the fields that will be used to display a pointer to another object
  1729. //
  1730. if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  1731. {
  1732. // oAttDef is either
  1733. // - an external KEY / FIELD (direct),
  1734. // - an external field pointing to an external KEY / FIELD
  1735. // - an external field pointing to an external field pointing to....
  1736. $sRemoteClass = $oAttDef->GetTargetClass();
  1737. if ($oAttDef->IsExternalField())
  1738. {
  1739. // This is a key, but the value comes from elsewhere
  1740. // Create an external field pointing to the remote friendly name attribute
  1741. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1742. $sRemoteAttCode = $oAttDef->GetExtAttCode()."_friendlyname";
  1743. $sFriendlyNameAttCode = $sAttCode.'_friendlyname';
  1744. $oFriendlyName = new AttributeExternalField($sFriendlyNameAttCode, array("allowed_values"=>null, "extkey_attcode"=>$sKeyAttCode, "target_attcode"=>$sRemoteAttCode, "depends_on"=>array()));
  1745. self::AddMagicAttribute($oFriendlyName, $sClass, self::$m_aAttribOrigins[$sClass][$sKeyAttCode]);
  1746. }
  1747. else
  1748. {
  1749. // Create the friendly name attribute
  1750. $sFriendlyNameAttCode = $sAttCode.'_friendlyname';
  1751. $oFriendlyName = new AttributeFriendlyName($sFriendlyNameAttCode, $sAttCode);
  1752. self::AddMagicAttribute($oFriendlyName, $sClass, self::$m_aAttribOrigins[$sClass][$sAttCode]);
  1753. if (self::HasChildrenClasses($sRemoteClass))
  1754. {
  1755. // First, create an external field attribute, that gets the final class
  1756. $sClassRecallAttCode = $sAttCode.'_finalclass_recall';
  1757. $oClassRecall = new AttributeExternalField($sClassRecallAttCode, array(
  1758. "allowed_values"=>null,
  1759. "extkey_attcode"=>$sAttCode,
  1760. "target_attcode"=>"finalclass",
  1761. "is_null_allowed"=>true,
  1762. "depends_on"=>array()
  1763. ));
  1764. self::AddMagicAttribute($oClassRecall, $sClass, self::$m_aAttribOrigins[$sClass][$sAttCode]);
  1765. // Add it to the ZLists where the external key is present
  1766. //foreach(self::$m_aListData[$sClass] as $sListCode => $aAttributes)
  1767. $sListCode = 'list';
  1768. if (isset(self::$m_aListData[$sClass][$sListCode]))
  1769. {
  1770. $aAttributes = self::$m_aListData[$sClass][$sListCode];
  1771. // temporary.... no loop
  1772. {
  1773. if (in_array($sAttCode, $aAttributes))
  1774. {
  1775. $aNewList = array();
  1776. foreach($aAttributes as $iPos => $sAttToDisplay)
  1777. {
  1778. if (is_string($sAttToDisplay) && ($sAttToDisplay == $sAttCode))
  1779. {
  1780. // Insert the final class right before
  1781. $aNewList[] = $sClassRecallAttCode;
  1782. }
  1783. $aNewList[] = $sAttToDisplay;
  1784. }
  1785. self::$m_aListData[$sClass][$sListCode] = $aNewList;
  1786. }
  1787. }
  1788. }
  1789. }
  1790. }
  1791. // Get the real external key attribute
  1792. // It will be our reference to determine the other ext fields related to the same ext key
  1793. $oFinalKeyAttDef = $oAttDef->GetKeyAttDef(EXTKEY_ABSOLUTE);
  1794. self::$m_aExtKeyFriends[$sClass][$sAttCode] = array();
  1795. foreach (self::GetExternalFields($sClass, $oAttDef->GetKeyAttCode($sAttCode)) as $oExtField)
  1796. {
  1797. // skip : those extfields will be processed as external keys
  1798. if ($oExtField->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  1799. // Note: I could not compare the objects by the mean of '==='
  1800. // because they are copied for the inheritance, and the internal references are NOT updated
  1801. if ($oExtField->GetKeyAttDef(EXTKEY_ABSOLUTE) == $oFinalKeyAttDef)
  1802. {
  1803. self::$m_aExtKeyFriends[$sClass][$sAttCode][$oExtField->GetCode()] = $oExtField;
  1804. }
  1805. }
  1806. if (self::IsArchivable($sRemoteClass))
  1807. {
  1808. $sArchiveRemote = $sAttCode.'_archive_flag';
  1809. $oArchiveRemote = new AttributeExternalField($sArchiveRemote, array("allowed_values"=>null, "extkey_attcode"=>$sAttCode, "target_attcode"=>'archive_flag', "depends_on"=>array()));
  1810. self::AddMagicAttribute($oArchiveRemote, $sClass, self::$m_aAttribOrigins[$sClass][$sAttCode]);
  1811. }
  1812. }
  1813. if ($oAttDef instanceof AttributeMetaEnum)
  1814. {
  1815. $aMappingData = $oAttDef->GetMapRule($sClass);
  1816. if ($aMappingData != null)
  1817. {
  1818. $sEnumAttCode = $aMappingData['attcode'];
  1819. self::$m_aEnumToMeta[$sClass][$sEnumAttCode][$sAttCode] = $oAttDef;
  1820. }
  1821. }
  1822. }
  1823. // Add a 'id' filter
  1824. //
  1825. if (array_key_exists('id', self::$m_aAttribDefs[$sClass]))
  1826. {
  1827. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as an attribute code");
  1828. }
  1829. if (array_key_exists('id', self::$m_aFilterDefs[$sClass]))
  1830. {
  1831. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as a filter code");
  1832. }
  1833. $oFilter = new FilterPrivateKey('id', array('id_field' => self::DBGetKey($sClass)));
  1834. self::$m_aFilterDefs[$sClass]['id'] = $oFilter;
  1835. self::$m_aFilterOrigins[$sClass]['id'] = $sClass;
  1836. // Define defaults values for the standard ZLists
  1837. //
  1838. //foreach (self::$m_aListInfos as $sListCode => $aListConfig)
  1839. //{
  1840. // if (!isset(self::$m_aListData[$sClass][$sListCode]))
  1841. // {
  1842. // $aAllAttributes = array_keys(self::$m_aAttribDefs[$sClass]);
  1843. // self::$m_aListData[$sClass][$sListCode] = $aAllAttributes;
  1844. // //echo "<p>$sClass: $sListCode (".count($aAllAttributes)." attributes)</p>\n";
  1845. // }
  1846. //}
  1847. }
  1848. }
  1849. // To be overriden, must be called for any object class (optimization)
  1850. public static function Init()
  1851. {
  1852. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  1853. }
  1854. // To be overloaded by biz model declarations
  1855. public static function GetRelationQueries($sRelCode)
  1856. {
  1857. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  1858. return array();
  1859. }
  1860. public static function Init_Params($aParams)
  1861. {
  1862. // Check mandatory params
  1863. $aMandatParams = array(
  1864. "category" => "group classes by modules defining their visibility in the UI",
  1865. "key_type" => "autoincrement | string",
  1866. "name_attcode" => "define wich attribute is the class name, may be an array of attributes (format specified in the dictionary as 'Class:myclass/Name' => '%1\$s %2\$s...'",
  1867. "state_attcode" => "define wich attribute is representing the state (object lifecycle)",
  1868. "reconc_keys" => "define the attributes that will 'almost uniquely' identify an object in batch processes",
  1869. "db_table" => "database table",
  1870. "db_key_field" => "database field which is the key",
  1871. "db_finalclass_field" => "database field wich is the reference to the actual class of the object, considering that this will be a compound class",
  1872. );
  1873. $sClass = self::GetCallersPHPClass("Init", self::$m_bTraceSourceFiles);
  1874. foreach($aMandatParams as $sParamName=>$sParamDesc)
  1875. {
  1876. if (!array_key_exists($sParamName, $aParams))
  1877. {
  1878. throw new CoreException("Declaration of class $sClass - missing parameter $sParamName");
  1879. }
  1880. }
  1881. $aCategories = explode(',', $aParams['category']);
  1882. foreach ($aCategories as $sCategory)
  1883. {
  1884. self::$m_Category2Class[$sCategory][] = $sClass;
  1885. }
  1886. self::$m_Category2Class[''][] = $sClass; // all categories, include this one
  1887. self::$m_aRootClasses[$sClass] = $sClass; // first, let consider that I am the root... updated on inheritance
  1888. self::$m_aParentClasses[$sClass] = array();
  1889. self::$m_aChildClasses[$sClass] = array();
  1890. self::$m_aClassParams[$sClass]= $aParams;
  1891. self::$m_aAttribDefs[$sClass] = array();
  1892. self::$m_aAttribOrigins[$sClass] = array();
  1893. self::$m_aExtKeyFriends[$sClass] = array();
  1894. self::$m_aFilterDefs[$sClass] = array();
  1895. self::$m_aFilterOrigins[$sClass] = array();
  1896. }
  1897. protected static function object_array_mergeclone($aSource1, $aSource2)
  1898. {
  1899. $aRes = array();
  1900. foreach ($aSource1 as $key=>$object)
  1901. {
  1902. $aRes[$key] = clone $object;
  1903. }
  1904. foreach ($aSource2 as $key=>$object)
  1905. {
  1906. $aRes[$key] = clone $object;
  1907. }
  1908. return $aRes;
  1909. }
  1910. public static function Init_InheritAttributes($sSourceClass = null)
  1911. {
  1912. $sTargetClass = self::GetCallersPHPClass("Init");
  1913. if (empty($sSourceClass))
  1914. {
  1915. // Default: inherit from parent class
  1916. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  1917. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  1918. }
  1919. if (isset(self::$m_aAttribDefs[$sSourceClass]))
  1920. {
  1921. if (!isset(self::$m_aAttribDefs[$sTargetClass]))
  1922. {
  1923. self::$m_aAttribDefs[$sTargetClass] = array();
  1924. self::$m_aAttribOrigins[$sTargetClass] = array();
  1925. }
  1926. self::$m_aAttribDefs[$sTargetClass] = self::object_array_mergeclone(self::$m_aAttribDefs[$sTargetClass], self::$m_aAttribDefs[$sSourceClass]);
  1927. foreach(self::$m_aAttribDefs[$sTargetClass] as $sAttCode => $oAttDef)
  1928. {
  1929. $oAttDef->SetHostClass($sTargetClass);
  1930. }
  1931. self::$m_aAttribOrigins[$sTargetClass] = array_merge(self::$m_aAttribOrigins[$sTargetClass], self::$m_aAttribOrigins[$sSourceClass]);
  1932. }
  1933. // Build root class information
  1934. if (array_key_exists($sSourceClass, self::$m_aRootClasses))
  1935. {
  1936. // Inherit...
  1937. self::$m_aRootClasses[$sTargetClass] = self::$m_aRootClasses[$sSourceClass];
  1938. }
  1939. else
  1940. {
  1941. // This class will be the root class
  1942. self::$m_aRootClasses[$sSourceClass] = $sSourceClass;
  1943. self::$m_aRootClasses[$sTargetClass] = $sSourceClass;
  1944. }
  1945. self::$m_aParentClasses[$sTargetClass] += self::$m_aParentClasses[$sSourceClass];
  1946. self::$m_aParentClasses[$sTargetClass][] = $sSourceClass;
  1947. // I am the child of each and every parent...
  1948. foreach(self::$m_aParentClasses[$sTargetClass] as $sAncestorClass)
  1949. {
  1950. self::$m_aChildClasses[$sAncestorClass][] = $sTargetClass;
  1951. }
  1952. }
  1953. protected static function Init_IsKnownClass($sClass)
  1954. {
  1955. // Differs from self::IsValidClass()
  1956. // because it is being called before all the classes have been initialized
  1957. if (!class_exists($sClass)) return false;
  1958. if (!is_subclass_of($sClass, 'DBObject')) return false;
  1959. return true;
  1960. }
  1961. public static function Init_AddAttribute(AttributeDefinition $oAtt, $sTargetClass = null)
  1962. {
  1963. if (!$sTargetClass)
  1964. {
  1965. $sTargetClass = self::GetCallersPHPClass("Init");
  1966. }
  1967. $sAttCode = $oAtt->GetCode();
  1968. if ($sAttCode == 'finalclass')
  1969. {
  1970. throw new Exception("Declaration of $sTargetClass: using the reserved keyword '$sAttCode' in attribute declaration");
  1971. }
  1972. if ($sAttCode == 'friendlyname')
  1973. {
  1974. throw new Exception("Declaration of $sTargetClass: using the reserved keyword '$sAttCode' in attribute declaration");
  1975. }
  1976. if (array_key_exists($sAttCode, self::$m_aAttribDefs[$sTargetClass]))
  1977. {
  1978. throw new Exception("Declaration of $sTargetClass: attempting to redeclare the inherited attribute '$sAttCode', originaly declared in ".self::$m_aAttribOrigins[$sTargetClass][$sAttCode]);
  1979. }
  1980. // Set the "host class" as soon as possible, since HierarchicalKeys use it for their 'target class' as well
  1981. // and this needs to be know early (for Init_IsKnowClass 19 lines below)
  1982. $oAtt->SetHostClass($sTargetClass);
  1983. // Some attributes could refer to a class
  1984. // declared in a module which is currently not installed/active
  1985. // We simply discard those attributes
  1986. //
  1987. if ($oAtt->IsLinkSet())
  1988. {
  1989. $sRemoteClass = $oAtt->GetLinkedClass();
  1990. if (!self::Init_IsKnownClass($sRemoteClass))
  1991. {
  1992. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
  1993. return;
  1994. }
  1995. }
  1996. elseif($oAtt->IsExternalKey())
  1997. {
  1998. $sRemoteClass = $oAtt->GetTargetClass();
  1999. if (!self::Init_IsKnownClass($sRemoteClass))
  2000. {
  2001. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
  2002. return;
  2003. }
  2004. }
  2005. elseif($oAtt->IsExternalField())
  2006. {
  2007. $sExtKeyAttCode = $oAtt->GetKeyAttCode();
  2008. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode]))
  2009. {
  2010. // The corresponding external key has already been ignored
  2011. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode];
  2012. return;
  2013. }
  2014. // #@# todo - Check if the target attribute is still there
  2015. // this is not simple to implement because is involves
  2016. // several passes (the load order has a significant influence on that)
  2017. }
  2018. self::$m_aAttribDefs[$sTargetClass][$oAtt->GetCode()] = $oAtt;
  2019. self::$m_aAttribOrigins[$sTargetClass][$oAtt->GetCode()] = $sTargetClass;
  2020. // Note: it looks redundant to put targetclass there, but a mix occurs when inheritance is used
  2021. }
  2022. public static function Init_SetZListItems($sListCode, $aItems, $sTargetClass = null)
  2023. {
  2024. MyHelpers::CheckKeyInArray('list code', $sListCode, self::$m_aListInfos);
  2025. if (!$sTargetClass)
  2026. {
  2027. $sTargetClass = self::GetCallersPHPClass("Init");
  2028. }
  2029. // Discard attributes that do not make sense
  2030. // (missing classes in the current module combination, resulting in irrelevant ext key or link set)
  2031. //
  2032. self::Init_CheckZListItems($aItems, $sTargetClass);
  2033. self::$m_aListData[$sTargetClass][$sListCode] = $aItems;
  2034. }
  2035. protected static function Init_CheckZListItems(&$aItems, $sTargetClass)
  2036. {
  2037. foreach($aItems as $iFoo => $attCode)
  2038. {
  2039. if (is_array($attCode))
  2040. {
  2041. // Note: to make sure that the values will be updated recursively,
  2042. // do not pass $attCode, but $aItems[$iFoo] instead
  2043. self::Init_CheckZListItems($aItems[$iFoo], $sTargetClass);
  2044. if (count($aItems[$iFoo]) == 0)
  2045. {
  2046. unset($aItems[$iFoo]);
  2047. }
  2048. }
  2049. else if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$attCode]))
  2050. {
  2051. unset($aItems[$iFoo]);
  2052. }
  2053. }
  2054. }
  2055. public static function FlattenZList($aList)
  2056. {
  2057. $aResult = array();
  2058. foreach($aList as $value)
  2059. {
  2060. if (!is_array($value))
  2061. {
  2062. $aResult[] = $value;
  2063. }
  2064. else
  2065. {
  2066. $aResult = array_merge($aResult, self::FlattenZList($value));
  2067. }
  2068. }
  2069. return $aResult;
  2070. }
  2071. public static function Init_DefineState($sStateCode, $aStateDef)
  2072. {
  2073. $sTargetClass = self::GetCallersPHPClass("Init");
  2074. if (is_null($aStateDef['attribute_list'])) $aStateDef['attribute_list'] = array();
  2075. $sParentState = $aStateDef['attribute_inherit'];
  2076. if (!empty($sParentState))
  2077. {
  2078. // Inherit from the given state (must be defined !)
  2079. //
  2080. $aToInherit = self::$m_aStates[$sTargetClass][$sParentState];
  2081. // Reset the constraint when it was mandatory to set the value at the previous state
  2082. //
  2083. foreach ($aToInherit['attribute_list'] as $sState => $iFlags)
  2084. {
  2085. $iFlags = $iFlags & ~OPT_ATT_MUSTPROMPT;
  2086. $iFlags = $iFlags & ~OPT_ATT_MUSTCHANGE;
  2087. $aToInherit['attribute_list'][$sState] = $iFlags;
  2088. }
  2089. // The inherited configuration could be overriden
  2090. $aStateDef['attribute_list'] = array_merge($aToInherit['attribute_list'], $aStateDef['attribute_list']);
  2091. }
  2092. foreach($aStateDef['attribute_list'] as $sAttCode => $iFlags)
  2093. {
  2094. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sAttCode]))
  2095. {
  2096. unset($aStateDef['attribute_list'][$sAttCode]);
  2097. }
  2098. }
  2099. self::$m_aStates[$sTargetClass][$sStateCode] = $aStateDef;
  2100. // by default, create an empty set of transitions associated to that state
  2101. self::$m_aTransitions[$sTargetClass][$sStateCode] = array();
  2102. }
  2103. public static function Init_DefineHighlightScale($aHighlightScale)
  2104. {
  2105. $sTargetClass = self::GetCallersPHPClass("Init");
  2106. self::$m_aHighlightScales[$sTargetClass] = $aHighlightScale;
  2107. }
  2108. public static function GetHighlightScale($sTargetClass)
  2109. {
  2110. $aScale = array();
  2111. $aParentScale = array();
  2112. $sParentClass = self::GetParentPersistentClass($sTargetClass);
  2113. if (!empty($sParentClass))
  2114. {
  2115. // inherit the scale from the parent class
  2116. $aParentScale = self::GetHighlightScale($sParentClass);
  2117. }
  2118. if (array_key_exists($sTargetClass, self::$m_aHighlightScales))
  2119. {
  2120. $aScale = self::$m_aHighlightScales[$sTargetClass];
  2121. }
  2122. return array_merge($aParentScale, $aScale); // Merge both arrays, the values from the last one have precedence
  2123. }
  2124. public static function GetHighlightCode($sTargetClass, $sStateCode)
  2125. {
  2126. $sCode = '';
  2127. if ( array_key_exists($sTargetClass, self::$m_aStates)
  2128. && array_key_exists($sStateCode, self::$m_aStates[$sTargetClass])
  2129. && array_key_exists('highlight', self::$m_aStates[$sTargetClass][$sStateCode]) )
  2130. {
  2131. $sCode = self::$m_aStates[$sTargetClass][$sStateCode]['highlight']['code'];
  2132. }
  2133. else
  2134. {
  2135. // Check the parent's definition
  2136. $sParentClass = self::GetParentPersistentClass($sTargetClass);
  2137. if (!empty($sParentClass))
  2138. {
  2139. $sCode = self::GetHighlightCode($sParentClass, $sStateCode);
  2140. }
  2141. }
  2142. return $sCode;
  2143. }
  2144. public static function Init_OverloadStateAttribute($sStateCode, $sAttCode, $iFlags)
  2145. {
  2146. // Warning: this is not sufficient: the flags have to be copied to the states that are inheriting from this state
  2147. $sTargetClass = self::GetCallersPHPClass("Init");
  2148. self::$m_aStates[$sTargetClass][$sStateCode]['attribute_list'][$sAttCode] = $iFlags;
  2149. }
  2150. public static function Init_DefineStimulus($oStimulus)
  2151. {
  2152. $sTargetClass = self::GetCallersPHPClass("Init");
  2153. self::$m_aStimuli[$sTargetClass][$oStimulus->GetCode()] = $oStimulus;
  2154. // I wanted to simplify the syntax of the declaration of objects in the biz model
  2155. // Therefore, the reference to the host class is set there
  2156. $oStimulus->SetHostClass($sTargetClass);
  2157. }
  2158. public static function Init_DefineTransition($sStateCode, $sStimulusCode, $aTransitionDef)
  2159. {
  2160. $sTargetClass = self::GetCallersPHPClass("Init");
  2161. if (is_null($aTransitionDef['actions'])) $aTransitionDef['actions'] = array();
  2162. self::$m_aTransitions[$sTargetClass][$sStateCode][$sStimulusCode] = $aTransitionDef;
  2163. }
  2164. public static function Init_InheritLifecycle($sSourceClass = '')
  2165. {
  2166. $sTargetClass = self::GetCallersPHPClass("Init");
  2167. if (empty($sSourceClass))
  2168. {
  2169. // Default: inherit from parent class
  2170. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  2171. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  2172. }
  2173. self::$m_aClassParams[$sTargetClass]["state_attcode"] = self::$m_aClassParams[$sSourceClass]["state_attcode"];
  2174. self::$m_aStates[$sTargetClass] = self::$m_aStates[$sSourceClass];
  2175. // #@# Note: the aim is to clone the data, could be an issue if the simuli objects are changed
  2176. self::$m_aStimuli[$sTargetClass] = self::$m_aStimuli[$sSourceClass];
  2177. self::$m_aTransitions[$sTargetClass] = self::$m_aTransitions[$sSourceClass];
  2178. }
  2179. //
  2180. // Static API
  2181. //
  2182. public static function GetRootClass($sClass = null)
  2183. {
  2184. self::_check_subclass($sClass);
  2185. return self::$m_aRootClasses[$sClass];
  2186. }
  2187. public static function IsRootClass($sClass)
  2188. {
  2189. self::_check_subclass($sClass);
  2190. return (self::GetRootClass($sClass) == $sClass);
  2191. }
  2192. public static function GetParentClass($sClass)
  2193. {
  2194. if (count(self::$m_aParentClasses[$sClass]) == 0)
  2195. {
  2196. return null;
  2197. }
  2198. else
  2199. {
  2200. return end(self::$m_aParentClasses[$sClass]);
  2201. }
  2202. }
  2203. public static function GetLowestCommonAncestor($aClasses)
  2204. {
  2205. $sAncestor = null;
  2206. foreach($aClasses as $sClass)
  2207. {
  2208. if (is_null($sAncestor))
  2209. {
  2210. // first loop
  2211. $sAncestor = $sClass;
  2212. }
  2213. elseif ($sClass == $sAncestor)
  2214. {
  2215. // remains the same
  2216. }
  2217. elseif (self::GetRootClass($sClass) != self::GetRootClass($sAncestor))
  2218. {
  2219. $sAncestor = null;
  2220. break;
  2221. }
  2222. else
  2223. {
  2224. $sAncestor = self::LowestCommonAncestor($sAncestor, $sClass);
  2225. }
  2226. }
  2227. return $sAncestor;
  2228. }
  2229. /**
  2230. * Note: assumes that class A and B have a common ancestor
  2231. */
  2232. protected static function LowestCommonAncestor($sClassA, $sClassB)
  2233. {
  2234. if ($sClassA == $sClassB)
  2235. {
  2236. $sRet = $sClassA;
  2237. }
  2238. elseif (is_subclass_of($sClassA, $sClassB))
  2239. {
  2240. $sRet = $sClassB;
  2241. }
  2242. elseif (is_subclass_of($sClassB, $sClassA))
  2243. {
  2244. $sRet = $sClassA;
  2245. }
  2246. else
  2247. {
  2248. // Recurse
  2249. $sRet = self::LowestCommonAncestor($sClassA, self::GetParentClass($sClassB));
  2250. }
  2251. return $sRet;
  2252. }
  2253. /**
  2254. * Tells if a class contains a hierarchical key, and if so what is its AttCode
  2255. * @return mixed String = sAttCode or false if the class is not part of a hierarchy
  2256. */
  2257. public static function IsHierarchicalClass($sClass)
  2258. {
  2259. $sHierarchicalKeyCode = false;
  2260. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  2261. {
  2262. if ($oAtt->IsHierarchicalKey())
  2263. {
  2264. $sHierarchicalKeyCode = $sAttCode; // Found the hierarchical key, no need to continue
  2265. break;
  2266. }
  2267. }
  2268. return $sHierarchicalKeyCode;
  2269. }
  2270. public static function EnumRootClasses()
  2271. {
  2272. return array_unique(self::$m_aRootClasses);
  2273. }
  2274. public static function EnumParentClasses($sClass, $iOption = ENUM_PARENT_CLASSES_EXCLUDELEAF, $bRootFirst = true)
  2275. {
  2276. self::_check_subclass($sClass);
  2277. if ($bRootFirst)
  2278. {
  2279. $aRes = self::$m_aParentClasses[$sClass];
  2280. }
  2281. else
  2282. {
  2283. $aRes = array_reverse(self::$m_aParentClasses[$sClass], true);
  2284. }
  2285. if ($iOption != ENUM_PARENT_CLASSES_EXCLUDELEAF)
  2286. {
  2287. if ($bRootFirst)
  2288. {
  2289. // Leaf class at the end
  2290. $aRes[] = $sClass;
  2291. }
  2292. else
  2293. {
  2294. // Leaf class on top
  2295. array_unshift($aRes, $sClass);
  2296. }
  2297. }
  2298. return $aRes;
  2299. }
  2300. public static function EnumChildClasses($sClass, $iOption = ENUM_CHILD_CLASSES_EXCLUDETOP)
  2301. {
  2302. self::_check_subclass($sClass);
  2303. $aRes = self::$m_aChildClasses[$sClass];
  2304. if ($iOption != ENUM_CHILD_CLASSES_EXCLUDETOP)
  2305. {
  2306. // Add it to the list
  2307. $aRes[] = $sClass;
  2308. }
  2309. return $aRes;
  2310. }
  2311. public static function EnumArchivableClasses()
  2312. {
  2313. $aRes = array();
  2314. foreach (self::GetClasses() as $sClass)
  2315. {
  2316. if (self::IsArchivable($sClass))
  2317. {
  2318. $aRes[] = $sClass;
  2319. }
  2320. }
  2321. return $aRes;
  2322. }
  2323. public static function HasChildrenClasses($sClass)
  2324. {
  2325. return (count(self::$m_aChildClasses[$sClass]) > 0);
  2326. }
  2327. public static function EnumCategories()
  2328. {
  2329. return array_keys(self::$m_Category2Class);
  2330. }
  2331. // Note: use EnumChildClasses to take the compound objects into account
  2332. public static function GetSubclasses($sClass)
  2333. {
  2334. self::_check_subclass($sClass);
  2335. $aSubClasses = array();
  2336. foreach(self::$m_aClassParams as $sSubClass => $foo)
  2337. {
  2338. if (is_subclass_of($sSubClass, $sClass))
  2339. {
  2340. $aSubClasses[] = $sSubClass;
  2341. }
  2342. }
  2343. return $aSubClasses;
  2344. }
  2345. public static function GetClasses($sCategories = '', $bStrict = false)
  2346. {
  2347. $aCategories = explode(',', $sCategories);
  2348. $aClasses = array();
  2349. foreach($aCategories as $sCategory)
  2350. {
  2351. $sCategory = trim($sCategory);
  2352. if (strlen($sCategory) == 0)
  2353. {
  2354. return array_keys(self::$m_aClassParams);
  2355. }
  2356. if (array_key_exists($sCategory, self::$m_Category2Class))
  2357. {
  2358. $aClasses = array_merge($aClasses, self::$m_Category2Class[$sCategory]);
  2359. }
  2360. elseif ($bStrict)
  2361. {
  2362. throw new CoreException("unkown class category '$sCategory', expecting a value in {".implode(', ', array_keys(self::$m_Category2Class))."}");
  2363. }
  2364. }
  2365. return array_unique($aClasses);
  2366. }
  2367. public static function HasTable($sClass)
  2368. {
  2369. if (strlen(self::DBGetTable($sClass)) == 0) return false;
  2370. return true;
  2371. }
  2372. public static function IsAbstract($sClass)
  2373. {
  2374. $oReflection = new ReflectionClass($sClass);
  2375. return $oReflection->isAbstract();
  2376. }
  2377. /**
  2378. * Normalizes query arguments and adds magic parameters:
  2379. * - current_contact_id
  2380. * - current_contact (DBObject)
  2381. * - current_user (DBObject)
  2382. *
  2383. * @param array $aArgs Context arguments (some can be persistent objects)
  2384. * @param array $aMoreArgs Other query parameters
  2385. * @return array
  2386. */
  2387. public static function PrepareQueryArguments($aArgs, $aMoreArgs = array())
  2388. {
  2389. $aScalarArgs = array();
  2390. foreach(array_merge($aArgs, $aMoreArgs) as $sArgName => $value)
  2391. {
  2392. if (self::IsValidObject($value))
  2393. {
  2394. if (strpos($sArgName, '->object()') === false)
  2395. {
  2396. // Normalize object arguments
  2397. $aScalarArgs[$sArgName.'->object()'] = $value;
  2398. }
  2399. else
  2400. {
  2401. // Leave as is
  2402. $aScalarArgs[$sArgName] = $value;
  2403. }
  2404. }
  2405. else
  2406. {
  2407. if (is_scalar($value))
  2408. {
  2409. $aScalarArgs[$sArgName] = (string) $value;
  2410. }
  2411. elseif (is_null($value))
  2412. {
  2413. $aScalarArgs[$sArgName] = null;
  2414. }
  2415. elseif (is_array($value))
  2416. {
  2417. $aScalarArgs[$sArgName] = $value;
  2418. }
  2419. }
  2420. }
  2421. // Add standard magic arguments
  2422. //
  2423. $aScalarArgs['current_contact_id'] = UserRights::GetContactId(); // legacy
  2424. $oUser = UserRights::GetUserObject();
  2425. if (!is_null($oUser))
  2426. {
  2427. $aScalarArgs['current_user->object()'] = $oUser;
  2428. $oContact = UserRights::GetContactObject();
  2429. if (!is_null($oContact))
  2430. {
  2431. $aScalarArgs['current_contact->object()'] = $oContact;
  2432. }
  2433. }
  2434. return $aScalarArgs;
  2435. }
  2436. public static function MakeModifierProperties($oFilter)
  2437. {
  2438. // Compute query modifiers properties (can be set in the search itself, by the context, etc.)
  2439. //
  2440. $aModifierProperties = array();
  2441. foreach (MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier)
  2442. {
  2443. // Lowest precedence: the application context
  2444. $aPluginProps = ApplicationContext::GetPluginProperties($sPluginClass);
  2445. // Highest precedence: programmatically specified (or OQL)
  2446. foreach($oFilter->GetModifierProperties($sPluginClass) as $sProp => $value)
  2447. {
  2448. $aPluginProps[$sProp] = $value;
  2449. }
  2450. if (count($aPluginProps) > 0)
  2451. {
  2452. $aModifierProperties[$sPluginClass] = $aPluginProps;
  2453. }
  2454. }
  2455. return $aModifierProperties;
  2456. }
  2457. /**
  2458. * Special processing for the hierarchical keys stored as nested sets
  2459. * @param $iId integer The identifier of the parent
  2460. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  2461. * @param $stable string The name of the database table containing the hierarchical key
  2462. */
  2463. public static function HKInsertChildUnder($iId, $oAttDef, $sTable)
  2464. {
  2465. // Get the parent id.right value
  2466. if ($iId == 0)
  2467. {
  2468. // No parent, insert completely at the right of the tree
  2469. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  2470. $aRes = CMDBSource::QueryToArray($sSQL);
  2471. if (count($aRes) == 0)
  2472. {
  2473. $iMyRight = 1;
  2474. }
  2475. else
  2476. {
  2477. $iMyRight = $aRes[0]['max']+1;
  2478. }
  2479. }
  2480. else
  2481. {
  2482. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` FROM `$sTable` WHERE id=".$iId;
  2483. $iMyRight = CMDBSource::QueryToScalar($sSQL);
  2484. $sSQLUpdateRight = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` + 2 WHERE `".$oAttDef->GetSQLRight()."` >= $iMyRight";
  2485. CMDBSource::Query($sSQLUpdateRight);
  2486. $sSQLUpdateLeft = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` + 2 WHERE `".$oAttDef->GetSQLLeft()."` > $iMyRight";
  2487. CMDBSource::Query($sSQLUpdateLeft);
  2488. }
  2489. return array($oAttDef->GetSQLRight() => $iMyRight+1, $oAttDef->GetSQLLeft() => $iMyRight);
  2490. }
  2491. /**
  2492. * Special processing for the hierarchical keys stored as nested sets: temporary remove the branch
  2493. * @param $iId integer The identifier of the parent
  2494. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  2495. * @param $sTable string The name of the database table containing the hierarchical key
  2496. */
  2497. public static function HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable)
  2498. {
  2499. $iDelta = $iMyRight - $iMyLeft + 1;
  2500. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = $iMyLeft - `".$oAttDef->GetSQLRight()."`, `".$oAttDef->GetSQLLeft()."` = $iMyLeft - `".$oAttDef->GetSQLLeft();
  2501. $sSQL .= "` WHERE `".$oAttDef->GetSQLLeft()."`> $iMyLeft AND `".$oAttDef->GetSQLRight()."`< $iMyRight";
  2502. CMDBSource::Query($sSQL);
  2503. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` - $iDelta WHERE `".$oAttDef->GetSQLLeft()."` > $iMyRight";
  2504. CMDBSource::Query($sSQL);
  2505. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` - $iDelta WHERE `".$oAttDef->GetSQLRight()."` > $iMyRight";
  2506. CMDBSource::Query($sSQL);
  2507. }
  2508. /**
  2509. * Special processing for the hierarchical keys stored as nested sets: replug the temporary removed branch
  2510. * @param $iId integer The identifier of the parent
  2511. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  2512. * @param $sTable string The name of the database table containing the hierarchical key
  2513. */
  2514. public static function HKReplugBranch($iNewLeft, $iNewRight, $oAttDef, $sTable)
  2515. {
  2516. $iDelta = $iNewRight - $iNewLeft + 1;
  2517. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` + $iDelta WHERE `".$oAttDef->GetSQLLeft()."` > $iNewLeft";
  2518. CMDBSource::Query($sSQL);
  2519. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` + $iDelta WHERE `".$oAttDef->GetSQLRight()."` >= $iNewLeft";
  2520. CMDBSource::Query($sSQL);
  2521. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = $iNewLeft - `".$oAttDef->GetSQLRight()."`, `".$oAttDef->GetSQLLeft()."` = $iNewLeft - `".$oAttDef->GetSQLLeft()."` WHERE `".$oAttDef->GetSQLRight()."`< 0";
  2522. CMDBSource::Query($sSQL);
  2523. }
  2524. /**
  2525. * Check (and updates if needed) the hierarchical keys
  2526. * @param $bDiagnosticsOnly boolean If true only a diagnostic pass will be run, returning true or false
  2527. * @param $bVerbose boolean Displays some information about what is done/what needs to be done
  2528. * @param $bForceComputation boolean If true, the _left and _right parameters will be recomputed even if some values already exist in the DB
  2529. */
  2530. public static function CheckHKeys($bDiagnosticsOnly = false, $bVerbose = false, $bForceComputation = false)
  2531. {
  2532. $bChangeNeeded = false;
  2533. foreach (self::GetClasses() as $sClass)
  2534. {
  2535. if (!self::HasTable($sClass)) continue;
  2536. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2537. {
  2538. // Check (once) all the attributes that are hierarchical keys
  2539. if((self::GetAttributeOrigin($sClass, $sAttCode) == $sClass) && $oAttDef->IsHierarchicalKey())
  2540. {
  2541. if ($bVerbose)
  2542. {
  2543. echo "The attribute $sAttCode from $sClass is a hierarchical key.\n";
  2544. }
  2545. $bResult = self::HKInit($sClass, $sAttCode, $bDiagnosticsOnly, $bVerbose, $bForceComputation);
  2546. $bChangeNeeded |= $bResult;
  2547. if ($bVerbose && !$bResult)
  2548. {
  2549. echo "Ok, the attribute $sAttCode from class $sClass seems up to date.\n";
  2550. }
  2551. }
  2552. }
  2553. }
  2554. return $bChangeNeeded;
  2555. }
  2556. /**
  2557. * Initializes (i.e converts) a hierarchy stored using a 'parent_id' external key
  2558. * into a hierarchy stored with a HierarchicalKey, by initializing the _left and _right values
  2559. * to correspond to the existing hierarchy in the database
  2560. * @param $sClass string Name of the class to process
  2561. * @param $sAttCode string Code of the attribute to process
  2562. * @param $bDiagnosticsOnly boolean If true only a diagnostic pass will be run, returning true or false
  2563. * @param $bVerbose boolean Displays some information about what is done/what needs to be done
  2564. * @param $bForceComputation boolean If true, the _left and _right parameters will be recomputed even if some values already exist in the DB
  2565. * @return true if an update is needed (diagnostics only) / was performed
  2566. */
  2567. public static function HKInit($sClass, $sAttCode, $bDiagnosticsOnly = false, $bVerbose = false, $bForceComputation = false)
  2568. {
  2569. $idx = 1;
  2570. $bUpdateNeeded = $bForceComputation;
  2571. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  2572. $sTable = self::DBGetTable($sClass, $sAttCode);
  2573. if ($oAttDef->IsHierarchicalKey())
  2574. {
  2575. // Check if some values already exist in the table for the _right value, if so, do nothing
  2576. $sRight = $oAttDef->GetSQLRight();
  2577. $sSQL = "SELECT MAX(`$sRight`) AS MaxRight FROM `$sTable`";
  2578. $iMaxRight = CMDBSource::QueryToScalar($sSQL);
  2579. $sSQL = "SELECT COUNT(*) AS Count FROM `$sTable`"; // Note: COUNT(field) returns zero if the given field contains only NULLs
  2580. $iCount = CMDBSource::QueryToScalar($sSQL);
  2581. if (!$bForceComputation && ($iCount != 0) && ($iMaxRight == 0))
  2582. {
  2583. $bUpdateNeeded = true;
  2584. if ($bVerbose)
  2585. {
  2586. echo "The table '$sTable' must be updated to compute the fields $sRight and ".$oAttDef->GetSQLLeft()."\n";
  2587. }
  2588. }
  2589. if ($bForceComputation && !$bDiagnosticsOnly)
  2590. {
  2591. echo "Rebuilding the fields $sRight and ".$oAttDef->GetSQLLeft()." from table '$sTable'...\n";
  2592. }
  2593. if ($bUpdateNeeded && !$bDiagnosticsOnly)
  2594. {
  2595. try
  2596. {
  2597. CMDBSource::Query('START TRANSACTION');
  2598. self::HKInitChildren($sTable, $sAttCode, $oAttDef, 0, $idx);
  2599. CMDBSource::Query('COMMIT');
  2600. if ($bVerbose)
  2601. {
  2602. echo "Ok, table '$sTable' successfully updated.\n";
  2603. }
  2604. }
  2605. catch(Exception $e)
  2606. {
  2607. CMDBSource::Query('ROLLBACK');
  2608. throw new Exception("An error occured (".$e->getMessage().") while initializing the hierarchy for ($sClass, $sAttCode). The database was not modified.");
  2609. }
  2610. }
  2611. }
  2612. return $bUpdateNeeded;
  2613. }
  2614. /**
  2615. * Recursive helper function called by HKInit
  2616. */
  2617. protected static function HKInitChildren($sTable, $sAttCode, $oAttDef, $iId, &$iCurrIndex)
  2618. {
  2619. $sSQL = "SELECT id FROM `$sTable` WHERE `$sAttCode` = $iId";
  2620. $aRes = CMDBSource::QueryToArray($sSQL);
  2621. $aTree = array();
  2622. $sLeft = $oAttDef->GetSQLLeft();
  2623. $sRight = $oAttDef->GetSQLRight();
  2624. foreach($aRes as $aValues)
  2625. {
  2626. $iChildId = $aValues['id'];
  2627. $iLeft = $iCurrIndex++;
  2628. $aChildren = self::HKInitChildren($sTable, $sAttCode, $oAttDef, $iChildId, $iCurrIndex);
  2629. $iRight = $iCurrIndex++;
  2630. $sSQL = "UPDATE `$sTable` SET `$sLeft` = $iLeft, `$sRight` = $iRight WHERE id= $iChildId";
  2631. CMDBSource::Query($sSQL);
  2632. }
  2633. }
  2634. /**
  2635. * Update the meta enums
  2636. * See Also AttributeMetaEnum::MapValue that must be aligned with the above implementation
  2637. *
  2638. * @param $bVerbose boolean Displays some information about what is done/what needs to be done
  2639. */
  2640. public static function RebuildMetaEnums($bVerbose = false)
  2641. {
  2642. foreach (self::GetClasses() as $sClass)
  2643. {
  2644. if (!self::HasTable($sClass)) continue;
  2645. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2646. {
  2647. // Check (once) all the attributes that are hierarchical keys
  2648. if((self::GetAttributeOrigin($sClass, $sAttCode) == $sClass) && $oAttDef instanceof AttributeEnum)
  2649. {
  2650. if (isset(self::$m_aEnumToMeta[$sClass][$sAttCode]))
  2651. {
  2652. foreach (self::$m_aEnumToMeta[$sClass][$sAttCode] as $sMetaAttCode => $oMetaAttDef)
  2653. {
  2654. $aMetaValues = array(); // array of (metavalue => array of values)
  2655. foreach ($oAttDef->GetAllowedValues() as $sCode => $sLabel)
  2656. {
  2657. $aMappingData = $oMetaAttDef->GetMapRule($sClass);
  2658. if ($aMappingData == null)
  2659. {
  2660. $sMetaValue = $oMetaAttDef->GetDefaultValue();
  2661. }
  2662. else
  2663. {
  2664. if (array_key_exists($sCode, $aMappingData['values']))
  2665. {
  2666. $sMetaValue = $aMappingData['values'][$sCode];
  2667. }
  2668. elseif ($oMetaAttDef->GetDefaultValue() != '')
  2669. {
  2670. $sMetaValue = $oMetaAttDef->GetDefaultValue();
  2671. }
  2672. else
  2673. {
  2674. throw new Exception('MetaModel::RebuildMetaEnums(): mapping not found for value "'.$sCode.'"" in '.$sClass.', on attribute '.self::GetAttributeOrigin($sClass, $oMetaAttDef->GetCode()).'::'.$oMetaAttDef->GetCode());
  2675. }
  2676. }
  2677. $aMetaValues[$sMetaValue][] = $sCode;
  2678. }
  2679. foreach ($aMetaValues as $sMetaValue => $aEnumValues)
  2680. {
  2681. $sMetaTable = self::DBGetTable($sClass, $sMetaAttCode);
  2682. $sEnumTable = self::DBGetTable($sClass);
  2683. $aColumns = array_keys($oMetaAttDef->GetSQLColumns());
  2684. $sMetaColumn = reset($aColumns);
  2685. $aColumns = array_keys($oAttDef->GetSQLColumns());
  2686. $sEnumColumn = reset($aColumns);
  2687. $sValueList = implode(', ', CMDBSource::Quote($aEnumValues));
  2688. $sSql = "UPDATE `$sMetaTable` JOIN `$sEnumTable` ON `$sEnumTable`.id = `$sMetaTable`.id SET `$sMetaTable`.`$sMetaColumn` = '$sMetaValue' WHERE `$sEnumTable`.`$sEnumColumn` IN ($sValueList) AND `$sMetaTable`.`$sMetaColumn` != '$sMetaValue'";
  2689. if ($bVerbose)
  2690. {
  2691. echo "Executing query: $sSql\n";
  2692. }
  2693. CMDBSource::Query($sSql);
  2694. }
  2695. }
  2696. }
  2697. }
  2698. }
  2699. }
  2700. }
  2701. public static function CheckDataSources($bDiagnostics, $bVerbose)
  2702. {
  2703. $sOQL = 'SELECT SynchroDataSource';
  2704. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
  2705. $bFixNeeded = false;
  2706. if ($bVerbose && $oSet->Count() == 0)
  2707. {
  2708. echo "There are no Data Sources in the database.\n";
  2709. }
  2710. while($oSource = $oSet->Fetch())
  2711. {
  2712. if ($bVerbose)
  2713. {
  2714. echo "Checking Data Source '".$oSource->GetName()."'...\n";
  2715. $bFixNeeded = $bFixNeeded | $oSource->CheckDBConsistency($bDiagnostics, $bVerbose);
  2716. }
  2717. }
  2718. if (!$bFixNeeded && $bVerbose)
  2719. {
  2720. echo "Ok.\n";
  2721. }
  2722. return $bFixNeeded;
  2723. }
  2724. public static function GenerateUniqueAlias(&$aAliases, $sNewName, $sRealName)
  2725. {
  2726. if (!array_key_exists($sNewName, $aAliases))
  2727. {
  2728. $aAliases[$sNewName] = $sRealName;
  2729. return $sNewName;
  2730. }
  2731. for ($i = 1 ; $i < 100 ; $i++)
  2732. {
  2733. $sAnAlias = $sNewName.$i;
  2734. if (!array_key_exists($sAnAlias, $aAliases))
  2735. {
  2736. // Create that new alias
  2737. $aAliases[$sAnAlias] = $sRealName;
  2738. return $sAnAlias;
  2739. }
  2740. }
  2741. throw new CoreException('Failed to create an alias', array('aliases' => $aAliases, 'new'=>$sNewName));
  2742. }
  2743. public static function CheckDefinitions($bExitOnError = true)
  2744. {
  2745. if (count(self::GetClasses()) == 0)
  2746. {
  2747. throw new CoreException("MetaModel::InitClasses() has not been called, or no class has been declared ?!?!");
  2748. }
  2749. $aErrors = array();
  2750. $aSugFix = array();
  2751. foreach (self::GetClasses() as $sClass)
  2752. {
  2753. $sTable = self::DBGetTable($sClass);
  2754. $sTableLowercase = strtolower($sTable);
  2755. if ($sTableLowercase != $sTable)
  2756. {
  2757. $aErrors[$sClass][] = "Table name '".$sTable."' has upper case characters. You might encounter issues when moving your installation between Linux and Windows.";
  2758. $aSugFix[$sClass][] = "Use '$sTableLowercase' instead. Step 1: If already installed, then rename manually in the DB: RENAME TABLE `$sTable` TO `{$sTableLowercase}_tempname`, `{$sTableLowercase}_tempname` TO `$sTableLowercase`; Step 2: Rename the table in the datamodel and compile the application. Note: the MySQL statement provided in step 1 has been designed to be compatible with Windows or Linux.";
  2759. }
  2760. $aNameSpec = self::GetNameSpec($sClass);
  2761. foreach($aNameSpec[1] as $i => $sAttCode)
  2762. {
  2763. if(!self::IsValidAttCode($sClass, $sAttCode))
  2764. {
  2765. $aErrors[$sClass][] = "Unknown attribute code '".$sAttCode."' for the name definition";
  2766. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  2767. }
  2768. }
  2769. foreach(self::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  2770. {
  2771. if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode))
  2772. {
  2773. $aErrors[$sClass][] = "Unknown attribute code '".$sReconcKeyAttCode."' in the list of reconciliation keys";
  2774. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  2775. }
  2776. }
  2777. $bHasWritableAttribute = false;
  2778. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2779. {
  2780. // It makes no sense to check the attributes again and again in the subclasses
  2781. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2782. if ($oAttDef->IsExternalKey())
  2783. {
  2784. if (!self::IsValidClass($oAttDef->GetTargetClass()))
  2785. {
  2786. $aErrors[$sClass][] = "Unknown class '".$oAttDef->GetTargetClass()."' for the external key '$sAttCode'";
  2787. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetClasses())."}";
  2788. }
  2789. }
  2790. elseif ($oAttDef->IsExternalField())
  2791. {
  2792. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  2793. if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode))
  2794. {
  2795. $aErrors[$sClass][] = "Unknown key attribute code '".$sKeyAttCode."' for the external field $sAttCode";
  2796. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sClass))."}";
  2797. }
  2798. else
  2799. {
  2800. $oKeyAttDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  2801. $sTargetClass = $oKeyAttDef->GetTargetClass();
  2802. $sExtAttCode = $oAttDef->GetExtAttCode();
  2803. if (!self::IsValidAttCode($sTargetClass, $sExtAttCode))
  2804. {
  2805. $aErrors[$sClass][] = "Unknown key attribute code '".$sExtAttCode."' for the external field $sAttCode";
  2806. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sTargetClass))."}";
  2807. }
  2808. }
  2809. }
  2810. else if ($oAttDef->IsLinkSet())
  2811. {
  2812. // Do nothing...
  2813. }
  2814. else if ($oAttDef instanceof AttributeStopWatch)
  2815. {
  2816. $aThresholds = $oAttDef->ListThresholds();
  2817. if (is_array($aThresholds))
  2818. {
  2819. foreach($aThresholds as $iPercent => $aDef)
  2820. {
  2821. if (array_key_exists('highlight', $aDef))
  2822. {
  2823. if(!array_key_exists('code', $aDef['highlight']))
  2824. {
  2825. $aErrors[$sClass][] = "The 'code' element is missing for the 'highlight' property of the $iPercent% threshold in the attribute: '$sAttCode'.";
  2826. $aSugFix[$sClass][] = "Add a 'code' entry specifying the value of the highlight code for this threshold.";
  2827. }
  2828. else
  2829. {
  2830. $aScale = self::GetHighlightScale($sClass);
  2831. if (!array_key_exists($aDef['highlight']['code'], $aScale))
  2832. {
  2833. $aErrors[$sClass][] = "'{$aDef['highlight']['code']}' is not a valid value for the 'code' element of the $iPercent% threshold in the attribute: '$sAttCode'.";
  2834. $aSugFix[$sClass][] = "The possible highlight codes for this class are: ".implode(', ', array_keys($aScale)).".";
  2835. }
  2836. }
  2837. }
  2838. }
  2839. }
  2840. }
  2841. else // standard attributes
  2842. {
  2843. // Check that the default values definition is a valid object!
  2844. $oValSetDef = $oAttDef->GetValuesDef();
  2845. if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition)
  2846. {
  2847. $aErrors[$sClass][] = "Allowed values for attribute $sAttCode is not of the relevant type";
  2848. $aSugFix[$sClass][] = "Please set it as an instance of a ValueSetDefinition object.";
  2849. }
  2850. else
  2851. {
  2852. // Default value must be listed in the allowed values (if defined)
  2853. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  2854. if (!is_null($aAllowedValues))
  2855. {
  2856. $sDefaultValue = $oAttDef->GetDefaultValue();
  2857. if (is_string($sDefaultValue) && !array_key_exists($sDefaultValue, $aAllowedValues))
  2858. {
  2859. $aErrors[$sClass][] = "Default value '".$sDefaultValue."' for attribute $sAttCode is not an allowed value";
  2860. $aSugFix[$sClass][] = "Please pickup the default value out of {'".implode(", ", array_keys($aAllowedValues))."'}";
  2861. }
  2862. }
  2863. }
  2864. }
  2865. // Check dependencies
  2866. if ($oAttDef->IsWritable())
  2867. {
  2868. $bHasWritableAttribute = true;
  2869. foreach ($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode)
  2870. {
  2871. if (!self::IsValidAttCode($sClass, $sDependOnAttCode))
  2872. {
  2873. $aErrors[$sClass][] = "Unknown attribute code '".$sDependOnAttCode."' in the list of prerequisite attributes";
  2874. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  2875. }
  2876. }
  2877. }
  2878. }
  2879. foreach(self::GetClassFilterDefs($sClass) as $sFltCode=>$oFilterDef)
  2880. {
  2881. if (method_exists($oFilterDef, '__GetRefAttribute'))
  2882. {
  2883. $oAttDef = $oFilterDef->__GetRefAttribute();
  2884. if (!self::IsValidAttCode($sClass, $oAttDef->GetCode()))
  2885. {
  2886. $aErrors[$sClass][] = "Wrong attribute code '".$oAttDef->GetCode()."' (wrong class) for the \"basic\" filter $sFltCode";
  2887. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  2888. }
  2889. }
  2890. }
  2891. // Lifecycle
  2892. //
  2893. $sStateAttCode = self::GetStateAttributeCode($sClass);
  2894. if (strlen($sStateAttCode) > 0)
  2895. {
  2896. // Lifecycle - check that the state attribute does exist as an attribute
  2897. if (!self::IsValidAttCode($sClass, $sStateAttCode))
  2898. {
  2899. $aErrors[$sClass][] = "Unknown attribute code '".$sStateAttCode."' for the state definition";
  2900. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  2901. }
  2902. else
  2903. {
  2904. // Lifecycle - check that there is a value set constraint on the state attribute
  2905. $aAllowedValuesRaw = self::GetAllowedValues_att($sClass, $sStateAttCode);
  2906. $aStates = array_keys(self::EnumStates($sClass));
  2907. if (is_null($aAllowedValuesRaw))
  2908. {
  2909. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' will reflect the state of the object. It must be restricted to a set of values";
  2910. $aSugFix[$sClass][] = "Please define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')]";
  2911. }
  2912. else
  2913. {
  2914. $aAllowedValues = array_keys($aAllowedValuesRaw);
  2915. // Lifecycle - check the the state attribute allowed values are defined states
  2916. foreach($aAllowedValues as $sValue)
  2917. {
  2918. if (!in_array($sValue, $aStates))
  2919. {
  2920. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has an allowed value ($sValue) which is not a known state";
  2921. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  2922. }
  2923. }
  2924. // Lifecycle - check that defined states are allowed values
  2925. foreach($aStates as $sStateValue)
  2926. {
  2927. if (!in_array($sStateValue, $aAllowedValues))
  2928. {
  2929. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has a state ($sStateValue) which is not an allowed value";
  2930. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  2931. }
  2932. }
  2933. }
  2934. // Lifecycle - check that the action handlers are defined
  2935. foreach (self::EnumStates($sClass) as $sStateCode => $aStateDef)
  2936. {
  2937. foreach(self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef)
  2938. {
  2939. foreach ($aTransitionDef['actions'] as $actionHandler)
  2940. {
  2941. if (is_string($actionHandler))
  2942. {
  2943. if (!method_exists($sClass, $actionHandler))
  2944. {
  2945. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  2946. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(\$sStimulusCode){return true;}]";
  2947. }
  2948. }
  2949. else // if(is_array($actionHandler))
  2950. {
  2951. $sActionHandler = $actionHandler['verb'];
  2952. if (!method_exists($sClass, $sActionHandler))
  2953. {
  2954. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  2955. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(...){return true;}]";
  2956. }
  2957. }
  2958. }
  2959. }
  2960. if (array_key_exists('highlight', $aStateDef))
  2961. {
  2962. if(!array_key_exists('code', $aStateDef['highlight']))
  2963. {
  2964. $aErrors[$sClass][] = "The 'code' element is missing for the 'highlight' property of state: '$sStateCode'.";
  2965. $aSugFix[$sClass][] = "Add a 'code' entry specifying the value of the highlight code for this state.";
  2966. }
  2967. else
  2968. {
  2969. $aScale = self::GetHighlightScale($sClass);
  2970. if (!array_key_exists($aStateDef['highlight']['code'], $aScale))
  2971. {
  2972. $aErrors[$sClass][] = "'{$aStateDef['highlight']['code']}' is not a valid value for the 'code' element in the 'highlight' property of state: '$sStateCode'.";
  2973. $aSugFix[$sClass][] = "The possible highlight codes for this class are: ".implode(', ', array_keys($aScale)).".";
  2974. }
  2975. }
  2976. }
  2977. }
  2978. }
  2979. }
  2980. if ($bHasWritableAttribute)
  2981. {
  2982. if (!self::HasTable($sClass))
  2983. {
  2984. $aErrors[$sClass][] = "No table has been defined for this class";
  2985. $aSugFix[$sClass][] = "Either define a table name or move the attributes elsewhere";
  2986. }
  2987. }
  2988. // ZList
  2989. //
  2990. foreach(self::EnumZLists() as $sListCode)
  2991. {
  2992. foreach (self::FlattenZList(self::GetZListItems($sClass, $sListCode)) as $sMyAttCode)
  2993. {
  2994. if (!self::IsValidAttCode($sClass, $sMyAttCode))
  2995. {
  2996. $aErrors[$sClass][] = "Unknown attribute code '".$sMyAttCode."' from ZList '$sListCode'";
  2997. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  2998. }
  2999. }
  3000. }
  3001. // Check unicity of the SQL columns
  3002. //
  3003. if (self::HasTable($sClass))
  3004. {
  3005. $aTableColumns = array(); // array of column => attcode (the column is used by this attribute)
  3006. $aTableColumns[self::DBGetKey($sClass)] = 'id';
  3007. // Check that SQL columns are declared only once
  3008. //
  3009. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3010. {
  3011. // Skip this attribute if not originaly defined in this class
  3012. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3013. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  3014. {
  3015. if (array_key_exists($sField, $aTableColumns))
  3016. {
  3017. $aErrors[$sClass][] = "Column '$sField' declared for attribute $sAttCode, but already used for attribute ".$aTableColumns[$sField];
  3018. $aSugFix[$sClass][] = "Please find another name for the SQL column";
  3019. }
  3020. else
  3021. {
  3022. $aTableColumns[$sField] = $sAttCode;
  3023. }
  3024. }
  3025. }
  3026. }
  3027. } // foreach class
  3028. if (count($aErrors) > 0)
  3029. {
  3030. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  3031. echo "<h3>Business model inconsistencies have been found</h3>\n";
  3032. // #@# later -> this is the responsibility of the caller to format the output
  3033. foreach ($aErrors as $sClass => $aMessages)
  3034. {
  3035. echo "<p>Wrong declaration for class <b>$sClass</b></p>\n";
  3036. echo "<ul class=\"treeview\">\n";
  3037. $i = 0;
  3038. foreach ($aMessages as $sMsg)
  3039. {
  3040. echo "<li>$sMsg ({$aSugFix[$sClass][$i]})</li>\n";
  3041. $i++;
  3042. }
  3043. echo "</ul>\n";
  3044. }
  3045. if ($bExitOnError) echo "<p>Aborting...</p>\n";
  3046. echo "</div>\n";
  3047. if ($bExitOnError) exit;
  3048. }
  3049. }
  3050. public static function DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes)
  3051. {
  3052. if (empty($sRepairUrl)) return;
  3053. // By design, some queries might be blank, we have to ignore them
  3054. $aCleanFixes = array();
  3055. foreach($aSQLFixes as $sSQLFix)
  3056. {
  3057. if (!empty($sSQLFix))
  3058. {
  3059. $aCleanFixes[] = $sSQLFix;
  3060. }
  3061. }
  3062. if (count($aCleanFixes) == 0) return;
  3063. echo "<form action=\"$sRepairUrl\" method=\"POST\">\n";
  3064. echo " <input type=\"hidden\" name=\"$sSQLStatementArgName\" value=\"".htmlentities(implode("##SEP##", $aCleanFixes), ENT_QUOTES, 'UTF-8')."\">\n";
  3065. echo " <input type=\"submit\" value=\" Apply changes (".count($aCleanFixes)." queries) \">\n";
  3066. echo "</form>\n";
  3067. }
  3068. public static function DBExists($bMustBeComplete = true)
  3069. {
  3070. // returns true if at least one table exists
  3071. //
  3072. if (!CMDBSource::IsDB(self::$m_sDBName))
  3073. {
  3074. return false;
  3075. }
  3076. CMDBSource::SelectDB(self::$m_sDBName);
  3077. $aFound = array();
  3078. $aMissing = array();
  3079. foreach (self::DBEnumTables() as $sTable => $aClasses)
  3080. {
  3081. if (CMDBSource::IsTable($sTable))
  3082. {
  3083. $aFound[] = $sTable;
  3084. }
  3085. else
  3086. {
  3087. $aMissing[] = $sTable;
  3088. }
  3089. }
  3090. if (count($aFound) == 0)
  3091. {
  3092. // no expected table has been found
  3093. return false;
  3094. }
  3095. else
  3096. {
  3097. if (count($aMissing) == 0)
  3098. {
  3099. // the database is complete (still, could be some fields missing!)
  3100. return true;
  3101. }
  3102. else
  3103. {
  3104. // not all the tables, could be an older version
  3105. if ($bMustBeComplete)
  3106. {
  3107. return false;
  3108. }
  3109. else
  3110. {
  3111. return true;
  3112. }
  3113. }
  3114. }
  3115. }
  3116. public static function DBDrop()
  3117. {
  3118. $bDropEntireDB = true;
  3119. if (!empty(self::$m_sTablePrefix))
  3120. {
  3121. // Do drop only tables corresponding to the sub-database (table prefix)
  3122. // then possibly drop the DB itself (if no table remain)
  3123. foreach (CMDBSource::EnumTables() as $sTable)
  3124. {
  3125. // perform a case insensitive test because on Windows the table names become lowercase :-(
  3126. if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix))
  3127. {
  3128. CMDBSource::DropTable($sTable);
  3129. }
  3130. else
  3131. {
  3132. // There is at least one table which is out of the scope of the current application
  3133. $bDropEntireDB = false;
  3134. }
  3135. }
  3136. }
  3137. if ($bDropEntireDB)
  3138. {
  3139. CMDBSource::DropDB(self::$m_sDBName);
  3140. }
  3141. }
  3142. public static function DBCreate($aCallback = null)
  3143. {
  3144. // Note: we have to check if the DB does exist, because we may share the DB
  3145. // with other applications (in which case the DB does exist, not the tables with the given prefix)
  3146. if (!CMDBSource::IsDB(self::$m_sDBName))
  3147. {
  3148. CMDBSource::CreateDB(self::$m_sDBName);
  3149. }
  3150. self::DBCreateTables($aCallback);
  3151. self::DBCreateViews();
  3152. }
  3153. protected static function DBCreateTables($aCallback = null)
  3154. {
  3155. list($aErrors, $aSugFix, $aCondensedQueries) = self::DBCheckFormat();
  3156. //$sSQL = implode('; ', $aCondensedQueries); Does not work - multiple queries not allowed
  3157. foreach($aCondensedQueries as $sQuery)
  3158. {
  3159. $fStart = microtime(true);
  3160. CMDBSource::CreateTable($sQuery);
  3161. $fDuration = microtime(true) - $fStart;
  3162. if ($aCallback != null)
  3163. {
  3164. call_user_func($aCallback, $sQuery, $fDuration);
  3165. }
  3166. }
  3167. }
  3168. protected static function DBCreateViews()
  3169. {
  3170. list($aErrors, $aSugFix) = self::DBCheckViews();
  3171. $aSQL = array();
  3172. foreach ($aSugFix as $sClass => $aTarget)
  3173. {
  3174. foreach ($aTarget as $aQueries)
  3175. {
  3176. foreach ($aQueries as $sQuery)
  3177. {
  3178. if (!empty($sQuery))
  3179. {
  3180. //$aSQL[] = $sQuery;
  3181. // forces a refresh of cached information
  3182. CMDBSource::CreateTable($sQuery);
  3183. }
  3184. }
  3185. }
  3186. }
  3187. }
  3188. public static function DBDump()
  3189. {
  3190. $aDataDump = array();
  3191. foreach (self::DBEnumTables() as $sTable => $aClasses)
  3192. {
  3193. $aRows = CMDBSource::DumpTable($sTable);
  3194. $aDataDump[$sTable] = $aRows;
  3195. }
  3196. return $aDataDump;
  3197. }
  3198. /*
  3199. * Determines wether the target DB is frozen or not
  3200. */
  3201. public static function DBIsReadOnly()
  3202. {
  3203. // Improvement: check the mySQL variable -> Read-only
  3204. if (utils::IsArchiveMode())
  3205. {
  3206. return true;
  3207. }
  3208. if (UserRights::IsAdministrator())
  3209. {
  3210. return (!self::DBHasAccess(ACCESS_ADMIN_WRITE));
  3211. }
  3212. else
  3213. {
  3214. return (!self::DBHasAccess(ACCESS_USER_WRITE));
  3215. }
  3216. }
  3217. public static function DBHasAccess($iRequested = ACCESS_FULL)
  3218. {
  3219. $iMode = self::$m_oConfig->Get('access_mode');
  3220. if (($iMode & $iRequested) == 0) return false;
  3221. return true;
  3222. }
  3223. protected static function MakeDictEntry($sKey, $sValueFromOldSystem, $sDefaultValue, &$bNotInDico)
  3224. {
  3225. $sValue = Dict::S($sKey, 'x-no-nothing');
  3226. if ($sValue == 'x-no-nothing')
  3227. {
  3228. $bNotInDico = true;
  3229. $sValue = $sValueFromOldSystem;
  3230. if (strlen($sValue) == 0)
  3231. {
  3232. $sValue = $sDefaultValue;
  3233. }
  3234. }
  3235. return " '$sKey' => '".str_replace("'", "\\'", $sValue)."',\n";
  3236. }
  3237. public static function MakeDictionaryTemplate($sModules = '', $sOutputFilter = 'NotInDictionary')
  3238. {
  3239. $sRes = '';
  3240. $sRes .= "// Dictionnay conventions\n";
  3241. $sRes .= htmlentities("// Class:<class_name>\n", ENT_QUOTES, 'UTF-8');
  3242. $sRes .= htmlentities("// Class:<class_name>+\n", ENT_QUOTES, 'UTF-8');
  3243. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>\n", ENT_QUOTES, 'UTF-8');
  3244. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>+\n", ENT_QUOTES, 'UTF-8');
  3245. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>\n", ENT_QUOTES, 'UTF-8');
  3246. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>+\n", ENT_QUOTES, 'UTF-8');
  3247. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>\n", ENT_QUOTES, 'UTF-8');
  3248. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>+\n", ENT_QUOTES, 'UTF-8');
  3249. $sRes .= "\n";
  3250. // Note: I did not use EnumCategories(), because a given class maybe found in several categories
  3251. // Need to invent the "module", to characterize the origins of a class
  3252. if (strlen($sModules) == 0)
  3253. {
  3254. $aModules = array('bizmodel', 'core/cmdb', 'gui' , 'application', 'addon/userrights');
  3255. }
  3256. else
  3257. {
  3258. $aModules = explode(', ', $sModules);
  3259. }
  3260. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3261. $sRes .= "// Note: The classes have been grouped by categories: ".implode(', ', $aModules)."\n";
  3262. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3263. foreach ($aModules as $sCategory)
  3264. {
  3265. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3266. $sRes .= "// Classes in '<em>$sCategory</em>'\n";
  3267. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3268. $sRes .= "//\n";
  3269. $sRes .= "\n";
  3270. foreach (self::GetClasses($sCategory) as $sClass)
  3271. {
  3272. if (!self::HasTable($sClass)) continue;
  3273. $bNotInDico = false;
  3274. $sClassRes = "//\n";
  3275. $sClassRes .= "// Class: $sClass\n";
  3276. $sClassRes .= "//\n";
  3277. $sClassRes .= "\n";
  3278. $sClassRes .= "Dict::Add('EN US', 'English', 'English', array(\n";
  3279. $sClassRes .= self::MakeDictEntry("Class:$sClass", self::GetName_Obsolete($sClass), $sClass, $bNotInDico);
  3280. $sClassRes .= self::MakeDictEntry("Class:$sClass+", self::GetClassDescription_Obsolete($sClass), '', $bNotInDico);
  3281. foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  3282. {
  3283. // Skip this attribute if not originaly defined in this class
  3284. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3285. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode", $oAttDef->GetLabel_Obsolete(), $sAttCode, $bNotInDico);
  3286. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode+", $oAttDef->GetDescription_Obsolete(), '', $bNotInDico);
  3287. if ($oAttDef instanceof AttributeEnum)
  3288. {
  3289. if (self::GetStateAttributeCode($sClass) == $sAttCode)
  3290. {
  3291. foreach (self::EnumStates($sClass) as $sStateCode => $aStateData)
  3292. {
  3293. if (array_key_exists('label', $aStateData))
  3294. {
  3295. $sValue = $aStateData['label'];
  3296. }
  3297. else
  3298. {
  3299. $sValue = MetaModel::GetStateLabel($sClass, $sStateCode);
  3300. }
  3301. if (array_key_exists('description', $aStateData))
  3302. {
  3303. $sValuePlus = $aStateData['description'];
  3304. }
  3305. else
  3306. {
  3307. $sValuePlus = MetaModel::GetStateDescription($sClass, $sStateCode);
  3308. }
  3309. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode", $sValue, '', $bNotInDico);
  3310. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode+", $sValuePlus, '', $bNotInDico);
  3311. }
  3312. }
  3313. else
  3314. {
  3315. foreach ($oAttDef->GetAllowedValues() as $sKey => $value)
  3316. {
  3317. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey", $value, '', $bNotInDico);
  3318. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey+", $value, '', $bNotInDico);
  3319. }
  3320. }
  3321. }
  3322. }
  3323. foreach(self::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
  3324. {
  3325. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode", $oStimulus->GetLabel_Obsolete(), '', $bNotInDico);
  3326. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode+", $oStimulus->GetDescription_Obsolete(), '', $bNotInDico);
  3327. }
  3328. $sClassRes .= "));\n";
  3329. $sClassRes .= "\n";
  3330. if ($bNotInDico || ($sOutputFilter != 'NotInDictionary'))
  3331. {
  3332. $sRes .= $sClassRes;
  3333. }
  3334. }
  3335. }
  3336. return $sRes;
  3337. }
  3338. public static function DBCheckFormat()
  3339. {
  3340. $aErrors = array();
  3341. $aSugFix = array();
  3342. // A new way of representing things to be done - quicker to execute !
  3343. $aCreateTable = array(); // array of <table> => <table options>
  3344. $aCreateTableItems = array(); // array of <table> => array of <create definition>
  3345. $aAlterTableItems = array(); // array of <table> => <alter specification>
  3346. foreach (self::GetClasses() as $sClass)
  3347. {
  3348. if (!self::HasTable($sClass)) continue;
  3349. // Check that the table exists
  3350. //
  3351. $sTable = self::DBGetTable($sClass);
  3352. $sKeyField = self::DBGetKey($sClass);
  3353. $sAutoIncrement = (self::IsAutoIncrementKey($sClass) ? "AUTO_INCREMENT" : "");
  3354. $sKeyFieldDefinition = "`$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY";
  3355. if (!CMDBSource::IsTable($sTable))
  3356. {
  3357. $aErrors[$sClass]['*'][] = "table '$sTable' could not be found into the DB";
  3358. $aSugFix[$sClass]['*'][] = "CREATE TABLE `$sTable` ($sKeyFieldDefinition) ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  3359. $aCreateTable[$sTable] = "ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  3360. $aCreateTableItems[$sTable][$sKeyField] = $sKeyFieldDefinition;
  3361. }
  3362. // Check that the key field exists
  3363. //
  3364. elseif (!CMDBSource::IsField($sTable, $sKeyField))
  3365. {
  3366. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) could not be found";
  3367. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` ADD $sKeyFieldDefinition";
  3368. if (!array_key_exists($sTable, $aCreateTable))
  3369. {
  3370. $aAlterTableItems[$sTable][$sKeyField] = "ADD $sKeyFieldDefinition";
  3371. }
  3372. }
  3373. else
  3374. {
  3375. // Check the key field properties
  3376. //
  3377. if (!CMDBSource::IsKey($sTable, $sKeyField))
  3378. {
  3379. $aErrors[$sClass]['id'][] = "key '$sKeyField' is not a key for table '$sTable'";
  3380. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable`, DROP PRIMARY KEY, ADD PRIMARY key(`$sKeyField`)";
  3381. if (!array_key_exists($sTable, $aCreateTable))
  3382. {
  3383. $aAlterTableItems[$sTable][$sKeyField] = "CHANGE `$sKeyField` $sKeyFieldDefinition";
  3384. }
  3385. }
  3386. if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField))
  3387. {
  3388. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) is not automatically incremented";
  3389. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` CHANGE `$sKeyField` $sKeyFieldDefinition";
  3390. if (!array_key_exists($sTable, $aCreateTable))
  3391. {
  3392. $aAlterTableItems[$sTable][$sKeyField] = "CHANGE `$sKeyField` $sKeyFieldDefinition";
  3393. }
  3394. }
  3395. }
  3396. // Check that any defined field exists
  3397. //
  3398. $aTableInfo = CMDBSource::GetTableInfo($sTable);
  3399. $aTableInfo['Fields'][$sKeyField]['used'] = true;
  3400. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3401. {
  3402. if (!$oAttDef->CopyOnAllTables())
  3403. {
  3404. // Skip this attribute if not originaly defined in this class
  3405. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3406. }
  3407. foreach($oAttDef->GetSQLColumns(true) as $sField => $sDBFieldSpec)
  3408. {
  3409. // Keep track of columns used by iTop
  3410. $aTableInfo['Fields'][$sField]['used'] = true;
  3411. $bIndexNeeded = $oAttDef->RequiresIndex();
  3412. $sFieldDefinition = "`$sField` $sDBFieldSpec";
  3413. if (!CMDBSource::IsField($sTable, $sField))
  3414. {
  3415. $aErrors[$sClass][$sAttCode][] = "field '$sField' could not be found in table '$sTable'";
  3416. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD $sFieldDefinition";
  3417. if ($bIndexNeeded)
  3418. {
  3419. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  3420. }
  3421. if (array_key_exists($sTable, $aCreateTable))
  3422. {
  3423. $aCreateTableItems[$sTable][$sField] = $sFieldDefinition;
  3424. if ($bIndexNeeded)
  3425. {
  3426. $aCreateTableItems[$sTable][] = "INDEX (`$sField`)";
  3427. }
  3428. }
  3429. else
  3430. {
  3431. $aAlterTableItems[$sTable][$sField] = "ADD $sFieldDefinition";
  3432. if ($bIndexNeeded)
  3433. {
  3434. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  3435. }
  3436. }
  3437. }
  3438. else
  3439. {
  3440. // The field already exists, does it have the relevant properties?
  3441. //
  3442. $bToBeChanged = false;
  3443. $sActualFieldSpec = CMDBSource::GetFieldSpec($sTable, $sField);
  3444. if (strcasecmp($sDBFieldSpec, $sActualFieldSpec) != 0)
  3445. {
  3446. $bToBeChanged = true;
  3447. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' has a wrong type: found '$sActualFieldSpec' while expecting '$sDBFieldSpec'";
  3448. }
  3449. if ($bToBeChanged)
  3450. {
  3451. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` $sFieldDefinition";
  3452. $aAlterTableItems[$sTable][$sField] = "CHANGE `$sField` $sFieldDefinition";
  3453. }
  3454. // Create indexes (external keys only... so far)
  3455. //
  3456. if ($bIndexNeeded && !CMDBSource::HasIndex($sTable, $sField, array($sField)))
  3457. {
  3458. $aErrors[$sClass][$sAttCode][] = "Foreign key '$sField' in table '$sTable' should have an index";
  3459. if (CMDBSource::HasIndex($sTable, $sField))
  3460. {
  3461. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` DROP INDEX `$sField`, ADD INDEX (`$sField`)";
  3462. $aAlterTableItems[$sTable][] = "DROP INDEX `$sField`";
  3463. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  3464. }
  3465. else
  3466. {
  3467. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  3468. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  3469. }
  3470. }
  3471. }
  3472. }
  3473. }
  3474. // Check indexes
  3475. foreach (self::DBGetIndexes($sClass) as $aColumns)
  3476. {
  3477. $sIndexId = implode('_', $aColumns);
  3478. if(!CMDBSource::HasIndex($sTable, $sIndexId, $aColumns))
  3479. {
  3480. $sColumns = "`".implode("`, `", $aColumns)."`";
  3481. if (CMDBSource::HasIndex($sTable, $sIndexId))
  3482. {
  3483. $aErrors[$sClass]['*'][] = "Wrong index '$sIndexId' ($sColumns) in table '$sTable'";
  3484. $aSugFix[$sClass]['*'][] = "ALTER TABLE `$sTable` DROP INDEX `$sIndexId`, ADD INDEX `$sIndexId` ($sColumns)";
  3485. }
  3486. else
  3487. {
  3488. $aErrors[$sClass]['*'][] = "Missing index '$sIndexId' ($sColumns) in table '$sTable'";
  3489. $aSugFix[$sClass]['*'][] = "ALTER TABLE `$sTable` ADD INDEX `$sIndexId` ($sColumns)";
  3490. }
  3491. if (array_key_exists($sTable, $aCreateTable))
  3492. {
  3493. $aCreateTableItems[$sTable][] = "INDEX `$sIndexId` ($sColumns)";
  3494. }
  3495. else
  3496. {
  3497. if (CMDBSource::HasIndex($sTable, $sIndexId))
  3498. {
  3499. $aAlterTableItems[$sTable][] = "DROP INDEX `$sIndexId`";
  3500. }
  3501. $aAlterTableItems[$sTable][] = "ADD INDEX `$sIndexId` ($sColumns)";
  3502. }
  3503. }
  3504. }
  3505. // Find out unused columns
  3506. //
  3507. foreach($aTableInfo['Fields'] as $sField => $aFieldData)
  3508. {
  3509. if (!isset($aFieldData['used']) || !$aFieldData['used'])
  3510. {
  3511. $aErrors[$sClass]['*'][] = "Column '$sField' in table '$sTable' is not used";
  3512. if (!CMDBSource::IsNullAllowed($sTable, $sField))
  3513. {
  3514. // Allow null values so that new record can be inserted
  3515. // without specifying the value of this unknown column
  3516. $sFieldDefinition = "`$sField` ".CMDBSource::GetFieldType($sTable, $sField).' NULL';
  3517. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` $sFieldDefinition";
  3518. $aAlterTableItems[$sTable][$sField] = "CHANGE `$sField` $sFieldDefinition";
  3519. }
  3520. }
  3521. }
  3522. }
  3523. $aCondensedQueries = array();
  3524. foreach($aCreateTable as $sTable => $sTableOptions)
  3525. {
  3526. $sTableItems = implode(', ', $aCreateTableItems[$sTable]);
  3527. $aCondensedQueries[] = "CREATE TABLE `$sTable` ($sTableItems) $sTableOptions";
  3528. }
  3529. foreach($aAlterTableItems as $sTable => $aChangeList)
  3530. {
  3531. $sChangeList = implode(', ', $aChangeList);
  3532. $aCondensedQueries[] = "ALTER TABLE `$sTable` $sChangeList";
  3533. }
  3534. return array($aErrors, $aSugFix, $aCondensedQueries);
  3535. }
  3536. public static function DBCheckViews()
  3537. {
  3538. $aErrors = array();
  3539. $aSugFix = array();
  3540. // Reporting views (must be created after any other table)
  3541. //
  3542. foreach (self::GetClasses('bizmodel') as $sClass)
  3543. {
  3544. $sView = self::DBGetView($sClass);
  3545. if (CMDBSource::IsTable($sView))
  3546. {
  3547. // Check that the view is complete
  3548. //
  3549. // Note: checking the list of attributes is not enough because the columns can be stable while the SELECT is not stable
  3550. // Example: new way to compute the friendly name
  3551. // The correct comparison algorithm is to compare the queries,
  3552. // by using "SHOW CREATE VIEW" (MySQL 5.0.1 required) or to look into INFORMATION_SCHEMA/views
  3553. // both requiring some privileges
  3554. // Decision: to simplify, let's consider the views as being wrong anytime
  3555. if (true)
  3556. {
  3557. // Rework the view
  3558. //
  3559. $oFilter = new DBObjectSearch($sClass, '');
  3560. $oFilter->AllowAllData();
  3561. $sSQL = $oFilter->MakeSelectQuery();
  3562. $aErrors[$sClass]['*'][] = "Redeclare view '$sView' (systematic - to support an eventual change in the friendly name computation)";
  3563. $aSugFix[$sClass]['*'][] = "ALTER VIEW `$sView` AS $sSQL";
  3564. }
  3565. }
  3566. else
  3567. {
  3568. // Create the view
  3569. //
  3570. $oFilter = new DBObjectSearch($sClass, '');
  3571. $oFilter->AllowAllData();
  3572. $sSQL = $oFilter->MakeSelectQuery();
  3573. $aErrors[$sClass]['*'][] = "Missing view for class: $sClass";
  3574. $aSugFix[$sClass]['*'][] = "DROP VIEW IF EXISTS `$sView`";
  3575. $aSugFix[$sClass]['*'][] = "CREATE VIEW `$sView` AS $sSQL";
  3576. }
  3577. }
  3578. return array($aErrors, $aSugFix);
  3579. }
  3580. private static function DBCheckIntegrity_Check2Delete($sSelWrongRecs, $sErrorDesc, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel, $bProcessingFriends = false)
  3581. {
  3582. $sRootClass = self::GetRootClass($sClass);
  3583. $sTable = self::DBGetTable($sClass);
  3584. $sKeyField = self::DBGetKey($sClass);
  3585. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  3586. {
  3587. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  3588. }
  3589. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  3590. if (count($aWrongRecords) == 0) return;
  3591. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  3592. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  3593. foreach ($aWrongRecords as $iRecordId)
  3594. {
  3595. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  3596. {
  3597. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  3598. {
  3599. case 'Delete':
  3600. // Already planned for a deletion
  3601. // Let's concatenate the errors description together
  3602. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  3603. break;
  3604. case 'Update':
  3605. // Let's plan a deletion
  3606. break;
  3607. }
  3608. }
  3609. else
  3610. {
  3611. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  3612. }
  3613. if (!$bProcessingFriends)
  3614. {
  3615. if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable]))
  3616. {
  3617. // Something new to be deleted...
  3618. $iNewDelCount++;
  3619. }
  3620. }
  3621. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Delete';
  3622. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array();
  3623. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  3624. $aPlannedDel[$sTable][] = $iRecordId;
  3625. }
  3626. // Now make sure that we would delete the records of the other tables for that class
  3627. //
  3628. if (!$bProcessingFriends)
  3629. {
  3630. $sDeleteKeys = "'".implode("', '", $aWrongRecords)."'";
  3631. foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass)
  3632. {
  3633. $sFriendTable = self::DBGetTable($sFriendClass);
  3634. $sFriendKey = self::DBGetKey($sFriendClass);
  3635. // skip the current table
  3636. if ($sFriendTable == $sTable) continue;
  3637. $sFindRelatedRec = "SELECT DISTINCT maintable.`$sFriendKey` AS id FROM `$sFriendTable` AS maintable WHERE maintable.`$sFriendKey` IN ($sDeleteKeys)";
  3638. self::DBCheckIntegrity_Check2Delete($sFindRelatedRec, "Cascading deletion of record in friend table `<em>$sTable</em>`", $sFriendClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel, true);
  3639. }
  3640. }
  3641. }
  3642. private static function DBCheckIntegrity_Check2Update($sSelWrongRecs, $sErrorDesc, $sColumn, $sNewValue, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  3643. {
  3644. $sRootClass = self::GetRootClass($sClass);
  3645. $sTable = self::DBGetTable($sClass);
  3646. $sKeyField = self::DBGetKey($sClass);
  3647. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  3648. {
  3649. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  3650. }
  3651. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  3652. if (count($aWrongRecords) == 0) return;
  3653. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  3654. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  3655. foreach ($aWrongRecords as $iRecordId)
  3656. {
  3657. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  3658. {
  3659. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  3660. {
  3661. case 'Delete':
  3662. // No need to update, the record will be deleted!
  3663. break;
  3664. case 'Update':
  3665. // Already planned for an update
  3666. // Add this new update spec to the list
  3667. $bFoundSameSpec = false;
  3668. foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec)
  3669. {
  3670. if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue']))
  3671. {
  3672. $bFoundSameSpec = true;
  3673. }
  3674. }
  3675. if (!$bFoundSameSpec)
  3676. {
  3677. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = (array('column' => $sColumn, 'newvalue'=>$sNewValue));
  3678. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  3679. }
  3680. break;
  3681. }
  3682. }
  3683. else
  3684. {
  3685. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  3686. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Update';
  3687. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array(array('column' => $sColumn, 'newvalue'=>$sNewValue));
  3688. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  3689. }
  3690. }
  3691. }
  3692. // returns the count of records found for deletion
  3693. public static function DBCheckIntegrity_SinglePass(&$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  3694. {
  3695. foreach (self::GetClasses() as $sClass)
  3696. {
  3697. if (!self::HasTable($sClass)) continue;
  3698. $sRootClass = self::GetRootClass($sClass);
  3699. $sTable = self::DBGetTable($sClass);
  3700. $sKeyField = self::DBGetKey($sClass);
  3701. if (!self::IsStandaloneClass($sClass))
  3702. {
  3703. if (self::IsRootClass($sClass))
  3704. {
  3705. // Check that the final class field contains the name of a class which inherited from the current class
  3706. //
  3707. $sFinalClassField = self::DBGetClassField($sClass);
  3708. $aAllowedValues = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  3709. $sAllowedValues = implode(",", CMDBSource::Quote($aAllowedValues, true));
  3710. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE `$sFinalClassField` NOT IN ($sAllowedValues)";
  3711. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "final class (field `<em>$sFinalClassField</em>`) is wrong (expected a value in {".$sAllowedValues."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3712. }
  3713. else
  3714. {
  3715. $sRootTable = self::DBGetTable($sRootClass);
  3716. $sRootKey = self::DBGetKey($sRootClass);
  3717. $sFinalClassField = self::DBGetClassField($sRootClass);
  3718. $aExpectedClasses = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  3719. $sExpectedClasses = implode(",", CMDBSource::Quote($aExpectedClasses, true));
  3720. // Check that any record found here has its counterpart in the root table
  3721. // and which refers to a child class
  3722. //
  3723. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` as maintable LEFT JOIN `$sRootTable` ON maintable.`$sKeyField` = `$sRootTable`.`$sRootKey` AND `$sRootTable`.`$sFinalClassField` IN ($sExpectedClasses) WHERE `$sRootTable`.`$sRootKey` IS NULL";
  3724. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Found a record in `<em>$sTable</em>`, but no counterpart in root table `<em>$sRootTable</em>` (inc. records pointing to a class in {".$sExpectedClasses."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3725. // Check that any record found in the root table and referring to a child class
  3726. // has its counterpart here (detect orphan nodes -root or in the middle of the hierarchy)
  3727. //
  3728. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sRootKey` AS id FROM `$sRootTable` AS maintable LEFT JOIN `$sTable` ON maintable.`$sRootKey` = `$sTable`.`$sKeyField` WHERE `$sTable`.`$sKeyField` IS NULL AND maintable.`$sFinalClassField` IN ($sExpectedClasses)";
  3729. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Found a record in root table `<em>$sRootTable</em>`, but no counterpart in table `<em>$sTable</em>` (root records pointing to a class in {".$sExpectedClasses."})", $sRootClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3730. }
  3731. }
  3732. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3733. {
  3734. // Skip this attribute if not defined in this table
  3735. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3736. if ($oAttDef->IsExternalKey())
  3737. {
  3738. // Check that any external field is pointing to an existing object
  3739. //
  3740. $sRemoteClass = $oAttDef->GetTargetClass();
  3741. $sRemoteTable = self::DBGetTable($sRemoteClass);
  3742. $sRemoteKey = self::DBGetKey($sRemoteClass);
  3743. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  3744. $sExtKeyField = current($aCols); // get the first column for an external key
  3745. // Note: a class/table may have an external key on itself
  3746. $sSelBase = "SELECT DISTINCT maintable.`$sKeyField` AS id, maintable.`$sExtKeyField` AS extkey FROM `$sTable` AS maintable LEFT JOIN `$sRemoteTable` ON maintable.`$sExtKeyField` = `$sRemoteTable`.`$sRemoteKey`";
  3747. $sSelWrongRecs = $sSelBase." WHERE `$sRemoteTable`.`$sRemoteKey` IS NULL";
  3748. if ($oAttDef->IsNullAllowed())
  3749. {
  3750. // Exclude the records pointing to 0/null from the errors
  3751. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  3752. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  3753. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3754. }
  3755. else
  3756. {
  3757. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3758. }
  3759. // Do almost the same, taking into account the records planned for deletion
  3760. if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0)
  3761. {
  3762. // This could be done by the mean of a 'OR ... IN (aIgnoreRecords)
  3763. // but in that case you won't be able to track the root cause (cascading)
  3764. $sSelWrongRecs = $sSelBase." WHERE maintable.`$sExtKeyField` IN ('".implode("', '", $aPlannedDel[$sRemoteTable])."')";
  3765. if ($oAttDef->IsNullAllowed())
  3766. {
  3767. // Exclude the records pointing to 0/null from the errors
  3768. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  3769. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  3770. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3771. }
  3772. else
  3773. {
  3774. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3775. }
  3776. }
  3777. }
  3778. else if ($oAttDef->IsDirectField())
  3779. {
  3780. // Check that the values fit the allowed values
  3781. //
  3782. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  3783. if (!is_null($aAllowedValues) && count($aAllowedValues) > 0)
  3784. {
  3785. $sExpectedValues = implode(",", CMDBSource::Quote(array_keys($aAllowedValues), true));
  3786. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  3787. $sMyAttributeField = current($aCols); // get the first column for the moment
  3788. $sDefaultValue = $oAttDef->GetDefaultValue();
  3789. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE maintable.`$sMyAttributeField` NOT IN ($sExpectedValues)";
  3790. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record having a column ('<em>$sAttCode</em>') with an unexpected value", $sMyAttributeField, CMDBSource::Quote($sDefaultValue), $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3791. }
  3792. }
  3793. }
  3794. }
  3795. }
  3796. public static function DBCheckIntegrity($sRepairUrl = "", $sSQLStatementArgName = "")
  3797. {
  3798. // Records in error, and action to be taken: delete or update
  3799. // by RootClass/Table/Record
  3800. $aErrorsAndFixes = array();
  3801. // Records to be ignored in the current/next pass
  3802. // by Table = array of RecordId
  3803. $aPlannedDel = array();
  3804. // Count of errors in the next pass: no error means that we can leave...
  3805. $iErrorCount = 0;
  3806. // Limit in case of a bug in the algorythm
  3807. $iLoopCount = 0;
  3808. $iNewDelCount = 1; // startup...
  3809. while ($iNewDelCount > 0)
  3810. {
  3811. $iNewDelCount = 0;
  3812. self::DBCheckIntegrity_SinglePass($aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3813. $iErrorCount += $iNewDelCount;
  3814. // Safety net #1 - limit the planned deletions
  3815. //
  3816. $iMaxDel = 1000;
  3817. $iPlannedDel = 0;
  3818. foreach ($aPlannedDel as $sTable => $aPlannedDelOnTable)
  3819. {
  3820. $iPlannedDel += count($aPlannedDelOnTable);
  3821. }
  3822. if ($iPlannedDel > $iMaxDel)
  3823. {
  3824. throw new CoreWarning("DB Integrity Check safety net - Exceeding the limit of $iMaxDel planned record deletion");
  3825. break;
  3826. }
  3827. // Safety net #2 - limit the iterations
  3828. //
  3829. $iLoopCount++;
  3830. $iMaxLoops = 10;
  3831. if ($iLoopCount > $iMaxLoops)
  3832. {
  3833. throw new CoreWarning("DB Integrity Check safety net - Reached the limit of $iMaxLoops loops");
  3834. break;
  3835. }
  3836. }
  3837. // Display the results
  3838. //
  3839. $iIssueCount = 0;
  3840. $aFixesDelete = array();
  3841. $aFixesUpdate = array();
  3842. foreach ($aErrorsAndFixes as $sRootClass => $aTables)
  3843. {
  3844. foreach ($aTables as $sTable => $aRecords)
  3845. {
  3846. foreach ($aRecords as $iRecord => $aError)
  3847. {
  3848. $sAction = $aError['Action'];
  3849. $sReason = $aError['Reason'];
  3850. $iPass = $aError['Pass'];
  3851. switch ($sAction)
  3852. {
  3853. case 'Delete':
  3854. $sActionDetails = "";
  3855. $aFixesDelete[$sTable][] = $iRecord;
  3856. break;
  3857. case 'Update':
  3858. $aUpdateDesc = array();
  3859. foreach($aError['Action_Details'] as $aUpdateSpec)
  3860. {
  3861. $aUpdateDesc[] = $aUpdateSpec['column']." -&gt; ".$aUpdateSpec['newvalue'];
  3862. $aFixesUpdate[$sTable][$aUpdateSpec['column']][$aUpdateSpec['newvalue']][] = $iRecord;
  3863. }
  3864. $sActionDetails = "Set ".implode(", ", $aUpdateDesc);
  3865. break;
  3866. default:
  3867. $sActionDetails = "bug: unknown action '$sAction'";
  3868. }
  3869. $aIssues[] = "$sRootClass / $sTable / $iRecord / $sReason / $sAction / $sActionDetails";
  3870. $iIssueCount++;
  3871. }
  3872. }
  3873. }
  3874. if ($iIssueCount > 0)
  3875. {
  3876. // Build the queries to fix in the database
  3877. //
  3878. // First step, be able to get class data out of the table name
  3879. // Could be optimized, because we've made the job earlier... but few benefits, so...
  3880. $aTable2ClassProp = array();
  3881. foreach (self::GetClasses() as $sClass)
  3882. {
  3883. if (!self::HasTable($sClass)) continue;
  3884. $sRootClass = self::GetRootClass($sClass);
  3885. $sTable = self::DBGetTable($sClass);
  3886. $sKeyField = self::DBGetKey($sClass);
  3887. $aErrorsAndFixes[$sRootClass][$sTable] = array();
  3888. $aTable2ClassProp[$sTable] = array('rootclass'=>$sRootClass, 'class'=>$sClass, 'keyfield'=>$sKeyField);
  3889. }
  3890. // Second step, build a flat list of SQL queries
  3891. $aSQLFixes = array();
  3892. $iPlannedUpdate = 0;
  3893. foreach ($aFixesUpdate as $sTable => $aColumns)
  3894. {
  3895. foreach ($aColumns as $sColumn => $aNewValues)
  3896. {
  3897. foreach ($aNewValues as $sNewValue => $aRecords)
  3898. {
  3899. $iPlannedUpdate += count($aRecords);
  3900. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  3901. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  3902. $aSQLFixes[] = "UPDATE `$sTable` SET `$sColumn` = $sNewValue WHERE `$sKeyField` IN ($sWrongRecords)";
  3903. }
  3904. }
  3905. }
  3906. $iPlannedDel = 0;
  3907. foreach ($aFixesDelete as $sTable => $aRecords)
  3908. {
  3909. $iPlannedDel += count($aRecords);
  3910. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  3911. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  3912. $aSQLFixes[] = "DELETE FROM `$sTable` WHERE `$sKeyField` IN ($sWrongRecords)";
  3913. }
  3914. // Report the results
  3915. //
  3916. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  3917. echo "<h3>Database corruption error(s): $iErrorCount issues have been encountered. $iPlannedDel records will be deleted, $iPlannedUpdate records will be updated:</h3>\n";
  3918. // #@# later -> this is the responsibility of the caller to format the output
  3919. echo "<ul class=\"treeview\">\n";
  3920. foreach ($aIssues as $sIssueDesc)
  3921. {
  3922. echo "<li>$sIssueDesc</li>\n";
  3923. }
  3924. echo "</ul>\n";
  3925. self::DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes);
  3926. echo "<p>Aborting...</p>\n";
  3927. echo "</div>\n";
  3928. exit;
  3929. }
  3930. }
  3931. public static function Startup($config, $bModelOnly = false, $bAllowCache = true, $bTraceSourceFiles = false, $sEnvironment = 'production')
  3932. {
  3933. self::$m_sEnvironment = $sEnvironment;
  3934. if (!defined('MODULESROOT'))
  3935. {
  3936. define('MODULESROOT', APPROOT.'env-'.self::$m_sEnvironment.'/');
  3937. self::$m_bTraceSourceFiles = $bTraceSourceFiles;
  3938. // $config can be either a filename, or a Configuration object (volatile!)
  3939. if ($config instanceof Config)
  3940. {
  3941. self::LoadConfig($config, $bAllowCache);
  3942. }
  3943. else
  3944. {
  3945. self::LoadConfig(new Config($config), $bAllowCache);
  3946. }
  3947. if ($bModelOnly) return;
  3948. }
  3949. CMDBSource::SelectDB(self::$m_sDBName);
  3950. foreach(get_declared_classes() as $sPHPClass)
  3951. {
  3952. if (is_subclass_of($sPHPClass, 'ModuleHandlerAPI'))
  3953. {
  3954. $aCallSpec = array($sPHPClass, 'OnMetaModelStarted');
  3955. call_user_func_array($aCallSpec, array());
  3956. }
  3957. }
  3958. if (false)
  3959. {
  3960. echo "Debug<br/>\n";
  3961. self::static_var_dump();
  3962. }
  3963. }
  3964. public static function LoadConfig($oConfiguration, $bAllowCache = false)
  3965. {
  3966. self::$m_oConfig = $oConfiguration;
  3967. // Set log ASAP
  3968. if (self::$m_oConfig->GetLogGlobal())
  3969. {
  3970. if (self::$m_oConfig->GetLogIssue())
  3971. {
  3972. self::$m_bLogIssue = true;
  3973. IssueLog::Enable(APPROOT.'log/error.log');
  3974. }
  3975. self::$m_bLogNotification = self::$m_oConfig->GetLogNotification();
  3976. self::$m_bLogWebService = self::$m_oConfig->GetLogWebService();
  3977. ToolsLog::Enable(APPROOT.'log/tools.log');
  3978. }
  3979. else
  3980. {
  3981. self::$m_bLogIssue = false;
  3982. self::$m_bLogNotification = false;
  3983. self::$m_bLogWebService = false;
  3984. }
  3985. ExecutionKPI::EnableDuration(self::$m_oConfig->Get('log_kpi_duration'));
  3986. ExecutionKPI::EnableMemory(self::$m_oConfig->Get('log_kpi_memory'));
  3987. ExecutionKPI::SetAllowedUser(self::$m_oConfig->Get('log_kpi_user_id'));
  3988. self::$m_bSkipCheckToWrite = self::$m_oConfig->Get('skip_check_to_write');
  3989. self::$m_bSkipCheckExtKeys = self::$m_oConfig->Get('skip_check_ext_keys');
  3990. self::$m_bUseAPCCache = $bAllowCache
  3991. && self::$m_oConfig->Get('apc_cache.enabled')
  3992. && function_exists('apc_fetch')
  3993. && function_exists('apc_store');
  3994. DBSearch::EnableQueryCache(self::$m_oConfig->GetQueryCacheEnabled(), self::$m_bUseAPCCache, self::$m_oConfig->Get('apc_cache.query_ttl'));
  3995. DBSearch::EnableQueryTrace(self::$m_oConfig->GetLogQueries());
  3996. DBSearch::EnableQueryIndentation(self::$m_oConfig->Get('query_indentation_enabled'));
  3997. DBSearch::EnableOptimizeQuery(self::$m_oConfig->Get('query_optimization_enabled'));
  3998. // PHP timezone first...
  3999. //
  4000. $sPHPTimezone = self::$m_oConfig->Get('timezone');
  4001. if ($sPHPTimezone == '')
  4002. {
  4003. // Leave as is... up to the admin to set a value somewhere...
  4004. //$sPHPTimezone = date_default_timezone_get();
  4005. }
  4006. else
  4007. {
  4008. date_default_timezone_set($sPHPTimezone);
  4009. }
  4010. // Note: load the dictionary as soon as possible, because it might be
  4011. // needed when some error occur
  4012. $sAppIdentity = 'itop-'.MetaModel::GetEnvironmentId();
  4013. $bDictInitializedFromData = false;
  4014. if (self::$m_bUseAPCCache)
  4015. {
  4016. Dict::EnableCache($sAppIdentity);
  4017. }
  4018. require_once(APPROOT.'env-'.self::$m_sEnvironment.'/dictionaries/languages.php');
  4019. // Set the default language...
  4020. Dict::SetDefaultLanguage(self::$m_oConfig->GetDefaultLanguage());
  4021. // Romain: this is the only way I've found to cope with the fact that
  4022. // classes have to be derived from cmdbabstract (to be editable in the UI)
  4023. require_once(APPROOT.'/application/cmdbabstract.class.inc.php');
  4024. require_once(APPROOT.'core/autoload.php');
  4025. require_once(APPROOT.'env-'.self::$m_sEnvironment.'/autoload.php');
  4026. foreach (self::$m_oConfig->GetAddons() as $sModule => $sToInclude)
  4027. {
  4028. self::IncludeModule($sToInclude, 'addons');
  4029. }
  4030. $sServer = self::$m_oConfig->GetDBHost();
  4031. $sUser = self::$m_oConfig->GetDBUser();
  4032. $sPwd = self::$m_oConfig->GetDBPwd();
  4033. $sSource = self::$m_oConfig->GetDBName();
  4034. $sTablePrefix = self::$m_oConfig->GetDBSubname();
  4035. $sCharacterSet = self::$m_oConfig->GetDBCharacterSet();
  4036. $sCollation = self::$m_oConfig->GetDBCollation();
  4037. if (self::$m_bUseAPCCache)
  4038. {
  4039. $oKPI = new ExecutionKPI();
  4040. // Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
  4041. //
  4042. $sOqlAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-metamodel';
  4043. $result = apc_fetch($sOqlAPCCacheId);
  4044. if (is_array($result))
  4045. {
  4046. // todo - verifier que toutes les classes mentionnees ici sont chargees dans InitClasses()
  4047. self::$m_aExtensionClasses = $result['m_aExtensionClasses'];
  4048. self::$m_Category2Class = $result['m_Category2Class'];
  4049. self::$m_aRootClasses = $result['m_aRootClasses'];
  4050. self::$m_aParentClasses = $result['m_aParentClasses'];
  4051. self::$m_aChildClasses = $result['m_aChildClasses'];
  4052. self::$m_aClassParams = $result['m_aClassParams'];
  4053. self::$m_aAttribDefs = $result['m_aAttribDefs'];
  4054. self::$m_aAttribOrigins = $result['m_aAttribOrigins'];
  4055. self::$m_aExtKeyFriends = $result['m_aExtKeyFriends'];
  4056. self::$m_aIgnoredAttributes = $result['m_aIgnoredAttributes'];
  4057. self::$m_aFilterDefs = $result['m_aFilterDefs'];
  4058. self::$m_aFilterOrigins = $result['m_aFilterOrigins'];
  4059. self::$m_aListInfos = $result['m_aListInfos'];
  4060. self::$m_aListData = $result['m_aListData'];
  4061. self::$m_aRelationInfos = $result['m_aRelationInfos'];
  4062. self::$m_aStates = $result['m_aStates'];
  4063. self::$m_aStimuli = $result['m_aStimuli'];
  4064. self::$m_aTransitions = $result['m_aTransitions'];
  4065. self::$m_aHighlightScales = $result['m_aHighlightScales'];
  4066. self::$m_aEnumToMeta = $result['m_aEnumToMeta'];
  4067. }
  4068. $oKPI->ComputeAndReport('Metamodel APC (fetch + read)');
  4069. }
  4070. if (count(self::$m_aAttribDefs) == 0)
  4071. {
  4072. // The includes have been included, let's browse the existing classes and
  4073. // develop some data based on the proposed model
  4074. $oKPI = new ExecutionKPI();
  4075. self::InitClasses($sTablePrefix);
  4076. $oKPI->ComputeAndReport('Initialization of Data model structures');
  4077. if (self::$m_bUseAPCCache)
  4078. {
  4079. $oKPI = new ExecutionKPI();
  4080. $aCache = array();
  4081. $aCache['m_aExtensionClasses'] = self::$m_aExtensionClasses;
  4082. $aCache['m_Category2Class'] = self::$m_Category2Class;
  4083. $aCache['m_aRootClasses'] = self::$m_aRootClasses; // array of "classname" => "rootclass"
  4084. $aCache['m_aParentClasses'] = self::$m_aParentClasses; // array of ("classname" => array of "parentclass")
  4085. $aCache['m_aChildClasses'] = self::$m_aChildClasses; // array of ("classname" => array of "childclass")
  4086. $aCache['m_aClassParams'] = self::$m_aClassParams; // array of ("classname" => array of class information)
  4087. $aCache['m_aAttribDefs'] = self::$m_aAttribDefs; // array of ("classname" => array of attributes)
  4088. $aCache['m_aAttribOrigins'] = self::$m_aAttribOrigins; // array of ("classname" => array of ("attcode"=>"sourceclass"))
  4089. $aCache['m_aExtKeyFriends'] = self::$m_aExtKeyFriends; // array of ("classname" => array of ("indirect ext key attcode"=> array of ("relative ext field")))
  4090. $aCache['m_aIgnoredAttributes'] = self::$m_aIgnoredAttributes; //array of ("classname" => array of ("attcode")
  4091. $aCache['m_aFilterDefs'] = self::$m_aFilterDefs; // array of ("classname" => array filterdef)
  4092. $aCache['m_aFilterOrigins'] = self::$m_aFilterOrigins; // array of ("classname" => array of ("attcode"=>"sourceclass"))
  4093. $aCache['m_aListInfos'] = self::$m_aListInfos; // array of ("listcode" => various info on the list, common to every classes)
  4094. $aCache['m_aListData'] = self::$m_aListData; // array of ("classname" => array of "listcode" => list)
  4095. $aCache['m_aRelationInfos'] = self::$m_aRelationInfos; // array of ("relcode" => various info on the list, common to every classes)
  4096. $aCache['m_aStates'] = self::$m_aStates; // array of ("classname" => array of "statecode"=>array('label'=>..., attribute_inherit=> attribute_list=>...))
  4097. $aCache['m_aStimuli'] = self::$m_aStimuli; // array of ("classname" => array of ("stimuluscode"=>array('label'=>...)))
  4098. $aCache['m_aTransitions'] = self::$m_aTransitions; // array of ("classname" => array of ("statcode_from"=>array of ("stimuluscode" => array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD)))
  4099. $aCache['m_aHighlightScales'] = self::$m_aHighlightScales; // array of ("classname" => array of higlightcodes)))
  4100. $aCache['m_aEnumToMeta'] = self::$m_aEnumToMeta;
  4101. apc_store($sOqlAPCCacheId, $aCache);
  4102. $oKPI->ComputeAndReport('Metamodel APC (store)');
  4103. }
  4104. }
  4105. self::$m_sDBName = $sSource;
  4106. self::$m_sTablePrefix = $sTablePrefix;
  4107. CMDBSource::Init($sServer, $sUser, $sPwd); // do not select the DB (could not exist)
  4108. CMDBSource::SetCharacterSet($sCharacterSet, $sCollation);
  4109. // Later when timezone implementation is correctly done: CMDBSource::SetTimezone($sDBTimezone);
  4110. }
  4111. public static function GetModuleSetting($sModule, $sProperty, $defaultvalue = null)
  4112. {
  4113. return self::$m_oConfig->GetModuleSetting($sModule, $sProperty, $defaultvalue);
  4114. }
  4115. public static function GetModuleParameter($sModule, $sProperty, $defaultvalue = null)
  4116. {
  4117. $value = $defaultvalue;
  4118. if (!array_key_exists($sModule, self::$m_aModulesParameters))
  4119. {
  4120. }
  4121. if (!self::$m_aModulesParameters[$sModule] == null)
  4122. {
  4123. $value = self::$m_aModulesParameters[$sModule]->Get($sProperty, $defaultvalue);
  4124. }
  4125. return $value;
  4126. }
  4127. public static function GetConfig()
  4128. {
  4129. return self::$m_oConfig;
  4130. }
  4131. public static function GetEnvironmentId()
  4132. {
  4133. return md5(APPROOT).'-'.self::$m_sEnvironment;
  4134. }
  4135. protected static $m_aExtensionClasses = array();
  4136. protected static function IncludeModule($sToInclude, $sModuleType = null)
  4137. {
  4138. $sFirstChar = substr($sToInclude, 0, 1);
  4139. $sSecondChar = substr($sToInclude, 1, 1);
  4140. if (($sFirstChar != '/') && ($sFirstChar != '\\') && ($sSecondChar != ':'))
  4141. {
  4142. // It is a relative path, prepend APPROOT
  4143. if (substr($sToInclude, 0, 3) == '../')
  4144. {
  4145. // Preserve compatibility with config files written before 1.0.1
  4146. // Replace '../' by '<root>/'
  4147. $sFile = APPROOT.'/'.substr($sToInclude, 3);
  4148. }
  4149. else
  4150. {
  4151. $sFile = APPROOT.'/'.$sToInclude;
  4152. }
  4153. }
  4154. else
  4155. {
  4156. // Leave as is - should be an absolute path
  4157. $sFile = $sToInclude;
  4158. }
  4159. if (!file_exists($sFile))
  4160. {
  4161. $sConfigFile = self::$m_oConfig->GetLoadedFile();
  4162. if ($sModuleType == null)
  4163. {
  4164. throw new CoreException("Include: unable to load the file '$sFile'");
  4165. }
  4166. else
  4167. {
  4168. if (strlen($sConfigFile) > 0)
  4169. {
  4170. throw new CoreException('Include: wrong file name in configuration file', array('config file' => $sConfigFile, 'section' => $sModuleType, 'filename' => $sFile));
  4171. }
  4172. else
  4173. {
  4174. // The configuration is in memory only
  4175. throw new CoreException('Include: wrong file name in configuration file (in memory)', array('section' => $sModuleType, 'filename' => $sFile));
  4176. }
  4177. }
  4178. }
  4179. // Note: We do not expect the modules to output characters while loading them.
  4180. // Therefore, and because unexpected characters can corrupt the output,
  4181. // they must be trashed here.
  4182. // Additionnaly, pages aiming at delivering data in their output can call WebPage::TrashUnexpectedOutput()
  4183. // to get rid of chars that could be generated during the execution of the code
  4184. ob_start();
  4185. require_once($sFile);
  4186. $sPreviousContent = ob_get_clean();
  4187. if (self::$m_oConfig->Get('debug_report_spurious_chars'))
  4188. {
  4189. if ($sPreviousContent != '')
  4190. {
  4191. IssueLog::Error("Spurious characters injected by '$sFile'");
  4192. }
  4193. }
  4194. }
  4195. // Building an object
  4196. //
  4197. //
  4198. private static $aQueryCacheGetObject = array();
  4199. private static $aQueryCacheGetObjectHits = array();
  4200. public static function GetQueryCacheStatus()
  4201. {
  4202. $aRes = array();
  4203. $iTotalHits = 0;
  4204. foreach(self::$aQueryCacheGetObjectHits as $sClassSign => $iHits)
  4205. {
  4206. $aRes[] = "$sClassSign: $iHits";
  4207. $iTotalHits += $iHits;
  4208. }
  4209. return $iTotalHits.' ('.implode(', ', $aRes).')';
  4210. }
  4211. public static function MakeSingleRow($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false, $aModifierProperties = null)
  4212. {
  4213. // Build the query cache signature
  4214. //
  4215. $sQuerySign = $sClass;
  4216. if($bAllowAllData)
  4217. {
  4218. $sQuerySign .= '_all_';
  4219. }
  4220. if (count($aModifierProperties))
  4221. {
  4222. array_multisort($aModifierProperties);
  4223. $sModifierProperties = json_encode($aModifierProperties);
  4224. $sQuerySign .= '_all_'.md5($sModifierProperties);
  4225. }
  4226. $sQuerySign .= utils::IsArchiveMode() ? '_arch_' : '';
  4227. if (!array_key_exists($sQuerySign, self::$aQueryCacheGetObject))
  4228. {
  4229. // NOTE: Quick and VERY dirty caching mechanism which relies on
  4230. // the fact that the string '987654321' will never appear in the
  4231. // standard query
  4232. // This could be simplified a little, relying solely on the query cache,
  4233. // but this would slow down -by how much time?- the application
  4234. $oFilter = new DBObjectSearch($sClass);
  4235. $oFilter->AddCondition('id', 987654321, '=');
  4236. if ($aModifierProperties)
  4237. {
  4238. foreach ($aModifierProperties as $sPluginClass => $aProperties)
  4239. {
  4240. foreach ($aProperties as $sProperty => $value)
  4241. {
  4242. $oFilter->SetModifierProperty($sPluginClass, $sProperty, $value);
  4243. }
  4244. }
  4245. }
  4246. if ($bAllowAllData)
  4247. {
  4248. $oFilter->AllowAllData();
  4249. }
  4250. $oFilter->NoContextParameters();
  4251. $sSQL = $oFilter->MakeSelectQuery();
  4252. self::$aQueryCacheGetObject[$sQuerySign] = $sSQL;
  4253. self::$aQueryCacheGetObjectHits[$sQuerySign] = 0;
  4254. }
  4255. else
  4256. {
  4257. $sSQL = self::$aQueryCacheGetObject[$sQuerySign];
  4258. self::$aQueryCacheGetObjectHits[$sQuerySign] += 1;
  4259. // echo " -load $sClass/$iKey- ".self::$aQueryCacheGetObjectHits[$sQuerySign]."<br/>\n";
  4260. }
  4261. $sSQL = str_replace(CMDBSource::Quote(987654321), CMDBSource::Quote($iKey), $sSQL);
  4262. $res = CMDBSource::Query($sSQL);
  4263. $aRow = CMDBSource::FetchArray($res);
  4264. CMDBSource::FreeResult($res);
  4265. if ($bMustBeFound && empty($aRow))
  4266. {
  4267. throw new CoreException("No result for the single row query: '$sSQL'");
  4268. }
  4269. return $aRow;
  4270. }
  4271. public static function GetObjectByRow($sClass, $aRow, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  4272. {
  4273. self::_check_subclass($sClass);
  4274. if (strlen($sClassAlias) == 0)
  4275. {
  4276. $sClassAlias = $sClass;
  4277. }
  4278. // Compound objects: if available, get the final object class
  4279. //
  4280. if (!array_key_exists($sClassAlias."finalclass", $aRow))
  4281. {
  4282. // Either this is a bug (forgot to specify a root class with a finalclass field
  4283. // Or this is the expected behavior, because the object is not made of several tables
  4284. }
  4285. elseif (empty($aRow[$sClassAlias."finalclass"]))
  4286. {
  4287. // The data is missing in the DB
  4288. // @#@ possible improvement: check that the class is valid !
  4289. $sRootClass = self::GetRootClass($sClass);
  4290. $sFinalClassField = self::DBGetClassField($sRootClass);
  4291. throw new CoreException("Empty class name for object $sClass::{$aRow["id"]} (root class '$sRootClass', field '{$sFinalClassField}' is empty)");
  4292. }
  4293. else
  4294. {
  4295. // do the job for the real target class
  4296. $sClass = $aRow[$sClassAlias."finalclass"];
  4297. }
  4298. return new $sClass($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
  4299. }
  4300. public static function GetObject($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false, $aModifierProperties = null)
  4301. {
  4302. self::_check_subclass($sClass);
  4303. $aRow = self::MakeSingleRow($sClass, $iKey, $bMustBeFound, $bAllowAllData, $aModifierProperties);
  4304. if (empty($aRow))
  4305. {
  4306. return null;
  4307. }
  4308. return self::GetObjectByRow($sClass, $aRow);
  4309. }
  4310. public static function GetObjectWithArchive($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false, $aModifierProperties = null)
  4311. {
  4312. utils::PushArchiveMode(true);
  4313. $oObject = static::GetObject($sClass, $iKey, $bMustBeFound, $bAllowAllData, $aModifierProperties);
  4314. utils::PopArchiveMode();
  4315. return $oObject;
  4316. }
  4317. public static function GetObjectByName($sClass, $sName, $bMustBeFound = true)
  4318. {
  4319. self::_check_subclass($sClass);
  4320. $oObjSearch = new DBObjectSearch($sClass);
  4321. $oObjSearch->AddNameCondition($sName);
  4322. $oSet = new DBObjectSet($oObjSearch);
  4323. if ($oSet->Count() != 1)
  4324. {
  4325. if ($bMustBeFound) throw new CoreException('Failed to get an object by its name', array('class'=>$sClass, 'name'=>$sName));
  4326. return null;
  4327. }
  4328. $oObj = $oSet->fetch();
  4329. return $oObj;
  4330. }
  4331. static protected $m_aCacheObjectByColumn = array();
  4332. public static function GetObjectByColumn($sClass, $sAttCode, $value, $bMustBeFoundUnique = true)
  4333. {
  4334. if (!isset(self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value]))
  4335. {
  4336. self::_check_subclass($sClass);
  4337. $oObjSearch = new DBObjectSearch($sClass);
  4338. $oObjSearch->AddCondition($sAttCode, $value, '=');
  4339. $oSet = new DBObjectSet($oObjSearch);
  4340. if ($oSet->Count() == 1)
  4341. {
  4342. self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = $oSet->fetch();
  4343. }
  4344. else
  4345. {
  4346. if ($bMustBeFoundUnique) throw new CoreException('Failed to get an object by column', array('class'=>$sClass, 'attcode'=>$sAttCode, 'value'=>$value, 'matches' => $oSet->Count()));
  4347. self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = null;
  4348. }
  4349. }
  4350. return self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value];
  4351. }
  4352. public static function GetObjectFromOQL($sQuery, $aParams = null, $bAllowAllData = false)
  4353. {
  4354. $oFilter = DBObjectSearch::FromOQL($sQuery, $aParams);
  4355. if ($bAllowAllData)
  4356. {
  4357. $oFilter->AllowAllData();
  4358. }
  4359. $oSet = new DBObjectSet($oFilter);
  4360. $oObject = $oSet->Fetch();
  4361. return $oObject;
  4362. }
  4363. public static function GetHyperLink($sTargetClass, $iKey)
  4364. {
  4365. if ($iKey < 0)
  4366. {
  4367. return "$sTargetClass: $iKey (invalid value)";
  4368. }
  4369. $oObj = self::GetObject($sTargetClass, $iKey, false);
  4370. if (is_null($oObj))
  4371. {
  4372. // Whatever we are looking for, the root class is the key to search for
  4373. $sRootClass = self::GetRootClass($sTargetClass);
  4374. $oSearch = DBObjectSearch::FromOQL('SELECT CMDBChangeOpDelete WHERE objclass = :objclass AND objkey = :objkey', array('objclass' => $sRootClass, 'objkey' => $iKey));
  4375. $oSet = new DBObjectSet($oSearch);
  4376. $oRecord = $oSet->Fetch();
  4377. // An empty fname is obtained with iTop < 2.0
  4378. if (is_null($oRecord) || (strlen(trim($oRecord->Get('fname'))) == 0))
  4379. {
  4380. $sName = Dict::Format('Core:UnknownObjectLabel', $sTargetClass, $iKey);
  4381. $sTitle = Dict::S('Core:UnknownObjectTip');
  4382. }
  4383. else
  4384. {
  4385. $sName = $oRecord->Get('fname');
  4386. $sTitle = Dict::Format('Core:DeletedObjectTip', $oRecord->Get('date'), $oRecord->Get('userinfo'));
  4387. }
  4388. return '<span class="itop-deleted-object" title="'.htmlentities($sTitle, ENT_QUOTES, 'UTF-8').'">'.htmlentities($sName, ENT_QUOTES, 'UTF-8').'</span>';
  4389. }
  4390. return $oObj->GetHyperLink();
  4391. }
  4392. public static function NewObject($sClass)
  4393. {
  4394. self::_check_subclass($sClass);
  4395. return new $sClass();
  4396. }
  4397. public static function GetNextKey($sClass)
  4398. {
  4399. $sRootClass = MetaModel::GetRootClass($sClass);
  4400. $sRootTable = MetaModel::DBGetTable($sRootClass);
  4401. $iNextKey = CMDBSource::GetNextInsertId($sRootTable);
  4402. return $iNextKey;
  4403. }
  4404. /**
  4405. * Deletion of records, bypassing DBObject::DBDelete !!!
  4406. * It is NOT recommended to use this shortcut
  4407. * In particular, it will not work
  4408. * - if the class is not a final class
  4409. * - if the class has a hierarchical key (need to rebuild the indexes)
  4410. * - if the class overload DBDelete !
  4411. * Todo: protect it against forbidden usages (in such a case, delete objects one by one)
  4412. */
  4413. public static function BulkDelete(DBObjectSearch $oFilter)
  4414. {
  4415. $sSQL = $oFilter->MakeDeleteQuery();
  4416. if (!self::DBIsReadOnly())
  4417. {
  4418. CMDBSource::Query($sSQL);
  4419. }
  4420. }
  4421. public static function BulkUpdate(DBObjectSearch $oFilter, array $aValues)
  4422. {
  4423. // $aValues is an array of $sAttCode => $value
  4424. $sSQL = $oFilter->MakeUpdateQuery($aValues);
  4425. if (!self::DBIsReadOnly())
  4426. {
  4427. CMDBSource::Query($sSQL);
  4428. }
  4429. }
  4430. /**
  4431. * Helper to remove selected objects without calling any handler
  4432. * Surpasses BulkDelete as it can handle abstract classes, but has the other limitation as it bypasses standard objects handlers
  4433. *
  4434. * @param string $oFilter Scope of objects to wipe out
  4435. * @return The count of deleted objects
  4436. */
  4437. public static function PurgeData($oFilter)
  4438. {
  4439. $sTargetClass = $oFilter->GetClass();
  4440. $oSet = new DBObjectSet($oFilter);
  4441. $oSet->OptimizeColumnLoad(array($sTargetClass => array('finalclass')));
  4442. $aIdToClass = $oSet->GetColumnAsArray('finalclass', true);
  4443. $aIds = array_keys($aIdToClass);
  4444. if (count($aIds) > 0)
  4445. {
  4446. $aQuotedIds = CMDBSource::Quote($aIds);
  4447. $sIdList = implode(',', $aQuotedIds);
  4448. $aTargetClasses = array_merge(
  4449. self::EnumChildClasses($sTargetClass, ENUM_CHILD_CLASSES_ALL),
  4450. self::EnumParentClasses($sTargetClass, ENUM_PARENT_CLASSES_EXCLUDELEAF)
  4451. );
  4452. foreach ($aTargetClasses as $sSomeClass)
  4453. {
  4454. $sTable = MetaModel::DBGetTable($sSomeClass);
  4455. $sPKField = MetaModel::DBGetKey($sSomeClass);
  4456. $sDeleteSQL = "DELETE FROM `$sTable` WHERE `$sPKField` IN ($sIdList)";
  4457. CMDBSource::DeleteFrom($sDeleteSQL);
  4458. }
  4459. }
  4460. return count($aIds);
  4461. }
  4462. // Links
  4463. //
  4464. //
  4465. public static function EnumReferencedClasses($sClass)
  4466. {
  4467. self::_check_subclass($sClass);
  4468. // 1-N links (referenced by my class), returns an array of sAttCode=>sClass
  4469. $aResult = array();
  4470. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode=>$oAttDef)
  4471. {
  4472. if ($oAttDef->IsExternalKey())
  4473. {
  4474. $aResult[$sAttCode] = $oAttDef->GetTargetClass();
  4475. }
  4476. }
  4477. return $aResult;
  4478. }
  4479. public static function EnumReferencingClasses($sClass, $bSkipLinkingClasses = false, $bInnerJoinsOnly = false)
  4480. {
  4481. self::_check_subclass($sClass);
  4482. if ($bSkipLinkingClasses)
  4483. {
  4484. $aLinksClasses = self::EnumLinksClasses();
  4485. }
  4486. // 1-N links (referencing my class), array of sClass => array of sAttcode
  4487. $aResult = array();
  4488. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  4489. {
  4490. if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses)) continue;
  4491. $aExtKeys = array();
  4492. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  4493. {
  4494. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  4495. if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass)))
  4496. {
  4497. if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed()) continue;
  4498. // Ok, I want this one
  4499. $aExtKeys[$sAttCode] = $oAttDef;
  4500. }
  4501. }
  4502. if (count($aExtKeys) != 0)
  4503. {
  4504. $aResult[$sSomeClass] = $aExtKeys;
  4505. }
  4506. }
  4507. return $aResult;
  4508. }
  4509. /**
  4510. * It is not recommended to use this function: call GetLinkClasses instead
  4511. * Return classes having at least to external keys (thus too many classes as compared to GetLinkClasses)
  4512. * The only difference with EnumLinkingClasses is the output format
  4513. */
  4514. public static function EnumLinksClasses()
  4515. {
  4516. // Returns a flat array of classes having at least two external keys
  4517. $aResult = array();
  4518. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  4519. {
  4520. $iExtKeyCount = 0;
  4521. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  4522. {
  4523. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  4524. if ($oAttDef->IsExternalKey())
  4525. {
  4526. $iExtKeyCount++;
  4527. }
  4528. }
  4529. if ($iExtKeyCount >= 2)
  4530. {
  4531. $aResult[] = $sSomeClass;
  4532. }
  4533. }
  4534. return $aResult;
  4535. }
  4536. /**
  4537. * It is not recommended to use this function: call GetLinkClasses instead
  4538. * Return classes having at least to external keys (thus too many classes as compared to GetLinkClasses)
  4539. * The only difference with EnumLinksClasses is the output format
  4540. */
  4541. public static function EnumLinkingClasses($sClass = "")
  4542. {
  4543. // N-N links, array of sLinkClass => (array of sAttCode=>sClass)
  4544. $aResult = array();
  4545. foreach (self::EnumLinksClasses() as $sSomeClass)
  4546. {
  4547. $aTargets = array();
  4548. $bFoundClass = false;
  4549. foreach (self::ListAttributeDefs($sSomeClass) as $sAttCode=>$oAttDef)
  4550. {
  4551. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  4552. if ($oAttDef->IsExternalKey())
  4553. {
  4554. $sRemoteClass = $oAttDef->GetTargetClass();
  4555. if (empty($sClass))
  4556. {
  4557. $aTargets[$sAttCode] = $sRemoteClass;
  4558. }
  4559. elseif ($sClass == $sRemoteClass)
  4560. {
  4561. $bFoundClass = true;
  4562. }
  4563. else
  4564. {
  4565. $aTargets[$sAttCode] = $sRemoteClass;
  4566. }
  4567. }
  4568. }
  4569. if (empty($sClass) || $bFoundClass)
  4570. {
  4571. $aResult[$sSomeClass] = $aTargets;
  4572. }
  4573. }
  4574. return $aResult;
  4575. }
  4576. /**
  4577. * This function has two siblings that will be soon deprecated:
  4578. * EnumLinkingClasses and EnumLinkClasses
  4579. *
  4580. * Using GetLinkClasses is the recommended way to determine if a class is
  4581. * actually an N-N relation because it is based on the decision made by the
  4582. * designer the data model
  4583. */
  4584. public static function GetLinkClasses()
  4585. {
  4586. $aRet = array();
  4587. foreach(self::GetClasses() as $sClass)
  4588. {
  4589. if (isset(self::$m_aClassParams[$sClass]["is_link"]))
  4590. {
  4591. if (self::$m_aClassParams[$sClass]["is_link"])
  4592. {
  4593. $aExtKeys = array();
  4594. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  4595. {
  4596. if ($oAttDef->IsExternalKey())
  4597. {
  4598. $aExtKeys[$sAttCode] = $oAttDef->GetTargetClass();
  4599. }
  4600. }
  4601. $aRet[$sClass] = $aExtKeys;
  4602. }
  4603. }
  4604. }
  4605. return $aRet;
  4606. }
  4607. public static function GetLinkLabel($sLinkClass, $sAttCode)
  4608. {
  4609. self::_check_subclass($sLinkClass);
  4610. // e.g. "supported by" (later: $this->GetLinkLabel(), computed on link data!)
  4611. return self::GetLabel($sLinkClass, $sAttCode);
  4612. }
  4613. /**
  4614. * Replaces all the parameters by the values passed in the hash array
  4615. */
  4616. static public function ApplyParams($sInput, $aParams)
  4617. {
  4618. // Declare magic parameters
  4619. $aParams['APP_URL'] = utils::GetAbsoluteUrlAppRoot();
  4620. $aParams['MODULES_URL'] = utils::GetAbsoluteUrlModulesRoot();
  4621. $aSearches = array();
  4622. $aReplacements = array();
  4623. foreach($aParams as $sSearch => $replace)
  4624. {
  4625. // Some environment parameters are objects, we just need scalars
  4626. if (is_object($replace))
  4627. {
  4628. $iPos = strpos($sSearch, '->object()');
  4629. if ($iPos !== false)
  4630. {
  4631. // Expand the parameters for the object
  4632. $sName = substr($sSearch, 0, $iPos);
  4633. if (preg_match_all('/\\$'.$sName.'-(>|&gt;)([^\\$]+)\\$/', $sInput, $aMatches)) // Support both syntaxes: $this->xxx$ or $this-&gt;xxx$ for HTML compatibility
  4634. {
  4635. foreach($aMatches[2] as $idx => $sPlaceholderAttCode)
  4636. {
  4637. try
  4638. {
  4639. $sReplacement = $replace->GetForTemplate($sPlaceholderAttCode);
  4640. if ($sReplacement !== null)
  4641. {
  4642. $aReplacements[] = $sReplacement;
  4643. $aSearches[] = '$'.$sName.'-'.$aMatches[1][$idx].$sPlaceholderAttCode.'$';
  4644. }
  4645. }
  4646. catch(Exception $e)
  4647. {
  4648. // No replacement will occur
  4649. }
  4650. }
  4651. }
  4652. }
  4653. else
  4654. {
  4655. continue; // Ignore this non-scalar value
  4656. }
  4657. }
  4658. else
  4659. {
  4660. $aSearches[] = '$'.$sSearch.'$';
  4661. $aReplacements[] = (string) $replace;
  4662. }
  4663. }
  4664. return str_replace($aSearches, $aReplacements, $sInput);
  4665. }
  4666. /**
  4667. * Returns an array of classes=>instance implementing the given interface
  4668. */
  4669. public static function EnumPlugins($sInterface)
  4670. {
  4671. if (array_key_exists($sInterface, self::$m_aExtensionClasses))
  4672. {
  4673. return self::$m_aExtensionClasses[$sInterface];
  4674. }
  4675. else
  4676. {
  4677. return array();
  4678. }
  4679. }
  4680. /**
  4681. * Returns the instance of the specified plug-ins for the given interface
  4682. */
  4683. public static function GetPlugins($sInterface, $sClassName)
  4684. {
  4685. $oInstance = null;
  4686. if (array_key_exists($sInterface, self::$m_aExtensionClasses))
  4687. {
  4688. if (array_key_exists($sClassName, self::$m_aExtensionClasses[$sInterface]))
  4689. {
  4690. return self::$m_aExtensionClasses[$sInterface][$sClassName];
  4691. }
  4692. }
  4693. return $oInstance;
  4694. }
  4695. public static function GetCacheEntries($sEnvironment = null)
  4696. {
  4697. if (!function_exists('apc_cache_info')) return array();
  4698. if (is_null($sEnvironment))
  4699. {
  4700. $sEnvironment = MetaModel::GetEnvironmentId();
  4701. }
  4702. $aEntries = array();
  4703. if (extension_loaded('apcu'))
  4704. {
  4705. // Beware: APCu behaves slightly differently from APC !!
  4706. $aCacheUserData = @apc_cache_info();
  4707. }
  4708. else
  4709. {
  4710. $aCacheUserData = @apc_cache_info('user');
  4711. }
  4712. if (is_array($aCacheUserData) && isset($aCacheUserData['cache_list']))
  4713. {
  4714. $sPrefix = 'itop-'.$sEnvironment.'-';
  4715. foreach($aCacheUserData['cache_list'] as $i => $aEntry)
  4716. {
  4717. $sEntryKey = array_key_exists('info', $aEntry) ? $aEntry['info'] : $aEntry['key'];
  4718. if (strpos($sEntryKey, $sPrefix) === 0)
  4719. {
  4720. $sCleanKey = substr($sEntryKey, strlen($sPrefix));
  4721. $aEntries[$sCleanKey] = $aEntry;
  4722. $aEntries[$sCleanKey]['info'] = $sEntryKey;
  4723. }
  4724. }
  4725. }
  4726. return $aEntries;
  4727. }
  4728. public static function ResetCache($sEnvironmentId = null)
  4729. {
  4730. if (!function_exists('apc_delete')) return;
  4731. if (is_null($sEnvironmentId))
  4732. {
  4733. $sEnvironmentId = MetaModel::GetEnvironmentId();
  4734. }
  4735. $sAppIdentity = 'itop-'.$sEnvironmentId;
  4736. Dict::ResetCache($sAppIdentity);
  4737. foreach(self::GetCacheEntries($sEnvironmentId) as $sKey => $aAPCInfo)
  4738. {
  4739. $sAPCKey = $aAPCInfo['info'];
  4740. apc_delete($sAPCKey);
  4741. }
  4742. }
  4743. /**
  4744. * Given a field spec, get the most relevant (unique) representation
  4745. * Examples for a user request:
  4746. * - friendlyname => ref
  4747. * - org_name => org_id->name
  4748. * - org_id_friendlyname => org_id=>name
  4749. * - caller_name => caller_id->name
  4750. * - caller_id_friendlyname => caller_id->friendlyname
  4751. * @param string $sClass
  4752. * @param string $sField
  4753. * @return string
  4754. */
  4755. public static function NormalizeFieldSpec($sClass, $sField)
  4756. {
  4757. $sRet = $sField;
  4758. if ($sField == 'id')
  4759. {
  4760. $sRet = 'id';
  4761. }
  4762. elseif ($sField == 'friendlyname')
  4763. {
  4764. $sFriendlyNameAttCode = static::GetFriendlyNameAttributeCode($sClass);
  4765. if (!is_null($sFriendlyNameAttCode))
  4766. {
  4767. // The friendly name is made of a single attribute
  4768. $sRet = $sFriendlyNameAttCode;
  4769. }
  4770. }
  4771. else
  4772. {
  4773. $oAttDef = static::GetAttributeDef($sClass, $sField);
  4774. if ($oAttDef instanceof AttributeFriendlyName)
  4775. {
  4776. $oKeyAttDef = MetaModel::GetAttributeDef($sClass, $oAttDef->GetKeyAttCode());
  4777. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  4778. $sFriendlyNameAttCode = static::GetFriendlyNameAttributeCode($sRemoteClass);
  4779. if (is_null($sFriendlyNameAttCode))
  4780. {
  4781. // The friendly name is made of several attributes
  4782. $sRet = $oAttDef->GetKeyAttCode().'->friendlyname';
  4783. }
  4784. else
  4785. {
  4786. // The friendly name is made of a single attribute
  4787. $sRet = $oAttDef->GetKeyAttCode().'->'.$sFriendlyNameAttCode;
  4788. }
  4789. }
  4790. elseif ($oAttDef->IsExternalField())
  4791. {
  4792. $sRet = $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode();
  4793. }
  4794. }
  4795. return $sRet;
  4796. }
  4797. } // class MetaModel
  4798. // Standard attribute lists
  4799. MetaModel::RegisterZList("noneditable", array("description"=>"non editable fields", "type"=>"attributes"));
  4800. MetaModel::RegisterZList("details", array("description"=>"All attributes to be displayed for the 'details' of an object", "type"=>"attributes"));
  4801. MetaModel::RegisterZList("list", array("description"=>"All attributes to be displayed for a list of objects", "type"=>"attributes"));
  4802. MetaModel::RegisterZList("preview", array("description"=>"All attributes visible in preview mode", "type"=>"attributes"));
  4803. MetaModel::RegisterZList("standard_search", array("description"=>"List of criteria for the standard search", "type"=>"filters"));
  4804. MetaModel::RegisterZList("advanced_search", array("description"=>"List of criteria for the advanced search", "type"=>"filters"));