PageRenderTime 32ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/htdocs/core/class/hookmanager.class.php

http://github.com/Dolibarr/dolibarr
PHP | 346 lines | 218 code | 40 blank | 88 comment | 48 complexity | f7162380d4db0013da341f76dda81ed9 MD5 | raw file
Possible License(s): GPL-2.0, AGPL-3.0, LGPL-2.0, CC-BY-SA-4.0, BSD-3-Clause, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, MIT
  1. <?php
  2. /* Copyright (C) 2010-2016 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2010-2014 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2010-2011 Juanjo Menent <jmenent@2byte.es>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU 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. * This program 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 General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. /**
  20. * \file htdocs/core/class/hookmanager.class.php
  21. * \ingroup core
  22. * \brief File of class to manage hooks
  23. */
  24. /**
  25. * Class to manage hooks
  26. */
  27. class HookManager
  28. {
  29. /**
  30. * @var DoliDB Database handler.
  31. */
  32. public $db;
  33. /**
  34. * @var string Error code (or message)
  35. */
  36. public $error = '';
  37. /**
  38. * @var string[] Error codes (or messages)
  39. */
  40. public $errors = array();
  41. // Context hookmanager was created for ('thirdpartycard', 'thirdpartydao', ...)
  42. public $contextarray = array();
  43. // Array with instantiated classes
  44. public $hooks = array();
  45. // Array result
  46. public $resArray = array();
  47. // Printable result
  48. public $resPrint = '';
  49. // Nb of qualified hook ran
  50. public $resNbOfHooks = 0;
  51. /**
  52. * Constructor
  53. *
  54. * @param DoliDB $db Database handler
  55. */
  56. public function __construct($db)
  57. {
  58. $this->db = $db;
  59. }
  60. /**
  61. * Init array $this->hooks with instantiated action controlers.
  62. * First, a hook is declared by a module by adding a constant MAIN_MODULE_MYMODULENAME_HOOKS with value 'nameofcontext1:nameofcontext2:...' into $this->const of module descriptor file.
  63. * This makes $conf->hooks_modules loaded with an entry ('modulename'=>array(nameofcontext1,nameofcontext2,...))
  64. * When initHooks function is called, with initHooks(list_of_contexts), an array $this->hooks is defined with instance of controler
  65. * class found into file /mymodule/class/actions_mymodule.class.php (if module has declared the context as a managed context).
  66. * Then when a hook executeHooks('aMethod'...) is called, the method aMethod found into class will be executed.
  67. *
  68. * @param string[] $arraycontext Array list of searched hooks tab/features. For example: 'thirdpartycard' (for hook methods into page card thirdparty), 'thirdpartydao' (for hook methods into Societe), ...
  69. * @return int Always 1
  70. */
  71. public function initHooks($arraycontext)
  72. {
  73. global $conf;
  74. // Test if there is hooks to manage
  75. if (!is_array($conf->modules_parts['hooks']) || empty($conf->modules_parts['hooks'])) {
  76. return;
  77. }
  78. // For backward compatibility
  79. if (!is_array($arraycontext)) {
  80. $arraycontext = array($arraycontext);
  81. }
  82. $this->contextarray = array_unique(array_merge($arraycontext, $this->contextarray)); // All contexts are concatenated
  83. $arraytolog = array();
  84. foreach ($conf->modules_parts['hooks'] as $module => $hooks) { // Loop on each module that brings hooks
  85. if (empty($conf->$module->enabled)) {
  86. continue;
  87. }
  88. //dol_syslog(get_class($this).'::initHooks module='.$module.' arraycontext='.join(',',$arraycontext));
  89. foreach ($arraycontext as $context) {
  90. if (is_array($hooks)) {
  91. $arrayhooks = $hooks; // New system
  92. } else {
  93. $arrayhooks = explode(':', $hooks); // Old system (for backward compatibility)
  94. }
  95. if (in_array($context, $arrayhooks) || in_array('all', $arrayhooks)) { // We instantiate action class only if initialized hook is handled by module
  96. // Include actions class overwriting hooks
  97. if (empty($this->hooks[$context][$module]) || !is_object($this->hooks[$context][$module])) { // If set to an object value, class was already loaded
  98. $path = '/'.$module.'/class/';
  99. $actionfile = 'actions_'.$module.'.class.php';
  100. $arraytolog[] = 'context='.$context.'-path='.$path.$actionfile;
  101. $resaction = dol_include_once($path.$actionfile);
  102. if ($resaction) {
  103. $controlclassname = 'Actions'.ucfirst($module);
  104. $actionInstance = new $controlclassname($this->db);
  105. $priority = empty($actionInstance->priority) ? 50 : $actionInstance->priority;
  106. $this->hooks[$context][$priority.':'.$module] = $actionInstance;
  107. }
  108. }
  109. }
  110. }
  111. }
  112. if (count($arraytolog) > 0) {
  113. dol_syslog(get_class($this)."::initHooks Loading hooks: ".join(', ', $arraytolog), LOG_DEBUG);
  114. }
  115. if (!empty($this->hooks[$context])) {
  116. ksort($this->hooks[$context], SORT_NATURAL);
  117. }
  118. return 1;
  119. }
  120. /**
  121. * Execute hooks (if they were initialized) for the given method
  122. *
  123. * @param string $method Name of method hooked ('doActions', 'printSearchForm', 'showInputField', ...)
  124. * @param array $parameters Array of parameters
  125. * @param Object $object Object to use hooks on
  126. * @param string $action Action code on calling page ('create', 'edit', 'view', 'add', 'update', 'delete'...)
  127. * @return mixed For 'addreplace' hooks (doActions, formConfirm, formObjectOptions, pdf_xxx,...): Return 0 if we want to keep standard actions, >0 if we want to stop/replace standard actions, <0 if KO. Things to print are returned into ->resprints and set into ->resPrint. Things to return are returned into ->results by hook and set into ->resArray for caller.
  128. * For 'output' hooks (printLeftBlock, formAddObjectLine, formBuilddocOptions, ...): Return 0, <0 if KO. Things to print are returned into ->resprints and set into ->resPrint. Things to return are returned into ->results by hook and set into ->resArray for caller.
  129. * All types can also return some values into an array ->results that will be finaly merged into this->resArray for caller.
  130. * $this->error or this->errors are also defined by class called by this function if error.
  131. */
  132. public function executeHooks($method, $parameters = array(), &$object = '', &$action = '')
  133. {
  134. if (!is_array($this->hooks) || empty($this->hooks)) {
  135. return 0; // No hook available, do nothing.
  136. }
  137. $parameters['context'] = join(':', $this->contextarray);
  138. //dol_syslog(get_class($this).'::executeHooks method='.$method." action=".$action." context=".$parameters['context']);
  139. // Define type of hook ('output' or 'addreplace').
  140. // TODO Remove hooks with type 'output' (exemple getNomUrl). All hooks must be converted into 'addreplace' hooks.
  141. $hooktype = 'output';
  142. if (in_array(
  143. $method,
  144. array(
  145. 'addCalendarChoice',
  146. 'addCalendarView',
  147. 'addMoreActionsButtons',
  148. 'addMoreMassActions',
  149. 'addSearchEntry',
  150. 'addStatisticLine',
  151. 'addSectionECMAuto',
  152. 'checkSecureAccess',
  153. 'createDictionaryFieldlist',
  154. 'editDictionaryFieldlist',
  155. 'getFormMail',
  156. 'deleteFile',
  157. 'doActions',
  158. 'doMassActions',
  159. 'formatEvent',
  160. 'formConfirm',
  161. 'formCreateThirdpartyOptions',
  162. 'formObjectOptions',
  163. 'formattachOptions',
  164. 'formBuilddocLineOptions',
  165. 'formatNotificationMessage',
  166. 'formConfirm',
  167. 'getAccessForbiddenMessage',
  168. 'getDirList',
  169. 'hookGetEntity',
  170. 'getFormMail',
  171. 'getFormatedCustomerRef',
  172. 'getFormatedSupplierRef',
  173. 'getIdProfUrl',
  174. 'getInputIdProf',
  175. 'menuLeftMenuItems',
  176. 'moveUploadedFile',
  177. 'moreHtmlStatus',
  178. 'pdf_build_address',
  179. 'pdf_writelinedesc',
  180. 'pdf_getlinenum',
  181. 'pdf_getlineref',
  182. 'pdf_getlineref_supplier',
  183. 'pdf_getlinevatrate',
  184. 'pdf_getlineupexcltax',
  185. 'pdf_getlineupwithtax',
  186. 'pdf_getlineqty',
  187. 'pdf_getlineqty_asked',
  188. 'pdf_getlineqty_shipped',
  189. 'pdf_getlineqty_keeptoship',
  190. 'pdf_getlineunit',
  191. 'pdf_getlineremisepercent',
  192. 'pdf_getlineprogress',
  193. 'pdf_getlinetotalexcltax',
  194. 'pdf_getlinetotalwithtax',
  195. 'paymentsupplierinvoices',
  196. 'printAddress',
  197. 'printEmail',
  198. 'printSearchForm',
  199. 'printTabsHead',
  200. 'printObjectLine',
  201. 'printObjectSubLine',
  202. 'restrictedArea',
  203. 'sendMail',
  204. 'sendMailAfter',
  205. 'showOptionals',
  206. 'showLinkToObjectBlock',
  207. 'setContentSecurityPolicy',
  208. 'setHtmlTitle',
  209. 'completeTabsHead',
  210. 'formDolBanner'
  211. )
  212. )) {
  213. $hooktype = 'addreplace';
  214. }
  215. // Init return properties
  216. $this->resPrint = '';
  217. $this->resArray = array();
  218. $this->resNbOfHooks = 0;
  219. // Loop on each hook to qualify modules that have declared context
  220. $modulealreadyexecuted = array();
  221. $resaction = 0;
  222. $error = 0;
  223. foreach ($this->hooks as $context => $modules) { // $this->hooks is an array with context as key and value is an array of modules that handle this context
  224. if (!empty($modules)) {
  225. // Loop on each active hooks of module for this context
  226. foreach ($modules as $module => $actionclassinstance) {
  227. $module = preg_replace('/^\d+:/', '', $module);
  228. //print "Before hook ".get_class($actionclassinstance)." method=".$method." module=".$module." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction."<br>\n";
  229. // test to avoid running twice a hook, when a module implements several active contexts
  230. if (in_array($module, $modulealreadyexecuted)) {
  231. continue;
  232. }
  233. // jump to next module/class if method does not exist
  234. if (!method_exists($actionclassinstance, $method)) {
  235. continue;
  236. }
  237. $this->resNbOfHooks++;
  238. $modulealreadyexecuted[$module] = $module; // Use the $currentcontext in method to avoid running twice
  239. // Clean class (an error may have been set from a previous call of another method for same module/hook)
  240. $actionclassinstance->error = 0;
  241. $actionclassinstance->errors = array();
  242. dol_syslog(get_class($this)."::executeHooks Qualified hook found (hooktype=".$hooktype."). We call method ".get_class($actionclassinstance).'->'.$method.", context=".$context.", module=".$module.", action=".$action.((is_object($object) && property_exists($object, 'id')) ? ', object id='.$object->id : '').((is_object($object) && property_exists($object, 'element')) ? ', object element='.$object->element : ''), LOG_DEBUG);
  243. // Add current context to avoid method execution in bad context, you can add this test in your method : eg if($currentcontext != 'formfile') return;
  244. $parameters['currentcontext'] = $context;
  245. // Hooks that must return int (hooks with type 'addreplace')
  246. if ($hooktype == 'addreplace') {
  247. $resactiontmp = $actionclassinstance->$method($parameters, $object, $action, $this); // $object and $action can be changed by method ($object->id during creation for example or $action to go back to other action for example)
  248. $resaction += $resactiontmp;
  249. if ($resactiontmp < 0 || !empty($actionclassinstance->error) || (!empty($actionclassinstance->errors) && count($actionclassinstance->errors) > 0)) {
  250. $error++;
  251. $this->error = $actionclassinstance->error;
  252. $this->errors = array_merge($this->errors, (array) $actionclassinstance->errors);
  253. dol_syslog("Error on hook module=".$module.", method ".$method.", class ".get_class($actionclassinstance).", hooktype=".$hooktype.(empty($this->error) ? '' : " ".$this->error).(empty($this->errors) ? '' : " ".join(",", $this->errors)), LOG_ERR);
  254. }
  255. if (isset($actionclassinstance->results) && is_array($actionclassinstance->results)) {
  256. if ($resactiontmp > 0) {
  257. $this->resArray = $actionclassinstance->results;
  258. } else {
  259. $this->resArray = array_merge($this->resArray, $actionclassinstance->results);
  260. }
  261. }
  262. if (!empty($actionclassinstance->resprints)) {
  263. if ($resactiontmp > 0) {
  264. $this->resPrint = $actionclassinstance->resprints;
  265. } else {
  266. $this->resPrint .= $actionclassinstance->resprints;
  267. }
  268. }
  269. } else {
  270. // Generic hooks that return a string or array (printLeftBlock, formAddObjectLine, formBuilddocOptions, ...)
  271. // TODO. this test should be done into the method of hook by returning nothing
  272. if (is_array($parameters) && !empty($parameters['special_code']) && $parameters['special_code'] > 3 && $parameters['special_code'] != $actionclassinstance->module_number) {
  273. continue;
  274. }
  275. //dol_syslog("Call method ".$method." of class ".get_class($actionclassinstance).", module=".$module.", hooktype=".$hooktype, LOG_DEBUG);
  276. $resaction = $actionclassinstance->$method($parameters, $object, $action, $this); // $object and $action can be changed by method ($object->id during creation for example or $action to go back to other action for example)
  277. if (!empty($actionclassinstance->results) && is_array($actionclassinstance->results)) {
  278. $this->resArray = array_merge($this->resArray, $actionclassinstance->results);
  279. }
  280. if (!empty($actionclassinstance->resprints)) {
  281. $this->resPrint .= $actionclassinstance->resprints;
  282. }
  283. if (is_numeric($resaction) && $resaction < 0) {
  284. $error++;
  285. $this->error = $actionclassinstance->error;
  286. $this->errors = array_merge($this->errors, (array) $actionclassinstance->errors);
  287. dol_syslog("Error on hook module=".$module.", method ".$method.", class ".get_class($actionclassinstance).", hooktype=".$hooktype.(empty($this->error) ? '' : " ".$this->error).(empty($this->errors) ? '' : " ".join(",", $this->errors)), LOG_ERR);
  288. }
  289. // TODO dead code to remove (do not enable this, but fix hook instead): result must not be a string but an int. you must use $actionclassinstance->resprints to return a string
  290. if (!is_array($resaction) && !is_numeric($resaction)) {
  291. dol_syslog('Error: Bug into hook '.$method.' of module class '.get_class($actionclassinstance).'. Method must not return a string but an int (0=OK, 1=Replace, -1=KO) and set string into ->resprints', LOG_ERR);
  292. if (empty($actionclassinstance->resprints)) {
  293. $this->resPrint .= $resaction;
  294. $resaction = 0;
  295. }
  296. }
  297. }
  298. //print "After hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction."<br>\n";
  299. unset($actionclassinstance->results);
  300. unset($actionclassinstance->resprints);
  301. }
  302. }
  303. }
  304. return ($error ? -1 : $resaction);
  305. }
  306. }