modulediscovery.class.inc.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. }
  27. class ModuleDiscovery
  28. {
  29. static $m_aModuleArgs = array(
  30. 'label' => 'One line description shown during the interactive setup',
  31. 'dependencies' => 'array of module ids',
  32. 'mandatory' => 'boolean',
  33. 'visible' => 'boolean',
  34. 'datamodel' => 'array of data model files',
  35. //'dictionary' => 'array of dictionary files', // No longer mandatory, now automated
  36. 'data.struct' => 'array of structural data files',
  37. 'data.sample' => 'array of sample data files',
  38. 'doc.manual_setup' => 'url',
  39. 'doc.more_information' => 'url',
  40. );
  41. // Cache the results and the source directories
  42. protected static $m_aSearchDirs = null;
  43. protected static $m_aModules = array();
  44. // All the entries below are list of file paths relative to the module directory
  45. protected static $m_aFilesList = array('datamodel', 'webservice', 'dictionary', 'data.struct', 'data.sample');
  46. // ModulePath is used by AddModule to get the path of the module being included (in ListModuleFiles)
  47. protected static $m_sModulePath = null;
  48. protected static function SetModulePath($sModulePath)
  49. {
  50. self::$m_sModulePath = $sModulePath;
  51. }
  52. public static function AddModule($sFilePath, $sId, $aArgs)
  53. {
  54. if (!array_key_exists('itop_version', $aArgs))
  55. {
  56. // Assume 1.0.2
  57. $aArgs['itop_version'] = '1.0.2';
  58. }
  59. foreach (self::$m_aModuleArgs as $sArgName => $sArgDesc)
  60. {
  61. if (!array_key_exists($sArgName, $aArgs))
  62. {
  63. throw new Exception("Module '$sId': missing argument '$sArgName'");
  64. }
  65. }
  66. $aArgs['root_dir'] = dirname($sFilePath);
  67. $aArgs['module_file'] = $sFilePath;
  68. self::$m_aModules[$sId] = $aArgs;
  69. foreach(self::$m_aFilesList as $sAttribute)
  70. {
  71. if (isset(self::$m_aModules[$sId][$sAttribute]))
  72. {
  73. // All the items below are list of files, that are relative to the current file
  74. // being loaded, let's update their path to store path relative to the application directory
  75. foreach(self::$m_aModules[$sId][$sAttribute] as $idx => $sRelativePath)
  76. {
  77. self::$m_aModules[$sId][$sAttribute][$idx] = self::$m_sModulePath.'/'.$sRelativePath;
  78. }
  79. }
  80. }
  81. // Populate automatically the list of dictionary files
  82. if(preg_match('|^([^/]+)|', $sId, $aMatches)) // ModuleName = everything before the first forward slash
  83. {
  84. $sModuleName = $aMatches[1];
  85. $sDir = dirname($sFilePath);
  86. if ($hDir = opendir($sDir))
  87. {
  88. while (($sFile = readdir($hDir)) !== false)
  89. {
  90. $aMatches = array();
  91. if (preg_match("/^[^\\.]+.dict.$sModuleName.php$/i", $sFile, $aMatches)) // Dictionary files named like <Lang>.dict.<ModuleName>.php are loaded automatically
  92. {
  93. self::$m_aModules[$sId]['dictionary'][] = self::$m_sModulePath.'/'.$sFile;
  94. }
  95. }
  96. closedir($hDir);
  97. }
  98. }
  99. }
  100. /**
  101. *
  102. * @param bool $bAbortOnMissingDependency ...
  103. * @param hash $aModulesToLoad List of modules to search for, defaults to all if ommitted
  104. */
  105. protected static function GetModules($bAbortOnMissingDependency = false, $aModulesToLoad = null)
  106. {
  107. // Order the modules to take into account their inter-dependencies
  108. $aDependencies = array();
  109. foreach(self::$m_aModules as $sId => $aModule)
  110. {
  111. list($sModuleName, $sModuleVersion) = self::GetModuleName($sId);
  112. if (is_null($aModulesToLoad) || in_array($sModuleName, $aModulesToLoad))
  113. {
  114. $aDependencies[$sId] = $aModule['dependencies'];
  115. }
  116. }
  117. ksort($aDependencies);
  118. $aOrderedModules = array();
  119. $iLoopCount = 1;
  120. while(($iLoopCount < count(self::$m_aModules)) && (count($aDependencies) > 0) )
  121. {
  122. foreach($aDependencies as $sId => $aRemainingDeps)
  123. {
  124. $bDependenciesSolved = true;
  125. foreach($aRemainingDeps as $sDepId)
  126. {
  127. if (!self::DependencyIsResolved($sDepId, $aOrderedModules))
  128. {
  129. $bDependenciesSolved = false;
  130. }
  131. }
  132. if ($bDependenciesSolved)
  133. {
  134. $aOrderedModules[] = $sId;
  135. unset($aDependencies[$sId]);
  136. }
  137. }
  138. $iLoopCount++;
  139. }
  140. if ($bAbortOnMissingDependency && count($aDependencies) > 0)
  141. {
  142. $aModuleDeps = array();
  143. foreach($aDependencies as $sId => $aDeps)
  144. {
  145. $aModule = self::$m_aModules[$sId];
  146. $aModuleDeps[] = "{$aModule['label']} (id: $sId) depends on ".implode(' + ', $aDeps);
  147. }
  148. $sMessage = "The following modules have unmet dependencies: ".implode(', ', $aModuleDeps);
  149. throw new MissingDependencyException($sMessage);
  150. }
  151. // Return the ordered list, so that the dependencies are met...
  152. $aResult = array();
  153. foreach($aOrderedModules as $sId)
  154. {
  155. $aResult[$sId] = self::$m_aModules[$sId];
  156. }
  157. return $aResult;
  158. }
  159. protected static function DependencyIsResolved($sDepString, $aOrderedModules)
  160. {
  161. $bResult = false;
  162. $aModuleVersions = array();
  163. // Separate the module names from their version for an easier comparison later
  164. foreach($aOrderedModules as $sModuleId)
  165. {
  166. if (preg_match('|^([^/]+)/(.*)$|', $sModuleId, $aMatches))
  167. {
  168. $aModuleVersions[$aMatches[1]] = $aMatches[2];
  169. }
  170. else
  171. {
  172. // No version number found, assume 1.0.0
  173. $aModuleVersions[$sModuleId] = '1.0.0';
  174. }
  175. }
  176. if (preg_match_all('/([^\(\)&| ]+)/', $sDepString, $aMatches))
  177. {
  178. $aReplacements = array();
  179. foreach($aMatches as $aMatch)
  180. {
  181. foreach($aMatch as $sModuleId)
  182. {
  183. // $sModuleId in the dependency string is made of a <name>/<optional_operator><version>
  184. // where the operator is < <= = > >= (by default >=)
  185. if(preg_match('|^([^/]+)/(<?>?=?)([^><=]+)$|', $sModuleId, $aModuleMatches))
  186. {
  187. $sModuleName = $aModuleMatches[1];
  188. $sOperator = $aModuleMatches[2];
  189. if ($sOperator == '')
  190. {
  191. $sOperator = '>=';
  192. }
  193. $sExpectedVersion = $aModuleMatches[3];
  194. if (array_key_exists($sModuleName, $aModuleVersions))
  195. {
  196. // module is present, check the version
  197. $sCurrentVersion = $aModuleVersions[$sModuleName];
  198. if (version_compare($sCurrentVersion, $sExpectedVersion, $sOperator))
  199. {
  200. $aReplacements[$sModuleId] = '(true)'; // Add parentheses to protect against invalid condition causing
  201. // a function call that results in a runtime fatal error
  202. }
  203. else
  204. {
  205. $aReplacements[$sModuleId] = '(false)'; // Add parentheses to protect against invalid condition causing
  206. // a function call that results in a runtime fatal error
  207. }
  208. }
  209. else
  210. {
  211. // module is not present
  212. $aReplacements[$sModuleId] = '(false)'; // Add parentheses to protect against invalid condition causing
  213. // a function call that results in a runtime fatal error
  214. }
  215. }
  216. }
  217. }
  218. $sBooleanExpr = str_replace(array_keys($aReplacements), array_values($aReplacements), $sDepString);
  219. $bOk = @eval('$bResult = '.$sBooleanExpr.'; return true;');
  220. if($bOk == false)
  221. {
  222. SetupPage::log_warning("Eval of $sRelDir/$sFile returned false");
  223. echo "Failed to parse the boolean Expression = '$sBooleanExpr'<br/>";
  224. }
  225. }
  226. return $bResult;
  227. }
  228. /**
  229. * Search (on the disk) for all defined iTop modules, load them and returns the list (as an array)
  230. * of the possible iTop modules to install
  231. * @param aSearchDirs Array of directories to search (absolute paths)
  232. * @param bool $bAbortOnMissingDependency ...
  233. * @param hash $aModulesToLoad List of modules to search for, defaults to all if ommitted
  234. * @return Hash A big array moduleID => ModuleData
  235. */
  236. public static function GetAvailableModules($aSearchDirs, $bAbortOnMissingDependency = false, $aModulesToLoad = null)
  237. {
  238. if (self::$m_aSearchDirs != $aSearchDirs)
  239. {
  240. self::ResetCache();
  241. }
  242. if (is_null(self::$m_aSearchDirs))
  243. {
  244. self::$m_aSearchDirs = $aSearchDirs;
  245. // Not in cache, let's scan the disk
  246. foreach($aSearchDirs as $sSearchDir)
  247. {
  248. $sLookupDir = realpath($sSearchDir);
  249. if ($sLookupDir == '')
  250. {
  251. throw new Exception("Invalid directory '$sSearchDir'");
  252. }
  253. clearstatcache();
  254. self::ListModuleFiles(basename($sSearchDir), dirname($sSearchDir));
  255. }
  256. return self::GetModules($bAbortOnMissingDependency, $aModulesToLoad);
  257. }
  258. else
  259. {
  260. // Reuse the previous results
  261. return self::GetModules($bAbortOnMissingDependency, $aModulesToLoad);
  262. }
  263. }
  264. public static function ResetCache()
  265. {
  266. self::$m_aSearchDirs = null;
  267. self::$m_aModules = array();
  268. }
  269. /**
  270. * Helper function to interpret the name of a module
  271. * @param $sModuleId string Identifier of the module, in the form 'name/version'
  272. * @return array(name, version)
  273. */
  274. public static function GetModuleName($sModuleId)
  275. {
  276. if (preg_match('!^(.*)/(.*)$!', $sModuleId, $aMatches))
  277. {
  278. $sName = $aMatches[1];
  279. $sVersion = $aMatches[2];
  280. }
  281. else
  282. {
  283. $sName = $sModuleId;
  284. $sVersion = "";
  285. }
  286. return array($sName, $sVersion);
  287. }
  288. /**
  289. * Helper function to browse a directory and get the modules
  290. * @param $sRelDir string Directory to start from
  291. * @return array(name, version)
  292. */
  293. protected static function ListModuleFiles($sRelDir, $sRootDir)
  294. {
  295. static $iDummyClassIndex = 0;
  296. static $aDefinedClasses = array();
  297. $sDirectory = $sRootDir.'/'.$sRelDir;
  298. if ($hDir = opendir($sDirectory))
  299. {
  300. // This is the correct way to loop over the directory. (according to the documentation)
  301. while (($sFile = readdir($hDir)) !== false)
  302. {
  303. $aMatches = array();
  304. if (is_dir($sDirectory.'/'.$sFile))
  305. {
  306. if (($sFile != '.') && ($sFile != '..') && ($sFile != '.svn'))
  307. {
  308. self::ListModuleFiles($sRelDir.'/'.$sFile, $sRootDir);
  309. }
  310. }
  311. else if (preg_match('/^module\.(.*).php$/i', $sFile, $aMatches))
  312. {
  313. self::SetModulePath($sRelDir);
  314. try
  315. {
  316. $sModuleFileContents = file_get_contents($sDirectory.'/'.$sFile);
  317. $sModuleFileContents = str_replace(array('<?php', '?>'), '', $sModuleFileContents);
  318. $sModuleFileContents = str_replace('__FILE__', "'".addslashes($sDirectory.'/'.$sFile)."'", $sModuleFileContents);
  319. preg_match_all('/class ([A-Za-z0-9_]+) extends ([A-Za-z0-9_]+)/', $sModuleFileContents, $aMatches);
  320. //print_r($aMatches);
  321. $idx = 0;
  322. foreach($aMatches[1] as $sClassName)
  323. {
  324. if (class_exists($sClassName))
  325. {
  326. // rename the class inside the code to prevent a "duplicate class" declaration
  327. // and change its parent class as well so that nobody will find it and try to execute it
  328. $sModuleFileContents = str_replace($sClassName.' extends '.$aMatches[2][$idx], $sClassName.'_'.($iDummyClassIndex++).' extends DummyHandler', $sModuleFileContents);
  329. }
  330. $idx++;
  331. }
  332. $bRet = eval($sModuleFileContents);
  333. if ($bRet === false)
  334. {
  335. SetupPage::log_warning("Eval of $sRelDir/$sFile returned false");
  336. }
  337. //echo "<p>Done.</p>\n";
  338. }
  339. catch(Exception $e)
  340. {
  341. // Continue...
  342. SetupPage::log_warning("Eval of $sRelDir/$sFile caused an exception: ".$e->getMessage());
  343. }
  344. }
  345. }
  346. closedir($hDir);
  347. }
  348. else
  349. {
  350. throw new Exception("Data directory (".$sDirectory.") not found or not readable.");
  351. }
  352. }
  353. } // End of class
  354. /** Alias for backward compatibility with old module files in which
  355. * the declaration of a module invokes SetupWebPage::AddModule()
  356. * whereas the new form is ModuleDiscovery::AddModule()
  357. */
  358. class SetupWebPage extends ModuleDiscovery
  359. {
  360. // For backward compatibility with old modules...
  361. public static function log_error($sText)
  362. {
  363. SetupPage::log_error($sText);
  364. }
  365. public static function log_warning($sText)
  366. {
  367. SetupPage::log_warning($sText);
  368. }
  369. public static function log_info($sText)
  370. {
  371. SetupPage::log_info($sText);
  372. }
  373. public static function log_ok($sText)
  374. {
  375. SetupPage::log_ok($sText);
  376. }
  377. public static function log($sText)
  378. {
  379. SetupPage::log($sText);
  380. }
  381. }
  382. /** Ugly patch !!!
  383. * In order to be able to analyse / load several times
  384. * the same module file, we rename the class (to avoid duplicate class definitions)
  385. * and we make the class extends the dummy class below in order to "deactivate" completely
  386. * the class (in case some piece of code enumerate the classes derived from a well known class)
  387. * Note that this will not work if someone enumerates the classes that implement a given interface
  388. */
  389. class DummyHandler {
  390. }