modulediscovery.class.inc.php 10 KB

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