BxDolStorage.php 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  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 DolphinCore Dolphin 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. bx_import('BxDolStorageQuery');
  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 in Dolphin root directory
  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 . "languages.inc.php");
  134. * require_once(BX_DIRECTORY_PATH_INC . "params.inc.php");
  135. * require_once(BX_DIRECTORY_PATH_INC . "design.inc.php");
  136. *
  137. * bx_import('BxDolStorage');
  138. * BxDolStorage::pruning(); // pruning is needed to clear expired security tokens, you can call it on cron when your server is not busy
  139. * $oStorage = BxDolStorage::getObjectInstance('my_module'); // create storage object instance, 'my_module' is value of 'object' field in 'sys_objects_storage' table
  140. *
  141. * if (isset($_POST['add'])) { // if form is submitted
  142. * $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
  143. * if ($iId) { // storeFileFromForm returns file id, not false value means operation is successful.
  144. * // save $iId somewhere, so you can refer to the file after
  145. * $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)
  146. * echo "uploaded file id: " . $iId . "(deleted orphans:" . $iCount . ")";
  147. * } else {
  148. * // something went wrong - print the error
  149. * echo "error uploading file: " . $oStorage->getErrorString()
  150. * }
  151. * }
  152. * @endcode
  153. *
  154. * Please refer to the functions definition for more additional description of functions params.
  155. *
  156. *
  157. * Step 4:
  158. * Displaying the file.
  159. *
  160. * Use the following code to retrieve saved file. Remember you saved filed id somewhere in the previous step.
  161. * Lets assume that the uploaded file is image, then we can show it using the following code:
  162. *
  163. * @code
  164. * require_once('./inc/header.inc.php');
  165. * require_once(BX_DIRECTORY_PATH_INC . "languages.inc.php");
  166. * require_once(BX_DIRECTORY_PATH_INC . "params.inc.php");
  167. * require_once(BX_DIRECTORY_PATH_INC . "design.inc.php");
  168. *
  169. * bx_import('BxDolStorage');
  170. * $oStorage = BxDolStorage::getObjectInstance('my_module');
  171. *
  172. * $iId = 1234; // since you've saved it somewhere in the previous step, you can retrieve it here
  173. *
  174. * echo "Uploaded image: <img src="' . $oStorage->getFileUrlById($iId) . '" />;";
  175. * @endcode
  176. *
  177. * It will show the file, regardless if it is private or public.
  178. * You need to control it by yourself who will view the file.
  179. * The difference in viewing private files is that link to the file is expiring after N seconds,
  180. * you control this period using 'token_life' field in 'sys_objects_storage' table.
  181. *
  182. */
  183. abstract class BxDolStorage extends BxDol implements iBxDolFactoryObject {
  184. protected $_aObject; ///< object properties
  185. protected $_iCacheControl; ///< browser cache in seconds, 0 - disabled
  186. protected $_aParams; ///< custom params
  187. protected $_iErrorCode; ///< last error code
  188. protected $_oDb; ///< database relates function are in this object
  189. /**
  190. * constructor
  191. */
  192. protected function BxDolStorage($aObject) {
  193. parent::BxDol();
  194. $this->_aObject = $aObject;
  195. $this->_iCacheControl = $aObject['cache_control'];
  196. $this->_aParams = $aObject['params'] ? unserialize($aObject['params']) : '';
  197. $this->_oDb = new BxDolStorageQuery($aObject);
  198. }
  199. /**
  200. * Get storage object instance by object name
  201. * @param $sObject object name
  202. * @return object instance or false on error
  203. */
  204. public static function getObjectInstance($sObject) {
  205. if (isset($GLOBALS['bxDolClasses']['BxDolStorage!'.$sObject]))
  206. return $GLOBALS['bxDolClasses']['BxDolStorage!'.$sObject];
  207. $aObject = BxDolStorageQuery::getStorageObject($sObject);
  208. if (!$aObject || !is_array($aObject))
  209. return false;
  210. $sClass = 'BxDolStorage' . $aObject['engine'];
  211. bx_import($sClass);
  212. $o = new $sClass($aObject);
  213. if (!$o->isInstalled() || !$o->isAvailable())
  214. return false;
  215. return ($GLOBALS['bxDolClasses']['BxDolStorage!'.$sObject] = $o);
  216. }
  217. /**
  218. * Delete old security tokens from database.
  219. * It is alutomatically called upin cron execution, usually once in a day.
  220. * @return number of deleted records
  221. */
  222. public static function pruning() {
  223. $iDeleted = 0;
  224. $a = BxDolStorageQuery::getStorageObjects();
  225. foreach ($a as $aObject) {
  226. $oDb = new BxDolStorageQuery($aObject);
  227. $iDeleted += $oDb->prune();
  228. }
  229. return $iDeleted;
  230. }
  231. /**
  232. * Is storage engine available?
  233. * @return boolean
  234. */
  235. function isAvailable() {
  236. return true;
  237. }
  238. /**
  239. * Are required php modules installed for this storage engine ?
  240. * @return boolean
  241. */
  242. public function isInstalled() {
  243. return true;
  244. }
  245. /**
  246. * Get error code from the last occured error
  247. * @return error code
  248. */
  249. public function getErrorCode() {
  250. return $this->_iErrorCode;
  251. }
  252. /**
  253. * Get error string from the last occured error
  254. * @return error string
  255. */
  256. public function getErrorString() {
  257. $a = array (
  258. 1000 => '_sys_storage_err_no_input_method',
  259. 1001 => '_sys_storage_err_no_file',
  260. 1002 => '_sys_storage_invalid_file',
  261. 1003 => '_sys_storage_err_file_too_big',
  262. 1004 => '_sys_storage_err_wrong_ext',
  263. 1005 => '_sys_storage_err_user_quota_exceeded',
  264. 1006 => '_sys_storage_err_object_quota_exceeded',
  265. 1007 => '_sys_storage_err_site_quota_exceeded',
  266. 1008 => '_sys_storage_err_engine_add',
  267. 2001 => '_sys_storage_err_file_not_found',
  268. 2002 => '_sys_storage_err_unlink',
  269. 5001 => '_sys_storage_err_db',
  270. 5002 => '_sys_storage_err_filesystem_perm',
  271. 5003 => '_sys_storage_err_permission_denied',
  272. 5004 => '_sys_storage_err_engine_get',
  273. );
  274. return _t($a[$this->_iErrorCode]);
  275. }
  276. /**
  277. * Get max file size allowed for current user, it checks user quota, object quota, site quota and php setting
  278. * @param $iProfileId profile id to check quota for
  279. * @return quota size in bytes
  280. */
  281. public function getMaxUploadFileSize ($iProfileId) {
  282. $iMin = PHP_INT_MAX;
  283. $aUserQuota = $this->_oDb->getUserQuota($iProfileId);
  284. if ($aUserQuota['max_file_size'] && $aUserQuota['max_file_size'] < $iMin)
  285. $iMin = $aUserQuota['max_file_size'];
  286. $aObjectQuota = $this->_oDb->getStorageObjectQuota();
  287. if ($aObjectQuota['max_file_size'] && $aObjectQuota['max_file_size'] < $iMin)
  288. $iMin = $aObjectQuota['max_file_size'];
  289. // TODO: get and check site quota
  290. $iUploadMaxFilesize = return_bytes(ini_get('upload_max_filesize'));
  291. if ($iUploadMaxFilesize && $iUploadMaxFilesize < $iMin)
  292. $iMin = $iUploadMaxFilesize;
  293. return $iMin;
  294. }
  295. /**
  296. * Store file in the storage area. It is not recommended to use this function directly,
  297. * use other funtions like: storeFileFromForm, storeFileFromXhr, storeFileFromPath
  298. * @param $sMethod upload method, like regular Form upload, upload from URL, etc
  299. * @param $aMethodParams upload method params
  300. * @param $sName file name with extention
  301. * @param $isPrivate private or public file
  302. * @param $iProfileId profile id of the upload action performer
  303. * @param $iContentId content id to associate with ghost file
  304. * @return id of added file on success, false on error - to get exact error string call getErrorString()
  305. */
  306. public function storeFile($sMethod, $aMethodParams, $sName = false, $isPrivate = true, $iProfileId = 0, $iContentId = 0) {
  307. // setup input source using helper classes, like $_FILES or some URL for example
  308. $sHelperClass = 'BxDolStorageHelper' . $sMethod;
  309. if (!class_exists($sHelperClass)) {
  310. $this->setErrorCode(BX_DOL_STORAGE_ERR_NO_INPUT_METHOD);
  311. return false;
  312. }
  313. $oHelper = new $sHelperClass($aMethodParams);
  314. // check for errors, like size and extentions checking
  315. if ($iImmediateError = $oHelper->getImmediateError()) {
  316. $this->setErrorCode($iImmediateError);
  317. return false;
  318. }
  319. $sExt = $this->getFileExt($oHelper->getName());
  320. $sMimeType = $this->getMimeTypeByFileName($oHelper->getName());
  321. if (!$this->isValidExt($sExt)) {
  322. $this->setErrorCode(BX_DOL_STORAGE_ERR_WRONG_EXT);
  323. return false;
  324. }
  325. // before upload callback + additional checking
  326. if (!$this->onBeforeFileAdd (array(
  327. 'profile_id' => $iProfileId,
  328. 'content_id' => $iContentId,
  329. 'file_name' => $oHelper->getName(),
  330. 'mime_type' => $sMimeType,
  331. 'ext' => $sExt,
  332. 'size' => $oHelper->getSize(),
  333. 'private' => $isPrivate ? 1 : 0,
  334. ))) {
  335. return false;
  336. }
  337. // create tmp file
  338. $sTmpFile = tempnam(realpath(sys_get_temp_dir()), 'bxdol');
  339. if (!$oHelper->save($sTmpFile)) {
  340. $this->setErrorCode(BX_DOL_STORAGE_INVALID_FILE);
  341. return false;
  342. }
  343. // store file to storage engine
  344. $sLocalId = $this->genRandName();
  345. $sPath = $this->genPath($sLocalId, $this->_aObject['levels']);
  346. $sRemoteNamePath = $this->genRemoteNamePath ($sPath, $sLocalId, $sExt);
  347. if (!$this->addFileToEngine($sTmpFile, $sLocalId, $oHelper->getName(), $isPrivate, $iProfileId)) {
  348. unlink($sTmpFile);
  349. $this->setErrorCode(BX_DOL_STORAGE_ERR_ENGINE_ADD);
  350. return false;
  351. }
  352. unlink($sTmpFile);
  353. // add record in db
  354. $iTime = time();
  355. $iSize = $oHelper->getSize();
  356. $bFileAdded = $this->_oDb->addFile($iProfileId, $sLocalId, $sRemoteNamePath, $oHelper->getName(), $sMimeType, $sExt, $iSize, $iTime, $isPrivate);
  357. $iId = $this->_oDb->lastId();
  358. if (!$bFileAdded || !$iId) {
  359. $this->deleteFileFromEngine($sPath . $sLocalId, $isPrivate);
  360. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  361. return false;
  362. }
  363. // after upload callback + triggers update
  364. if (!$this->onFileAdded (array(
  365. 'id' => $iId,
  366. 'profile_id' => $iProfileId,
  367. 'content_id' => $iContentId,
  368. 'remote_id' => $sLocalId,
  369. 'path' => $sPath . $sLocalId,
  370. 'file_name' => $oHelper->getName(),
  371. 'mime_type' => $sMimeType,
  372. 'size' => $iSize,
  373. 'private' => $isPrivate ? 1 : 0,
  374. ))) {
  375. $this->deleteFileFromEngine($sPath . $sLocalId, $isPrivate);
  376. $this->_oDb->deleteFile($iId);
  377. return false;
  378. }
  379. return $iId;
  380. }
  381. /**
  382. * convert default multiple files array into more logical one
  383. */
  384. public function convertMultipleFilesArray($aFiles) {
  385. if (!is_array($aFiles) || !is_array($aFiles['name']))
  386. return false;
  387. $aRet = array ();
  388. foreach ($aFiles['name'] as $i => $sName) {
  389. foreach ($aFiles as $sKey => $r) {
  390. if (!$aFiles['name'][$i])
  391. break;
  392. $aRet[$i][$sKey] = $aFiles[$sKey][$i];
  393. }
  394. }
  395. return $aRet;
  396. }
  397. /**
  398. * the same as storeFile, but it tries to do it directly from uploaded file
  399. */
  400. public function storeFileFromForm($aFile, $isPrivate = true, $iProfileId = 0, $iContentId = 0) {
  401. return $this->storeFile('Form', array('file' => $aFile), false, $isPrivate, $iProfileId, $iContentId);
  402. }
  403. /**
  404. * the same as storeFile, but it tries to do it directly from HTML5 file upload method
  405. */
  406. public function storeFileFromXhr($sName, $isPrivate = true, $iProfileId = 0, $iContentId = 0) {
  407. return $this->storeFile('Xhr', array('name' => $sName), false, $isPrivate, $iProfileId, $iContentId);
  408. }
  409. /**
  410. * the same as storeFile, but it tries to do it directly from local file
  411. */
  412. public function storeFileFromPath($sPath, $isPrivate = true, $iProfileId = 0, $iContentId = 0) {
  413. return $this->storeFile('Path', array('path' => $sPath), false, $isPrivate, $iProfileId, $iContentId);
  414. }
  415. /**
  416. * the same as storeFile, but it tries to do it directly from the same or another storage by file id
  417. * @param $aParams['id'] - file ID in the storage
  418. * @param $aParams['storage'] - the storage name
  419. */
  420. public function storeFileFromStorage($aParams, $isPrivate = true, $iProfileId = 0, $iContentId = 0) {
  421. if (!isset($aParams['id']) || !(int)$aParams['id'])
  422. $aParams['id'] = 0;
  423. if (!isset($aParams['storage']))
  424. $aParams['storage'] = $this->_aObject['object'];
  425. return $this->storeFile('Storage', $aParams, false, $isPrivate, $iProfileId, $iContentId = 0);
  426. }
  427. /**
  428. * Delete file by file id.
  429. */
  430. public function deleteFile($iFileId, $iProfileId = 0) {
  431. $aFile = $this->_oDb->getFileById ($iFileId);
  432. if (!$aFile) {
  433. $this->setErrorCode(BX_DOL_STORAGE_ERR_FILE_NOT_FOUND);
  434. return false;
  435. }
  436. if (!$this->onBeforeFileDelete ($aFile, $iProfileId)) {
  437. return false;
  438. }
  439. if (!$this->deleteFileFromEngine($aFile['path'], $aFile['private'])) {
  440. return false;
  441. }
  442. if (!$this->_oDb->deleteFile($aFile['id'])) {
  443. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  444. return false;
  445. }
  446. if (!$this->onFileDeleted ($aFile, $iProfileId)) {
  447. return false;
  448. }
  449. return true;
  450. }
  451. /**
  452. * Set file private or public.
  453. */
  454. public function setFilePrivate($iFileId, $isPrivate = true) {
  455. if (!$this->_oDb->modifyFilePrivate ($iFileId, $isPrivate)) {
  456. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  457. return false;
  458. }
  459. return true;
  460. }
  461. /**
  462. * Get file url.
  463. * @param $iFileId file id
  464. * @return file url or false on error
  465. */
  466. public function getFileUrlById($iFileId) { }
  467. /**
  468. * Get file info array by file id.
  469. * @param $iFileId file id
  470. * @return array
  471. */
  472. public function getFile($iFileId) {
  473. return $this->_oDb->getFileById($iFileId);
  474. }
  475. /**
  476. * check if file is private or public
  477. * @param $iFileId file id
  478. * @return boolean
  479. */
  480. public function isFilePrivate($iFileId) {
  481. $aFile = $this->getFile ($iFileId);
  482. return $aFile['private'] ? true : false;
  483. }
  484. /**
  485. * Call this function after saving/associate just uploaded file id, so file is not orphaned/ghost.
  486. * Ghost files appear on download form automaticaly during next upload,
  487. * for example if file was uploaded but was not submitted for some reason.
  488. * This mechanism ensure that the file is not lost.
  489. * @param $mixedFileIds array of file ids or just one file id
  490. * @param $iProfileId profile id
  491. * @param return number of deleted ghost files
  492. */
  493. public function afterUploadCleanup($mixedFileIds, $iProfileId, $iContentId = false) {
  494. return $this->_oDb->deleteGhosts($mixedFileIds, $iProfileId, $iContentId);
  495. }
  496. /**
  497. * Get ghost/orphaned files for particular user.
  498. * @param $iProfileId profile id
  499. * @param $iContentId content id, or false to not consider content id at all
  500. * @return array of arrays
  501. */
  502. public function getGhosts($iProfileId, $iContentId = false) {
  503. return $this->_oDb->getGhosts($iProfileId, $iContentId);
  504. }
  505. /**
  506. * Update ghosts' content id.
  507. * @param $mixedFileIds array of file ids or just one file id
  508. * @param $iProfileId profile id
  509. * @param $iContentId content id
  510. * @return true on success or false otherwise
  511. */
  512. public function updateGhostsContentId($mixedFileIds, $iProfileId, $iContentId) {
  513. return $this->_oDb->updateGhostsContentId($mixedFileIds, $iProfileId, $iContentId);
  514. }
  515. /**
  516. * Get files list for particular user.
  517. * @param $iProfileId profile id
  518. * @return array of arrays
  519. */
  520. public function getFiles($iProfileId) {
  521. return $this->_oDb->getFiles($iProfileId);
  522. }
  523. public function tmpDebugGetFilesList() { // TODO: remove this function, since it is for debugging purposes only
  524. $sQuery = "SELECT * FROM `" . $this->_aObject['table_files'] . "`";
  525. return $this->_oDb->getAll($sQuery);
  526. }
  527. /**
  528. * Get readable representation of restrictions by file extentions.
  529. * @param $iProfileId profile id
  530. * @return string
  531. */
  532. public function getRestrictionsTextExtensions ($iProfileId) {
  533. switch ($this->_aObject['ext_mode']) {
  534. case 'allow-deny':
  535. if (!$this->_aObject['ext_allow'])
  536. return _t('_sys_storage_restriction_ext_all_denied');
  537. return _t('_sys_storage_restriction_ext_allowed', _t_format_extensions($this->_aObject['ext_allow']));
  538. case 'deny-allow':
  539. if (!$this->_aObject['ext_deny'])
  540. return _t('_sys_storage_restriction_ext_all_allowed');
  541. return _t('_sys_storage_restriction_ext_denied', _t_format_extensions($this->_aObject['ext_deny']));
  542. default:
  543. return _t('_sys_storage_restriction_ext_all_denied');
  544. }
  545. }
  546. /**
  547. * Get readable representation of restrictions by file size.
  548. * @param $iProfileId profile id
  549. * @return string
  550. */
  551. public function getRestrictionsTextFileSize ($iProfileId) {
  552. return _t('_sys_storage_restriction_size', _t_format_size($this->getMaxUploadFileSize($iProfileId)));
  553. }
  554. /**
  555. * Get readable representation of all restrictions.
  556. * @param $iProfileId profile id
  557. * @return array of strings
  558. */
  559. public function getRestrictionsTextArray ($iProfileId) {
  560. $aTypes = array('Extensions', 'FileSize');
  561. $aRet = array();
  562. foreach ($aTypes as $sType) {
  563. $sFunc = 'getRestrictionsText' . $sType;
  564. $s = $this->$sFunc ($iProfileId);
  565. if ($s)
  566. $aRet[] = $s;
  567. }
  568. return $aRet;
  569. }
  570. /**
  571. * Reread available mimetypes from particular file.
  572. * It clears 'sys_storage_mime_types' table and fill it with data form provided file.
  573. * The format of file is: mime/type _space_or_tab_ extentions_sperated_by_space.
  574. * Usually the file is mime.types file from apache or /etc/mime.types from unix systems.
  575. * @param $sFile file to read mime types from
  576. * @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.
  577. */
  578. public function reloadMimeTypesFromFile ($sFile) {
  579. $sResult = '';
  580. $aIcons = array (
  581. 'mime-type-psd.png' => array('psd'),
  582. 'mime-type-png.png' => array('png'),
  583. 'mime-type-image.png' => 'image/',
  584. 'mime-type-video.png' => 'video/',
  585. 'mime-type-audio.png' => 'audio/',
  586. 'mime-type-presentation.png' => array('ppt', 'pptx', 'sxi', 'sti', 'odp', 'sdp', 'sdd'),
  587. 'mime-type-spreadsheet.png' => array('xls', 'xlt', 'xlsx', 'sxc', 'stc', 'ods', 'ots', 'sdc', 'csv', 'dif', 'slk', 'pxl'),
  588. 'mime-type-document.png' => array('doc', 'docx', 'odt', 'ott', 'sxw', 'stw', 'rtf', 'sdw', 'txt', 'pdb', 'psw', 'pdf'),
  589. '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'),
  590. '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'),
  591. );
  592. $f = fopen ($sFile, 'r');
  593. if (!$f)
  594. return false;
  595. $this->_oDb->clearAllMimeTypes();
  596. while (!feof($f) && ($s = fgets($f, 4096)) !== false) {
  597. $s = trim($s);
  598. if (!$s || '#' == $s[0])
  599. continue;
  600. $a = preg_split ("/[\s\\b]+/", $s, 2);
  601. if (!isset($a[0]) || !isset($a[1]))
  602. continue;
  603. $sMimeType = $a[0];
  604. $aExts = preg_split ("/[\s]+/", $a[1]);
  605. foreach ($aExts as $sExt) {
  606. $sIcon = '';
  607. foreach ($aIcons as $sIc => $if) {
  608. if (!(is_array($if) && in_array($sExt, $if)) && !(is_string($if) && 0 == strncmp($if, $sMimeType, strlen($if))))
  609. continue;
  610. $sIcon = $sIc;
  611. break;
  612. }
  613. if (!$this->_oDb->addMimeType($sMimeType, $sExt, $sIcon))
  614. $sResult .= _t('_Error') . ': ' . $sMimeType . "\t" . $sExt . "\n";
  615. }
  616. }
  617. fclose($f);
  618. if (!$sResult)
  619. $sResult = _t('_Success');
  620. return $sResult;
  621. }
  622. /**
  623. * Get file extension by file name.
  624. * @param $sFileName file name
  625. * @return file extention string
  626. */
  627. public function getFileExt ($sFileName) {
  628. return strtolower(pathinfo($sFileName, PATHINFO_EXTENSION));
  629. }
  630. /**
  631. * Get file title by file name, actually file title is file name without extension.
  632. * @param $sFileName file name
  633. * @return file title string
  634. */
  635. public function getFileTitle ($sFileName) {
  636. return pathinfo($sFileName, PATHINFO_FILENAME);
  637. }
  638. /**
  639. * Get file mime/type by file name.
  640. * @param $sFileName file name
  641. * @return file mime type string
  642. */
  643. public function getMimeTypeByFileName ($sFileName) {
  644. $sExt = $this->getFileExt($sFileName);
  645. $sMimeType = $this->_oDb->getMimeTypeByExt($sExt);
  646. if (!$sMimeType)
  647. $sMimeType = BX_DOL_STORAGE_DEFAULT_MIME_TYPE;
  648. return $sMimeType;
  649. }
  650. /**
  651. * Get file icon by file name.
  652. * File icon is just icon filename without patch or URL.
  653. * File icons must be located in images/icons directory in your template subfolder.
  654. * @param $sFileName file name
  655. * @return file icon string
  656. */
  657. public function getIconNameByFileName ($sFileName) {
  658. $sExt = $this->getFileExt($sFileName);
  659. $sIcon = $this->_oDb->getIconByExt($sExt);
  660. if (!$sIcon)
  661. $sIcon = BX_DOL_STORAGE_DEFAULT_ICON;
  662. return $sIcon;
  663. }
  664. // ------------ internal functions - events
  665. protected function onBeforeFileAdd ($aFileInfo) {
  666. if ($aFileInfo['size'] > $this->getMaxUploadFileSize($aFileInfo['profile_id'])) {
  667. $this->setErrorCode(BX_DOL_STORAGE_ERR_FILE_TOO_BIG);
  668. return false;
  669. }
  670. // TODO: check site quota - BX_DOL_STORAGE_ERR_SITE_QUOTA_EXCEEDED
  671. $aObjectQuota = $this->_oDb->getStorageObjectQuota();
  672. if (
  673. ($aObjectQuota['quota_size'] && ($aObjectQuota['current_size'] + $aFileInfo['size'] > $aObjectQuota['quota_size']))
  674. ||
  675. ($aObjectQuota['quota_number'] && ($aObjectQuota['current_number'] + 1 > $aObjectQuota['quota_number']))
  676. ) {
  677. $this->setErrorCode(BX_DOL_STORAGE_ERR_OBJECT_QUOTA_EXCEEDED);
  678. return false;
  679. }
  680. $aUserQuota = $this->_oDb->getUserQuota($aFileInfo['profile_id']);
  681. if (
  682. ($aUserQuota['quota_size'] && ($aUserQuota['current_size'] + $aFileInfo['size'] > $aUserQuota['quota_size']))
  683. ||
  684. ($aUserQuota['quota_number'] && ($aUserQuota['current_number'] + 1 > $aUserQuota['quota_number']))
  685. ) {
  686. $this->setErrorCode(BX_DOL_STORAGE_ERR_USER_QUOTA_EXCEEDED);
  687. return false;
  688. }
  689. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  690. $bRet = true;
  691. bx_alert($this->_aObject['object'], 'before_file_add', 0, $aFileInfo['profile_id'], array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  692. return $bRet;
  693. }
  694. protected function onFileAdded ($aFileInfo) {
  695. // TODO: update site quota - BX_DOL_STORAGE_ERR_SITE_QUOTA_EXCEEDED
  696. if (!$this->_oDb->updateStorageObjectQuota($aFileInfo['size'], 1)) {
  697. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  698. return false;
  699. }
  700. if (!$this->_oDb->updateUserQuota($aFileInfo['profile_id'], $aFileInfo['size'], 1)) {
  701. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  702. return false;
  703. }
  704. if (!$this->insertGhost ($aFileInfo['id'], $aFileInfo['profile_id'], $aFileInfo['content_id'])) {
  705. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  706. return false;
  707. }
  708. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  709. $bRet = true;
  710. bx_alert($this->_aObject['object'], 'file_added', $aFileInfo['id'], $aFileInfo['profile_id'], array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  711. return $bRet;
  712. }
  713. function insertGhost($iFileId, $iProfileId, $iContentId = 0) {
  714. return $this->_oDb->insertGhosts ($iFileId, $iProfileId, $iContentId);
  715. }
  716. function onBeforeFileDelete ($aFileInfo, $iProfileId) {
  717. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  718. $bRet = true;
  719. bx_alert($this->_aObject['object'], 'before_file_delete', $aFileInfo['id'], $iProfileId, array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  720. return $bRet;
  721. }
  722. function onFileDeleted ($aFileInfo, $iProfileId) {
  723. // TODO: update site quota
  724. if (!$this->_oDb->updateStorageObjectQuota(-$aFileInfo['size'], -1)) {
  725. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  726. return false;
  727. }
  728. if (!$this->_oDb->updateUserQuota($aFileInfo['profile_id'], -$aFileInfo['size'], -1)) {
  729. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  730. return false;
  731. }
  732. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  733. $bRet = true;
  734. bx_alert($this->_aObject['object'], 'file_deleted', $aFileInfo['id'], $iProfileId, array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  735. return $bRet;
  736. }
  737. // ------------ internal functions
  738. protected function setErrorCode($i) {
  739. return ($this->_iErrorCode = $i);
  740. }
  741. protected function genRandName($isCheckForUniq = true) {
  742. $sRandName = genRndPwd(32, false);
  743. if ($isCheckForUniq) {
  744. $iTries = 10;
  745. do {
  746. $aFile = $this->_oDb->getFileByRemoteId($sRandName);
  747. $bExist = is_array($aFile) && $aFile;
  748. } while (--$iTries && $bExist);
  749. }
  750. return $sRandName;
  751. }
  752. protected function genPath($s, $iLevels) {
  753. $sRet = '';
  754. $i = 1;
  755. while ($iLevels-- > 0)
  756. $sRet .= substr($s, 0, $i++) . '/';
  757. return $sRet;
  758. }
  759. protected function genRemoteNamePath ($sPath, $sLocalId, $sExt) {
  760. return $sPath . $sLocalId;
  761. }
  762. protected function isValidExt ($sExt) {
  763. switch ($this->_aObject['ext_mode']) {
  764. case 'allow-deny':
  765. if ($this->isAllowedExt($sExt))
  766. return true;
  767. return false;
  768. case 'deny-allow':
  769. if ($this->isDeniedExt($sExt))
  770. return false;
  771. return true;
  772. default:
  773. return false;
  774. }
  775. }
  776. protected function isAllowedExt ($sExt) {
  777. return $this->isAllowedDeniedExt($sExt, 'ext_allow');
  778. }
  779. protected function isDeniedExt ($sExt) {
  780. return $this->isAllowedDeniedExt($sExt, 'ext_deny');
  781. }
  782. protected function isAllowedDeniedExt ($sExt, $sExtMode) {
  783. if ('' == $this->_aObject[$sExtMode])
  784. return false;
  785. if (!is_array($this->_aObject[$sExtMode]))
  786. $this->_aObject[$sExtMode] = explode(',', $this->_aObject[$sExtMode]);
  787. return in_array ($sExt, $this->_aObject[$sExtMode]);
  788. }
  789. }
  790. /**
  791. * Handle file uploads via XMLHttpRequest
  792. */
  793. class BxDolStorageHelperXhr {
  794. var $sName;
  795. function BxDolStorageHelperXhr ($aParams) {
  796. $this->sName = $aParams['name'];
  797. }
  798. function getImmediateError() {
  799. return BX_DOL_STORAGE_ERR_OK;
  800. }
  801. function save($path) {
  802. $input = fopen("php://input", "r");
  803. $temp = tmpfile();
  804. $realSize = stream_copy_to_stream($input, $temp);
  805. fclose($input);
  806. if (false === $this->getSize() || $realSize != $this->getSize())
  807. return false;
  808. $target = fopen($path, "w");
  809. fseek($temp, 0, SEEK_SET);
  810. stream_copy_to_stream($temp, $target);
  811. fclose($target);
  812. fclose($temp);
  813. return true;
  814. }
  815. function getName() {
  816. return $this->sName;
  817. }
  818. function getSize() {
  819. if (isset($_SERVER["CONTENT_LENGTH"]))
  820. return (int)$_SERVER["CONTENT_LENGTH"];
  821. else
  822. return false;
  823. }
  824. }
  825. /**
  826. * Handle file uploads via regular form post (uses the $_FILES array)
  827. */
  828. class BxDolStorageHelperForm {
  829. var $aFile;
  830. function BxDolStorageHelperForm ($aParams) {
  831. $this->aFile = $aParams['file'];
  832. }
  833. function getImmediateError() {
  834. if (!$this->aFile['size'] || !$this->aFile['tmp_name'])
  835. return BX_DOL_STORAGE_ERR_NO_FILE;
  836. if (UPLOAD_ERR_OK != $this->aFile['error'])
  837. return (int)$this->aFile['error'];
  838. return BX_DOL_STORAGE_ERR_OK;
  839. }
  840. function save($path) {
  841. if (!move_uploaded_file($this->aFile['tmp_name'], $path)){
  842. return false;
  843. }
  844. return true;
  845. }
  846. function getName() {
  847. return $this->aFile['name'];
  848. }
  849. function getSize() {
  850. return $this->aFile['size'];
  851. }
  852. }
  853. /**
  854. * Store file from local file path
  855. */
  856. class BxDolStorageHelperPath {
  857. var $sPath;
  858. function BxDolStorageHelperPath ($aParams) {
  859. $this->sPath = $aParams['path'];
  860. }
  861. function getImmediateError() {
  862. if (!file_exists($this->sPath))
  863. return BX_DOL_STORAGE_ERR_NO_FILE;
  864. return BX_DOL_STORAGE_ERR_OK;
  865. }
  866. function save($path) {
  867. if (!copy($this->sPath, $path)) {
  868. return false;
  869. }
  870. return true;
  871. }
  872. function getName() {
  873. return pathinfo($this->sPath, PATHINFO_BASENAME);
  874. }
  875. function getSize() {
  876. return filesize($this->sPath);
  877. }
  878. }
  879. /**
  880. * Handle file uploads from the same or another storage object
  881. */
  882. class BxDolStorageHelperStorage {
  883. var $iFileId;
  884. var $oStorage;
  885. var $aFile;
  886. function BxDolStorageHelperStorage ($aParams) {
  887. $this->iFileId = $aParams['id'];
  888. $this->oStorage = BxDolStorage::getObjectInstance($aParams['storage']);
  889. $this->aFile = false;
  890. if ($this->oStorage)
  891. $this->aFile = $this->oStorage->getFile($this->iFileId);
  892. }
  893. function getImmediateError() {
  894. if (!$this->iFileId)
  895. return BX_DOL_STORAGE_ERR_NO_FILE;
  896. if (!$this->oStorage)
  897. return BX_DOL_STORAGE_ERR_ENGINE_GET;
  898. if (!$this->aFile)
  899. return BX_DOL_STORAGE_ERR_NO_FILE;
  900. return BX_DOL_STORAGE_ERR_OK;
  901. }
  902. function save($path) {
  903. $s = bx_file_get_contents ($this->oStorage->getFileUrlById($this->iFileId));
  904. if (!$s)
  905. return false;
  906. return file_put_contents($path, $s) ? true : false;
  907. }
  908. function getName() {
  909. return $this->aFile['file_name'];
  910. }
  911. function getSize() {
  912. return $this->aFile['size'];
  913. }
  914. }
  915. /** @} */