modulediscovery.class.inc.php 16 KB

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