transaction.class.inc.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. self::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. $sFilepath = APPROOT.'data/transactions/'.$id;
  196. clearstatcache(true, $sFilepath);
  197. $bResult = file_exists($sFilepath);
  198. if ($bResult)
  199. {
  200. if ($bRemoveTransaction)
  201. {
  202. $bResult = @unlink($sFilepath);
  203. if (!$bResult)
  204. {
  205. self::Error('IsTransactionValid: FAILED to remove transaction '.$id);
  206. }
  207. else
  208. {
  209. self::Info('IsTransactionValid: OK. Removed transaction: '.$id);
  210. }
  211. }
  212. }
  213. else
  214. {
  215. self::Info("IsTransactionValid: Transaction '$id' not found. Pending transactions for this user:\n".implode("\n", self::GetPendingTransactions()));
  216. }
  217. return $bResult;
  218. }
  219. /**
  220. * Removes the transaction specified by its id
  221. * @param int $id The Identifier (as returned by GetNewTransactionId) of the transaction to be removed.
  222. * @return void
  223. */
  224. public static function RemoveTransaction($id)
  225. {
  226. $bSuccess = true;
  227. $sFilepath = APPROOT.'data/transactions/'.$id;
  228. clearstatcache(true, $sFilepath);
  229. if(!file_exists($sFilepath))
  230. {
  231. $bSuccess = false;
  232. self::Error("RemoveTransaction: Transaction '$id' not found. Pending transactions for this user:\n".implode("\n", self::GetPendingTransactions()));
  233. }
  234. $bSuccess = @unlink($sFilepath);
  235. if (!$bSuccess)
  236. {
  237. self::Error('RemoveTransaction: FAILED to remove transaction '.$id);
  238. }
  239. else
  240. {
  241. self::Info('RemoveTransaction: OK '.$id);
  242. }
  243. return $bSuccess;
  244. }
  245. /**
  246. * Cleanup old transactions which have been pending since more than 24 hours
  247. * Use filemtime instead of filectime since filectime may be affected by operations on the directory (like changing the access rights)
  248. */
  249. protected static function CleanupOldTransactions()
  250. {
  251. $iLimit = time() - 24*3600;
  252. clearstatcache();
  253. $aTransactions = glob(APPROOT.'data/transactions/*-*');
  254. foreach($aTransactions as $sFileName)
  255. {
  256. if (filemtime($sFileName) < $iLimit)
  257. {
  258. @unlink($sFileName);
  259. self::Info('CleanupOldTransactions: Deleted transaction: '.$sFileName);
  260. }
  261. }
  262. }
  263. /**
  264. * For debugging purposes: gets the pending transactions of the current user
  265. * as an array, with the date of the creation of the transaction file
  266. */
  267. protected static function GetPendingTransactions()
  268. {
  269. clearstatcache();
  270. $aResult = array();
  271. $aTransactions = glob(APPROOT.'data/transactions/'.UserRights::GetUser().'-*');
  272. foreach($aTransactions as $sFileName)
  273. {
  274. $aResult[] = date('Y-m-d H:i:s', filectime($sFileName)).' - '.basename($sFileName);
  275. }
  276. sort($aResult);
  277. return $aResult;
  278. }
  279. protected static function Info($sText)
  280. {
  281. self::Write('Info | '.$sText);
  282. }
  283. protected static function Warning($sText)
  284. {
  285. self::Write('Warning | '.$sText);
  286. }
  287. protected static function Error($sText)
  288. {
  289. self::Write('Error | '.$sText);
  290. }
  291. protected static function Write($sText)
  292. {
  293. $hLogFile = @fopen(APPROOT.'log/transactions.log', 'a');
  294. if ($hLogFile !== false)
  295. {
  296. flock($hLogFile, LOCK_EX);
  297. $sDate = date('Y-m-d H:i:s');
  298. fwrite($hLogFile, "$sDate | $sText\n");
  299. fflush($hLogFile);
  300. flock($hLogFile, LOCK_UN);
  301. fclose($hLogFile);
  302. }
  303. }
  304. }