modulediscovery.class.inc.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. <?php
  2. // Copyright (C) 2010-2012 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * ModuleDiscovery: list available modules
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. class MissingDependencyException extends Exception
  25. {
  26. public $aModulesInfo;
  27. }
  28. class ModuleDiscovery
  29. {
  30. static $m_aModuleArgs = array(
  31. 'label' => 'One line description shown during the interactive setup',
  32. 'dependencies' => 'array of module ids',
  33. 'mandatory' => 'boolean',
  34. 'visible' => 'boolean',
  35. 'datamodel' => 'array of data model files',
  36. //'dictionary' => 'array of dictionary files', // No longer mandatory, now automated
  37. 'data.struct' => 'array of structural data files',
  38. 'data.sample' => 'array of sample data files',
  39. 'doc.manual_setup' => 'url',
  40. 'doc.more_information' => 'url',
  41. );
  42. // Cache the results and the source directories
  43. protected static $m_aSearchDirs = null;
  44. protected static $m_aModules = array();
  45. protected static $m_aModuleVersionByName = array();
  46. // All the entries below are list of file paths relative to the module directory
  47. protected static $m_aFilesList = array('datamodel', 'webservice', 'dictionary', 'data.struct', 'data.sample');
  48. // ModulePath is used by AddModule to get the path of the module being included (in ListModuleFiles)
  49. protected static $m_sModulePath = null;
  50. protected static function SetModulePath($sModulePath)
  51. {
  52. self::$m_sModulePath = $sModulePath;
  53. }
  54. public static function AddModule($sFilePath, $sId, $aArgs)
  55. {
  56. if (!array_key_exists('itop_version', $aArgs))
  57. {
  58. // Assume 1.0.2
  59. $aArgs['itop_version'] = '1.0.2';
  60. }
  61. foreach (self::$m_aModuleArgs as $sArgName => $sArgDesc)
  62. {
  63. if (!array_key_exists($sArgName, $aArgs))
  64. {
  65. throw new Exception("Module '$sId': missing argument '$sArgName'");
  66. }
  67. }
  68. $aArgs['root_dir'] = dirname($sFilePath);
  69. $aArgs['module_file'] = $sFilePath;
  70. list($sModuleName, $sModuleVersion) = static::GetModuleName($sId);
  71. if ($sModuleVersion == '')
  72. {
  73. $sModuleVersion = '1.0.0';
  74. }
  75. if (array_key_exists($sModuleName, self::$m_aModuleVersionByName))
  76. {
  77. if (version_compare($sModuleVersion, self::$m_aModuleVersionByName[$sModuleName], '>'))
  78. {
  79. // Newer version, let's upgrade
  80. self::$m_aModuleVersionByName[$sModuleName] = $sModuleVersion;
  81. }
  82. else
  83. {
  84. // Older (or equal) version, let's ignore it
  85. return;
  86. }
  87. }
  88. else
  89. {
  90. // First version to be loaded for this module, remember it
  91. self::$m_aModuleVersionByName[$sModuleName] = $sModuleVersion;
  92. }
  93. self::$m_aModules[$sId] = $aArgs;
  94. foreach(self::$m_aFilesList as $sAttribute)
  95. {
  96. if (isset(self::$m_aModules[$sId][$sAttribute]))
  97. {
  98. // All the items below are list of files, that are relative to the current file
  99. // being loaded, let's update their path to store path relative to the application directory
  100. foreach(self::$m_aModules[$sId][$sAttribute] as $idx => $sRelativePath)
  101. {
  102. self::$m_aModules[$sId][$sAttribute][$idx] = self::$m_sModulePath.'/'.$sRelativePath;
  103. }
  104. }
  105. }
  106. // Populate automatically the list of dictionary files
  107. if(preg_match('|^([^/]+)|', $sId, $aMatches)) // ModuleName = everything before the first forward slash
  108. {
  109. $sModuleName = $aMatches[1];
  110. $sDir = dirname($sFilePath);
  111. if ($hDir = opendir($sDir))
  112. {
  113. while (($sFile = readdir($hDir)) !== false)
  114. {
  115. $aMatches = array();
  116. if (preg_match("/^[^\\.]+.dict.$sModuleName.php$/i", $sFile, $aMatches)) // Dictionary files named like <Lang>.dict.<ModuleName>.php are loaded automatically
  117. {
  118. self::$m_aModules[$sId]['dictionary'][] = self::$m_sModulePath.'/'.$sFile;
  119. }
  120. }
  121. closedir($hDir);
  122. }
  123. }
  124. }
  125. /**
  126. * Get the list of "discovered" modules, ordered based on their (inter) dependencies
  127. * @param bool $bAbortOnMissingDependency ...
  128. * @param hash $aModulesToLoad List of modules to search for, defaults to all if ommitted
  129. */
  130. protected static function GetModules($bAbortOnMissingDependency = false, $aModulesToLoad = null)
  131. {
  132. // Order the modules to take into account their inter-dependencies
  133. return self::OrderModulesByDependencies(self::$m_aModules, $bAbortOnMissingDependency, $aModulesToLoad);
  134. }
  135. /**
  136. * Arrange an list of modules, based on their (inter) dependencies
  137. * @param hash $aModules The list of modules to process: 'id' => $aModuleInfo
  138. * @param bool $bAbortOnMissingDependency ...
  139. * @param hash $aModulesToLoad List of modules to search for, defaults to all if ommitted
  140. * @return hash
  141. */
  142. public static function OrderModulesByDependencies($aModules, $bAbortOnMissingDependency = false, $aModulesToLoad = null)
  143. {
  144. // Order the modules to take into account their inter-dependencies
  145. $aDependencies = array();
  146. $aSelectedModules = array();
  147. foreach($aModules as $sId => $aModule)
  148. {
  149. list($sModuleName, $sModuleVersion) = self::GetModuleName($sId);
  150. if (is_null($aModulesToLoad) || in_array($sModuleName, $aModulesToLoad))
  151. {
  152. $aDependencies[$sId] = $aModule['dependencies'];
  153. $aSelectedModules[$sModuleName] = true;
  154. }
  155. }
  156. ksort($aDependencies);
  157. $aOrderedModules = array();
  158. $iLoopCount = 1;
  159. while(($iLoopCount < count($aModules)) && (count($aDependencies) > 0) )
  160. {
  161. foreach($aDependencies as $sId => $aRemainingDeps)
  162. {
  163. $bDependenciesSolved = true;
  164. foreach($aRemainingDeps as $sDepId)
  165. {
  166. if (!self::DependencyIsResolved($sDepId, $aOrderedModules, $aSelectedModules))
  167. {
  168. $bDependenciesSolved = false;
  169. }
  170. }
  171. if ($bDependenciesSolved)
  172. {
  173. $aOrderedModules[] = $sId;
  174. unset($aDependencies[$sId]);
  175. }
  176. }
  177. $iLoopCount++;
  178. }
  179. if ($bAbortOnMissingDependency && count($aDependencies) > 0)
  180. {
  181. $aModulesInfo = array();
  182. $aModuleDeps = array();
  183. foreach($aDependencies as $sId => $aDeps)
  184. {
  185. $aModule = $aModules[$sId];
  186. $aModuleDeps[] = "{$aModule['label']} (id: $sId) depends on ".implode(' + ', $aDeps);
  187. $aModulesInfo[$sId] = array('module' => $aModule, 'dependencies' => $aDeps);
  188. }
  189. $sMessage = "The following modules have unmet dependencies: ".implode(', ', $aModuleDeps);
  190. $oException = new MissingDependencyException($sMessage);
  191. $oException->aModulesInfo = $aModulesInfo;
  192. throw $oException;
  193. }
  194. // Return the ordered list, so that the dependencies are met...
  195. $aResult = array();
  196. foreach($aOrderedModules as $sId)
  197. {
  198. $aResult[$sId] = $aModules[$sId];
  199. }
  200. return $aResult;
  201. }
  202. /**
  203. * Remove the duplicate modules (i.e. modules with the same name but with a different version) from the supplied list of modules
  204. * @param hash $aModules
  205. * @return hash The ordered modules as a duplicate-free list of modules
  206. */
  207. public static function RemoveDuplicateModules($aModules)
  208. {
  209. // No longer needed, kept only for compatibility
  210. // The de-duplication is now done directly by the AddModule method
  211. return $aModules;
  212. }
  213. protected static function DependencyIsResolved($sDepString, $aOrderedModules, $aSelectedModules)
  214. {
  215. $bResult = false;
  216. $aModuleVersions = array();
  217. // Separate the module names from their version for an easier comparison later
  218. foreach($aOrderedModules as $sModuleId)
  219. {
  220. if (preg_match('|^([^/]+)/(.*)$|', $sModuleId, $aMatches))
  221. {
  222. $aModuleVersions[$aMatches[1]] = $aMatches[2];
  223. }
  224. else
  225. {
  226. // No version number found, assume 1.0.0
  227. $aModuleVersions[$sModuleId] = '1.0.0';
  228. }
  229. }
  230. if (preg_match_all('/([^\(\)&| ]+)/', $sDepString, $aMatches))
  231. {
  232. $aReplacements = array();
  233. $aPotentialPrerequisites = array();
  234. foreach($aMatches as $aMatch)
  235. {
  236. foreach($aMatch as $sModuleId)
  237. {
  238. // $sModuleId in the dependency string is made of a <name>/<optional_operator><version>
  239. // where the operator is < <= = > >= (by default >=)
  240. if(preg_match('|^([^/]+)/(<?>?=?)([^><=]+)$|', $sModuleId, $aModuleMatches))
  241. {
  242. $sModuleName = $aModuleMatches[1];
  243. $aPotentialPrerequisites[$sModuleName] = true;
  244. $sOperator = $aModuleMatches[2];
  245. if ($sOperator == '')
  246. {
  247. $sOperator = '>=';
  248. }
  249. $sExpectedVersion = $aModuleMatches[3];
  250. if (array_key_exists($sModuleName, $aModuleVersions))
  251. {
  252. // module is present, check the version
  253. $sCurrentVersion = $aModuleVersions[$sModuleName];
  254. if (version_compare($sCurrentVersion, $sExpectedVersion, $sOperator))
  255. {
  256. $aReplacements[$sModuleId] = '(true)'; // Add parentheses to protect against invalid condition causing
  257. // a function call that results in a runtime fatal error
  258. }
  259. else
  260. {
  261. $aReplacements[$sModuleId] = '(false)'; // Add parentheses to protect against invalid condition causing
  262. // a function call that results in a runtime fatal error
  263. }
  264. }
  265. else
  266. {
  267. // module is not present
  268. $aReplacements[$sModuleId] = '(false)'; // Add parentheses to protect against invalid condition causing
  269. // a function call that results in a runtime fatal error
  270. }
  271. }
  272. }
  273. }
  274. $bMissingPrerequisite = false;
  275. foreach ($aPotentialPrerequisites as $sModuleName => $void)
  276. {
  277. if (array_key_exists($sModuleName, $aSelectedModules))
  278. {
  279. // This module is actually a prerequisite
  280. if (!array_key_exists($sModuleName, $aModuleVersions))
  281. {
  282. $bMissingPrerequisite = true;
  283. }
  284. }
  285. }
  286. if ($bMissingPrerequisite)
  287. {
  288. $bResult = false;
  289. }
  290. else
  291. {
  292. $sBooleanExpr = str_replace(array_keys($aReplacements), array_values($aReplacements), $sDepString);
  293. $bOk = @eval('$bResult = '.$sBooleanExpr.'; return true;');
  294. if ($bOk == false)
  295. {
  296. SetupPage::log_warning("Eval of '$sBooleanExpr' returned false");
  297. echo "Failed to parse the boolean Expression = '$sBooleanExpr'<br/>";
  298. }
  299. }
  300. }
  301. return $bResult;
  302. }
  303. /**
  304. * Search (on the disk) for all defined iTop modules, load them and returns the list (as an array)
  305. * of the possible iTop modules to install
  306. * @param aSearchDirs Array of directories to search (absolute paths)
  307. * @param bool $bAbortOnMissingDependency ...
  308. * @param hash $aModulesToLoad List of modules to search for, defaults to all if ommitted
  309. * @return Hash A big array moduleID => ModuleData
  310. */
  311. public static function GetAvailableModules($aSearchDirs, $bAbortOnMissingDependency = false, $aModulesToLoad = null)
  312. {
  313. if (self::$m_aSearchDirs != $aSearchDirs)
  314. {
  315. self::ResetCache();
  316. }
  317. if (is_null(self::$m_aSearchDirs))
  318. {
  319. self::$m_aSearchDirs = $aSearchDirs;
  320. // Not in cache, let's scan the disk
  321. foreach($aSearchDirs as $sSearchDir)
  322. {
  323. $sLookupDir = realpath($sSearchDir);
  324. if ($sLookupDir == '')
  325. {
  326. throw new Exception("Invalid directory '$sSearchDir'");
  327. }
  328. clearstatcache();
  329. self::ListModuleFiles(basename($sSearchDir), dirname($sSearchDir));
  330. }
  331. return self::GetModules($bAbortOnMissingDependency, $aModulesToLoad);
  332. }
  333. else
  334. {
  335. // Reuse the previous results
  336. return self::GetModules($bAbortOnMissingDependency, $aModulesToLoad);
  337. }
  338. }
  339. public static function ResetCache()
  340. {
  341. self::$m_aSearchDirs = null;
  342. self::$m_aModules = array();
  343. self::$m_aModuleVersionByName = array();
  344. }
  345. /**
  346. * Helper function to interpret the name of a module
  347. * @param $sModuleId string Identifier of the module, in the form 'name/version'
  348. * @return array(name, version)
  349. */
  350. public static function GetModuleName($sModuleId)
  351. {
  352. if (preg_match('!^(.*)/(.*)$!', $sModuleId, $aMatches))
  353. {
  354. $sName = $aMatches[1];
  355. $sVersion = $aMatches[2];
  356. }
  357. else
  358. {
  359. $sName = $sModuleId;
  360. $sVersion = "";
  361. }
  362. return array($sName, $sVersion);
  363. }
  364. /**
  365. * Helper function to browse a directory and get the modules
  366. * @param $sRelDir string Directory to start from
  367. * @return array(name, version)
  368. */
  369. protected static function ListModuleFiles($sRelDir, $sRootDir)
  370. {
  371. static $iDummyClassIndex = 0;
  372. static $aDefinedClasses = array();
  373. $sDirectory = $sRootDir.'/'.$sRelDir;
  374. if ($hDir = opendir($sDirectory))
  375. {
  376. // This is the correct way to loop over the directory. (according to the documentation)
  377. while (($sFile = readdir($hDir)) !== false)
  378. {
  379. $aMatches = array();
  380. if (is_dir($sDirectory.'/'.$sFile))
  381. {
  382. if (($sFile != '.') && ($sFile != '..') && ($sFile != '.svn'))
  383. {
  384. self::ListModuleFiles($sRelDir.'/'.$sFile, $sRootDir);
  385. }
  386. }
  387. else if (preg_match('/^module\.(.*).php$/i', $sFile, $aMatches))
  388. {
  389. self::SetModulePath($sRelDir);
  390. try
  391. {
  392. $sModuleFileContents = file_get_contents($sDirectory.'/'.$sFile);
  393. $sModuleFileContents = str_replace(array('<?php', '?>'), '', $sModuleFileContents);
  394. $sModuleFileContents = str_replace('__FILE__', "'".addslashes($sDirectory.'/'.$sFile)."'", $sModuleFileContents);
  395. preg_match_all('/class ([A-Za-z0-9_]+) extends ([A-Za-z0-9_]+)/', $sModuleFileContents, $aMatches);
  396. //print_r($aMatches);
  397. $idx = 0;
  398. foreach($aMatches[1] as $sClassName)
  399. {
  400. if (class_exists($sClassName))
  401. {
  402. // rename the class inside the code to prevent a "duplicate class" declaration
  403. // and change its parent class as well so that nobody will find it and try to execute it
  404. $sModuleFileContents = str_replace($sClassName.' extends '.$aMatches[2][$idx], $sClassName.'_'.($iDummyClassIndex++).' extends DummyHandler', $sModuleFileContents);
  405. }
  406. $idx++;
  407. }
  408. $bRet = eval($sModuleFileContents);
  409. if ($bRet === false)
  410. {
  411. SetupPage::log_warning("Eval of $sRelDir/$sFile returned false");
  412. }
  413. //echo "<p>Done.</p>\n";
  414. }
  415. catch(Exception $e)
  416. {
  417. // Continue...
  418. SetupPage::log_warning("Eval of $sRelDir/$sFile caused an exception: ".$e->getMessage());
  419. }
  420. }
  421. }
  422. closedir($hDir);
  423. }
  424. else
  425. {
  426. throw new Exception("Data directory (".$sDirectory.") not found or not readable.");
  427. }
  428. }
  429. } // End of class
  430. /** Alias for backward compatibility with old module files in which
  431. * the declaration of a module invokes SetupWebPage::AddModule()
  432. * whereas the new form is ModuleDiscovery::AddModule()
  433. */
  434. class SetupWebPage extends ModuleDiscovery
  435. {
  436. // For backward compatibility with old modules...
  437. public static function log_error($sText)
  438. {
  439. SetupPage::log_error($sText);
  440. }
  441. public static function log_warning($sText)
  442. {
  443. SetupPage::log_warning($sText);
  444. }
  445. public static function log_info($sText)
  446. {
  447. SetupPage::log_info($sText);
  448. }
  449. public static function log_ok($sText)
  450. {
  451. SetupPage::log_ok($sText);
  452. }
  453. public static function log($sText)
  454. {
  455. SetupPage::log($sText);
  456. }
  457. }
  458. /** Ugly patch !!!
  459. * In order to be able to analyse / load several times
  460. * the same module file, we rename the class (to avoid duplicate class definitions)
  461. * and we make the class extends the dummy class below in order to "deactivate" completely
  462. * the class (in case some piece of code enumerate the classes derived from a well known class)
  463. * Note that this will not work if someone enumerates the classes that implement a given interface
  464. */
  465. class DummyHandler {
  466. }