BxDolStorage.php 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  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. * check if file is private or public
  574. * @param $iFileId file id
  575. * @return boolean
  576. */
  577. public function isFilePrivate($iFileId)
  578. {
  579. $aFile = $this->getFile ($iFileId);
  580. return $aFile['private'] ? true : false;
  581. }
  582. /**
  583. * Call this function after saving/associate just uploaded file id, so file is not orphaned/ghost.
  584. * Ghost files appear on download form automaticaly during next upload,
  585. * for example if file was uploaded but was not submitted for some reason.
  586. * This mechanism ensure that the file is not lost.
  587. * @param $mixedFileIds array of file ids or just one file id
  588. * @param $iProfileId profile id
  589. * @param return number of deleted ghost files
  590. */
  591. public function afterUploadCleanup($mixedFileIds, $iProfileId, $iContentId = false)
  592. {
  593. return $this->_oDb->deleteGhosts($mixedFileIds, $iProfileId, $iContentId);
  594. }
  595. /**
  596. * Get ghost/orphaned files for particular user.
  597. * @param $iProfileId profile id
  598. * @param $iContentId content id, or false to not consider content id at all
  599. * @param $isCheckAllAccountProfiles get all files associated with all account profiles
  600. * @return array of arrays
  601. */
  602. public function getGhosts($iProfileId, $iContentId = false, $isCheckAllAccountProfiles = false)
  603. {
  604. if ($isCheckAllAccountProfiles && ($oProfile = BxDolProfile::getInstance($iProfileId))) {
  605. $oAccount = $oProfile->getAccountObject();
  606. $aProfiles = $oAccount->getProfilesIds();
  607. return $this->_oDb->getGhosts($aProfiles, $iContentId);
  608. }
  609. return $this->_oDb->getGhosts($iProfileId, $iContentId);
  610. }
  611. /**
  612. * Update ghosts' content id.
  613. * @param $mixedFileIds array of file ids or just one file id
  614. * @param $iProfileId profile id
  615. * @param $iContentId content id
  616. * @return true on success or false otherwise
  617. */
  618. public function updateGhostsContentId($mixedFileIds, $iProfileId, $iContentId)
  619. {
  620. $aProfiles = array();
  621. if ($oProfile = BxDolProfile::getInstance($iProfileId)) {
  622. $oAccount = $oProfile->getAccountObject();
  623. $aProfiles = $oAccount->getProfilesIds();
  624. }
  625. return $this->_oDb->updateGhostsContentId($mixedFileIds, $iProfileId, $iContentId, $aProfiles);
  626. }
  627. /**
  628. * Get files list for particular user.
  629. * @param $iProfileId profile id
  630. * @return array of arrays
  631. */
  632. public function getFiles($iProfileId)
  633. {
  634. return $this->_oDb->getFiles($iProfileId);
  635. }
  636. /**
  637. * Get all files in the storage
  638. */
  639. public function getFilesAll($iStart = 0, $iPerPage = 1000)
  640. {
  641. return $this->_oDb->getFilesAll($iStart, $iPerPage);
  642. }
  643. /**
  644. * Get readable representation of restrictions by file extentions.
  645. * @param $iProfileId profile id
  646. * @return string
  647. */
  648. public function getRestrictionsTextExtensions ($iProfileId)
  649. {
  650. switch ($this->_aObject['ext_mode']) {
  651. case 'allow-deny':
  652. if (!$this->_aObject['ext_allow'])
  653. return _t('_sys_storage_restriction_ext_all_denied');
  654. return _t('_sys_storage_restriction_ext_allowed', _t_format_extensions($this->_aObject['ext_allow']));
  655. case 'deny-allow':
  656. if (!$this->_aObject['ext_deny'])
  657. return _t('_sys_storage_restriction_ext_all_allowed');
  658. return _t('_sys_storage_restriction_ext_denied', _t_format_extensions($this->_aObject['ext_deny']));
  659. default:
  660. return _t('_sys_storage_restriction_ext_all_denied');
  661. }
  662. }
  663. /**
  664. * Get readable representation of restrictions by file size.
  665. * @param $iProfileId profile id
  666. * @return string
  667. */
  668. public function getRestrictionsTextFileSize ($iProfileId)
  669. {
  670. return _t('_sys_storage_restriction_size', _t_format_size($this->getMaxUploadFileSize($iProfileId)));
  671. }
  672. /**
  673. * Get readable representation of all restrictions.
  674. * @param $iProfileId profile id
  675. * @return array of strings
  676. */
  677. public function getRestrictionsTextArray ($iProfileId)
  678. {
  679. $aTypes = array('Extensions', 'FileSize');
  680. $aRet = array();
  681. foreach ($aTypes as $sType) {
  682. $sFunc = 'getRestrictionsText' . $sType;
  683. $s = $this->$sFunc ($iProfileId);
  684. if ($s)
  685. $aRet[] = $s;
  686. }
  687. return $aRet;
  688. }
  689. /**
  690. * Reread available mimetypes from particular file.
  691. * It clears 'sys_storage_mime_types' table and fill it with data form provided file.
  692. * The format of file is: mime/type _space_or_tab_ extentions_sperated_by_space.
  693. * Usually the file is mime.types file from apache or /etc/mime.types from unix systems.
  694. * @param $sFile file to read mime types from
  695. * @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.
  696. */
  697. public function reloadMimeTypesFromFile ($sFile)
  698. {
  699. $sResult = '';
  700. $aIcons = array (
  701. 'mime-type-psd.png' => array('psd'),
  702. 'mime-type-png.png' => array('png'),
  703. 'mime-type-image.png' => 'image/',
  704. 'mime-type-video.png' => 'video/',
  705. 'mime-type-audio.png' => 'audio/',
  706. 'mime-type-presentation.png' => array('ppt', 'pptx', 'sxi', 'sti', 'odp', 'sdp', 'sdd'),
  707. 'mime-type-spreadsheet.png' => array('xls', 'xlt', 'xlsx', 'sxc', 'stc', 'ods', 'ots', 'sdc', 'csv', 'dif', 'slk', 'pxl'),
  708. 'mime-type-document.png' => array('doc', 'docx', 'odt', 'ott', 'sxw', 'stw', 'rtf', 'sdw', 'txt', 'pdb', 'psw', 'pdf'),
  709. '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'),
  710. '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'),
  711. );
  712. $f = fopen ($sFile, 'r');
  713. if (!$f)
  714. return false;
  715. $this->_oDb->clearAllMimeTypes();
  716. while (!feof($f) && ($s = fgets($f, 4096)) !== false) {
  717. $s = trim($s);
  718. if (!$s || '#' == $s[0])
  719. continue;
  720. $a = preg_split ("/[\s\\b]+/", $s, 2);
  721. if (!isset($a[0]) || !isset($a[1]))
  722. continue;
  723. $sMimeType = $a[0];
  724. $aExts = preg_split ("/[\s]+/", $a[1]);
  725. foreach ($aExts as $sExt) {
  726. $sIcon = '';
  727. foreach ($aIcons as $sIc => $if) {
  728. if (!(is_array($if) && in_array($sExt, $if)) && !(is_string($if) && 0 == strncmp($if, $sMimeType, strlen($if))))
  729. continue;
  730. $sIcon = $sIc;
  731. break;
  732. }
  733. if (!$this->_oDb->addMimeType($sMimeType, $sExt, $sIcon))
  734. $sResult .= _t('_Error') . ': ' . $sMimeType . "\t" . $sExt . "\n";
  735. }
  736. }
  737. fclose($f);
  738. if (!$sResult)
  739. $sResult = _t('_Success');
  740. return $sResult;
  741. }
  742. /**
  743. * Get file extension by file name.
  744. * @param $sFileName file name
  745. * @return file extention string
  746. */
  747. public function getFileExt ($sFileName)
  748. {
  749. return strtolower(pathinfo($sFileName, PATHINFO_EXTENSION));
  750. }
  751. /**
  752. * Get file title by file name, actually file title is file name without extension.
  753. * @param $sFileName file name
  754. * @return file title string
  755. */
  756. public function getFileTitle ($sFileName)
  757. {
  758. return pathinfo($sFileName, PATHINFO_FILENAME);
  759. }
  760. /**
  761. * Get file mime/type by file name.
  762. * @param $sFileName file name
  763. * @return file mime type string
  764. */
  765. public function getMimeTypeByFileName ($sFileName)
  766. {
  767. $sExt = $this->getFileExt($sFileName);
  768. $sMimeType = $this->_oDb->getMimeTypeByExt($sExt);
  769. if (!$sMimeType)
  770. $sMimeType = BX_DOL_STORAGE_DEFAULT_MIME_TYPE;
  771. return $sMimeType;
  772. }
  773. /**
  774. * Get file icon by file name.
  775. * File icon is just icon filename without patch or URL.
  776. * File icons must be located in images/icons directory in your template subfolder.
  777. * @param $sFileName file name
  778. * @return file icon string
  779. */
  780. public function getIconNameByFileName ($sFileName)
  781. {
  782. $sExt = $this->getFileExt($sFileName);
  783. $sIcon = $this->_oDb->getIconByExt($sExt);
  784. if (!$sIcon)
  785. $sIcon = BX_DOL_STORAGE_DEFAULT_ICON;
  786. return $sIcon;
  787. }
  788. // ------------ internal functions - events
  789. protected function onBeforeFileAdd ($aFileInfo)
  790. {
  791. if ($aFileInfo['size'] > $this->getMaxUploadFileSize($aFileInfo['profile_id'])) {
  792. $this->setErrorCode(BX_DOL_STORAGE_ERR_FILE_TOO_BIG);
  793. return false;
  794. }
  795. // TODO: check site quota - BX_DOL_STORAGE_ERR_SITE_QUOTA_EXCEEDED
  796. $aObjectQuota = $this->_oDb->getStorageObjectQuota();
  797. if (
  798. ($aObjectQuota['quota_size'] && ($aObjectQuota['current_size'] + $aFileInfo['size'] > $aObjectQuota['quota_size']))
  799. ||
  800. ($aObjectQuota['quota_number'] && ($aObjectQuota['current_number'] + 1 > $aObjectQuota['quota_number']))
  801. ) {
  802. $this->setErrorCode(BX_DOL_STORAGE_ERR_OBJECT_QUOTA_EXCEEDED);
  803. return false;
  804. }
  805. $aUserQuota = $this->_oDb->getUserQuota($aFileInfo['profile_id']);
  806. if (
  807. ($aUserQuota['quota_size'] && ($aUserQuota['current_size'] + $aFileInfo['size'] > $aUserQuota['quota_size']))
  808. ||
  809. ($aUserQuota['quota_number'] && ($aUserQuota['current_number'] + 1 > $aUserQuota['quota_number']))
  810. ) {
  811. $this->setErrorCode(BX_DOL_STORAGE_ERR_USER_QUOTA_EXCEEDED);
  812. return false;
  813. }
  814. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  815. $bRet = true;
  816. bx_alert($this->_aObject['object'], 'before_file_add', 0, $aFileInfo['profile_id'], array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  817. return $bRet;
  818. }
  819. protected function onFileAdded ($aFileInfo)
  820. {
  821. // TODO: update site quota - BX_DOL_STORAGE_ERR_SITE_QUOTA_EXCEEDED
  822. if (!$this->_oDb->updateStorageObjectQuota($aFileInfo['size'], 1)) {
  823. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  824. return false;
  825. }
  826. if (!$this->_oDb->updateUserQuota($aFileInfo['profile_id'], $aFileInfo['size'], 1)) {
  827. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  828. return false;
  829. }
  830. if (!$this->insertGhost ($aFileInfo['id'], $aFileInfo['profile_id'], $aFileInfo['content_id'])) {
  831. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  832. return false;
  833. }
  834. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  835. $bRet = true;
  836. bx_alert($this->_aObject['object'], 'file_added', $aFileInfo['id'], $aFileInfo['profile_id'], array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  837. return $bRet;
  838. }
  839. function insertGhost($iFileId, $iProfileId, $iContentId = 0)
  840. {
  841. return $this->_oDb->insertGhosts ($iFileId, $iProfileId, $iContentId);
  842. }
  843. function onBeforeFileDelete ($aFileInfo, $iProfileId)
  844. {
  845. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  846. $bRet = true;
  847. bx_alert($this->_aObject['object'], 'before_file_delete', $aFileInfo['id'], $iProfileId, array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  848. return $bRet;
  849. }
  850. function onFileDeleted ($aFileInfo, $iProfileId, $aGhost = false)
  851. {
  852. // TODO: update site quota
  853. if (!$this->_oDb->updateStorageObjectQuota(-$aFileInfo['size'], -1)) {
  854. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  855. return false;
  856. }
  857. if (!$this->_oDb->updateUserQuota($aFileInfo['profile_id'], -$aFileInfo['size'], -1)) {
  858. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  859. return false;
  860. }
  861. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  862. $bRet = true;
  863. bx_alert($this->_aObject['object'], 'file_deleted', $aFileInfo['id'], $iProfileId, array('file_info' => $aFileInfo, 'ghost' => $aGhost, 'return_value' => &$bRet));
  864. return $bRet;
  865. }
  866. // ------------ internal functions
  867. protected function setErrorCode($i)
  868. {
  869. return ($this->_iErrorCode = $i);
  870. }
  871. protected function genRandName($isCheckForUniq = true)
  872. {
  873. $sRandName = strtolower(genRndPwd(32, false));
  874. if ($isCheckForUniq) {
  875. $iTries = 10;
  876. do {
  877. $aFile = $this->_oDb->getFileByRemoteId($sRandName);
  878. $bExist = is_array($aFile) && $aFile;
  879. } while (--$iTries && $bExist);
  880. }
  881. return $sRandName;
  882. }
  883. protected function genPath($s, $iLevels)
  884. {
  885. $sRet = '';
  886. $i = 1;
  887. while ($iLevels-- > 0)
  888. $sRet .= substr($s, 0, $i++) . '/';
  889. return $sRet;
  890. }
  891. protected function genRemoteNamePath ($sPath, $sLocalId, $sExt)
  892. {
  893. return $sPath . $sLocalId;
  894. }
  895. protected function isValidExt ($sExt)
  896. {
  897. switch ($this->_aObject['ext_mode']) {
  898. case 'allow-deny':
  899. if ($this->isAllowedExt($sExt))
  900. return true;
  901. return false;
  902. case 'deny-allow':
  903. if ($this->isDeniedExt($sExt))
  904. return false;
  905. return true;
  906. default:
  907. return false;
  908. }
  909. }
  910. protected function isAllowedExt ($sExt)
  911. {
  912. return $this->isAllowedDeniedExt($sExt, 'ext_allow');
  913. }
  914. protected function isDeniedExt ($sExt)
  915. {
  916. return $this->isAllowedDeniedExt($sExt, 'ext_deny');
  917. }
  918. protected function isAllowedDeniedExt ($sExt, $sExtMode)
  919. {
  920. if ('' == $this->_aObject[$sExtMode])
  921. return false;
  922. if (!is_array($this->_aObject[$sExtMode]))
  923. $this->_aObject[$sExtMode] = explode(',', $this->_aObject[$sExtMode]);
  924. return in_array ($sExt, $this->_aObject[$sExtMode]);
  925. }
  926. protected function queueFiles($aFiles)
  927. {
  928. if (!$aFiles)
  929. return 0;
  930. $a = array();
  931. foreach ($aFiles as $aFile)
  932. $a[] = $aFile['id'];
  933. return $this->queueFilesForDeletion($a);
  934. }
  935. }
  936. /**
  937. * Handle file uploads via XMLHttpRequest
  938. */
  939. class BxDolStorageHelperXhr
  940. {
  941. protected $sName;
  942. function BxDolStorageHelperXhr ($aParams)
  943. {
  944. $this->sName = $aParams['name'];
  945. }
  946. function getImmediateError()
  947. {
  948. return BX_DOL_STORAGE_ERR_OK;
  949. }
  950. function save($path)
  951. {
  952. $input = fopen("php://input", "r");
  953. $temp = tmpfile();
  954. $realSize = stream_copy_to_stream($input, $temp);
  955. fclose($input);
  956. if (false === $this->getSize() || $realSize != $this->getSize())
  957. return false;
  958. $target = fopen($path, "w");
  959. fseek($temp, 0, SEEK_SET);
  960. stream_copy_to_stream($temp, $target);
  961. fclose($target);
  962. fclose($temp);
  963. return true;
  964. }
  965. function getName()
  966. {
  967. return $this->sName;
  968. }
  969. function getSize()
  970. {
  971. if (isset($_SERVER["CONTENT_LENGTH"]))
  972. return (int)$_SERVER["CONTENT_LENGTH"];
  973. else
  974. return false;
  975. }
  976. }
  977. /**
  978. * Handle file uploads via regular form post (uses the $_FILES array)
  979. */
  980. class BxDolStorageHelperForm
  981. {
  982. protected $aFile;
  983. function BxDolStorageHelperForm ($aParams)
  984. {
  985. $this->aFile = $aParams['file'];
  986. }
  987. function getImmediateError()
  988. {
  989. if (!$this->aFile['size'] || !$this->aFile['tmp_name'])
  990. return BX_DOL_STORAGE_ERR_NO_FILE;
  991. if (UPLOAD_ERR_OK != $this->aFile['error'])
  992. return (int)$this->aFile['error'];
  993. return BX_DOL_STORAGE_ERR_OK;
  994. }
  995. function save($path)
  996. {
  997. if (!move_uploaded_file($this->aFile['tmp_name'], $path)){
  998. return false;
  999. }
  1000. return true;
  1001. }
  1002. function getName()
  1003. {
  1004. return $this->aFile['name'];
  1005. }
  1006. function getSize()
  1007. {
  1008. return $this->aFile['size'];
  1009. }
  1010. }
  1011. /**
  1012. * Store file from local file path
  1013. */
  1014. class BxDolStorageHelperPath
  1015. {
  1016. protected $sPath;
  1017. function BxDolStorageHelperPath ($aParams)
  1018. {
  1019. $this->sPath = $aParams['path'];
  1020. }
  1021. function getImmediateError()
  1022. {
  1023. if (!$this->sPath || !file_exists($this->sPath))
  1024. return BX_DOL_STORAGE_ERR_NO_FILE;
  1025. return BX_DOL_STORAGE_ERR_OK;
  1026. }
  1027. function save($path)
  1028. {
  1029. if (!copy($this->sPath, $path)) {
  1030. return false;
  1031. }
  1032. return true;
  1033. }
  1034. function getName()
  1035. {
  1036. return pathinfo($this->sPath, PATHINFO_BASENAME);
  1037. }
  1038. function getSize()
  1039. {
  1040. return filesize($this->sPath);
  1041. }
  1042. }
  1043. /**
  1044. * Store file from URL
  1045. */
  1046. class BxDolStorageHelperUrl extends BxDolStorageHelperPath
  1047. {
  1048. function BxDolStorageHelperUrl ($aParams)
  1049. {
  1050. $aParams['path'] = '';
  1051. $sExt = pathinfo(parse_url($aParams['url'], PHP_URL_PATH), PATHINFO_EXTENSION);
  1052. if ($sTmpFilename = tempnam(BX_DIRECTORY_PATH_TMP, '')) {
  1053. $aParams['path'] = $sTmpFilename . '.' . $sExt;
  1054. @rename($sTmpFilename, $aParams['path']);
  1055. if ($s = bx_file_get_contents ($aParams['url']))
  1056. file_put_contents($aParams['path'], $s);
  1057. }
  1058. parent::BxDolStorageHelperPath($aParams);
  1059. }
  1060. function getImmediateError()
  1061. {
  1062. $iRet = parent::getImmediateError();
  1063. if (BX_DOL_STORAGE_ERR_OK != $iRet)
  1064. return $iRet;
  1065. return $this->getSize() > 0 ? BX_DOL_STORAGE_ERR_OK : BX_DOL_STORAGE_INVALID_FILE;
  1066. }
  1067. function __destruct()
  1068. {
  1069. @unlink($this->sPath);
  1070. }
  1071. }
  1072. /**
  1073. * Handle file uploads from the same or another storage object
  1074. */
  1075. class BxDolStorageHelperStorage
  1076. {
  1077. protected $iFileId;
  1078. protected $oStorage;
  1079. protected $aFile;
  1080. function BxDolStorageHelperStorage ($aParams)
  1081. {
  1082. $this->iFileId = $aParams['id'];
  1083. $this->oStorage = BxDolStorage::getObjectInstance($aParams['storage']);
  1084. $this->aFile = false;
  1085. if ($this->oStorage)
  1086. $this->aFile = $this->oStorage->getFile($this->iFileId);
  1087. }
  1088. function getImmediateError()
  1089. {
  1090. if (!$this->iFileId)
  1091. return BX_DOL_STORAGE_ERR_NO_FILE;
  1092. if (!$this->oStorage)
  1093. return BX_DOL_STORAGE_ERR_ENGINE_GET;
  1094. if (!$this->aFile)
  1095. return BX_DOL_STORAGE_ERR_NO_FILE;
  1096. return BX_DOL_STORAGE_ERR_OK;
  1097. }
  1098. function save($path)
  1099. {
  1100. $s = bx_file_get_contents ($this->oStorage->getFileUrlById($this->iFileId));
  1101. if (!$s)
  1102. return false;
  1103. return file_put_contents($path, $s) ? true : false;
  1104. }
  1105. function getName()
  1106. {
  1107. return $this->aFile['file_name'];
  1108. }
  1109. function getSize()
  1110. {
  1111. return $this->aFile['size'];
  1112. }
  1113. }
  1114. /** @} */