metamodel.class.php 163 KB

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