metamodel.class.php 139 KB

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