modulediscovery.class.inc.php 16 KB

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