BxDolStorage.php 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
  4. * CC-BY License - http://creativecommons.org/licenses/by/3.0/
  5. *
  6. * @defgroup TridentCore Trident Core
  7. * @{
  8. */
  9. define('BX_DOL_STORAGE_ERR_OK', 0);
  10. // 1-8 are standard upload form errors
  11. /*
  12. UPLOAD_ERR_INI_SIZE
  13. Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
  14. UPLOAD_ERR_FORM_SIZE
  15. Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
  16. UPLOAD_ERR_PARTIAL
  17. Value: 3; The uploaded file was only partially uploaded.
  18. UPLOAD_ERR_NO_FILE
  19. Value: 4; No file was uploaded.
  20. UPLOAD_ERR_NO_TMP_DIR
  21. Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.
  22. UPLOAD_ERR_CANT_WRITE
  23. Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.
  24. UPLOAD_ERR_EXTENSION
  25. Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.
  26. */
  27. define('BX_DOL_STORAGE_ERR_NO_INPUT_METHOD', 1000); ///< there is such input method available
  28. define('BX_DOL_STORAGE_ERR_NO_FILE', 1001); ///< there is no file to upload
  29. define('BX_DOL_STORAGE_INVALID_FILE', 1002); ///< uploaded file is invalid or hack attempts
  30. define('BX_DOL_STORAGE_ERR_FILE_TOO_BIG', 1003); ///< file is too big
  31. define('BX_DOL_STORAGE_ERR_WRONG_EXT', 1004); ///< wrong file extension
  32. define('BX_DOL_STORAGE_ERR_USER_QUOTA_EXCEEDED', 1005); ///< user quota exceeded
  33. define('BX_DOL_STORAGE_ERR_OBJECT_QUOTA_EXCEEDED', 1006); ///< storage object quota exceeded
  34. define('BX_DOL_STORAGE_ERR_SITE_QUOTA_EXCEEDED', 1007); ///< site quota exceeded
  35. define('BX_DOL_STORAGE_ERR_ENGINE_ADD', 1008); ///< some other error during file adding occured, related to particular storage engine
  36. define('BX_DOL_STORAGE_ERR_FILE_NOT_FOUND', 2001); ///< file not found
  37. define('BX_DOL_STORAGE_ERR_UNLINK', 2002); ///< file deletiotion failed
  38. define('BX_DOL_STORAGE_ERR_DB', 5001); ///< database error
  39. define('BX_DOL_STORAGE_ERR_FILESYSTEM_PERM', 5002); ///< filesystem permissions error
  40. define('BX_DOL_STORAGE_ERR_PERMISSION_DENIED', 5003); ///< permission denied
  41. define('BX_DOL_STORAGE_ERR_ENGINE_GET', 5004); ///< some other error during file getting occured, related to particular storage engine
  42. define('BX_DOL_STORAGE_DEFAULT_MIME_TYPE', 'octet/stream'); ///< default mime type if it is not find by extension
  43. define('BX_DOL_STORAGE_DEFAULT_ICON', 'mime-type-any.png'); ///< default icon if no other icon can be determined by file extension
  44. define('BX_DOL_STORAGE_QUEUED_DELETIONS_PER_RUN', 200); ///< max number of file deletions per one cron run, @see BxDolStorage::pruneDeletions
  45. /**
  46. * @page objects
  47. * @section storage Storage
  48. * @ref BxDolStorage
  49. */
  50. /**
  51. * This class unify storage.
  52. * As the result there are many advantages:
  53. * - files can be stored as on localhost as on remote storage, for example Amazon s3
  54. * - all files are in one place and separated from other files, so the data can be organised more easily,
  55. * for example moved to dedicated disk if there is not enough storage
  56. * - simplicity of usage, there are hight level classes to handle all necessary operations, including upload and security
  57. * - quotas settings, so you always control how much space you are going to use
  58. * - persistent storage; uploaded, but not saved files appear upon page reload or future submission of the same form
  59. *
  60. *
  61. * Usage.
  62. *
  63. * Step 1:
  64. * Add record to 'sys_objects_storage' table, like you doing this for Comments or Voting objects:
  65. * - object - your storage object name, usually it is in the following format - vendor prefix, underscore, module prefix;
  66. * for example for BoonEx Forum module it can be bx_forum.
  67. * - engine - storage engine, for now the following engines are supported:
  68. * 1. Local - local storage, by default files are stored in /storage/ subfolder
  69. * 2. S3 - Amazon S3 storage, files are stored on Amazon S3 storage, you need to point AWS Access Key, AWS Secret Key and AWS Bucket in the settings
  70. * - params - custom storage engine params as php serialized string
  71. * - token_life - life of the security token in seconds for private files
  72. * - cache_control - control browser cache, allow browser to store files in browser's cache for this number of seconds, to disable browser cache,
  73. * or let browser to decide on its own set it to 0(zero)
  74. * - levels - store files in subfolders, generated from filename; it is useful when there is limit of number of files/folders per directory;
  75. * for example if level is 2 and file name is abc.jpg then the file will be stored in a/b/abc.jpg folder, set to to 0(zero) to disable this feature
  76. * - table_files - table where file info is stored, please refer to step 2 for more details
  77. * - ext_mode - file extensions restriction mode:
  78. * 1. allow-deny - allow only file types in ext_allow field and deny all other file types, ext_deny field is ignored.
  79. * 2. deny-allow - allow all files except the ones specified in ext_deny field, ext_allow field is ignored.
  80. * - ext_allow - allowed file extensions, comma separated, it is in effect when ext_mode is allow-deny; example - jpg,gif,png
  81. * - ext_deny - denied file extensions, comma separated, it is in effect when ext_mode is deny-allow; example - exe,com,bat
  82. * - quota_size - storage engine quota in bytes, the summary of all uploaded files can not be bigger than this number
  83. * - current_size - current storage engine usage, the sum of all uploaded file sizes
  84. * - quota_number - max number of files allowed in this storage engine
  85. * - current_number - current number of files in this storage engine
  86. * - max_file_size - max file size for this storage engine, please note that other server settings are used if they are less than this setting option
  87. * - ts - unix timestamp of the last file upload
  88. *
  89. *
  90. * Step 2:
  91. * Create table for files.
  92. *
  93. * @code
  94. * CREATE TABLE `my_sample_files` (
  95. * `id` int(11) NOT NULL AUTO_INCREMENT,
  96. * `profile_id` int(10) unsigned NOT NULL,
  97. * `remote_id` varchar(255) NOT NULL,
  98. * `path` varchar(255) NOT NULL,
  99. * `file_name` varchar(255) NOT NULL,
  100. * `mime_type` varchar(128) NOT NULL,
  101. * `ext` varchar(32) NOT NULL,
  102. * `size` int(11) NOT NULL,
  103. * `added` int(11) NOT NULL,
  104. * `modified` int(11) NOT NULL,
  105. * `private` int(11) NOT NULL,
  106. * PRIMARY KEY (`id`),
  107. * UNIQUE KEY `remote_id` (`remote_id`)
  108. * );
  109. * @endcode
  110. *
  111. * You need to enter this table name in 'table_files' field in 'sys_objects_storage' table, mentioned in step 1.
  112. * The files will be added to this table automatically, all you need is to save 'id' from this table, so you can refer to the file by the 'id'.
  113. * It is not recommended to change this table, it is better to create another table which will be connected with this one by file 'id'.
  114. *
  115. *
  116. * Step 3:
  117. * Handling upload.
  118. *
  119. * Sample HTML form:
  120. * @code
  121. * <form enctype="multipart/form-data" method="POST" action="store_file.php">
  122. * Choose a file to upload:
  123. * <input name="file" type="file" />
  124. * <br />
  125. * <input type="submit" name="add" value="Upload File" />
  126. * </form>
  127. * @endcode
  128. *
  129. * Add server code in sample store_file.php file:
  130. *
  131. * @code
  132. * require_once('./inc/header.inc.php');
  133. * require_once(BX_DIRECTORY_PATH_INC . "design.inc.php");
  134. *
  135. * BxDolStorage::pruning(); // pruning is needed to clear expired security tokens, you can call it on cron when your server is not busy
  136. * $oStorage = BxDolStorage::getObjectInstance('my_module'); // create storage object instance, 'my_module' is value of 'object' field in 'sys_objects_storage' table
  137. *
  138. * if (isset($_POST['add'])) { // if form is submitted
  139. * $iId = $oStorage->storeFileFromForm($_FILES['file'], true, 0); // store file from submitted HTML form, 'file' is input name with field, true means store file as private, 0 is profile id
  140. * if ($iId) { // storeFileFromForm returns file id, not false value means operation is successful.
  141. * // save $iId somewhere, so you can refer to the file after
  142. * $iCount = $oStorage->afterUploadCleanup($iId, $iProfileId); // since we saved $iId, we remove it from the orphans list, so it will not appear on the form next time (persistent storage)
  143. * echo "uploaded file id: " . $iId . "(deleted orphans:" . $iCount . ")";
  144. * } else {
  145. * // something went wrong - print the error
  146. * echo "error uploading file: " . $oStorage->getErrorString()
  147. * }
  148. * }
  149. * @endcode
  150. *
  151. * Please refer to the functions definition for more additional description of functions params.
  152. *
  153. *
  154. * Step 4:
  155. * Displaying the file.
  156. *
  157. * Use the following code to retrieve saved file. Remember you saved filed id somewhere in the previous step.
  158. * Lets assume that the uploaded file is image, then we can show it using the following code:
  159. *
  160. * @code
  161. * require_once('./inc/header.inc.php');
  162. * require_once(BX_DIRECTORY_PATH_INC . "design.inc.php");
  163. *
  164. * $oStorage = BxDolStorage::getObjectInstance('my_module');
  165. *
  166. * $iId = 1234; // since you've saved it somewhere in the previous step, you can retrieve it here
  167. *
  168. * echo "Uploaded image: <img src="' . $oStorage->getFileUrlById($iId) . '" />;";
  169. * @endcode
  170. *
  171. * It will show the file, regardless if it is private or public.
  172. * You need to control it by yourself who will view the file.
  173. * The difference in viewing private files is that link to the file is expiring after N seconds,
  174. * you control this period using 'token_life' field in 'sys_objects_storage' table.
  175. *
  176. */
  177. abstract class BxDolStorage extends BxDol implements iBxDolFactoryObject
  178. {
  179. protected $_aObject; ///< object properties
  180. protected $_iCacheControl; ///< browser cache in seconds, 0 - disabled
  181. protected $_aParams; ///< custom params
  182. protected $_iErrorCode; ///< last error code
  183. protected $_oDb; ///< database relates function are in this object
  184. /**
  185. * constructor
  186. */
  187. protected function __construct($aObject)
  188. {
  189. parent::__construct();
  190. $this->_aObject = $aObject;
  191. $this->_iCacheControl = $aObject['cache_control'];
  192. $this->_aParams = $aObject['params'] ? unserialize($aObject['params']) : '';
  193. $this->_oDb = new BxDolStorageQuery($aObject);
  194. }
  195. /**
  196. * Get storage object instance by object name
  197. * @param $sObject object name
  198. * @return object instance or false on error
  199. */
  200. public static function getObjectInstance($sObject)
  201. {
  202. if (isset($GLOBALS['bxDolClasses']['BxDolStorage!'.$sObject]))
  203. return $GLOBALS['bxDolClasses']['BxDolStorage!'.$sObject];
  204. $aObject = BxDolStorageQuery::getStorageObject($sObject);
  205. if (!$aObject || !is_array($aObject))
  206. return false;
  207. $sClass = 'BxDolStorage' . $aObject['engine'];
  208. $o = new $sClass($aObject);
  209. if (!$o->isInstalled() || !$o->isAvailable())
  210. return false;
  211. return ($GLOBALS['bxDolClasses']['BxDolStorage!'.$sObject] = $o);
  212. }
  213. /**
  214. * Delete old security tokens from database.
  215. * It is alutomatically called upin cron execution, usually once in a day.
  216. * @return number of deleted records
  217. */
  218. public static function pruning()
  219. {
  220. $iDeleted = 0;
  221. $a = BxDolStorageQuery::getStorageObjects();
  222. foreach ($a as $aObject) {
  223. $oDb = new BxDolStorageQuery($aObject);
  224. $iDeleted += $oDb->prune();
  225. }
  226. return $iDeleted;
  227. }
  228. /**
  229. * Delete files queued for deletions
  230. * It is alutomatically called upin cron execution, usually one time per minute.
  231. * Max number of deletetion per time is defined in @see BX_DOL_STORAGE_QUEUED_DELETIONS_PER_RUN
  232. * @return number of deleted records
  233. */
  234. public static function pruneDeletions()
  235. {
  236. $iDeleted = 0;
  237. $a = BxDolStorageQuery::getQueuedFilesForDeletion(BX_DOL_STORAGE_QUEUED_DELETIONS_PER_RUN);
  238. foreach ($a as $r) {
  239. $o = BxDolStorage::getObjectInstance($r['object']);
  240. $iDeleted += ($o && $o->deleteFile($r['file_id']) ? 1 : 0);
  241. }
  242. return $iDeleted;
  243. }
  244. /**
  245. * Check if module has any files pending for deletion, it is supposed that all module storage object names are prefixed with module name
  246. * @param $sPrefix - usually module name
  247. * @return number of files pending for deletion which were found by prefix
  248. */
  249. public static function isQueuedFilesForDeletion ($sPrefix)
  250. {
  251. return BxDolStorageQuery::isQueuedFilesForDeletion($sPrefix);
  252. }
  253. /**
  254. * Is storage engine available?
  255. * @return boolean
  256. */
  257. function isAvailable()
  258. {
  259. return true;
  260. }
  261. /**
  262. * Are required php modules installed for this storage engine ?
  263. * @return boolean
  264. */
  265. public function isInstalled()
  266. {
  267. return true;
  268. }
  269. public function getObject()
  270. {
  271. return $this->_aObject['object'];
  272. }
  273. /**
  274. * Get error code from the last occured error
  275. * @return error code
  276. */
  277. public function getErrorCode()
  278. {
  279. return $this->_iErrorCode;
  280. }
  281. /**
  282. * Get error string from the last occured error
  283. * @return error string
  284. */
  285. public function getErrorString()
  286. {
  287. $a = array (
  288. 1000 => '_sys_storage_err_no_input_method',
  289. 1001 => '_sys_storage_err_no_file',
  290. 1002 => '_sys_storage_invalid_file',
  291. 1003 => '_sys_storage_err_file_too_big',
  292. 1004 => '_sys_storage_err_wrong_ext',
  293. 1005 => '_sys_storage_err_user_quota_exceeded',
  294. 1006 => '_sys_storage_err_object_quota_exceeded',
  295. 1007 => '_sys_storage_err_site_quota_exceeded',
  296. 1008 => '_sys_storage_err_engine_add',
  297. 2001 => '_sys_storage_err_file_not_found',
  298. 2002 => '_sys_storage_err_unlink',
  299. 5001 => '_sys_storage_err_db',
  300. 5002 => '_sys_storage_err_filesystem_perm',
  301. 5003 => '_sys_storage_err_permission_denied',
  302. 5004 => '_sys_storage_err_engine_get',
  303. );
  304. return _t($a[$this->_iErrorCode]);
  305. }
  306. /**
  307. * Get max file size allowed for current user, it checks user quota, object quota, site quota and php setting
  308. * @param $iProfileId profile id to check quota for
  309. * @return quota size in bytes
  310. */
  311. public function getMaxUploadFileSize ($iProfileId)
  312. {
  313. $iMin = PHP_INT_MAX;
  314. $aUserQuota = $this->_oDb->getUserQuota($iProfileId);
  315. if ($aUserQuota['max_file_size'] && $aUserQuota['max_file_size'] < $iMin)
  316. $iMin = $aUserQuota['max_file_size'];
  317. $aObjectQuota = $this->_oDb->getStorageObjectQuota();
  318. if ($aObjectQuota['max_file_size'] && $aObjectQuota['max_file_size'] < $iMin)
  319. $iMin = $aObjectQuota['max_file_size'];
  320. // TODO: get and check site quota
  321. if (!defined('BX_DOL_CRON_EXECUTE')) {
  322. $iUploadMaxFilesize = return_bytes(ini_get('upload_max_filesize'));
  323. if ($iUploadMaxFilesize && $iUploadMaxFilesize < $iMin)
  324. $iMin = $iUploadMaxFilesize;
  325. }
  326. return $iMin;
  327. }
  328. /**
  329. * Store file in the storage area. It is not recommended to use this function directly,
  330. * use other funtions like: storeFileFromForm, storeFileFromXhr, storeFileFromPath, storeFileFromUrl
  331. * @param $sMethod upload method, like regular Form upload, upload from URL, etc
  332. * @param $aMethodParams upload method params
  333. * @param $sName file name with extention
  334. * @param $isPrivate private or public file
  335. * @param $iProfileId profile id of the upload action performer
  336. * @param $iContentId content id to associate with ghost file
  337. * @return id of added file on success, false on error - to get exact error string call getErrorString()
  338. */
  339. public function storeFile($sMethod, $aMethodParams, $sName = false, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  340. {
  341. // setup input source using helper classes, like $_FILES or some URL for example
  342. $sHelperClass = 'BxDolStorageHelper' . $sMethod;
  343. if (!class_exists($sHelperClass)) {
  344. $this->setErrorCode(BX_DOL_STORAGE_ERR_NO_INPUT_METHOD);
  345. return false;
  346. }
  347. $oHelper = new $sHelperClass($aMethodParams);
  348. // check for errors, like size and extentions checking
  349. if ($iImmediateError = $oHelper->getImmediateError()) {
  350. $this->setErrorCode($iImmediateError);
  351. return false;
  352. }
  353. $sExt = $this->getFileExt($oHelper->getName());
  354. $sMimeType = $this->getMimeTypeByFileName($oHelper->getName());
  355. if (!$this->isValidExt($sExt)) {
  356. $this->setErrorCode(BX_DOL_STORAGE_ERR_WRONG_EXT);
  357. return false;
  358. }
  359. // before upload callback + additional checking
  360. if (!$this->onBeforeFileAdd (array(
  361. 'profile_id' => $iProfileId,
  362. 'content_id' => $iContentId,
  363. 'file_name' => $oHelper->getName(),
  364. 'mime_type' => $sMimeType,
  365. 'ext' => $sExt,
  366. 'size' => $oHelper->getSize(),
  367. 'private' => $isPrivate ? 1 : 0,
  368. ))) {
  369. return false;
  370. }
  371. // create tmp file
  372. $sTmpFile = tempnam(BX_DIRECTORY_PATH_TMP, $this->_aObject['object']);
  373. if (!$oHelper->save($sTmpFile)) {
  374. $this->setErrorCode(BX_DOL_STORAGE_INVALID_FILE);
  375. return false;
  376. }
  377. // store file to storage engine
  378. $sLocalId = $this->genRandName();
  379. $sPath = $this->genPath($sLocalId, $this->_aObject['levels']);
  380. $sRemoteNamePath = $this->genRemoteNamePath ($sPath, $sLocalId, $sExt);
  381. if (!$this->addFileToEngine($sTmpFile, $sLocalId, $oHelper->getName(), $isPrivate, $iProfileId)) {
  382. unlink($sTmpFile);
  383. $this->setErrorCode(BX_DOL_STORAGE_ERR_ENGINE_ADD);
  384. return false;
  385. }
  386. unlink($sTmpFile);
  387. // add record in db
  388. $iTime = time();
  389. $iSize = $oHelper->getSize();
  390. $bFileAdded = $this->_oDb->addFile($iProfileId, $sLocalId, $sRemoteNamePath, $oHelper->getName(), $sMimeType, $sExt, $iSize, $iTime, $isPrivate);
  391. $iId = $this->_oDb->lastId();
  392. if (!$bFileAdded || !$iId) {
  393. $this->deleteFileFromEngine($sPath . $sLocalId, $isPrivate);
  394. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  395. return false;
  396. }
  397. // after upload callback + triggers update
  398. if (!$this->onFileAdded (array(
  399. 'id' => $iId,
  400. 'profile_id' => $iProfileId,
  401. 'content_id' => $iContentId,
  402. 'remote_id' => $sLocalId,
  403. 'path' => $sPath . $sLocalId,
  404. 'file_name' => $oHelper->getName(),
  405. 'mime_type' => $sMimeType,
  406. 'size' => $iSize,
  407. 'private' => $isPrivate ? 1 : 0,
  408. ))) {
  409. $this->deleteFileFromEngine($sPath . $sLocalId, $isPrivate);
  410. $this->_oDb->deleteFile($iId);
  411. return false;
  412. }
  413. return $iId;
  414. }
  415. /**
  416. * convert default multiple files array into more logical one
  417. */
  418. public function convertMultipleFilesArray($aFiles)
  419. {
  420. if (!is_array($aFiles) || !is_array($aFiles['name']))
  421. return false;
  422. $aRet = array ();
  423. foreach ($aFiles['name'] as $i => $sName) {
  424. foreach ($aFiles as $sKey => $r) {
  425. if (!$aFiles['name'][$i])
  426. break;
  427. $aRet[$i][$sKey] = $aFiles[$sKey][$i];
  428. }
  429. }
  430. return $aRet;
  431. }
  432. /**
  433. * the same as storeFile, but it tries to do it directly from uploaded file
  434. */
  435. public function storeFileFromForm($aFile, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  436. {
  437. return $this->storeFile('Form', array('file' => $aFile), false, $isPrivate, $iProfileId, $iContentId);
  438. }
  439. /**
  440. * the same as storeFile, but it tries to do it directly from HTML5 file upload method
  441. */
  442. public function storeFileFromXhr($sName, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  443. {
  444. return $this->storeFile('Xhr', array('name' => $sName), false, $isPrivate, $iProfileId, $iContentId);
  445. }
  446. /**
  447. * the same as storeFile, but it tries to do it directly from local file
  448. */
  449. public function storeFileFromPath($sPath, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  450. {
  451. return $this->storeFile('Path', array('path' => $sPath), false, $isPrivate, $iProfileId, $iContentId);
  452. }
  453. /**
  454. * the same as storeFileFromPath, but it tries to do it from URL
  455. */
  456. public function storeFileFromUrl($sUrl, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  457. {
  458. return $this->storeFile('Url', array('url' => $sUrl), false, $isPrivate, $iProfileId, $iContentId);
  459. }
  460. /**
  461. * the same as storeFile, but it tries to do it directly from the same or another storage by file id
  462. * @param $aParams['id'] - file ID in the storage
  463. * @param $aParams['storage'] - the storage name
  464. */
  465. public function storeFileFromStorage($aParams, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  466. {
  467. if (!isset($aParams['id']) || !(int)$aParams['id'])
  468. $aParams['id'] = 0;
  469. if (!isset($aParams['storage']))
  470. $aParams['storage'] = $this->_aObject['object'];
  471. return $this->storeFile('Storage', $aParams, false, $isPrivate, $iProfileId, $iContentId = 0);
  472. }
  473. /**
  474. * Delete file by file id.
  475. */
  476. public function deleteFile($iFileId, $iProfileId = 0)
  477. {
  478. $aFile = $this->_oDb->getFileById ($iFileId);
  479. if (!$aFile) {
  480. $this->setErrorCode(BX_DOL_STORAGE_ERR_FILE_NOT_FOUND);
  481. return false;
  482. }
  483. if (!$this->onBeforeFileDelete ($aFile, $iProfileId)) {
  484. return false;
  485. }
  486. if (!$this->deleteFileFromEngine($aFile['path'], $aFile['private'])) {
  487. return false;
  488. }
  489. $aGhost = $this->_oDb->getGhost($aFile['id']);
  490. if (!$this->_oDb->deleteFile($aFile['id'])) {
  491. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  492. return false;
  493. }
  494. if (!$this->onFileDeleted ($aFile, $iProfileId, $aGhost)) {
  495. return false;
  496. }
  497. return true;
  498. }
  499. /**
  500. * Queue file(s) for deletion. File(s) will be deleted later upon cron call (usually every minute).
  501. * @param $mixedFileId file id or array of file ids.
  502. * @return number of queued files
  503. */
  504. public function queueFilesForDeletion($mixedFileId)
  505. {
  506. if (!is_array($mixedFileId))
  507. $mixedFileId = array ($mixedFileId);
  508. bx_import('BxDolForm');
  509. $oChecker = new BxDolFormCheckerHelper();
  510. return $this->_oDb->queueFilesForDeletion (array_unique($oChecker->passInt($mixedFileId)));
  511. }
  512. /**
  513. * Queue file(s) for deletion by getting neccesary files from ghosts table by profile id and content id
  514. * @param $iProfileId profile id associated with files
  515. * @param $iContentId content id associated with files, or false if to check by profile id only
  516. * @return number of queued files
  517. */
  518. public function queueFilesForDeletionFromGhosts($iProfileId, $iContentId = false)
  519. {
  520. $aFiles = $this->getGhosts ($iProfileId, $iContentId);
  521. return $this->queueFiles($aFiles);
  522. }
  523. /**
  524. * Queue file(s) for deletion of the whole storage object
  525. * @return number of queued files
  526. */
  527. public function queueFilesForDeletionFromObject()
  528. {
  529. $aFiles = $this->getFiles (false);
  530. return $this->queueFiles($aFiles);
  531. }
  532. /**
  533. * Download file.
  534. * @param array $aFile downloading file info.
  535. */
  536. public function download ($aFile)
  537. {
  538. $bRet = true;
  539. bx_alert($this->_aObject['object'], 'file_downloaded', $aFile['id'], bx_get_logged_profile_id(), array(
  540. 'profile_ip' => getVisitorIP(),
  541. 'file_info' => $aFile,
  542. 'return_value' => &$bRet
  543. ));
  544. return $bRet;
  545. }
  546. /**
  547. * Set file private or public.
  548. */
  549. public function setFilePrivate($iFileId, $isPrivate = true)
  550. {
  551. if (!$this->_oDb->modifyFilePrivate ($iFileId, $isPrivate)) {
  552. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  553. return false;
  554. }
  555. return true;
  556. }
  557. /**
  558. * Get file url.
  559. * @param $iFileId file id
  560. * @return file url or false on error
  561. */
  562. public function getFileUrlById($iFileId) { }
  563. /**
  564. * Get file info array by file id.
  565. * @param $iFileId file id
  566. * @return array
  567. */
  568. public function getFile($iFileId)
  569. {
  570. return $this->_oDb->getFileById($iFileId);
  571. }
  572. /**
  573. * Get ghost file info array by file id.
  574. * @param $iFileId file id
  575. * @return array
  576. */
  577. public function getGhost($iFileId)
  578. {
  579. return $this->_oDb->getGhost($iFileId);
  580. }
  581. /**
  582. * check if file is private or public
  583. * @param $iFileId file id
  584. * @return boolean
  585. */
  586. public function isFilePrivate($iFileId)
  587. {
  588. $aFile = $this->getFile ($iFileId);
  589. return $aFile['private'] ? true : false;
  590. }
  591. /**
  592. * Call this function after saving/associate just uploaded file id, so file is not orphaned/ghost.
  593. * Ghost files appear on download form automaticaly during next upload,
  594. * for example if file was uploaded but was not submitted for some reason.
  595. * This mechanism ensure that the file is not lost.
  596. * @param $mixedFileIds array of file ids or just one file id
  597. * @param $iProfileId profile id
  598. * @param return number of deleted ghost files
  599. */
  600. public function afterUploadCleanup($mixedFileIds, $iProfileId, $iContentId = false)
  601. {
  602. return $this->_oDb->deleteGhosts($mixedFileIds, $iProfileId, $iContentId);
  603. }
  604. /**
  605. * Get ghost/orphaned files for particular user.
  606. * @param $iProfileId profile id
  607. * @param $iContentId content id, or false to not consider content id at all
  608. * @param $isCheckAllAccountProfiles get all files associated with all account profiles
  609. * @return array of arrays
  610. */
  611. public function getGhosts($iProfileId, $iContentId = false, $isCheckAllAccountProfiles = false)
  612. {
  613. if ($isCheckAllAccountProfiles && ($oProfile = BxDolProfile::getInstance($iProfileId))) {
  614. $oAccount = $oProfile->getAccountObject();
  615. $aProfiles = $oAccount->getProfilesIds(false);
  616. return $this->_oDb->getGhosts($aProfiles, $iContentId);
  617. }
  618. return $this->_oDb->getGhosts($iProfileId, $iContentId);
  619. }
  620. /**
  621. * Update ghosts' content id.
  622. * @param $mixedFileIds array of file ids or just one file id
  623. * @param $iProfileId profile id
  624. * @param $iContentId content id
  625. * @return true on success or false otherwise
  626. */
  627. public function updateGhostsContentId($mixedFileIds, $iProfileId, $iContentId)
  628. {
  629. $aProfiles = array();
  630. if ($oProfile = BxDolProfile::getInstance($iProfileId)) {
  631. $oAccount = $oProfile->getAccountObject();
  632. $aProfiles = $oAccount->getProfilesIds(false);
  633. }
  634. return $this->_oDb->updateGhostsContentId($mixedFileIds, $iProfileId, $iContentId, $aProfiles);
  635. }
  636. /**
  637. * Get files list for particular user.
  638. * @param $iProfileId profile id
  639. * @return array of arrays
  640. */
  641. public function getFiles($iProfileId)
  642. {
  643. return $this->_oDb->getFiles($iProfileId);
  644. }
  645. /**
  646. * Get all files in the storage
  647. */
  648. public function getFilesAll($iStart = 0, $iPerPage = 1000)
  649. {
  650. return $this->_oDb->getFilesAll($iStart, $iPerPage);
  651. }
  652. /**
  653. * Get readable representation of restrictions by file extentions.
  654. * @param $iProfileId profile id
  655. * @return string
  656. */
  657. public function getRestrictionsTextExtensions ($iProfileId)
  658. {
  659. switch ($this->_aObject['ext_mode']) {
  660. case 'allow-deny':
  661. if (!$this->_aObject['ext_allow'])
  662. return _t('_sys_storage_restriction_ext_all_denied');
  663. return _t('_sys_storage_restriction_ext_allowed', _t_format_extensions($this->_aObject['ext_allow']));
  664. case 'deny-allow':
  665. if (!$this->_aObject['ext_deny'])
  666. return _t('_sys_storage_restriction_ext_all_allowed');
  667. return _t('_sys_storage_restriction_ext_denied', _t_format_extensions($this->_aObject['ext_deny']));
  668. default:
  669. return _t('_sys_storage_restriction_ext_all_denied');
  670. }
  671. }
  672. /**
  673. * Get readable representation of restrictions by file size.
  674. * @param $iProfileId profile id
  675. * @return string
  676. */
  677. public function getRestrictionsTextFileSize ($iProfileId)
  678. {
  679. return _t('_sys_storage_restriction_size', _t_format_size($this->getMaxUploadFileSize($iProfileId)));
  680. }
  681. /**
  682. * Get readable representation of all restrictions.
  683. * @param $iProfileId profile id
  684. * @return array of strings
  685. */
  686. public function getRestrictionsTextArray ($iProfileId)
  687. {
  688. $aTypes = array('Extensions', 'FileSize');
  689. $aRet = array();
  690. foreach ($aTypes as $sType) {
  691. $sFunc = 'getRestrictionsText' . $sType;
  692. $s = $this->$sFunc ($iProfileId);
  693. if ($s)
  694. $aRet[] = $s;
  695. }
  696. return $aRet;
  697. }
  698. /**
  699. * Reread available mimetypes from particular file.
  700. * It clears 'sys_storage_mime_types' table and fill it with data form provided file.
  701. * The format of file is: mime/type _space_or_tab_ extentions_sperated_by_space.
  702. * Usually the file is mime.types file from apache or /etc/mime.types from unix systems.
  703. * @param $sFile file to read mime types from
  704. * @return false if file was not found or can not be read, string with result on other case - it can contains file markup errors or localized "Success" string if everything went fine.
  705. */
  706. public function reloadMimeTypesFromFile ($sFile)
  707. {
  708. $sResult = '';
  709. $aIcons = array (
  710. 'mime-type-psd.png' => array('psd'),
  711. 'mime-type-png.png' => array('png'),
  712. 'mime-type-image.png' => 'image/',
  713. 'mime-type-video.png' => 'video/',
  714. 'mime-type-audio.png' => 'audio/',
  715. 'mime-type-presentation.png' => array('ppt', 'pptx', 'sxi', 'sti', 'odp', 'sdp', 'sdd'),
  716. 'mime-type-spreadsheet.png' => array('xls', 'xlt', 'xlsx', 'sxc', 'stc', 'ods', 'ots', 'sdc', 'csv', 'dif', 'slk', 'pxl'),
  717. 'mime-type-document.png' => array('doc', 'docx', 'odt', 'ott', 'sxw', 'stw', 'rtf', 'sdw', 'txt', 'pdb', 'psw', 'pdf'),
  718. 'mime-type-vector.png' => array('ac5', 'ac6', 'aff', 'agd1', 'ai', 'ait', 'art', 'awg', 'b2f', 'cag', 'cbd', 'cdl', 'cdr', 'cdr3', 'cdr4', 'cdr5', 'cdr6', 'cdrw', 'cdx', 'cgm', 'cht', 'cil', 'cit', 'cnv', 'csl', 'ctn', 'cv5', 'cvg', 'cvi', 'cvl', 'cvs', 'cvx', 'dcs', 'ddoc', 'ddrw', 'ded', 'design', 'dmw', 'do', 'dpp', 'dpr', 'draw', 'drw', 'dsf', 'dsf', 'dsx', 'dvg', 'dxb', 'emb', 'evf', 'fcd', 'fh', 'fhd', 'fmv', 'fs', 'ft10', 'ft11', 'ft9', 'ft8', 'gem', 'gl2', 'graffle', 'gsd', 'gsd', 'hpg', 'hpgl', 'hpgl2', 'hpl', 'hplj', 'hpp', 'hppcl', 'idw', 'ima', 'macdraw', 'md', 'mgcb', 'mgs', 'mvg', 'nap', 'naplps', 'odg', 'p10', 'pat', 'pct', 'pd', 'pdw', 'pgs', 'pic', 'pif', 'pix', 'plo', 'plot', 'plt', 'ps', 'psid', 'pws', 'rdl', 's57', 'sdw', 'sif', 'sk2', 'slddwg', 'sp', 'spa', 'svf', 'svg', 'svgb', 'svgz', 'sxd', 'tdr', 'tlc', 'tng', 'vbr', 'vec', 'vect', 'veh', 'vml', 'vss', 'web', 'web', 'web', 'yal'),
  719. 'mime-type-archive.png' => array('7z', '7zip', 'aar', 'ace', 'alz', 'arj', 'bz2', 'bza', 'bzip2', 'bzp', 'bzp2', 'cab', 'czip', 'gnutar', 'gz', 'gza', 'gzi', 'gzip', 'ha', 'lhz', 'lzma', 'pzip', 'rar', 'roo', 's7z', 'tar', 'tar-gz', 'tar-lzma', 'tar-z', 'taz', 'tbz', 'tbz2', 'tgz', 'tz', 'z', 'zip', 'zipx', 'zix', 'zoo'),
  720. );
  721. $f = fopen ($sFile, 'r');
  722. if (!$f)
  723. return false;
  724. $this->_oDb->clearAllMimeTypes();
  725. while (!feof($f) && ($s = fgets($f, 4096)) !== false) {
  726. $s = trim($s);
  727. if (!$s || '#' == $s[0])
  728. continue;
  729. $a = preg_split ("/[\s\\b]+/", $s, 2);
  730. if (!isset($a[0]) || !isset($a[1]))
  731. continue;
  732. $sMimeType = $a[0];
  733. $aExts = preg_split ("/[\s]+/", $a[1]);
  734. foreach ($aExts as $sExt) {
  735. $sIcon = '';
  736. foreach ($aIcons as $sIc => $if) {
  737. if (!(is_array($if) && in_array($sExt, $if)) && !(is_string($if) && 0 == strncmp($if, $sMimeType, strlen($if))))
  738. continue;
  739. $sIcon = $sIc;
  740. break;
  741. }
  742. if (!$this->_oDb->addMimeType($sMimeType, $sExt, $sIcon))
  743. $sResult .= _t('_Error') . ': ' . $sMimeType . "\t" . $sExt . "\n";
  744. }
  745. }
  746. fclose($f);
  747. if (!$sResult)
  748. $sResult = _t('_Success');
  749. return $sResult;
  750. }
  751. /**
  752. * Get file extension by file name.
  753. * @param $sFileName file name
  754. * @return file extention string
  755. */
  756. public function getFileExt ($sFileName)
  757. {
  758. return strtolower(pathinfo($sFileName, PATHINFO_EXTENSION));
  759. }
  760. /**
  761. * Get file title by file name, actually file title is file name without extension.
  762. * @param $sFileName file name
  763. * @return file title string
  764. */
  765. public function getFileTitle ($sFileName)
  766. {
  767. return pathinfo($sFileName, PATHINFO_FILENAME);
  768. }
  769. /**
  770. * Get file mime/type by file name.
  771. * @param $sFileName file name
  772. * @return file mime type string
  773. */
  774. public function getMimeTypeByFileName ($sFileName)
  775. {
  776. $sExt = $this->getFileExt($sFileName);
  777. $sMimeType = $this->_oDb->getMimeTypeByExt($sExt);
  778. if (!$sMimeType)
  779. $sMimeType = BX_DOL_STORAGE_DEFAULT_MIME_TYPE;
  780. return $sMimeType;
  781. }
  782. /**
  783. * Get file icon by file name.
  784. * File icon is just icon filename without patch or URL.
  785. * File icons must be located in images/icons directory in your template subfolder.
  786. * @param $sFileName file name
  787. * @return file icon string
  788. */
  789. public function getIconNameByFileName ($sFileName)
  790. {
  791. $sExt = $this->getFileExt($sFileName);
  792. $sIcon = $this->_oDb->getIconByExt($sExt);
  793. if (!$sIcon)
  794. $sIcon = BX_DOL_STORAGE_DEFAULT_ICON;
  795. return $sIcon;
  796. }
  797. // ------------ internal functions - events
  798. protected function onBeforeFileAdd ($aFileInfo)
  799. {
  800. if ($aFileInfo['size'] > $this->getMaxUploadFileSize($aFileInfo['profile_id'])) {
  801. $this->setErrorCode(BX_DOL_STORAGE_ERR_FILE_TOO_BIG);
  802. return false;
  803. }
  804. // TODO: check site quota - BX_DOL_STORAGE_ERR_SITE_QUOTA_EXCEEDED
  805. $aObjectQuota = $this->_oDb->getStorageObjectQuota();
  806. if (
  807. ($aObjectQuota['quota_size'] && ($aObjectQuota['current_size'] + $aFileInfo['size'] > $aObjectQuota['quota_size']))
  808. ||
  809. ($aObjectQuota['quota_number'] && ($aObjectQuota['current_number'] + 1 > $aObjectQuota['quota_number']))
  810. ) {
  811. $this->setErrorCode(BX_DOL_STORAGE_ERR_OBJECT_QUOTA_EXCEEDED);
  812. return false;
  813. }
  814. $aUserQuota = $this->_oDb->getUserQuota($aFileInfo['profile_id']);
  815. if (
  816. ($aUserQuota['quota_size'] && ($aUserQuota['current_size'] + $aFileInfo['size'] > $aUserQuota['quota_size']))
  817. ||
  818. ($aUserQuota['quota_number'] && ($aUserQuota['current_number'] + 1 > $aUserQuota['quota_number']))
  819. ) {
  820. $this->setErrorCode(BX_DOL_STORAGE_ERR_USER_QUOTA_EXCEEDED);
  821. return false;
  822. }
  823. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  824. $bRet = true;
  825. bx_alert($this->_aObject['object'], 'before_file_add', 0, $aFileInfo['profile_id'], array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  826. return $bRet;
  827. }
  828. protected function onFileAdded ($aFileInfo)
  829. {
  830. // TODO: update site quota - BX_DOL_STORAGE_ERR_SITE_QUOTA_EXCEEDED
  831. if (!$this->_oDb->updateStorageObjectQuota($aFileInfo['size'], 1)) {
  832. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  833. return false;
  834. }
  835. if (!$this->_oDb->updateUserQuota($aFileInfo['profile_id'], $aFileInfo['size'], 1)) {
  836. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  837. return false;
  838. }
  839. if (!$this->insertGhost ($aFileInfo['id'], $aFileInfo['profile_id'], $aFileInfo['content_id'])) {
  840. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  841. return false;
  842. }
  843. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  844. $bRet = true;
  845. bx_alert($this->_aObject['object'], 'file_added', $aFileInfo['id'], $aFileInfo['profile_id'], array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  846. return $bRet;
  847. }
  848. function insertGhost($iFileId, $iProfileId, $iContentId = 0)
  849. {
  850. return $this->_oDb->insertGhosts ($iFileId, $iProfileId, $iContentId);
  851. }
  852. function onBeforeFileDelete ($aFileInfo, $iProfileId)
  853. {
  854. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  855. $bRet = true;
  856. bx_alert($this->_aObject['object'], 'before_file_delete', $aFileInfo['id'], $iProfileId, array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  857. return $bRet;
  858. }
  859. function onFileDeleted ($aFileInfo, $iProfileId, $aGhost = false)
  860. {
  861. // TODO: update site quota
  862. if (!$this->_oDb->updateStorageObjectQuota(-$aFileInfo['size'], -1)) {
  863. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  864. return false;
  865. }
  866. if (!$this->_oDb->updateUserQuota($aFileInfo['profile_id'], -$aFileInfo['size'], -1)) {
  867. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  868. return false;
  869. }
  870. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  871. $bRet = true;
  872. bx_alert($this->_aObject['object'], 'file_deleted', $aFileInfo['id'], $iProfileId, array('file_info' => $aFileInfo, 'ghost' => $aGhost, 'return_value' => &$bRet));
  873. return $bRet;
  874. }
  875. // ------------ internal functions
  876. protected function setErrorCode($i)
  877. {
  878. return ($this->_iErrorCode = $i);
  879. }
  880. protected function genRandName($isCheckForUniq = true)
  881. {
  882. $sRandName = strtolower(genRndPwd(32, false));
  883. if ($isCheckForUniq) {
  884. $iTries = 10;
  885. do {
  886. $aFile = $this->_oDb->getFileByRemoteId($sRandName);
  887. $bExist = is_array($aFile) && $aFile;
  888. } while (--$iTries && $bExist);
  889. }
  890. return $sRandName;
  891. }
  892. protected function genPath($s, $iLevels)
  893. {
  894. $sRet = '';
  895. $i = 1;
  896. while ($iLevels-- > 0)
  897. $sRet .= substr($s, 0, $i++) . '/';
  898. return $sRet;
  899. }
  900. protected function genRemoteNamePath ($sPath, $sLocalId, $sExt)
  901. {
  902. return $sPath . $sLocalId;
  903. }
  904. protected function isValidExt ($sExt)
  905. {
  906. switch ($this->_aObject['ext_mode']) {
  907. case 'allow-deny':
  908. if ($this->isAllowedExt($sExt))
  909. return true;
  910. return false;
  911. case 'deny-allow':
  912. if ($this->isDeniedExt($sExt))
  913. return false;
  914. return true;
  915. default:
  916. return false;
  917. }
  918. }
  919. protected function isAllowedExt ($sExt)
  920. {
  921. return $this->isAllowedDeniedExt($sExt, 'ext_allow');
  922. }
  923. protected function isDeniedExt ($sExt)
  924. {
  925. return $this->isAllowedDeniedExt($sExt, 'ext_deny');
  926. }
  927. protected function isAllowedDeniedExt ($sExt, $sExtMode)
  928. {
  929. if ('' == $this->_aObject[$sExtMode])
  930. return false;
  931. if (!is_array($this->_aObject[$sExtMode]))
  932. $this->_aObject[$sExtMode] = explode(',', $this->_aObject[$sExtMode]);
  933. return in_array ($sExt, $this->_aObject[$sExtMode]);
  934. }
  935. protected function queueFiles($aFiles)
  936. {
  937. if (!$aFiles)
  938. return 0;
  939. $a = array();
  940. foreach ($aFiles as $aFile)
  941. $a[] = $aFile['id'];
  942. return $this->queueFilesForDeletion($a);
  943. }
  944. }
  945. /**
  946. * Handle file uploads via XMLHttpRequest
  947. */
  948. class BxDolStorageHelperXhr
  949. {
  950. protected $sName;
  951. function BxDolStorageHelperXhr ($aParams)
  952. {
  953. $this->sName = $aParams['name'];
  954. }
  955. function getImmediateError()
  956. {
  957. return BX_DOL_STORAGE_ERR_OK;
  958. }
  959. function save($path)
  960. {
  961. $input = fopen("php://input", "r");
  962. $temp = tmpfile();
  963. $realSize = stream_copy_to_stream($input, $temp);
  964. fclose($input);
  965. if (false === $this->getSize() || $realSize != $this->getSize())
  966. return false;
  967. $target = fopen($path, "w");
  968. fseek($temp, 0, SEEK_SET);
  969. stream_copy_to_stream($temp, $target);
  970. fclose($target);
  971. fclose($temp);
  972. return true;
  973. }
  974. function getName()
  975. {
  976. return $this->sName;
  977. }
  978. function getSize()
  979. {
  980. if (isset($_SERVER["CONTENT_LENGTH"]))
  981. return (int)$_SERVER["CONTENT_LENGTH"];
  982. else
  983. return false;
  984. }
  985. }
  986. /**
  987. * Handle file uploads via regular form post (uses the $_FILES array)
  988. */
  989. class BxDolStorageHelperForm
  990. {
  991. protected $aFile;
  992. function BxDolStorageHelperForm ($aParams)
  993. {
  994. $this->aFile = $aParams['file'];
  995. }
  996. function getImmediateError()
  997. {
  998. if (!$this->aFile['size'] || !$this->aFile['tmp_name'])
  999. return BX_DOL_STORAGE_ERR_NO_FILE;
  1000. if (UPLOAD_ERR_OK != $this->aFile['error'])
  1001. return (int)$this->aFile['error'];
  1002. return BX_DOL_STORAGE_ERR_OK;
  1003. }
  1004. function save($path)
  1005. {
  1006. if (!move_uploaded_file($this->aFile['tmp_name'], $path)){
  1007. return false;
  1008. }
  1009. return true;
  1010. }
  1011. function getName()
  1012. {
  1013. return $this->aFile['name'];
  1014. }
  1015. function getSize()
  1016. {
  1017. return $this->aFile['size'];
  1018. }
  1019. }
  1020. /**
  1021. * Store file from local file path
  1022. */
  1023. class BxDolStorageHelperPath
  1024. {
  1025. protected $sPath;
  1026. function BxDolStorageHelperPath ($aParams)
  1027. {
  1028. $this->sPath = $aParams['path'];
  1029. }
  1030. function getImmediateError()
  1031. {
  1032. if (!$this->sPath || !file_exists($this->sPath))
  1033. return BX_DOL_STORAGE_ERR_NO_FILE;
  1034. return BX_DOL_STORAGE_ERR_OK;
  1035. }
  1036. function save($path)
  1037. {
  1038. if (!copy($this->sPath, $path)) {
  1039. return false;
  1040. }
  1041. return true;
  1042. }
  1043. function getName()
  1044. {
  1045. return pathinfo($this->sPath, PATHINFO_BASENAME);
  1046. }
  1047. function getSize()
  1048. {
  1049. return filesize($this->sPath);
  1050. }
  1051. }
  1052. /**
  1053. * Store file from URL
  1054. */
  1055. class BxDolStorageHelperUrl extends BxDolStorageHelperPath
  1056. {
  1057. function BxDolStorageHelperUrl ($aParams)
  1058. {
  1059. $aParams['path'] = '';
  1060. $sExt = pathinfo(parse_url($aParams['url'], PHP_URL_PATH), PATHINFO_EXTENSION);
  1061. if ($sTmpFilename = tempnam(BX_DIRECTORY_PATH_TMP, '')) {
  1062. $aParams['path'] = $sTmpFilename . '.' . $sExt;
  1063. @rename($sTmpFilename, $aParams['path']);
  1064. if ($s = bx_file_get_contents ($aParams['url']))
  1065. file_put_contents($aParams['path'], $s);
  1066. }
  1067. parent::BxDolStorageHelperPath($aParams);
  1068. }
  1069. function getImmediateError()
  1070. {
  1071. $iRet = parent::getImmediateError();
  1072. if (BX_DOL_STORAGE_ERR_OK != $iRet)
  1073. return $iRet;
  1074. return $this->getSize() > 0 ? BX_DOL_STORAGE_ERR_OK : BX_DOL_STORAGE_INVALID_FILE;
  1075. }
  1076. function __destruct()
  1077. {
  1078. @unlink($this->sPath);
  1079. }
  1080. }
  1081. /**
  1082. * Handle file uploads from the same or another storage object
  1083. */
  1084. class BxDolStorageHelperStorage
  1085. {
  1086. protected $iFileId;
  1087. protected $oStorage;
  1088. protected $aFile;
  1089. function BxDolStorageHelperStorage ($aParams)
  1090. {
  1091. $this->iFileId = $aParams['id'];
  1092. $this->oStorage = BxDolStorage::getObjectInstance($aParams['storage']);
  1093. $this->aFile = false;
  1094. if ($this->oStorage)
  1095. $this->aFile = $this->oStorage->getFile($this->iFileId);
  1096. }
  1097. function getImmediateError()
  1098. {
  1099. if (!$this->iFileId)
  1100. return BX_DOL_STORAGE_ERR_NO_FILE;
  1101. if (!$this->oStorage)
  1102. return BX_DOL_STORAGE_ERR_ENGINE_GET;
  1103. if (!$this->aFile)
  1104. return BX_DOL_STORAGE_ERR_NO_FILE;
  1105. return BX_DOL_STORAGE_ERR_OK;
  1106. }
  1107. function save($path)
  1108. {
  1109. $s = bx_file_get_contents ($this->oStorage->getFileUrlById($this->iFileId));
  1110. if (!$s)
  1111. return false;
  1112. return file_put_contents($path, $s) ? true : false;
  1113. }
  1114. function getName()
  1115. {
  1116. return $this->aFile['file_name'];
  1117. }
  1118. function getSize()
  1119. {
  1120. return $this->aFile['size'];
  1121. }
  1122. }
  1123. /** @} */