BxDolStorage.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  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. /**
  270. * Get error code from the last occured error
  271. * @return error code
  272. */
  273. public function getErrorCode()
  274. {
  275. return $this->_iErrorCode;
  276. }
  277. /**
  278. * Get error string from the last occured error
  279. * @return error string
  280. */
  281. public function getErrorString()
  282. {
  283. $a = array (
  284. 1000 => '_sys_storage_err_no_input_method',
  285. 1001 => '_sys_storage_err_no_file',
  286. 1002 => '_sys_storage_invalid_file',
  287. 1003 => '_sys_storage_err_file_too_big',
  288. 1004 => '_sys_storage_err_wrong_ext',
  289. 1005 => '_sys_storage_err_user_quota_exceeded',
  290. 1006 => '_sys_storage_err_object_quota_exceeded',
  291. 1007 => '_sys_storage_err_site_quota_exceeded',
  292. 1008 => '_sys_storage_err_engine_add',
  293. 2001 => '_sys_storage_err_file_not_found',
  294. 2002 => '_sys_storage_err_unlink',
  295. 5001 => '_sys_storage_err_db',
  296. 5002 => '_sys_storage_err_filesystem_perm',
  297. 5003 => '_sys_storage_err_permission_denied',
  298. 5004 => '_sys_storage_err_engine_get',
  299. );
  300. return _t($a[$this->_iErrorCode]);
  301. }
  302. /**
  303. * Get max file size allowed for current user, it checks user quota, object quota, site quota and php setting
  304. * @param $iProfileId profile id to check quota for
  305. * @return quota size in bytes
  306. */
  307. public function getMaxUploadFileSize ($iProfileId)
  308. {
  309. $iMin = PHP_INT_MAX;
  310. $aUserQuota = $this->_oDb->getUserQuota($iProfileId);
  311. if ($aUserQuota['max_file_size'] && $aUserQuota['max_file_size'] < $iMin)
  312. $iMin = $aUserQuota['max_file_size'];
  313. $aObjectQuota = $this->_oDb->getStorageObjectQuota();
  314. if ($aObjectQuota['max_file_size'] && $aObjectQuota['max_file_size'] < $iMin)
  315. $iMin = $aObjectQuota['max_file_size'];
  316. // TODO: get and check site quota
  317. if (!defined('BX_DOL_CRON_EXECUTE')) {
  318. $iUploadMaxFilesize = return_bytes(ini_get('upload_max_filesize'));
  319. if ($iUploadMaxFilesize && $iUploadMaxFilesize < $iMin)
  320. $iMin = $iUploadMaxFilesize;
  321. }
  322. return $iMin;
  323. }
  324. /**
  325. * Store file in the storage area. It is not recommended to use this function directly,
  326. * use other funtions like: storeFileFromForm, storeFileFromXhr, storeFileFromPath, storeFileFromUrl
  327. * @param $sMethod upload method, like regular Form upload, upload from URL, etc
  328. * @param $aMethodParams upload method params
  329. * @param $sName file name with extention
  330. * @param $isPrivate private or public file
  331. * @param $iProfileId profile id of the upload action performer
  332. * @param $iContentId content id to associate with ghost file
  333. * @return id of added file on success, false on error - to get exact error string call getErrorString()
  334. */
  335. public function storeFile($sMethod, $aMethodParams, $sName = false, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  336. {
  337. // setup input source using helper classes, like $_FILES or some URL for example
  338. $sHelperClass = 'BxDolStorageHelper' . $sMethod;
  339. if (!class_exists($sHelperClass)) {
  340. $this->setErrorCode(BX_DOL_STORAGE_ERR_NO_INPUT_METHOD);
  341. return false;
  342. }
  343. $oHelper = new $sHelperClass($aMethodParams);
  344. // check for errors, like size and extentions checking
  345. if ($iImmediateError = $oHelper->getImmediateError()) {
  346. $this->setErrorCode($iImmediateError);
  347. return false;
  348. }
  349. $sExt = $this->getFileExt($oHelper->getName());
  350. $sMimeType = $this->getMimeTypeByFileName($oHelper->getName());
  351. if (!$this->isValidExt($sExt)) {
  352. $this->setErrorCode(BX_DOL_STORAGE_ERR_WRONG_EXT);
  353. return false;
  354. }
  355. // before upload callback + additional checking
  356. if (!$this->onBeforeFileAdd (array(
  357. 'profile_id' => $iProfileId,
  358. 'content_id' => $iContentId,
  359. 'file_name' => $oHelper->getName(),
  360. 'mime_type' => $sMimeType,
  361. 'ext' => $sExt,
  362. 'size' => $oHelper->getSize(),
  363. 'private' => $isPrivate ? 1 : 0,
  364. ))) {
  365. return false;
  366. }
  367. // create tmp file
  368. $sTmpFile = tempnam(BX_DIRECTORY_PATH_TMP, $this->_aObject['object']);
  369. if (!$oHelper->save($sTmpFile)) {
  370. $this->setErrorCode(BX_DOL_STORAGE_INVALID_FILE);
  371. return false;
  372. }
  373. // store file to storage engine
  374. $sLocalId = $this->genRandName();
  375. $sPath = $this->genPath($sLocalId, $this->_aObject['levels']);
  376. $sRemoteNamePath = $this->genRemoteNamePath ($sPath, $sLocalId, $sExt);
  377. if (!$this->addFileToEngine($sTmpFile, $sLocalId, $oHelper->getName(), $isPrivate, $iProfileId)) {
  378. unlink($sTmpFile);
  379. $this->setErrorCode(BX_DOL_STORAGE_ERR_ENGINE_ADD);
  380. return false;
  381. }
  382. unlink($sTmpFile);
  383. // add record in db
  384. $iTime = time();
  385. $iSize = $oHelper->getSize();
  386. $bFileAdded = $this->_oDb->addFile($iProfileId, $sLocalId, $sRemoteNamePath, $oHelper->getName(), $sMimeType, $sExt, $iSize, $iTime, $isPrivate);
  387. $iId = $this->_oDb->lastId();
  388. if (!$bFileAdded || !$iId) {
  389. $this->deleteFileFromEngine($sPath . $sLocalId, $isPrivate);
  390. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  391. return false;
  392. }
  393. // after upload callback + triggers update
  394. if (!$this->onFileAdded (array(
  395. 'id' => $iId,
  396. 'profile_id' => $iProfileId,
  397. 'content_id' => $iContentId,
  398. 'remote_id' => $sLocalId,
  399. 'path' => $sPath . $sLocalId,
  400. 'file_name' => $oHelper->getName(),
  401. 'mime_type' => $sMimeType,
  402. 'size' => $iSize,
  403. 'private' => $isPrivate ? 1 : 0,
  404. ))) {
  405. $this->deleteFileFromEngine($sPath . $sLocalId, $isPrivate);
  406. $this->_oDb->deleteFile($iId);
  407. return false;
  408. }
  409. return $iId;
  410. }
  411. /**
  412. * convert default multiple files array into more logical one
  413. */
  414. public function convertMultipleFilesArray($aFiles)
  415. {
  416. if (!is_array($aFiles) || !is_array($aFiles['name']))
  417. return false;
  418. $aRet = array ();
  419. foreach ($aFiles['name'] as $i => $sName) {
  420. foreach ($aFiles as $sKey => $r) {
  421. if (!$aFiles['name'][$i])
  422. break;
  423. $aRet[$i][$sKey] = $aFiles[$sKey][$i];
  424. }
  425. }
  426. return $aRet;
  427. }
  428. /**
  429. * the same as storeFile, but it tries to do it directly from uploaded file
  430. */
  431. public function storeFileFromForm($aFile, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  432. {
  433. return $this->storeFile('Form', array('file' => $aFile), false, $isPrivate, $iProfileId, $iContentId);
  434. }
  435. /**
  436. * the same as storeFile, but it tries to do it directly from HTML5 file upload method
  437. */
  438. public function storeFileFromXhr($sName, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  439. {
  440. return $this->storeFile('Xhr', array('name' => $sName), false, $isPrivate, $iProfileId, $iContentId);
  441. }
  442. /**
  443. * the same as storeFile, but it tries to do it directly from local file
  444. */
  445. public function storeFileFromPath($sPath, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  446. {
  447. return $this->storeFile('Path', array('path' => $sPath), false, $isPrivate, $iProfileId, $iContentId);
  448. }
  449. /**
  450. * the same as storeFileFromPath, but it tries to do it from URL
  451. */
  452. public function storeFileFromUrl($sUrl, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  453. {
  454. return $this->storeFile('Url', array('url' => $sUrl), false, $isPrivate, $iProfileId, $iContentId);
  455. }
  456. /**
  457. * the same as storeFile, but it tries to do it directly from the same or another storage by file id
  458. * @param $aParams['id'] - file ID in the storage
  459. * @param $aParams['storage'] - the storage name
  460. */
  461. public function storeFileFromStorage($aParams, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  462. {
  463. if (!isset($aParams['id']) || !(int)$aParams['id'])
  464. $aParams['id'] = 0;
  465. if (!isset($aParams['storage']))
  466. $aParams['storage'] = $this->_aObject['object'];
  467. return $this->storeFile('Storage', $aParams, false, $isPrivate, $iProfileId, $iContentId = 0);
  468. }
  469. /**
  470. * Delete file by file id.
  471. */
  472. public function deleteFile($iFileId, $iProfileId = 0)
  473. {
  474. $aFile = $this->_oDb->getFileById ($iFileId);
  475. if (!$aFile) {
  476. $this->setErrorCode(BX_DOL_STORAGE_ERR_FILE_NOT_FOUND);
  477. return false;
  478. }
  479. if (!$this->onBeforeFileDelete ($aFile, $iProfileId)) {
  480. return false;
  481. }
  482. if (!$this->deleteFileFromEngine($aFile['path'], $aFile['private'])) {
  483. return false;
  484. }
  485. if (!$this->_oDb->deleteFile($aFile['id'])) {
  486. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  487. return false;
  488. }
  489. if (!$this->onFileDeleted ($aFile, $iProfileId)) {
  490. return false;
  491. }
  492. return true;
  493. }
  494. /**
  495. * Queue file(s) for deletion. File(s) will be deleted later upon cron call (usually every minute).
  496. * @param $mixedFileId file id or array of file ids.
  497. * @return number of queued files
  498. */
  499. public function queueFilesForDeletion($mixedFileId)
  500. {
  501. if (!is_array($mixedFileId))
  502. $mixedFileId = array ($mixedFileId);
  503. bx_import('BxDolForm');
  504. $oChecker = new BxDolFormCheckerHelper();
  505. return $this->_oDb->queueFilesForDeletion (array_unique($oChecker->passInt($mixedFileId)));
  506. }
  507. /**
  508. * Queue file(s) for deletion by getting neccesary files from ghosts table by profile id and content id
  509. * @param $iProfileId profile id associated with files
  510. * @param $iContentId content id associated with files, or false if to check by profile id only
  511. * @return number of queued files
  512. */
  513. public function queueFilesForDeletionFromGhosts($iProfileId, $iContentId = false)
  514. {
  515. $aFiles = $this->getGhosts ($iProfileId, $iContentId);
  516. return $this->queueFiles($aFiles);
  517. }
  518. /**
  519. * Queue file(s) for deletion of the whole storage object
  520. * @return number of queued files
  521. */
  522. public function queueFilesForDeletionFromObject()
  523. {
  524. $aFiles = $this->getFiles (false);
  525. return $this->queueFiles($aFiles);
  526. }
  527. /**
  528. * Set file private or public.
  529. */
  530. public function setFilePrivate($iFileId, $isPrivate = true)
  531. {
  532. if (!$this->_oDb->modifyFilePrivate ($iFileId, $isPrivate)) {
  533. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  534. return false;
  535. }
  536. return true;
  537. }
  538. /**
  539. * Get file url.
  540. * @param $iFileId file id
  541. * @return file url or false on error
  542. */
  543. public function getFileUrlById($iFileId) { }
  544. /**
  545. * Get file info array by file id.
  546. * @param $iFileId file id
  547. * @return array
  548. */
  549. public function getFile($iFileId)
  550. {
  551. return $this->_oDb->getFileById($iFileId);
  552. }
  553. /**
  554. * check if file is private or public
  555. * @param $iFileId file id
  556. * @return boolean
  557. */
  558. public function isFilePrivate($iFileId)
  559. {
  560. $aFile = $this->getFile ($iFileId);
  561. return $aFile['private'] ? true : false;
  562. }
  563. /**
  564. * Call this function after saving/associate just uploaded file id, so file is not orphaned/ghost.
  565. * Ghost files appear on download form automaticaly during next upload,
  566. * for example if file was uploaded but was not submitted for some reason.
  567. * This mechanism ensure that the file is not lost.
  568. * @param $mixedFileIds array of file ids or just one file id
  569. * @param $iProfileId profile id
  570. * @param return number of deleted ghost files
  571. */
  572. public function afterUploadCleanup($mixedFileIds, $iProfileId, $iContentId = false)
  573. {
  574. return $this->_oDb->deleteGhosts($mixedFileIds, $iProfileId, $iContentId);
  575. }
  576. /**
  577. * Get ghost/orphaned files for particular user.
  578. * @param $iProfileId profile id
  579. * @param $iContentId content id, or false to not consider content id at all
  580. * @return array of arrays
  581. */
  582. public function getGhosts($iProfileId, $iContentId = false)
  583. {
  584. return $this->_oDb->getGhosts($iProfileId, $iContentId);
  585. }
  586. /**
  587. * Update ghosts' content id.
  588. * @param $mixedFileIds array of file ids or just one file id
  589. * @param $iProfileId profile id
  590. * @param $iContentId content id
  591. * @return true on success or false otherwise
  592. */
  593. public function updateGhostsContentId($mixedFileIds, $iProfileId, $iContentId)
  594. {
  595. return $this->_oDb->updateGhostsContentId($mixedFileIds, $iProfileId, $iContentId);
  596. }
  597. /**
  598. * Get files list for particular user.
  599. * @param $iProfileId profile id
  600. * @return array of arrays
  601. */
  602. public function getFiles($iProfileId)
  603. {
  604. return $this->_oDb->getFiles($iProfileId);
  605. }
  606. /**
  607. * Get all files in the storage
  608. */
  609. public function getFilesAll($iStart = 0, $iPerPage = 1000)
  610. {
  611. return $this->_oDb->getFilesAll($iStart, $iPerPage);
  612. }
  613. /**
  614. * Get readable representation of restrictions by file extentions.
  615. * @param $iProfileId profile id
  616. * @return string
  617. */
  618. public function getRestrictionsTextExtensions ($iProfileId)
  619. {
  620. switch ($this->_aObject['ext_mode']) {
  621. case 'allow-deny':
  622. if (!$this->_aObject['ext_allow'])
  623. return _t('_sys_storage_restriction_ext_all_denied');
  624. return _t('_sys_storage_restriction_ext_allowed', _t_format_extensions($this->_aObject['ext_allow']));
  625. case 'deny-allow':
  626. if (!$this->_aObject['ext_deny'])
  627. return _t('_sys_storage_restriction_ext_all_allowed');
  628. return _t('_sys_storage_restriction_ext_denied', _t_format_extensions($this->_aObject['ext_deny']));
  629. default:
  630. return _t('_sys_storage_restriction_ext_all_denied');
  631. }
  632. }
  633. /**
  634. * Get readable representation of restrictions by file size.
  635. * @param $iProfileId profile id
  636. * @return string
  637. */
  638. public function getRestrictionsTextFileSize ($iProfileId)
  639. {
  640. return _t('_sys_storage_restriction_size', _t_format_size($this->getMaxUploadFileSize($iProfileId)));
  641. }
  642. /**
  643. * Get readable representation of all restrictions.
  644. * @param $iProfileId profile id
  645. * @return array of strings
  646. */
  647. public function getRestrictionsTextArray ($iProfileId)
  648. {
  649. $aTypes = array('Extensions', 'FileSize');
  650. $aRet = array();
  651. foreach ($aTypes as $sType) {
  652. $sFunc = 'getRestrictionsText' . $sType;
  653. $s = $this->$sFunc ($iProfileId);
  654. if ($s)
  655. $aRet[] = $s;
  656. }
  657. return $aRet;
  658. }
  659. /**
  660. * Reread available mimetypes from particular file.
  661. * It clears 'sys_storage_mime_types' table and fill it with data form provided file.
  662. * The format of file is: mime/type _space_or_tab_ extentions_sperated_by_space.
  663. * Usually the file is mime.types file from apache or /etc/mime.types from unix systems.
  664. * @param $sFile file to read mime types from
  665. * @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.
  666. */
  667. public function reloadMimeTypesFromFile ($sFile)
  668. {
  669. $sResult = '';
  670. $aIcons = array (
  671. 'mime-type-psd.png' => array('psd'),
  672. 'mime-type-png.png' => array('png'),
  673. 'mime-type-image.png' => 'image/',
  674. 'mime-type-video.png' => 'video/',
  675. 'mime-type-audio.png' => 'audio/',
  676. 'mime-type-presentation.png' => array('ppt', 'pptx', 'sxi', 'sti', 'odp', 'sdp', 'sdd'),
  677. 'mime-type-spreadsheet.png' => array('xls', 'xlt', 'xlsx', 'sxc', 'stc', 'ods', 'ots', 'sdc', 'csv', 'dif', 'slk', 'pxl'),
  678. 'mime-type-document.png' => array('doc', 'docx', 'odt', 'ott', 'sxw', 'stw', 'rtf', 'sdw', 'txt', 'pdb', 'psw', 'pdf'),
  679. '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'),
  680. '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'),
  681. );
  682. $f = fopen ($sFile, 'r');
  683. if (!$f)
  684. return false;
  685. $this->_oDb->clearAllMimeTypes();
  686. while (!feof($f) && ($s = fgets($f, 4096)) !== false) {
  687. $s = trim($s);
  688. if (!$s || '#' == $s[0])
  689. continue;
  690. $a = preg_split ("/[\s\\b]+/", $s, 2);
  691. if (!isset($a[0]) || !isset($a[1]))
  692. continue;
  693. $sMimeType = $a[0];
  694. $aExts = preg_split ("/[\s]+/", $a[1]);
  695. foreach ($aExts as $sExt) {
  696. $sIcon = '';
  697. foreach ($aIcons as $sIc => $if) {
  698. if (!(is_array($if) && in_array($sExt, $if)) && !(is_string($if) && 0 == strncmp($if, $sMimeType, strlen($if))))
  699. continue;
  700. $sIcon = $sIc;
  701. break;
  702. }
  703. if (!$this->_oDb->addMimeType($sMimeType, $sExt, $sIcon))
  704. $sResult .= _t('_Error') . ': ' . $sMimeType . "\t" . $sExt . "\n";
  705. }
  706. }
  707. fclose($f);
  708. if (!$sResult)
  709. $sResult = _t('_Success');
  710. return $sResult;
  711. }
  712. /**
  713. * Get file extension by file name.
  714. * @param $sFileName file name
  715. * @return file extention string
  716. */
  717. public function getFileExt ($sFileName)
  718. {
  719. return strtolower(pathinfo($sFileName, PATHINFO_EXTENSION));
  720. }
  721. /**
  722. * Get file title by file name, actually file title is file name without extension.
  723. * @param $sFileName file name
  724. * @return file title string
  725. */
  726. public function getFileTitle ($sFileName)
  727. {
  728. return pathinfo($sFileName, PATHINFO_FILENAME);
  729. }
  730. /**
  731. * Get file mime/type by file name.
  732. * @param $sFileName file name
  733. * @return file mime type string
  734. */
  735. public function getMimeTypeByFileName ($sFileName)
  736. {
  737. $sExt = $this->getFileExt($sFileName);
  738. $sMimeType = $this->_oDb->getMimeTypeByExt($sExt);
  739. if (!$sMimeType)
  740. $sMimeType = BX_DOL_STORAGE_DEFAULT_MIME_TYPE;
  741. return $sMimeType;
  742. }
  743. /**
  744. * Get file icon by file name.
  745. * File icon is just icon filename without patch or URL.
  746. * File icons must be located in images/icons directory in your template subfolder.
  747. * @param $sFileName file name
  748. * @return file icon string
  749. */
  750. public function getIconNameByFileName ($sFileName)
  751. {
  752. $sExt = $this->getFileExt($sFileName);
  753. $sIcon = $this->_oDb->getIconByExt($sExt);
  754. if (!$sIcon)
  755. $sIcon = BX_DOL_STORAGE_DEFAULT_ICON;
  756. return $sIcon;
  757. }
  758. // ------------ internal functions - events
  759. protected function onBeforeFileAdd ($aFileInfo)
  760. {
  761. if ($aFileInfo['size'] > $this->getMaxUploadFileSize($aFileInfo['profile_id'])) {
  762. $this->setErrorCode(BX_DOL_STORAGE_ERR_FILE_TOO_BIG);
  763. return false;
  764. }
  765. // TODO: check site quota - BX_DOL_STORAGE_ERR_SITE_QUOTA_EXCEEDED
  766. $aObjectQuota = $this->_oDb->getStorageObjectQuota();
  767. if (
  768. ($aObjectQuota['quota_size'] && ($aObjectQuota['current_size'] + $aFileInfo['size'] > $aObjectQuota['quota_size']))
  769. ||
  770. ($aObjectQuota['quota_number'] && ($aObjectQuota['current_number'] + 1 > $aObjectQuota['quota_number']))
  771. ) {
  772. $this->setErrorCode(BX_DOL_STORAGE_ERR_OBJECT_QUOTA_EXCEEDED);
  773. return false;
  774. }
  775. $aUserQuota = $this->_oDb->getUserQuota($aFileInfo['profile_id']);
  776. if (
  777. ($aUserQuota['quota_size'] && ($aUserQuota['current_size'] + $aFileInfo['size'] > $aUserQuota['quota_size']))
  778. ||
  779. ($aUserQuota['quota_number'] && ($aUserQuota['current_number'] + 1 > $aUserQuota['quota_number']))
  780. ) {
  781. $this->setErrorCode(BX_DOL_STORAGE_ERR_USER_QUOTA_EXCEEDED);
  782. return false;
  783. }
  784. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  785. $bRet = true;
  786. bx_alert($this->_aObject['object'], 'before_file_add', 0, $aFileInfo['profile_id'], array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  787. return $bRet;
  788. }
  789. protected function onFileAdded ($aFileInfo)
  790. {
  791. // TODO: update site quota - BX_DOL_STORAGE_ERR_SITE_QUOTA_EXCEEDED
  792. if (!$this->_oDb->updateStorageObjectQuota($aFileInfo['size'], 1)) {
  793. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  794. return false;
  795. }
  796. if (!$this->_oDb->updateUserQuota($aFileInfo['profile_id'], $aFileInfo['size'], 1)) {
  797. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  798. return false;
  799. }
  800. if (!$this->insertGhost ($aFileInfo['id'], $aFileInfo['profile_id'], $aFileInfo['content_id'])) {
  801. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  802. return false;
  803. }
  804. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  805. $bRet = true;
  806. bx_alert($this->_aObject['object'], 'file_added', $aFileInfo['id'], $aFileInfo['profile_id'], array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  807. return $bRet;
  808. }
  809. function insertGhost($iFileId, $iProfileId, $iContentId = 0)
  810. {
  811. return $this->_oDb->insertGhosts ($iFileId, $iProfileId, $iContentId);
  812. }
  813. function onBeforeFileDelete ($aFileInfo, $iProfileId)
  814. {
  815. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  816. $bRet = true;
  817. bx_alert($this->_aObject['object'], 'before_file_delete', $aFileInfo['id'], $iProfileId, array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  818. return $bRet;
  819. }
  820. function onFileDeleted ($aFileInfo, $iProfileId)
  821. {
  822. // TODO: update site quota
  823. if (!$this->_oDb->updateStorageObjectQuota(-$aFileInfo['size'], -1)) {
  824. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  825. return false;
  826. }
  827. if (!$this->_oDb->updateUserQuota($aFileInfo['profile_id'], -$aFileInfo['size'], -1)) {
  828. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  829. return false;
  830. }
  831. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  832. $bRet = true;
  833. bx_alert($this->_aObject['object'], 'file_deleted', $aFileInfo['id'], $iProfileId, array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  834. return $bRet;
  835. }
  836. // ------------ internal functions
  837. protected function setErrorCode($i)
  838. {
  839. return ($this->_iErrorCode = $i);
  840. }
  841. protected function genRandName($isCheckForUniq = true)
  842. {
  843. $sRandName = strtolower(genRndPwd(32, false));
  844. if ($isCheckForUniq) {
  845. $iTries = 10;
  846. do {
  847. $aFile = $this->_oDb->getFileByRemoteId($sRandName);
  848. $bExist = is_array($aFile) && $aFile;
  849. } while (--$iTries && $bExist);
  850. }
  851. return $sRandName;
  852. }
  853. protected function genPath($s, $iLevels)
  854. {
  855. $sRet = '';
  856. $i = 1;
  857. while ($iLevels-- > 0)
  858. $sRet .= substr($s, 0, $i++) . '/';
  859. return $sRet;
  860. }
  861. protected function genRemoteNamePath ($sPath, $sLocalId, $sExt)
  862. {
  863. return $sPath . $sLocalId;
  864. }
  865. protected function isValidExt ($sExt)
  866. {
  867. switch ($this->_aObject['ext_mode']) {
  868. case 'allow-deny':
  869. if ($this->isAllowedExt($sExt))
  870. return true;
  871. return false;
  872. case 'deny-allow':
  873. if ($this->isDeniedExt($sExt))
  874. return false;
  875. return true;
  876. default:
  877. return false;
  878. }
  879. }
  880. protected function isAllowedExt ($sExt)
  881. {
  882. return $this->isAllowedDeniedExt($sExt, 'ext_allow');
  883. }
  884. protected function isDeniedExt ($sExt)
  885. {
  886. return $this->isAllowedDeniedExt($sExt, 'ext_deny');
  887. }
  888. protected function isAllowedDeniedExt ($sExt, $sExtMode)
  889. {
  890. if ('' == $this->_aObject[$sExtMode])
  891. return false;
  892. if (!is_array($this->_aObject[$sExtMode]))
  893. $this->_aObject[$sExtMode] = explode(',', $this->_aObject[$sExtMode]);
  894. return in_array ($sExt, $this->_aObject[$sExtMode]);
  895. }
  896. protected function queueFiles($aFiles)
  897. {
  898. if (!$aFiles)
  899. return 0;
  900. $a = array();
  901. foreach ($aFiles as $aFile)
  902. $a[] = $aFile['id'];
  903. return $this->queueFilesForDeletion($a);
  904. }
  905. }
  906. /**
  907. * Handle file uploads via XMLHttpRequest
  908. */
  909. class BxDolStorageHelperXhr
  910. {
  911. protected $sName;
  912. function BxDolStorageHelperXhr ($aParams)
  913. {
  914. $this->sName = $aParams['name'];
  915. }
  916. function getImmediateError()
  917. {
  918. return BX_DOL_STORAGE_ERR_OK;
  919. }
  920. function save($path)
  921. {
  922. $input = fopen("php://input", "r");
  923. $temp = tmpfile();
  924. $realSize = stream_copy_to_stream($input, $temp);
  925. fclose($input);
  926. if (false === $this->getSize() || $realSize != $this->getSize())
  927. return false;
  928. $target = fopen($path, "w");
  929. fseek($temp, 0, SEEK_SET);
  930. stream_copy_to_stream($temp, $target);
  931. fclose($target);
  932. fclose($temp);
  933. return true;
  934. }
  935. function getName()
  936. {
  937. return $this->sName;
  938. }
  939. function getSize()
  940. {
  941. if (isset($_SERVER["CONTENT_LENGTH"]))
  942. return (int)$_SERVER["CONTENT_LENGTH"];
  943. else
  944. return false;
  945. }
  946. }
  947. /**
  948. * Handle file uploads via regular form post (uses the $_FILES array)
  949. */
  950. class BxDolStorageHelperForm
  951. {
  952. protected $aFile;
  953. function BxDolStorageHelperForm ($aParams)
  954. {
  955. $this->aFile = $aParams['file'];
  956. }
  957. function getImmediateError()
  958. {
  959. if (!$this->aFile['size'] || !$this->aFile['tmp_name'])
  960. return BX_DOL_STORAGE_ERR_NO_FILE;
  961. if (UPLOAD_ERR_OK != $this->aFile['error'])
  962. return (int)$this->aFile['error'];
  963. return BX_DOL_STORAGE_ERR_OK;
  964. }
  965. function save($path)
  966. {
  967. if (!move_uploaded_file($this->aFile['tmp_name'], $path)){
  968. return false;
  969. }
  970. return true;
  971. }
  972. function getName()
  973. {
  974. return $this->aFile['name'];
  975. }
  976. function getSize()
  977. {
  978. return $this->aFile['size'];
  979. }
  980. }
  981. /**
  982. * Store file from local file path
  983. */
  984. class BxDolStorageHelperPath
  985. {
  986. protected $sPath;
  987. function BxDolStorageHelperPath ($aParams)
  988. {
  989. $this->sPath = $aParams['path'];
  990. }
  991. function getImmediateError()
  992. {
  993. if (!$this->sPath || !file_exists($this->sPath))
  994. return BX_DOL_STORAGE_ERR_NO_FILE;
  995. return BX_DOL_STORAGE_ERR_OK;
  996. }
  997. function save($path)
  998. {
  999. if (!copy($this->sPath, $path)) {
  1000. return false;
  1001. }
  1002. return true;
  1003. }
  1004. function getName()
  1005. {
  1006. return pathinfo($this->sPath, PATHINFO_BASENAME);
  1007. }
  1008. function getSize()
  1009. {
  1010. return filesize($this->sPath);
  1011. }
  1012. }
  1013. /**
  1014. * Store file from URL
  1015. */
  1016. class BxDolStorageHelperUrl extends BxDolStorageHelperPath
  1017. {
  1018. function BxDolStorageHelperUrl ($aParams)
  1019. {
  1020. $aParams['path'] = '';
  1021. $sExt = pathinfo(parse_url($aParams['url'], PHP_URL_PATH), PATHINFO_EXTENSION);
  1022. if ($sTmpFilename = tempnam(BX_DIRECTORY_PATH_TMP, '')) {
  1023. $aParams['path'] = $sTmpFilename . '.' . $sExt;
  1024. @rename($sTmpFilename, $aParams['path']);
  1025. if ($s = bx_file_get_contents ($aParams['url']))
  1026. file_put_contents($aParams['path'], $s);
  1027. }
  1028. parent::BxDolStorageHelperPath($aParams);
  1029. }
  1030. function getImmediateError()
  1031. {
  1032. $iRet = parent::getImmediateError();
  1033. if (BX_DOL_STORAGE_ERR_OK != $iRet)
  1034. return $iRet;
  1035. return $this->getSize() > 0 ? BX_DOL_STORAGE_ERR_OK : BX_DOL_STORAGE_INVALID_FILE;
  1036. }
  1037. function __destruct()
  1038. {
  1039. @unlink($this->sPath);
  1040. }
  1041. }
  1042. /**
  1043. * Handle file uploads from the same or another storage object
  1044. */
  1045. class BxDolStorageHelperStorage
  1046. {
  1047. protected $iFileId;
  1048. protected $oStorage;
  1049. protected $aFile;
  1050. function BxDolStorageHelperStorage ($aParams)
  1051. {
  1052. $this->iFileId = $aParams['id'];
  1053. $this->oStorage = BxDolStorage::getObjectInstance($aParams['storage']);
  1054. $this->aFile = false;
  1055. if ($this->oStorage)
  1056. $this->aFile = $this->oStorage->getFile($this->iFileId);
  1057. }
  1058. function getImmediateError()
  1059. {
  1060. if (!$this->iFileId)
  1061. return BX_DOL_STORAGE_ERR_NO_FILE;
  1062. if (!$this->oStorage)
  1063. return BX_DOL_STORAGE_ERR_ENGINE_GET;
  1064. if (!$this->aFile)
  1065. return BX_DOL_STORAGE_ERR_NO_FILE;
  1066. return BX_DOL_STORAGE_ERR_OK;
  1067. }
  1068. function save($path)
  1069. {
  1070. $s = bx_file_get_contents ($this->oStorage->getFileUrlById($this->iFileId));
  1071. if (!$s)
  1072. return false;
  1073. return file_put_contents($path, $s) ? true : false;
  1074. }
  1075. function getName()
  1076. {
  1077. return $this->aFile['file_name'];
  1078. }
  1079. function getSize()
  1080. {
  1081. return $this->aFile['size'];
  1082. }
  1083. }
  1084. /** @} */