transaction.class.inc.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. $bTransactionsEnabled = MetaModel::GetConfig()->Get('transactions_enabled');
  38. if (!$bTransactionsEnabled)
  39. {
  40. return 'notransactions'; // Any value will do
  41. }
  42. $sClass = 'privUITransaction'.MetaModel::GetConfig()->Get('transaction_storage');
  43. if (!class_exists($sClass, false))
  44. {
  45. IssueLog::Error("Incorrect value '".MetaModel::GetConfig()->Get('transaction_storage')."' for 'transaction_storage', the class '$sClass' does not exists. Using privUITransactionSession instead for storing sessions.");
  46. $sClass = 'privUITransactionSession';
  47. }
  48. return (string)$sClass::GetNewTransactionId();
  49. }
  50. /**
  51. * Check whether a transaction is valid or not and (optionally) remove the valid transaction from
  52. * the session so that another call to IsTransactionValid for the same transaction id
  53. * will return false
  54. * @param int $id Identifier of the transaction, as returned by GetNewTransactionId
  55. * @param bool $bRemoveTransaction True if the transaction must be removed
  56. * @return bool True if the transaction is valid, false otherwise
  57. */
  58. public static function IsTransactionValid($id, $bRemoveTransaction = true)
  59. {
  60. $bTransactionsEnabled = MetaModel::GetConfig()->Get('transactions_enabled');
  61. if (!$bTransactionsEnabled)
  62. {
  63. return true; // All values are valid
  64. }
  65. $sClass = 'privUITransaction'.MetaModel::GetConfig()->Get('transaction_storage');
  66. if (!class_exists($sClass, false))
  67. {
  68. $sClass = 'privUITransactionSession';
  69. }
  70. return $sClass::IsTransactionValid($id, $bRemoveTransaction);
  71. }
  72. /**
  73. * Removes the transaction specified by its id
  74. * @param int $id The Identifier (as returned by GetNewTranscationId) of the transaction to be removed.
  75. * @return void
  76. */
  77. public static function RemoveTransaction($id)
  78. {
  79. $bTransactionsEnabled = MetaModel::GetConfig()->Get('transactions_enabled');
  80. if (!$bTransactionsEnabled)
  81. {
  82. return; // Nothing to do
  83. }
  84. $sClass = 'privUITransaction'.MetaModel::GetConfig()->Get('transaction_storage');
  85. if (!class_exists($sClass, false))
  86. {
  87. $sClass = 'privUITransactionSession';
  88. }
  89. $sClass::RemoveTransaction($id);
  90. }
  91. }
  92. /**
  93. * The original (and by default) mechanism for storing transaction information
  94. * as an array in the $_SESSION variable
  95. *
  96. */
  97. class privUITransactionSession
  98. {
  99. /**
  100. * Create a new transaction id, store it in the session and return its id
  101. * @param void
  102. * @return int The identifier of the new transaction
  103. */
  104. public static function GetNewTransactionId()
  105. {
  106. if (!isset($_SESSION['transactions']))
  107. {
  108. $_SESSION['transactions'] = array();
  109. }
  110. // Strictly speaking, the two lines below should be grouped together
  111. // by a critical section
  112. // sem_acquire($rSemIdentified);
  113. $id = str_replace(array('.', ' '), '', microtime()); //1 + count($_SESSION['transactions']);
  114. $_SESSION['transactions'][$id] = true;
  115. // sem_release($rSemIdentified);
  116. return (string)$id;
  117. }
  118. /**
  119. * Check whether a transaction is valid or not and (optionally) remove the valid transaction from
  120. * the session so that another call to IsTransactionValid for the same transaction id
  121. * will return false
  122. * @param int $id Identifier of the transaction, as returned by GetNewTransactionId
  123. * @param bool $bRemoveTransaction True if the transaction must be removed
  124. * @return bool True if the transaction is valid, false otherwise
  125. */
  126. public static function IsTransactionValid($id, $bRemoveTransaction = true)
  127. {
  128. $bResult = false;
  129. if (isset($_SESSION['transactions']))
  130. {
  131. // Strictly speaking, the eight lines below should be grouped together
  132. // inside the same critical section as above
  133. // sem_acquire($rSemIdentified);
  134. if (isset($_SESSION['transactions'][$id]))
  135. {
  136. $bResult = true;
  137. if ($bRemoveTransaction)
  138. {
  139. unset($_SESSION['transactions'][$id]);
  140. }
  141. }
  142. // sem_release($rSemIdentified);
  143. }
  144. return $bResult;
  145. }
  146. /**
  147. * Removes the transaction specified by its id
  148. * @param int $id The Identifier (as returned by GetNewTranscationId) of the transaction to be removed.
  149. * @return void
  150. */
  151. public static function RemoveTransaction($id)
  152. {
  153. if (isset($_SESSION['transactions']))
  154. {
  155. // Strictly speaking, the three lines below should be grouped together
  156. // inside the same critical section as above
  157. // sem_acquire($rSemIdentified);
  158. if (isset($_SESSION['transactions'][$id]))
  159. {
  160. unset($_SESSION['transactions'][$id]);
  161. }
  162. // sem_release($rSemIdentified);
  163. }
  164. }
  165. }
  166. /**
  167. * An alternate implementation for storing the transactions as temporary files
  168. * Useful when using an in-memory storage for the session which do not
  169. * guarantee mutual exclusion for writing
  170. */
  171. class privUITransactionFile
  172. {
  173. /**
  174. * Create a new transaction id, store it in the session and return its id
  175. * @param void
  176. * @return int The identifier of the new transaction
  177. */
  178. public static function GetNewTransactionId()
  179. {
  180. if (!is_dir(APPROOT.'data/transactions'))
  181. {
  182. if (!is_writable(APPROOT.'data'))
  183. {
  184. throw new Exception('The directory "'.APPROOT.'data" must be writable to the application.');
  185. }
  186. if (!@mkdir(APPROOT.'data/transactions'))
  187. {
  188. 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.');
  189. }
  190. }
  191. if (!is_writable(APPROOT.'data/transactions'))
  192. {
  193. throw new Exception('The directory "'.APPROOT.'data/transactions" must be writable to the application.');
  194. }
  195. self::CleanupOldTransactions();
  196. $id = basename(tempnam(APPROOT.'data/transactions', self::GetUserPrefix()));
  197. self::Info('GetNewTransactionId: Created transaction: '.$id);
  198. return (string)$id;
  199. }
  200. /**
  201. * Check whether a transaction is valid or not and (optionally) remove the valid transaction from
  202. * the session so that another call to IsTransactionValid for the same transaction id
  203. * will return false
  204. * @param int $id Identifier of the transaction, as returned by GetNewTransactionId
  205. * @param bool $bRemoveTransaction True if the transaction must be removed
  206. * @return bool True if the transaction is valid, false otherwise
  207. */
  208. public static function IsTransactionValid($id, $bRemoveTransaction = true)
  209. {
  210. $sFilepath = APPROOT.'data/transactions/'.$id;
  211. clearstatcache(true, $sFilepath);
  212. $bResult = file_exists($sFilepath);
  213. if ($bResult)
  214. {
  215. if ($bRemoveTransaction)
  216. {
  217. $bResult = @unlink($sFilepath);
  218. if (!$bResult)
  219. {
  220. self::Error('IsTransactionValid: FAILED to remove transaction '.$id);
  221. }
  222. else
  223. {
  224. self::Info('IsTransactionValid: OK. Removed transaction: '.$id);
  225. }
  226. }
  227. }
  228. else
  229. {
  230. self::Info("IsTransactionValid: Transaction '$id' not found. Pending transactions for this user:\n".implode("\n", self::GetPendingTransactions()));
  231. }
  232. return $bResult;
  233. }
  234. /**
  235. * Removes the transaction specified by its id
  236. * @param int $id The Identifier (as returned by GetNewTransactionId) of the transaction to be removed.
  237. * @return void
  238. */
  239. public static function RemoveTransaction($id)
  240. {
  241. $bSuccess = true;
  242. $sFilepath = APPROOT.'data/transactions/'.$id;
  243. clearstatcache(true, $sFilepath);
  244. if(!file_exists($sFilepath))
  245. {
  246. $bSuccess = false;
  247. self::Error("RemoveTransaction: Transaction '$id' not found. Pending transactions for this user:\n".implode("\n", self::GetPendingTransactions()));
  248. }
  249. $bSuccess = @unlink($sFilepath);
  250. if (!$bSuccess)
  251. {
  252. self::Error('RemoveTransaction: FAILED to remove transaction '.$id);
  253. }
  254. else
  255. {
  256. self::Info('RemoveTransaction: OK '.$id);
  257. }
  258. return $bSuccess;
  259. }
  260. /**
  261. * Cleanup old transactions which have been pending since more than 24 hours
  262. * Use filemtime instead of filectime since filectime may be affected by operations on the directory (like changing the access rights)
  263. */
  264. protected static function CleanupOldTransactions()
  265. {
  266. $iLimit = time() - 24*3600;
  267. clearstatcache();
  268. $aTransactions = glob(APPROOT.'data/transactions/*-*');
  269. foreach($aTransactions as $sFileName)
  270. {
  271. if (filemtime($sFileName) < $iLimit)
  272. {
  273. @unlink($sFileName);
  274. self::Info('CleanupOldTransactions: Deleted transaction: '.$sFileName);
  275. }
  276. }
  277. }
  278. /**
  279. * For debugging purposes: gets the pending transactions of the current user
  280. * as an array, with the date of the creation of the transaction file
  281. */
  282. protected static function GetPendingTransactions()
  283. {
  284. clearstatcache();
  285. $aResult = array();
  286. $aTransactions = glob(APPROOT.'data/transactions/'.self::GetUserPrefix().'*');
  287. foreach($aTransactions as $sFileName)
  288. {
  289. $aResult[] = date('Y-m-d H:i:s', filemtime($sFileName)).' - '.basename($sFileName);
  290. }
  291. sort($aResult);
  292. return $aResult;
  293. }
  294. protected static function GetUserPrefix()
  295. {
  296. $sPrefix = substr(UserRights::GetUser(), 0, 10);
  297. $sPrefix = preg_replace('/[^a-zA-Z0-9-_]/', '_', $sPrefix);
  298. return $sPrefix.'-';
  299. }
  300. protected static function Info($sText)
  301. {
  302. self::Write('Info | '.$sText);
  303. }
  304. protected static function Warning($sText)
  305. {
  306. self::Write('Warning | '.$sText);
  307. }
  308. protected static function Error($sText)
  309. {
  310. self::Write('Error | '.$sText);
  311. }
  312. protected static function Write($sText)
  313. {
  314. $bLogEnabled = MetaModel::GetConfig()->Get('log_transactions');
  315. if ($bLogEnabled)
  316. {
  317. $hLogFile = @fopen(APPROOT.'log/transactions.log', 'a');
  318. if ($hLogFile !== false)
  319. {
  320. flock($hLogFile, LOCK_EX);
  321. $sDate = date('Y-m-d H:i:s');
  322. fwrite($hLogFile, "$sDate | $sText\n");
  323. fflush($hLogFile);
  324. flock($hLogFile, LOCK_UN);
  325. fclose($hLogFile);
  326. }
  327. }
  328. }
  329. }