modulediscovery.class.inc.php 10 KB

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