hookmanager.class.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. <?php
  2. /* Copyright (C) 2010-2016 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2010-2014 Regis Houssin <regis.houssin@capnetworks.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 <http://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. var $db;
  30. var $error;
  31. var $errors=array();
  32. // Context hookmanager was created for ('thirdpartycard', 'thirdpartydao', ...)
  33. var $contextarray=array();
  34. // Array with instantiated classes
  35. var $hooks=array();
  36. // Array result
  37. var $resArray=array();
  38. // Printable result
  39. var $resPrint='';
  40. /**
  41. * Constructor
  42. *
  43. * @param DoliDB $db Database handler
  44. */
  45. function __construct($db)
  46. {
  47. $this->db = $db;
  48. }
  49. /**
  50. * Init array $this->hooks with instantiated action controlers.
  51. * First, a hook is declared by a module by adding a constant MAIN_MODULE_MYMODULENAME_HOOKS
  52. * with value 'nameofcontext1:nameofcontext2:...' into $this->const of module descriptor file.
  53. * This makes $conf->hooks_modules loaded with an entry ('modulename'=>array(nameofcontext1,nameofcontext2,...))
  54. * When initHooks function is called, with initHooks(list_of_contexts), an array $this->hooks is defined with instance of controler
  55. * class found into file /mymodule/class/actions_mymodule.class.php (if module has declared the context as a managed context).
  56. * Then when a hook executeHooks('aMethod'...) is called, the method aMethod found into class will be executed.
  57. *
  58. * @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), ...
  59. * @return int Always 1
  60. */
  61. function initHooks($arraycontext)
  62. {
  63. global $conf;
  64. // Test if there is hooks to manage
  65. if (! is_array($conf->modules_parts['hooks']) || empty($conf->modules_parts['hooks'])) return;
  66. // For backward compatibility
  67. if (! is_array($arraycontext)) $arraycontext=array($arraycontext);
  68. $this->contextarray=array_unique(array_merge($arraycontext,$this->contextarray)); // All contexts are concatenated
  69. foreach($conf->modules_parts['hooks'] as $module => $hooks)
  70. {
  71. if ($conf->$module->enabled)
  72. {
  73. foreach($arraycontext as $context)
  74. {
  75. if (is_array($hooks)) $arrayhooks=$hooks; // New system
  76. else $arrayhooks=explode(':',$hooks); // Old system (for backward compatibility)
  77. if (in_array($context,$arrayhooks) || in_array('all',$arrayhooks)) // We instantiate action class only if hook is required
  78. {
  79. $path = '/'.$module.'/class/';
  80. $actionfile = 'actions_'.$module.'.class.php';
  81. $pathroot = '';
  82. // Include actions class overwriting hooks
  83. dol_syslog('Loading hook:' . $actionfile, LOG_INFO);
  84. $resaction=dol_include_once($path.$actionfile);
  85. if ($resaction)
  86. {
  87. $controlclassname = 'Actions'.ucfirst($module);
  88. $actionInstance = new $controlclassname($this->db);
  89. $this->hooks[$context][$module] = $actionInstance;
  90. }
  91. }
  92. }
  93. }
  94. }
  95. return 1;
  96. }
  97. /**
  98. * Execute hooks (if they were initialized) for the given method
  99. *
  100. * @param string $method Name of method hooked ('doActions', 'printSearchForm', 'showInputField', ...)
  101. * @param array $parameters Array of parameters
  102. * @param Object $object Object to use hooks on
  103. * @param string $action Action code on calling page ('create', 'edit', 'view', 'add', 'update', 'delete'...)
  104. * @return mixed For 'addreplace' hooks (doActions,formObjectOptions,pdf_xxx,...): Return 0 if we want to keep standard actions, >0 if we want to stop 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.
  105. * 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.
  106. * All types can also return some values into an array ->results that will be finaly merged into this->resArray for caller.
  107. * $this->error or this->errors are also defined by class called by this function if error.
  108. */
  109. function executeHooks($method, $parameters=false, &$object='', &$action='')
  110. {
  111. if (! is_array($this->hooks) || empty($this->hooks)) return '';
  112. $parameters['context']=join(':',$this->contextarray);
  113. //dol_syslog(get_class($this).'::executeHooks method='.$method." action=".$action." context=".$parameters['context']);
  114. // Define type of hook ('output' or 'addreplace'. 'returnvalue' is deprecated because a 'addreplace' hook can also return resPrint and resArray).
  115. $hooktype='output';
  116. if (in_array(
  117. $method,
  118. array(
  119. 'addMoreActionsButtons',
  120. 'addSearchEntry',
  121. 'addStatisticLine',
  122. 'deleteFile',
  123. 'doActions',
  124. 'formCreateThirdpartyOptions',
  125. 'formObjectOptions',
  126. 'formattachOptions',
  127. 'formBuilddocLineOptions',
  128. 'formatNotificationMessage',
  129. 'getFormMail',
  130. 'getIdProfUrl',
  131. 'getDirList',
  132. 'moveUploadedFile',
  133. 'pdf_build_address',
  134. 'pdf_writelinedesc',
  135. 'pdf_getlinenum',
  136. 'pdf_getlineref',
  137. 'pdf_getlineref_supplier',
  138. 'pdf_getlinevatrate',
  139. 'pdf_getlineupexcltax',
  140. 'pdf_getlineupwithtax',
  141. 'pdf_getlineqty',
  142. 'pdf_getlineqty_asked',
  143. 'pdf_getlineqty_shipped',
  144. 'pdf_getlineqty_keeptoship',
  145. 'pdf_getlineunit',
  146. 'pdf_getlineremisepercent',
  147. 'pdf_getlineprogress',
  148. 'pdf_getlinetotalexcltax',
  149. 'pdf_getlinetotalwithtax',
  150. 'paymentsupplierinvoices',
  151. 'printAddress',
  152. 'printSearchForm',
  153. 'printTabsHead',
  154. 'formatEvent',
  155. 'addCalendarChoice',
  156. 'printObjectLine',
  157. 'printObjectSubLine',
  158. 'createDictionaryFieldList',
  159. 'editDictionaryFieldlist',
  160. 'getFormMail',
  161. 'showLinkToObjectBlock'
  162. )
  163. )) $hooktype='addreplace';
  164. if ($method == 'insertExtraFields')
  165. {
  166. $hooktype='returnvalue'; // deprecated. TODO Remove all code with "executeHooks('insertExtraFields'" as soon as there is a trigger available.
  167. dol_syslog("Warning: The hook 'insertExtraFields' is deprecated and must not be used. Use instead trigger on CRUD event (ask it to dev team if not implemented)", LOG_WARNING);
  168. }
  169. // Loop on each hook to qualify modules that have declared context
  170. $modulealreadyexecuted=array();
  171. $resaction=0; $error=0; $result='';
  172. $this->resPrint=''; $this->resArray=array();
  173. 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
  174. {
  175. if (! empty($modules))
  176. {
  177. foreach($modules as $module => $actionclassinstance)
  178. {
  179. //print "Before hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction." result=".$result."<br>\n";
  180. // jump to next module/class if method does not exist
  181. if (! method_exists($actionclassinstance,$method)) continue;
  182. // test to avoid running twice a hook, when a module implements several active contexts
  183. if (in_array($module,$modulealreadyexecuted)) continue;
  184. dol_syslog(get_class($this).'::executeHooks a qualified hook was found for method='.$method.' module='.$module." action=".$action." context=".$context);
  185. $modulealreadyexecuted[$module]=$module; // Use the $currentcontext in method to avoid running twice
  186. // Clean class (an error may have been set from a previous call of another method for same module/hook)
  187. $actionclassinstance->error=0;
  188. $actionclassinstance->errors=array();
  189. // Add current context to avoid method execution in bad context, you can add this test in your method : eg if($currentcontext != 'formfile') return;
  190. $parameters['currentcontext'] = $context;
  191. // Hooks that must return int (hooks with type 'addreplace')
  192. if ($hooktype == 'addreplace')
  193. {
  194. dol_syslog("Call method ".$method." of class ".get_class($actionclassinstance).", module=".$module.", hooktype=".$hooktype, LOG_DEBUG);
  195. $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)
  196. if ($resaction < 0 || ! empty($actionclassinstance->error) || (! empty($actionclassinstance->errors) && count($actionclassinstance->errors) > 0))
  197. {
  198. $error++;
  199. $this->error=$actionclassinstance->error; $this->errors=array_merge($this->errors, (array) $actionclassinstance->errors);
  200. 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);
  201. }
  202. if (isset($actionclassinstance->results) && is_array($actionclassinstance->results)) $this->resArray =array_merge($this->resArray, $actionclassinstance->results);
  203. if (! empty($actionclassinstance->resprints)) $this->resPrint.=$actionclassinstance->resprints;
  204. }
  205. // Generic hooks that return a string or array (printLeftBlock, formAddObjectLine, formBuilddocOptions, ...)
  206. else
  207. {
  208. // TODO. this should be done into the method of hook by returning nothing
  209. if (is_array($parameters) && ! empty($parameters['special_code']) && $parameters['special_code'] > 3 && $parameters['special_code'] != $actionclassinstance->module_number) continue;
  210. //dol_syslog("Call method ".$method." of class ".get_class($actionclassinstance).", module=".$module.", hooktype=".$hooktype, LOG_DEBUG);
  211. $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)
  212. if (! empty($actionclassinstance->results) && is_array($actionclassinstance->results)) $this->resArray =array_merge($this->resArray, $actionclassinstance->results);
  213. if (! empty($actionclassinstance->resprints)) $this->resPrint.=$actionclassinstance->resprints;
  214. // TODO dead code to remove (do not enable this, but fix hook instead): result must not be a string. we must use $actionclassinstance->resprints to return a string
  215. if (! is_array($resaction) && ! is_numeric($resaction))
  216. {
  217. 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);
  218. if (empty($actionclassinstance->resprints)) { $this->resPrint.=$resaction; $resaction=0; }
  219. }
  220. }
  221. //print "After hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction." result=".$result."<br>\n";
  222. unset($actionclassinstance->results);
  223. unset($actionclassinstance->resprints);
  224. }
  225. }
  226. }
  227. return ($error?-1:$resaction);
  228. }
  229. }