transaction.class.inc.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. <?php
  2. // Copyright (C) 2010-2015 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. * This class records the pending "transactions" corresponding to forms that have not been
  20. * submitted yet, in order to prevent double submissions. When created a transaction remains valid
  21. * until the user's session expires. This class is actually a wrapper to the underlying implementation
  22. * which choice is configured via the parameter 'transaction_storage'
  23. *
  24. * @package iTop
  25. * @copyright Copyright (C) 2010-2012 Combodo SARL
  26. * @license http://opensource.org/licenses/AGPL-3.0
  27. */
  28. class privUITransaction
  29. {
  30. /**
  31. * Create a new transaction id, store it in the session and return its id
  32. * @param void
  33. * @return int The identifier of the new transaction
  34. */
  35. public static function GetNewTransactionId()
  36. {
  37. $sClass = 'privUITransaction'.MetaModel::GetConfig()->Get('transaction_storage');
  38. if (!class_exists($sClass, false))
  39. {
  40. IssueLog::Error("Incorrect value '".MetaModel::GetConfig()->Get('transaction_storage')."' for 'transaction_storage', the class '$sClass' does not exists. Using privUITransactionSession instead for storing sessions.");
  41. $sClass = 'privUITransactionSession';
  42. }
  43. return (string)$sClass::GetNewTransactionId();
  44. }
  45. /**
  46. * Check whether a transaction is valid or not and (optionally) remove the valid transaction from
  47. * the session so that another call to IsTransactionValid for the same transaction id
  48. * will return false
  49. * @param int $id Identifier of the transaction, as returned by GetNewTransactionId
  50. * @param bool $bRemoveTransaction True if the transaction must be removed
  51. * @return bool True if the transaction is valid, false otherwise
  52. */
  53. public static function IsTransactionValid($id, $bRemoveTransaction = true)
  54. {
  55. $sClass = 'privUITransaction'.MetaModel::GetConfig()->Get('transaction_storage');
  56. if (!class_exists($sClass, false))
  57. {
  58. $sClass = 'privUITransactionSession';
  59. }
  60. return $sClass::IsTransactionValid($id, $bRemoveTransaction);
  61. }
  62. /**
  63. * Removes the transaction specified by its id
  64. * @param int $id The Identifier (as returned by GetNewTranscationId) of the transaction to be removed.
  65. * @return void
  66. */
  67. public static function RemoveTransaction($id)
  68. {
  69. $sClass = 'privUITransaction'.MetaModel::GetConfig()->Get('transaction_storage');
  70. if (!class_exists($sClass, false))
  71. {
  72. $sClass = 'privUITransactionSession';
  73. }
  74. $sClass::RemoveTransaction($id);
  75. }
  76. }
  77. /**
  78. * The original (and by default) mechanism for storing transaction information
  79. * as an array in the $_SESSION variable
  80. *
  81. */
  82. class privUITransactionSession
  83. {
  84. /**
  85. * Create a new transaction id, store it in the session and return its id
  86. * @param void
  87. * @return int The identifier of the new transaction
  88. */
  89. public static function GetNewTransactionId()
  90. {
  91. if (!isset($_SESSION['transactions']))
  92. {
  93. $_SESSION['transactions'] = array();
  94. }
  95. // Strictly speaking, the two lines below should be grouped together
  96. // by a critical section
  97. // sem_acquire($rSemIdentified);
  98. $id = str_replace(array('.', ' '), '', microtime()); //1 + count($_SESSION['transactions']);
  99. $_SESSION['transactions'][$id] = true;
  100. // sem_release($rSemIdentified);
  101. return (string)$id;
  102. }
  103. /**
  104. * Check whether a transaction is valid or not and (optionally) remove the valid transaction from
  105. * the session so that another call to IsTransactionValid for the same transaction id
  106. * will return false
  107. * @param int $id Identifier of the transaction, as returned by GetNewTransactionId
  108. * @param bool $bRemoveTransaction True if the transaction must be removed
  109. * @return bool True if the transaction is valid, false otherwise
  110. */
  111. public static function IsTransactionValid($id, $bRemoveTransaction = true)
  112. {
  113. $bResult = false;
  114. if (isset($_SESSION['transactions']))
  115. {
  116. // Strictly speaking, the eight lines below should be grouped together
  117. // inside the same critical section as above
  118. // sem_acquire($rSemIdentified);
  119. if (isset($_SESSION['transactions'][$id]))
  120. {
  121. $bResult = true;
  122. if ($bRemoveTransaction)
  123. {
  124. unset($_SESSION['transactions'][$id]);
  125. }
  126. }
  127. // sem_release($rSemIdentified);
  128. }
  129. return $bResult;
  130. }
  131. /**
  132. * Removes the transaction specified by its id
  133. * @param int $id The Identifier (as returned by GetNewTranscationId) of the transaction to be removed.
  134. * @return void
  135. */
  136. public static function RemoveTransaction($id)
  137. {
  138. if (isset($_SESSION['transactions']))
  139. {
  140. // Strictly speaking, the three lines below should be grouped together
  141. // inside the same critical section as above
  142. // sem_acquire($rSemIdentified);
  143. if (isset($_SESSION['transactions'][$id]))
  144. {
  145. unset($_SESSION['transactions'][$id]);
  146. }
  147. // sem_release($rSemIdentified);
  148. }
  149. }
  150. }
  151. /**
  152. * An alternate implementation for storing the transactions as temporary files
  153. * Useful when using an in-memory storage for the session which do not
  154. * guarantee mutual exclusion for writing
  155. */
  156. class privUITransactionFile
  157. {
  158. /**
  159. * Create a new transaction id, store it in the session and return its id
  160. * @param void
  161. * @return int The identifier of the new transaction
  162. */
  163. public static function GetNewTransactionId()
  164. {
  165. if (!is_dir(APPROOT.'data/transactions'))
  166. {
  167. if (!is_writable(APPROOT.'data'))
  168. {
  169. throw new Exception('The directory "'.APPROOT.'data" must be writable to the application.');
  170. }
  171. if (!@mkdir(APPROOT.'data/transactions'))
  172. {
  173. throw new Exception('Failed to create the directory "'.APPROOT.'data/transactions". Ajust the rights on the parent directory or let an administrator create the transactions directory and give the web sever enough rights to write into it.');
  174. }
  175. }
  176. if (!is_writable(APPROOT.'data/transactions'))
  177. {
  178. throw new Exception('The directory "'.APPROOT.'data/transactions" must be writable to the application.');
  179. }
  180. self::CleanupOldTransactions();
  181. $id = basename(tempnam(APPROOT.'data/transactions', substr(UserRights::GetUser(), 0, 10).'-'));
  182. IssueLog::Info('GetNewTransactionId: Created transaction: '.$id);
  183. return (string)$id;
  184. }
  185. /**
  186. * Check whether a transaction is valid or not and (optionally) remove the valid transaction from
  187. * the session so that another call to IsTransactionValid for the same transaction id
  188. * will return false
  189. * @param int $id Identifier of the transaction, as returned by GetNewTransactionId
  190. * @param bool $bRemoveTransaction True if the transaction must be removed
  191. * @return bool True if the transaction is valid, false otherwise
  192. */
  193. public static function IsTransactionValid($id, $bRemoveTransaction = true)
  194. {
  195. $bResult = file_exists(APPROOT.'data/transactions/'.$id);
  196. if ($bResult)
  197. {
  198. if ($bRemoveTransaction)
  199. {
  200. $bResult = @unlink(APPROOT.'data/transactions/'.$id);
  201. if (!$bSuccess)
  202. {
  203. IssueLog::Error('IsTransactionValid: FAILED to remove transaction '.$id);
  204. }
  205. else
  206. {
  207. IssueLog::Info('IsTransactionValid: Removed transaction: '.$id);
  208. }
  209. }
  210. }
  211. else
  212. {
  213. IssueLog::Info("IsTransactionValid: Transaction '$id' not found. Pending transactions for this user:\n".implode("\n", self::GetPendingTransactions()));
  214. }
  215. return $bResult;
  216. }
  217. /**
  218. * Removes the transaction specified by its id
  219. * @param int $id The Identifier (as returned by GetNewTransactionId) of the transaction to be removed.
  220. * @return void
  221. */
  222. public static function RemoveTransaction($id)
  223. {
  224. $bSuccess = true;
  225. if(!file_exists(APPROOT.'data/transactions/'.$id))
  226. {
  227. $bSuccess = false;
  228. IssueLog::Info("RemoveTransaction: Transaction '$id' not found. Pending transactions for this user:\n".implode("\n", self::GetPendingTransactions()));
  229. }
  230. $bSuccess = @unlink(APPROOT.'data/transactions/'.$id);
  231. if (!$bSuccess)
  232. {
  233. IssueLog::Error('RemoveTransaction: FAILED to remove transaction '.$id);
  234. }
  235. return $bSuccess;
  236. }
  237. /**
  238. * Cleanup old transactions which have been pending since more than 24 hours
  239. */
  240. protected static function CleanupOldTransactions()
  241. {
  242. $iLimit = time() - 24*3600;
  243. $aTransactions = glob(APPROOT.'data/transactions/*-*');
  244. foreach($aTransactions as $sFileName)
  245. {
  246. if (filectime($sFileName) < $iLimit)
  247. {
  248. @unlink($sFileName);
  249. }
  250. }
  251. }
  252. /**
  253. * For debugging purposes: gets the pending transactions of the current user
  254. * as an array, with the date of the creation of the transaction file
  255. */
  256. protected static function GetPendingTransactions()
  257. {
  258. clearstatcache();
  259. $aResult = array();
  260. $aTransactions = glob(APPROOT.'data/transactions/'.UserRights::GetUser().'-*');
  261. foreach($aTransactions as $sFileName)
  262. {
  263. $aResult[] = date('Y-m-d H:i:s', filectime($sFileName)).' - '.basename($sFileName);
  264. }
  265. sort($aResult);
  266. return $aResult;
  267. }
  268. }