BxDolStorage.php 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaCore UNA 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_DEFAULT_ICON_FONT', 'far file'); ///< default font icon if no other icon can be determined by file extension
  45. define('BX_DOL_STORAGE_QUEUED_DELETIONS_PER_RUN', 200); ///< max number of file deletions per one cron run, @see BxDolStorage::pruneDeletions
  46. /**
  47. * This class unify storage.
  48. * As the result there are many advantages:
  49. * - files can be stored as on localhost as on remote storage, for example Amazon s3
  50. * - all files are in one place and separated from other files, so the data can be organised more easily,
  51. * for example moved to dedicated disk if there is not enough storage
  52. * - simplicity of usage, there are hight level classes to handle all necessary operations, including upload and security
  53. * - quotas settings, so you always control how much space you are going to use
  54. * - persistent storage; uploaded, but not saved files appear upon page reload or future submission of the same form
  55. *
  56. *
  57. * Usage.
  58. *
  59. * Step 1:
  60. * Add record to 'sys_objects_storage' table, like you doing this for Comments or Voting objects:
  61. * - object - your storage object name, usually it is in the following format - vendor prefix, underscore, module prefix;
  62. * for example for BoonEx Forum module it can be bx_forum.
  63. * - engine - storage engine, for now the following engines are supported:
  64. * 1. Local - local storage, by default files are stored in /storage/ subfolder
  65. * 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
  66. * - params - custom storage engine params as php serialized string
  67. * - token_life - life of the security token in seconds for private files
  68. * - cache_control - control browser cache, allow browser to store files in browser's cache for this number of seconds, to disable browser cache,
  69. * or let browser to decide on its own set it to 0(zero)
  70. * - levels - store files in subfolders, generated from filename; it is useful when there is limit of number of files/folders per directory;
  71. * 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
  72. * - table_files - table where file info is stored, please refer to step 2 for more details
  73. * - ext_mode - file extensions restriction mode:
  74. * 1. allow-deny - allow only file types in ext_allow field and deny all other file types, ext_deny field is ignored.
  75. * 2. deny-allow - allow all files except the ones specified in ext_deny field, ext_allow field is ignored.
  76. * - ext_allow - allowed file extensions, comma separated, it is in effect when ext_mode is allow-deny; example - jpg,gif,png
  77. * - ext_deny - denied file extensions, comma separated, it is in effect when ext_mode is deny-allow; example - exe,com,bat
  78. * - quota_size - storage engine quota in bytes, the summary of all uploaded files can not be bigger than this number
  79. * - current_size - current storage engine usage, the sum of all uploaded file sizes
  80. * - quota_number - max number of files allowed in this storage engine
  81. * - current_number - current number of files in this storage engine
  82. * - 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
  83. * - ts - unix timestamp of the last file upload
  84. *
  85. *
  86. * Step 2:
  87. * Create table for files.
  88. *
  89. * @code
  90. * CREATE TABLE `my_sample_files` (
  91. * `id` int(11) NOT NULL AUTO_INCREMENT,
  92. * `profile_id` int(10) unsigned NOT NULL,
  93. * `remote_id` varchar(255) NOT NULL,
  94. * `path` varchar(255) NOT NULL,
  95. * `file_name` varchar(255) NOT NULL,
  96. * `mime_type` varchar(128) NOT NULL,
  97. * `ext` varchar(32) NOT NULL,
  98. * `size` int(11) NOT NULL,
  99. * `added` int(11) NOT NULL,
  100. * `modified` int(11) NOT NULL,
  101. * `private` int(11) NOT NULL,
  102. * PRIMARY KEY (`id`),
  103. * UNIQUE KEY `remote_id` (`remote_id`)
  104. * );
  105. * @endcode
  106. *
  107. * You need to enter this table name in 'table_files' field in 'sys_objects_storage' table, mentioned in step 1.
  108. * 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'.
  109. * 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'.
  110. *
  111. *
  112. * Step 3:
  113. * Handling upload.
  114. *
  115. * Sample HTML form:
  116. * @code
  117. * <form enctype="multipart/form-data" method="POST" action="store_file.php">
  118. * Choose a file to upload:
  119. * <input name="file" type="file" />
  120. * <br />
  121. * <input type="submit" name="add" value="Upload File" />
  122. * </form>
  123. * @endcode
  124. *
  125. * Add server code in sample store_file.php file:
  126. *
  127. * @code
  128. * require_once('./inc/header.inc.php');
  129. * require_once(BX_DIRECTORY_PATH_INC . "design.inc.php");
  130. *
  131. * BxDolStorage::pruning(); // pruning is needed to clear expired security tokens, you can call it on cron when your server is not busy
  132. * $oStorage = BxDolStorage::getObjectInstance('my_module'); // create storage object instance, 'my_module' is value of 'object' field in 'sys_objects_storage' table
  133. *
  134. * if (isset($_POST['add'])) { // if form is submitted
  135. * $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
  136. * if ($iId) { // storeFileFromForm returns file id, not false value means operation is successful.
  137. * // save $iId somewhere, so you can refer to the file after
  138. * $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)
  139. * echo "uploaded file id: " . $iId . "(deleted orphans:" . $iCount . ")";
  140. * } else {
  141. * // something went wrong - print the error
  142. * echo "error uploading file: " . $oStorage->getErrorString()
  143. * }
  144. * }
  145. * @endcode
  146. *
  147. * Please refer to the functions definition for more additional description of functions params.
  148. *
  149. *
  150. * Step 4:
  151. * Displaying the file.
  152. *
  153. * Use the following code to retrieve saved file. Remember you saved filed id somewhere in the previous step.
  154. * Lets assume that the uploaded file is image, then we can show it using the following code:
  155. *
  156. * @code
  157. * require_once('./inc/header.inc.php');
  158. * require_once(BX_DIRECTORY_PATH_INC . "design.inc.php");
  159. *
  160. * $oStorage = BxDolStorage::getObjectInstance('my_module');
  161. *
  162. * $iId = 1234; // since you've saved it somewhere in the previous step, you can retrieve it here
  163. *
  164. * echo "Uploaded image: <img src="' . $oStorage->getFileUrlById($iId) . '" />;";
  165. * @endcode
  166. *
  167. * It will show the file, regardless if it is private or public.
  168. * You need to control it by yourself who will view the file.
  169. * The difference in viewing private files is that link to the file is expiring after N seconds,
  170. * you control this period using 'token_life' field in 'sys_objects_storage' table.
  171. *
  172. */
  173. abstract class BxDolStorage extends BxDolFactory implements iBxDolFactoryObject
  174. {
  175. protected $_aObject; ///< object properties
  176. protected $_iCacheControl; ///< browser cache in seconds, 0 - disabled
  177. protected $_aParams; ///< custom params
  178. protected $_iErrorCode; ///< last error code
  179. protected $_oDb; ///< database relates function are in this object
  180. /**
  181. * constructor
  182. */
  183. protected function __construct($aObject)
  184. {
  185. parent::__construct();
  186. $this->_aObject = $aObject;
  187. $this->_iCacheControl = $aObject['cache_control'];
  188. $this->_aParams = $aObject['params'] ? unserialize($aObject['params']) : '';
  189. $this->_oDb = new BxDolStorageQuery($aObject);
  190. }
  191. /**
  192. * Get storage object instance by object name
  193. * @param $sObject object name
  194. * @return object instance or false on error
  195. */
  196. public static function getObjectInstance($sObject)
  197. {
  198. if (isset($GLOBALS['bxDolClasses']['BxDolStorage!'.$sObject]))
  199. return $GLOBALS['bxDolClasses']['BxDolStorage!'.$sObject];
  200. $aObject = BxDolStorageQuery::getStorageObject($sObject);
  201. if (!$aObject || !is_array($aObject))
  202. return false;
  203. $sClass = 'BxDolStorage' . $aObject['engine'];
  204. $o = new $sClass($aObject);
  205. if (!$o->isInstalled() || !$o->isAvailable())
  206. return false;
  207. return ($GLOBALS['bxDolClasses']['BxDolStorage!'.$sObject] = $o);
  208. }
  209. /**
  210. * Delete old security tokens from database.
  211. * It is alutomatically called upin cron execution, usually once in a day.
  212. * @return number of deleted records
  213. */
  214. public static function pruning()
  215. {
  216. $iDeleted = 0;
  217. $a = BxDolStorageQuery::getStorageObjects();
  218. foreach ($a as $aObject) {
  219. $oDb = new BxDolStorageQuery($aObject);
  220. $iDeleted += $oDb->prune();
  221. }
  222. return $iDeleted;
  223. }
  224. /**
  225. * Delete files queued for deletions
  226. * It is alutomatically called upin cron execution, usually one time per minute.
  227. * Max number of deletetion per time is defined in @see BX_DOL_STORAGE_QUEUED_DELETIONS_PER_RUN
  228. * @return number of deleted records
  229. */
  230. public static function pruneDeletions()
  231. {
  232. $iDeleted = 0;
  233. $a = BxDolStorageQuery::getQueuedFilesForDeletion(BX_DOL_STORAGE_QUEUED_DELETIONS_PER_RUN);
  234. foreach ($a as $r) {
  235. $o = BxDolStorage::getObjectInstance($r['object']);
  236. $iDeleted += ($o && $o->deleteFile($r['file_id']) ? 1 : 0);
  237. }
  238. return $iDeleted;
  239. }
  240. /**
  241. * Check if module has any files pending for deletion, it is supposed that all module storage object names are prefixed with module name
  242. * @param $sPrefix - usually module name
  243. * @return number of files pending for deletion which were found by prefix
  244. */
  245. public static function isQueuedFilesForDeletion ($sPrefix)
  246. {
  247. return BxDolStorageQuery::isQueuedFilesForDeletion($sPrefix);
  248. }
  249. /**
  250. * Get file token for private files.
  251. * @param $iFileId file
  252. * @return file token string
  253. */
  254. public function genToken($iFileId)
  255. {
  256. return $this->_oDb->genToken($iFileId);
  257. }
  258. /**
  259. * Change storage engine. It's possible to change it when there is no files in storage engine.
  260. * @param $sEngine new storage engine
  261. * @return true on success or false on error
  262. */
  263. public function changeStorageEngine ($sEngine)
  264. {
  265. if (0 == $this->_aObject['current_size'] && 0 == $this->_aObject['current_number'])
  266. return $this->_oDb->changeStorageEngine($sEngine);
  267. return false;
  268. }
  269. /**
  270. * Is storage engine available?
  271. * @return boolean
  272. */
  273. function isAvailable()
  274. {
  275. return true;
  276. }
  277. /**
  278. * Are required php modules installed for this storage engine ?
  279. * @return boolean
  280. */
  281. public function isInstalled()
  282. {
  283. return true;
  284. }
  285. public function getObject()
  286. {
  287. return $this->_aObject['object'];
  288. }
  289. /**
  290. * Get error code from the last occured error
  291. * @return error code
  292. */
  293. public function getErrorCode()
  294. {
  295. return $this->_iErrorCode;
  296. }
  297. /**
  298. * Get error string from the last occured error
  299. * @return error string
  300. */
  301. public function getErrorString()
  302. {
  303. bx_import('BxDolLanguages');
  304. $a = array (
  305. 1000 => '_sys_storage_err_no_input_method',
  306. 1001 => '_sys_storage_err_no_file',
  307. 1002 => '_sys_storage_invalid_file',
  308. 1003 => '_sys_storage_err_file_too_big',
  309. 1004 => '_sys_storage_err_wrong_ext',
  310. 1005 => '_sys_storage_err_user_quota_exceeded',
  311. 1006 => '_sys_storage_err_object_quota_exceeded',
  312. 1007 => '_sys_storage_err_site_quota_exceeded',
  313. 1008 => '_sys_storage_err_engine_add',
  314. 2001 => '_sys_storage_err_file_not_found',
  315. 2002 => '_sys_storage_err_unlink',
  316. 5001 => '_sys_storage_err_db',
  317. 5002 => '_sys_storage_err_filesystem_perm',
  318. 5003 => '_sys_storage_err_permission_denied',
  319. 5004 => '_sys_storage_err_engine_get',
  320. );
  321. return _t($a[$this->_iErrorCode]);
  322. }
  323. /**
  324. * Get max file size allowed for current user, it checks user quota, object quota, site quota and php setting
  325. * @param $iProfileId profile id to check quota for
  326. * @return quota size in bytes
  327. */
  328. public function getMaxUploadFileSize ($iProfileId)
  329. {
  330. $iMin = PHP_INT_MAX;
  331. $aUserQuota = $this->_oDb->getUserQuota($iProfileId);
  332. if ($aUserQuota['max_file_size'] && $aUserQuota['max_file_size'] < $iMin)
  333. $iMin = $aUserQuota['max_file_size'];
  334. $aObjectQuota = $this->_oDb->getStorageObjectQuota();
  335. if ($aObjectQuota['max_file_size'] && $aObjectQuota['max_file_size'] < $iMin)
  336. $iMin = $aObjectQuota['max_file_size'];
  337. // TODO: get and check site quota
  338. if (!defined('BX_DOL_CRON_EXECUTE')) {
  339. $iUploadMaxFilesize = return_bytes(ini_get('upload_max_filesize'));
  340. if ($iUploadMaxFilesize && $iUploadMaxFilesize < $iMin)
  341. $iMin = $iUploadMaxFilesize;
  342. }
  343. return $iMin;
  344. }
  345. /**
  346. * Store file in the storage area. It is not recommended to use this function directly,
  347. * use other funtions like: storeFileFromForm, storeFileFromXhr, storeFileFromPath, storeFileFromUrl
  348. * @param $sMethod upload method, like regular Form upload, upload from URL, etc
  349. * @param $aMethodParams upload method params
  350. * @param $sName file name with extention
  351. * @param $isPrivate private or public file
  352. * @param $iProfileId profile id of the upload action performer
  353. * @param $iContentId content id to associate with ghost file
  354. * @return id of added file on success, false on error - to get exact error string call getErrorString()
  355. */
  356. public function storeFile($sMethod, $aMethodParams, $sName = false, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  357. {
  358. // setup input source using helper classes, like $_FILES or some URL for example
  359. $sHelperClass = 'BxDolStorageHelper' . $sMethod;
  360. if (!class_exists($sHelperClass)) {
  361. $this->setErrorCode(BX_DOL_STORAGE_ERR_NO_INPUT_METHOD);
  362. return false;
  363. }
  364. $oHelper = new $sHelperClass($aMethodParams);
  365. // check for errors, like size and extentions checking
  366. if ($iImmediateError = $oHelper->getImmediateError()) {
  367. $this->setErrorCode($iImmediateError);
  368. return false;
  369. }
  370. $sExt = $this->getFileExt($oHelper->getName());
  371. $sMimeType = $this->getMimeTypeByFileName($oHelper->getName());
  372. if (!$this->isValidExt($sExt)) {
  373. $this->setErrorCode(BX_DOL_STORAGE_ERR_WRONG_EXT);
  374. return false;
  375. }
  376. // before upload callback + additional checking
  377. if (!$this->onBeforeFileAdd (array(
  378. 'profile_id' => $iProfileId,
  379. 'content_id' => $iContentId,
  380. 'file_name' => $oHelper->getName(),
  381. 'mime_type' => $sMimeType,
  382. 'ext' => $sExt,
  383. 'size' => $oHelper->getSize(),
  384. 'private' => $isPrivate ? 1 : 0,
  385. ))) {
  386. return false;
  387. }
  388. // create tmp file
  389. $sTmpFile = tempnam(BX_DIRECTORY_PATH_TMP, $this->_aObject['object']);
  390. if (!$oHelper->save($sTmpFile)) {
  391. $this->setErrorCode(BX_DOL_STORAGE_INVALID_FILE);
  392. return false;
  393. }
  394. // store file to storage engine
  395. $sLocalId = $this->genRandName();
  396. $sPath = $this->genPath($sLocalId, $this->_aObject['levels']);
  397. $sRemoteNamePath = $this->genRemoteNamePath ($sPath, $sLocalId, $sExt);
  398. if (!$this->addFileToEngine($sTmpFile, $sLocalId, $oHelper->getName(), $isPrivate, $iProfileId)) {
  399. unlink($sTmpFile);
  400. $this->setErrorCode(BX_DOL_STORAGE_ERR_ENGINE_ADD);
  401. return false;
  402. }
  403. unlink($sTmpFile);
  404. // add record in db
  405. $iTime = time();
  406. $iSize = $oHelper->getSize();
  407. $bFileAdded = $this->_oDb->addFile($iProfileId, $sLocalId, $sRemoteNamePath, $oHelper->getName(), $sMimeType, $sExt, $iSize, $iTime, $isPrivate);
  408. $iId = $this->_oDb->lastId();
  409. if (!$bFileAdded || !$iId) {
  410. $this->deleteFileFromEngine($sPath . $sLocalId, $isPrivate);
  411. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  412. return false;
  413. }
  414. // after upload callback + triggers update
  415. if (!$this->onFileAdded (array(
  416. 'id' => $iId,
  417. 'profile_id' => $iProfileId,
  418. 'content_id' => $iContentId,
  419. 'remote_id' => $sLocalId,
  420. 'path' => $sPath . $sLocalId,
  421. 'file_name' => $oHelper->getName(),
  422. 'mime_type' => $sMimeType,
  423. 'size' => $iSize,
  424. 'private' => $isPrivate ? 1 : 0,
  425. ))) {
  426. $this->deleteFileFromEngine($sPath . $sLocalId, $isPrivate);
  427. $this->_oDb->deleteFile($iId);
  428. return false;
  429. }
  430. return $iId;
  431. }
  432. /**
  433. * convert default multiple files array into more logical one
  434. */
  435. public function convertMultipleFilesArray($aFiles)
  436. {
  437. if (!is_array($aFiles) || !is_array($aFiles['name']))
  438. return false;
  439. $aRet = array ();
  440. foreach ($aFiles['name'] as $i => $sName) {
  441. foreach ($aFiles as $sKey => $r) {
  442. if (!$aFiles['name'][$i])
  443. break;
  444. $aRet[$i][$sKey] = $aFiles[$sKey][$i];
  445. }
  446. }
  447. return $aRet;
  448. }
  449. /**
  450. * the same as storeFile, but it tries to do it directly from uploaded file
  451. */
  452. public function storeFileFromForm($aFile, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  453. {
  454. return $this->storeFile('Form', array('file' => $aFile), false, $isPrivate, $iProfileId, $iContentId);
  455. }
  456. /**
  457. * the same as storeFile, but it tries to do it directly from HTML5 file upload method
  458. */
  459. public function storeFileFromXhr($sName, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  460. {
  461. return $this->storeFile('Xhr', array('name' => $sName), false, $isPrivate, $iProfileId, $iContentId);
  462. }
  463. /**
  464. * the same as storeFile, but it tries to do it directly from local file
  465. */
  466. public function storeFileFromPath($sPath, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  467. {
  468. return $this->storeFile('Path', array('path' => $sPath), false, $isPrivate, $iProfileId, $iContentId);
  469. }
  470. /**
  471. * the same as storeFileFromPath, but it tries to do it from URL
  472. */
  473. public function storeFileFromUrl($sUrl, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  474. {
  475. return $this->storeFile('Url', array('url' => $sUrl), false, $isPrivate, $iProfileId, $iContentId);
  476. }
  477. /**
  478. * the same as storeFile, but it tries to do it directly from the same or another storage by file id
  479. * @param $aParams['id'] - file ID in the storage
  480. * @param $aParams['storage'] - the storage name
  481. */
  482. public function storeFileFromStorage($aParams, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  483. {
  484. if (!isset($aParams['id']) || !(int)$aParams['id'])
  485. $aParams['id'] = 0;
  486. if (!isset($aParams['storage']))
  487. $aParams['storage'] = $this->_aObject['object'];
  488. return $this->storeFile('Storage', $aParams, false, $isPrivate, $iProfileId, $iContentId = 0);
  489. }
  490. /**
  491. * Delete file by file id.
  492. */
  493. public function deleteFile($iFileId, $iProfileId = 0)
  494. {
  495. $aFile = $this->_oDb->getFileById ($iFileId);
  496. if (!$aFile) {
  497. $this->setErrorCode(BX_DOL_STORAGE_ERR_FILE_NOT_FOUND);
  498. return false;
  499. }
  500. if (!$this->onBeforeFileDelete ($aFile, $iProfileId)) {
  501. return false;
  502. }
  503. if (!$this->deleteFileFromEngine($aFile['path'], $aFile['private'])) {
  504. return false;
  505. }
  506. $aGhost = $this->_oDb->getGhost($aFile['id']);
  507. if (!$this->_oDb->deleteFile($aFile['id'])) {
  508. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  509. return false;
  510. }
  511. if (!$this->onFileDeleted ($aFile, $iProfileId, $aGhost)) {
  512. return false;
  513. }
  514. return true;
  515. }
  516. /**
  517. * Queue file(s) for deletion. File(s) will be deleted later upon cron call (usually every minute).
  518. * @param $mixedFileId file id or array of file ids.
  519. * @return number of queued files
  520. */
  521. public function queueFilesForDeletion($mixedFileId)
  522. {
  523. if (!is_array($mixedFileId))
  524. $mixedFileId = array ($mixedFileId);
  525. bx_import('BxDolForm');
  526. $oChecker = new BxDolFormCheckerHelper();
  527. return $this->_oDb->queueFilesForDeletion (array_unique($oChecker->passInt($mixedFileId)));
  528. }
  529. /**
  530. * Queue file(s) for deletion by getting neccesary files from ghosts table by profile id and content id
  531. * @param $iProfileId profile id associated with files
  532. * @param $iContentId content id associated with files, or false if to check by profile id only
  533. * @return number of queued files
  534. */
  535. public function queueFilesForDeletionFromGhosts($iProfileId, $iContentId = false)
  536. {
  537. $aFiles = $this->getGhosts ($iProfileId, $iContentId);
  538. return $this->queueFiles($aFiles);
  539. }
  540. /**
  541. * Queue file(s) for deletion of the whole storage object
  542. * @return number of queued files
  543. */
  544. public function queueFilesForDeletionFromObject()
  545. {
  546. $aFiles = $this->getFiles (false);
  547. return $this->queueFiles($aFiles);
  548. }
  549. /**
  550. * Download file.
  551. * @param array $aFile downloading file info.
  552. */
  553. public function download ($aFile)
  554. {
  555. $bRet = true;
  556. bx_alert($this->_aObject['object'], 'file_downloaded', $aFile['id'], bx_get_logged_profile_id(), array(
  557. 'profile_ip' => getVisitorIP(),
  558. 'file_info' => $aFile,
  559. 'return_value' => &$bRet
  560. ));
  561. return $bRet;
  562. }
  563. /**
  564. * Set file private or public.
  565. */
  566. public function setFilePrivate($iFileId, $isPrivate = true)
  567. {
  568. if (!$this->_oDb->modifyFilePrivate ($iFileId, $isPrivate)) {
  569. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  570. return false;
  571. }
  572. return true;
  573. }
  574. /**
  575. * Get file url.
  576. * @param $iFileId file id
  577. * @return file url or false on error
  578. */
  579. public function getFileUrlById($iFileId) { }
  580. /**
  581. * Get file info array by file id.
  582. * @param $iFileId file id
  583. * @return array
  584. */
  585. public function getFile($iFileId)
  586. {
  587. return $this->_oDb->getFileById($iFileId);
  588. }
  589. /**
  590. * Get ghost file info array by file id.
  591. * @param $iFileId file id
  592. * @return array
  593. */
  594. public function getGhost($iFileId)
  595. {
  596. return $this->_oDb->getGhost($iFileId);
  597. }
  598. /**
  599. * check if file is private or public
  600. * @param $iFileId file id
  601. * @return boolean
  602. */
  603. public function isFilePrivate($iFileId)
  604. {
  605. $aFile = $this->getFile ($iFileId);
  606. return $aFile['private'] ? true : false;
  607. }
  608. /**
  609. * Call this function after saving/associate just uploaded file id, so file is not orphaned/ghost.
  610. * Ghost files appear on download form automaticaly during next upload,
  611. * for example if file was uploaded but was not submitted for some reason.
  612. * This mechanism ensure that the file is not lost.
  613. * @param $mixedFileIds array of file ids or just one file id
  614. * @param $iProfileId profile id
  615. * @param return number of deleted ghost files
  616. */
  617. public function afterUploadCleanup($mixedFileIds, $iProfileId, $iContentId = false)
  618. {
  619. return $this->_oDb->deleteGhosts($mixedFileIds, $iProfileId, $iContentId);
  620. }
  621. /**
  622. * Get ghost/orphaned files for particular user.
  623. * @param $iProfileId profile id
  624. * @param $iContentId content id, or false to not consider content id at all
  625. * @param $isCheckAllAccountProfiles get all files associated with all account profiles
  626. * @param $isAdmin if true, then don't check files ownership, it makes sense when $iContentId is provided, so it will return all files assiciated with content
  627. * @return array of arrays
  628. */
  629. public function getGhosts($iProfileId, $iContentId = false, $isCheckAllAccountProfiles = false, $isAdmin = false)
  630. {
  631. if ($isCheckAllAccountProfiles && ($oProfile = BxDolProfile::getInstance($iProfileId))) {
  632. $oAccount = $oProfile->getAccountObject();
  633. $aProfiles = $oAccount->getProfilesIds(false);
  634. return $this->_oDb->getGhosts($aProfiles, $iContentId, $isAdmin);
  635. }
  636. return $this->_oDb->getGhosts($iProfileId, $iContentId, $isAdmin);
  637. }
  638. /**
  639. * Update ghosts' content id.
  640. * @param $mixedFileIds array of file ids or just one file id
  641. * @param $iProfileId profile id
  642. * @param $iContentId content id
  643. * @param $isAdmin if true, then don't check files ownership
  644. * @return true on success or false otherwise
  645. */
  646. public function updateGhostsContentId($mixedFileIds, $iProfileId, $iContentId, $isAdmin = false)
  647. {
  648. $aProfiles = array();
  649. if ($oProfile = BxDolProfile::getInstance($iProfileId)) {
  650. $oAccount = $oProfile->getAccountObject();
  651. $aProfiles = $oAccount->getProfilesIds(false);
  652. }
  653. return $this->_oDb->updateGhostsContentId($mixedFileIds, $iProfileId, $iContentId, $aProfiles, $isAdmin);
  654. }
  655. /**
  656. * Get files list for particular user.
  657. * @param $iProfileId profile id
  658. * @return array of arrays
  659. */
  660. public function getFiles($iProfileId)
  661. {
  662. return $this->_oDb->getFiles($iProfileId);
  663. }
  664. /**
  665. * Get all files in the storage
  666. */
  667. public function getFilesAll($iStart = 0, $iPerPage = 1000)
  668. {
  669. return $this->_oDb->getFilesAll($iStart, $iPerPage);
  670. }
  671. /**
  672. * Get readable representation of restrictions by file extentions.
  673. * @param $iProfileId profile id
  674. * @return string
  675. */
  676. public function getRestrictionsTextExtensions ($iProfileId)
  677. {
  678. switch ($this->_aObject['ext_mode']) {
  679. case 'allow-deny':
  680. if (!$this->_aObject['ext_allow'])
  681. return _t('_sys_storage_restriction_ext_all_denied');
  682. return _t('_sys_storage_restriction_ext_allowed', _t_format_extensions($this->_aObject['ext_allow']));
  683. case 'deny-allow':
  684. if (!$this->_aObject['ext_deny'])
  685. return _t('_sys_storage_restriction_ext_all_allowed');
  686. return _t('_sys_storage_restriction_ext_denied', _t_format_extensions($this->_aObject['ext_deny']));
  687. default:
  688. return _t('_sys_storage_restriction_ext_all_denied');
  689. }
  690. }
  691. /**
  692. * @return list of allowed extensions, if ext_mode = 'allow-deny', returns false otherwise.
  693. */
  694. public function getAllowedExtensions ()
  695. {
  696. if ('allow-deny' == $this->_aObject['ext_mode'])
  697. return _t_format_extensions($this->_aObject['ext_allow']);
  698. return null;
  699. }
  700. /**
  701. * Get readable representation of restrictions by file size.
  702. * @param $iProfileId profile id
  703. * @return string
  704. */
  705. public function getRestrictionsTextFileSize ($iProfileId)
  706. {
  707. return _t('_sys_storage_restriction_size', _t_format_size($this->getMaxUploadFileSize($iProfileId)));
  708. }
  709. /**
  710. * Get readable representation of all restrictions.
  711. * @param $iProfileId profile id
  712. * @return array of strings
  713. */
  714. public function getRestrictionsTextArray ($iProfileId)
  715. {
  716. $aTypes = array('Extensions', 'FileSize');
  717. $aRet = array();
  718. foreach ($aTypes as $sType) {
  719. $sFunc = 'getRestrictionsText' . $sType;
  720. $s = $this->$sFunc ($iProfileId);
  721. if ($s)
  722. $aRet[] = $s;
  723. }
  724. return $aRet;
  725. }
  726. /**
  727. * Reread available mimetypes from particular file.
  728. * It clears 'sys_storage_mime_types' table and fill it with data form provided file.
  729. * The format of file is: mime/type _space_or_tab_ extentions_sperated_by_space.
  730. * Usually the file is mime.types file from apache or /etc/mime.types from unix systems.
  731. * @param $sFile file to read mime types from
  732. * @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.
  733. */
  734. public function reloadMimeTypesFromFile ($sFile)
  735. {
  736. $sResult = '';
  737. /*
  738. * These mime types must be manually added/replaced if they aren't defined in the mime type file
  739. *
  740. text/x-php php
  741. text/x-coffeescript coffee
  742. text/x-common-lisp lsp lisp
  743. text/x-diff diff
  744. text/x-go go
  745. text/x-java java
  746. text/x-lua lua
  747. text/x-perl pl prl perl
  748. text/x-python py
  749. text/nginx nginx
  750. text/x-ini ini
  751. text/x-ruby rb
  752. text/x-sass sass
  753. text/x-sh bash sh
  754. text/x-swift swift
  755. text/x-vb vb
  756. text/vbscript vbs
  757. text/x-vue vue
  758. text/x-yaml yaml
  759. text/x-sql sql
  760. text/x-markdown md
  761. application/xquery xq xquery
  762. application/x-powershell ps1
  763. application/x-aspx aps
  764. application/x-jsp jsp
  765. */
  766. $aIconsFont = array (
  767. 'far file-pdf' => array('pdf'),
  768. 'far file-word' => array('doc', 'docx'),
  769. 'far file-excel' => array('xls', 'xlt', 'xlsx', 'sxc', 'stc', 'ods', 'ots', 'sdc', 'csv', 'dif', 'slk', 'pxl'),
  770. 'far file-powerpoint' => array('ppt', 'pptx', 'sxi', 'sti', 'odp', 'sdp', 'sdd'),
  771. 'far file-code' => array('1st', 'aspx', 'asp', 'json', 'js', 'jsp', 'java', 'php', 'xml', 'html', 'xhtml', 'htm', 'rdf', 'xsd', 'xsl', 'xslt', 'sax', 'rss', 'dtd', 'cfm', 'js', 'asm', 'pl', 'prl', 'bas', 'b', 'fs', 'src', 'cs', 'ws', 'cgi', 'bat', 'py', 'c', 'cpp', 'cc', 'cp', 'h', 'hh', 'cxx', 'hxx', 'c++', 'm', 'lua', 'swift', 'sh', 'as', 'cob', 'tpl', 'lsp', 'x', 'cmd', 'rb', 'cbl', 'pas', 'pp', 'vb', 'vbs', 'f', 'perl', 'jl', 'lol', 'bal', 'pli', 'css', 'less', 'sass', 'saas', 'scss', 'bcc', 'coffee', 'jade', 'j', 'tea', 'c#', 'sas', 'diff', 'pro', 'for', 'sh', 'bsh', 'bash', 'twig', 'csh', 'lisp', 'lsp', 'cobol', 'pl', 'd', 'git', 'rb', 'hrl', 'cr', 'inp', 'a', 'go', 'as3', 'm', 'sql', 'md', 'mbox', 'nginx', 'pgp', 'asc', 'sig', 'ps1', 'rq', 'ttl', 'vue', 'xquery', 'xq'),
  772. 'far file-image' => 'image/',
  773. 'far file-video' => 'video/',
  774. 'far file-audio' => 'audio/',
  775. 'far file-alt' => 'text/',
  776. 'far file-archive' => 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'),
  777. );
  778. $aIcons = array (
  779. 'mime-type-psd.png' => array('psd'),
  780. 'mime-type-png.png' => array('png'),
  781. 'mime-type-image.png' => 'image/',
  782. 'mime-type-video.png' => 'video/',
  783. 'mime-type-audio.png' => 'audio/',
  784. 'mime-type-presentation.png' => array('ppt', 'pptx', 'sxi', 'sti', 'odp', 'sdp', 'sdd'),
  785. 'mime-type-spreadsheet.png' => array('xls', 'xlt', 'xlsx', 'sxc', 'stc', 'ods', 'ots', 'sdc', 'csv', 'dif', 'slk', 'pxl'),
  786. 'mime-type-document.png' => array('doc', 'docx', 'odt', 'ott', 'sxw', 'stw', 'rtf', 'sdw', 'txt', 'pdb', 'psw', 'pdf'),
  787. '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', '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'),
  788. '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'),
  789. );
  790. $f = fopen ($sFile, 'r');
  791. if (!$f)
  792. return false;
  793. $this->_oDb->clearAllMimeTypes();
  794. while (!feof($f) && ($s = fgets($f, 4096)) !== false) {
  795. $s = trim($s);
  796. if (!$s || '#' == $s[0])
  797. continue;
  798. $a = preg_split ("/[\s\\b]+/", $s, 2);
  799. if (!isset($a[0]) || !isset($a[1]))
  800. continue;
  801. $sMimeType = $a[0];
  802. $aExts = preg_split ("/[\s]+/", $a[1]);
  803. foreach ($aExts as $sExt) {
  804. $sIcon = $this->determineIcon($aIcons, $sExt, $sMimeType);
  805. $sIconFont = $this->determineIcon($aIconsFont, $sExt, $sMimeType);
  806. if (!$this->_oDb->addMimeType($sMimeType, $sExt, $sIcon, $sIconFont))
  807. $sResult .= _t('_Error') . ': ' . $sMimeType . "\t" . $sExt . "\n";
  808. }
  809. }
  810. fclose($f);
  811. if (!$sResult)
  812. $sResult = _t('_Success');
  813. return $sResult;
  814. }
  815. protected function determineIcon($aIcons, $sExt, $sMimeType)
  816. {
  817. foreach ($aIcons as $sIc => $if) {
  818. if (!(is_array($if) && in_array($sExt, $if)) && !(is_string($if) && 0 === strncmp($if, $sMimeType, strlen($if))))
  819. continue;
  820. return $sIc;
  821. }
  822. return false;
  823. }
  824. /**
  825. * Get file extension by file name.
  826. * @param $sFileName file name
  827. * @return file extention string
  828. */
  829. public function getFileExt ($sFileName)
  830. {
  831. return strtolower(pathinfo($sFileName, PATHINFO_EXTENSION));
  832. }
  833. /**
  834. * Get file title by file name, actually file title is file name without extension.
  835. * @param $sFileName file name
  836. * @return file title string
  837. */
  838. public function getFileTitle ($sFileName)
  839. {
  840. return pathinfo($sFileName, PATHINFO_FILENAME);
  841. }
  842. /**
  843. * Get file mime/type by file name.
  844. * @param $sFileName file name
  845. * @return file mime type string
  846. */
  847. public function getMimeTypeByFileName ($sFileName)
  848. {
  849. $sExt = $this->getFileExt($sFileName);
  850. $sMimeType = $this->_oDb->getMimeTypeByExt($sExt);
  851. if (!$sMimeType)
  852. $sMimeType = BX_DOL_STORAGE_DEFAULT_MIME_TYPE;
  853. return $sMimeType;
  854. }
  855. /**
  856. * Get file icon by file name.
  857. * File icon is just icon filename without patch or URL.
  858. * File icons must be located in images/icons directory in your template subfolder.
  859. * @param $sFileName file name
  860. * @return file icon string
  861. */
  862. public function getIconNameByFileName ($sFileName)
  863. {
  864. $sExt = $this->getFileExt($sFileName);
  865. $sIcon = $this->_oDb->getIconByExt($sExt);
  866. if (!$sIcon)
  867. $sIcon = BX_DOL_STORAGE_DEFAULT_ICON;
  868. return $sIcon;
  869. }
  870. /**
  871. * Get file font icon by file name.
  872. * Actually just a class name of icon is returnted.
  873. * @param $sFileName file name
  874. * @return file icon string
  875. */
  876. public function getFontIconNameByFileName ($sFileName)
  877. {
  878. $sExt = $this->getFileExt($sFileName);
  879. $sIcon = $this->_oDb->getIconFontByExt($sExt);
  880. if (!$sIcon)
  881. $sIcon = BX_DOL_STORAGE_DEFAULT_ICON_FONT;
  882. return $sIcon;
  883. }
  884. // ------------ internal functions - events
  885. protected function onBeforeFileAdd ($aFileInfo)
  886. {
  887. if ($aFileInfo['size'] > $this->getMaxUploadFileSize($aFileInfo['profile_id'])) {
  888. $this->setErrorCode(BX_DOL_STORAGE_ERR_FILE_TOO_BIG);
  889. return false;
  890. }
  891. // TODO: check site quota - BX_DOL_STORAGE_ERR_SITE_QUOTA_EXCEEDED
  892. $aObjectQuota = $this->_oDb->getStorageObjectQuota();
  893. if (
  894. ($aObjectQuota['quota_size'] && ($aObjectQuota['current_size'] + $aFileInfo['size'] > $aObjectQuota['quota_size']))
  895. ||
  896. ($aObjectQuota['quota_number'] && ($aObjectQuota['current_number'] + 1 > $aObjectQuota['quota_number']))
  897. ) {
  898. $this->setErrorCode(BX_DOL_STORAGE_ERR_OBJECT_QUOTA_EXCEEDED);
  899. return false;
  900. }
  901. $aUserQuota = $this->_oDb->getUserQuota($aFileInfo['profile_id']);
  902. if (
  903. ($aUserQuota['quota_size'] && ($aUserQuota['current_size'] + $aFileInfo['size'] > $aUserQuota['quota_size']))
  904. ||
  905. ($aUserQuota['quota_number'] && ($aUserQuota['current_number'] + 1 > $aUserQuota['quota_number']))
  906. ) {
  907. $this->setErrorCode(BX_DOL_STORAGE_ERR_USER_QUOTA_EXCEEDED);
  908. return false;
  909. }
  910. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  911. $bRet = true;
  912. bx_alert($this->_aObject['object'], 'before_file_add', 0, $aFileInfo['profile_id'], array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  913. return $bRet;
  914. }
  915. protected function onFileAdded ($aFileInfo)
  916. {
  917. // TODO: update site quota - BX_DOL_STORAGE_ERR_SITE_QUOTA_EXCEEDED
  918. if (!$this->_oDb->updateStorageObjectQuota($aFileInfo['size'], 1)) {
  919. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  920. return false;
  921. }
  922. if (!$this->_oDb->updateUserQuota($aFileInfo['profile_id'], $aFileInfo['size'], 1)) {
  923. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  924. return false;
  925. }
  926. if (!$this->insertGhost ($aFileInfo['id'], $aFileInfo['profile_id'], $aFileInfo['content_id'])) {
  927. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  928. return false;
  929. }
  930. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  931. $bRet = true;
  932. bx_alert($this->_aObject['object'], 'file_added', $aFileInfo['id'], $aFileInfo['profile_id'], array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  933. return $bRet;
  934. }
  935. function insertGhost($iFileId, $iProfileId, $iContentId = 0)
  936. {
  937. return $this->_oDb->insertGhosts ($iFileId, $iProfileId, $iContentId);
  938. }
  939. function onBeforeFileDelete ($aFileInfo, $iProfileId)
  940. {
  941. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  942. $bRet = true;
  943. bx_alert($this->_aObject['object'], 'before_file_delete', $aFileInfo['id'], $iProfileId, array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  944. return $bRet;
  945. }
  946. function onFileDeleted ($aFileInfo, $iProfileId, $aGhost = false)
  947. {
  948. // TODO: update site quota
  949. if (!$this->_oDb->updateStorageObjectQuota(-$aFileInfo['size'], -1)) {
  950. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  951. return false;
  952. }
  953. if (!$this->_oDb->updateUserQuota($aFileInfo['profile_id'], -$aFileInfo['size'], -1)) {
  954. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  955. return false;
  956. }
  957. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  958. $bRet = true;
  959. bx_alert($this->_aObject['object'], 'file_deleted', $aFileInfo['id'], $iProfileId, array('file_info' => $aFileInfo, 'ghost' => $aGhost, 'return_value' => &$bRet));
  960. return $bRet;
  961. }
  962. // ------------ internal functions
  963. protected function setErrorCode($i)
  964. {
  965. return ($this->_iErrorCode = $i);
  966. }
  967. protected function genRandName($isCheckForUniq = true)
  968. {
  969. $sRandName = strtolower(genRndPwd(32, false));
  970. if ($isCheckForUniq) {
  971. $iTries = 10;
  972. do {
  973. $aFile = $this->_oDb->getFileByRemoteId($sRandName);
  974. $bExist = is_array($aFile) && $aFile;
  975. } while (--$iTries && $bExist);
  976. }
  977. return $sRandName;
  978. }
  979. protected function genPath($s, $iLevels)
  980. {
  981. $sRet = '';
  982. $i = 1;
  983. while ($iLevels-- > 0)
  984. $sRet .= substr($s, 0, $i++) . '/';
  985. return $sRet;
  986. }
  987. protected function genRemoteNamePath ($sPath, $sLocalId, $sExt)
  988. {
  989. return $sPath . $sLocalId;
  990. }
  991. protected function isValidExt ($sExt)
  992. {
  993. switch ($this->_aObject['ext_mode']) {
  994. case 'allow-deny':
  995. if ($this->isAllowedExt($sExt))
  996. return true;
  997. return false;
  998. case 'deny-allow':
  999. if ($this->isDeniedExt($sExt))
  1000. return false;
  1001. return true;
  1002. default:
  1003. return false;
  1004. }
  1005. }
  1006. protected function isAllowedExt ($sExt)
  1007. {
  1008. return $this->isAllowedDeniedExt($sExt, 'ext_allow');
  1009. }
  1010. protected function isDeniedExt ($sExt)
  1011. {
  1012. return $this->isAllowedDeniedExt($sExt, 'ext_deny');
  1013. }
  1014. protected function isAllowedDeniedExt ($sExt, $sExtMode)
  1015. {
  1016. if ('' == $this->_aObject[$sExtMode])
  1017. return false;
  1018. if (!is_array($this->_aObject[$sExtMode]))
  1019. $this->_aObject[$sExtMode] = explode(',', $this->_aObject[$sExtMode]);
  1020. return in_array ($sExt, $this->_aObject[$sExtMode]);
  1021. }
  1022. protected function queueFiles($aFiles)
  1023. {
  1024. if (!$aFiles)
  1025. return 0;
  1026. $a = array();
  1027. foreach ($aFiles as $aFile)
  1028. $a[] = $aFile['id'];
  1029. return $this->queueFilesForDeletion($a);
  1030. }
  1031. }
  1032. /**
  1033. * Handle file uploads via XMLHttpRequest
  1034. */
  1035. class BxDolStorageHelperXhr
  1036. {
  1037. protected $sName;
  1038. function __construct ($aParams)
  1039. {
  1040. $this->sName = $aParams['name'];
  1041. }
  1042. function getImmediateError()
  1043. {
  1044. return BX_DOL_STORAGE_ERR_OK;
  1045. }
  1046. function save($path)
  1047. {
  1048. $input = fopen("php://input", "r");
  1049. $temp = tmpfile();
  1050. $realSize = stream_copy_to_stream($input, $temp);
  1051. fclose($input);
  1052. if (false === $this->getSize() || $realSize != $this->getSize())
  1053. return false;
  1054. $target = fopen($path, "w");
  1055. fseek($temp, 0, SEEK_SET);
  1056. stream_copy_to_stream($temp, $target);
  1057. fclose($target);
  1058. fclose($temp);
  1059. return true;
  1060. }
  1061. function getName()
  1062. {
  1063. return $this->sName;
  1064. }
  1065. function getSize()
  1066. {
  1067. if (isset($_SERVER["CONTENT_LENGTH"]))
  1068. return (int)$_SERVER["CONTENT_LENGTH"];
  1069. else
  1070. return false;
  1071. }
  1072. }
  1073. /**
  1074. * Handle file uploads via regular form post (uses the $_FILES array)
  1075. */
  1076. class BxDolStorageHelperForm
  1077. {
  1078. protected $aFile;
  1079. function __construct ($aParams)
  1080. {
  1081. $this->aFile = $aParams['file'];
  1082. }
  1083. function getImmediateError()
  1084. {
  1085. if (!$this->aFile['size'] || !$this->aFile['tmp_name'])
  1086. return BX_DOL_STORAGE_ERR_NO_FILE;
  1087. if (UPLOAD_ERR_OK != $this->aFile['error'])
  1088. return (int)$this->aFile['error'];
  1089. return BX_DOL_STORAGE_ERR_OK;
  1090. }
  1091. function save($path)
  1092. {
  1093. if (!move_uploaded_file($this->aFile['tmp_name'], $path)){
  1094. return false;
  1095. }
  1096. return true;
  1097. }
  1098. function getName()
  1099. {
  1100. return $this->aFile['name'];
  1101. }
  1102. function getSize()
  1103. {
  1104. return $this->aFile['size'];
  1105. }
  1106. }
  1107. /**
  1108. * Store file from local file path
  1109. */
  1110. class BxDolStorageHelperPath
  1111. {
  1112. protected $sPath;
  1113. function __construct ($aParams)
  1114. {
  1115. $this->sPath = $aParams['path'];
  1116. }
  1117. function getImmediateError()
  1118. {
  1119. if (!$this->sPath || !file_exists($this->sPath))
  1120. return BX_DOL_STORAGE_ERR_NO_FILE;
  1121. return BX_DOL_STORAGE_ERR_OK;
  1122. }
  1123. function save($path)
  1124. {
  1125. if (!copy($this->sPath, $path)) {
  1126. return false;
  1127. }
  1128. return true;
  1129. }
  1130. function getName()
  1131. {
  1132. return pathinfo($this->sPath, PATHINFO_BASENAME);
  1133. }
  1134. function getSize()
  1135. {
  1136. return filesize($this->sPath);
  1137. }
  1138. }
  1139. /**
  1140. * Store file from URL
  1141. */
  1142. class BxDolStorageHelperUrl extends BxDolStorageHelperPath
  1143. {
  1144. protected $aMime2Ext = array (
  1145. 'image/bmp' => 'bmp',
  1146. 'image/gif' => 'gif',
  1147. 'image/jpeg' => 'jpg',
  1148. 'image/pjpeg' => 'jpg',
  1149. 'image/png' => 'png',
  1150. );
  1151. function __construct ($aParams)
  1152. {
  1153. $aParams['path'] = '';
  1154. $sExt = pathinfo(parse_url($aParams['url'], PHP_URL_PATH), PATHINFO_EXTENSION);
  1155. if ($sTmpFilename = tempnam(BX_DIRECTORY_PATH_TMP, '')) {
  1156. $s = '';
  1157. if (!$sExt) {
  1158. $s = @file_get_contents($aParams['url']);
  1159. $oFinfo = new finfo(FILEINFO_MIME_TYPE);
  1160. $sMime = $oFinfo->buffer($s);
  1161. if (isset($this->aMime2Ext[$sMime]))
  1162. $sExt = $this->aMime2Ext[$sMime];
  1163. }
  1164. $aParams['path'] = $sTmpFilename . '.' . $sExt;
  1165. @rename($sTmpFilename, $aParams['path']);
  1166. if ($s) {
  1167. file_put_contents($aParams['path'], $s);
  1168. }
  1169. else {
  1170. $hRead = fopen($aParams['url'], "rb");
  1171. $hWrite = fopen($aParams['path'], "wb");
  1172. if (false !== $hRead && false !== $hWrite) {
  1173. while (!feof($hRead)) {
  1174. $data = fread($hRead, 8192);
  1175. if (false === fwrite($hWrite, $data)) {
  1176. fclose($hWrite);
  1177. file_put_contents($aParams['path'], '');
  1178. break;
  1179. }
  1180. }
  1181. fclose($hRead);
  1182. fclose($hWrite);
  1183. }
  1184. }
  1185. }
  1186. parent::__construct($aParams);
  1187. }
  1188. function getImmediateError()
  1189. {
  1190. $iRet = parent::getImmediateError();
  1191. if (BX_DOL_STORAGE_ERR_OK != $iRet)
  1192. return $iRet;
  1193. return $this->getSize() > 0 ? BX_DOL_STORAGE_ERR_OK : BX_DOL_STORAGE_INVALID_FILE;
  1194. }
  1195. function __destruct()
  1196. {
  1197. @unlink($this->sPath);
  1198. }
  1199. }
  1200. /**
  1201. * Handle file uploads from the same or another storage object
  1202. */
  1203. class BxDolStorageHelperStorage
  1204. {
  1205. protected $iFileId;
  1206. protected $oStorage;
  1207. protected $aFile;
  1208. function __construct ($aParams)
  1209. {
  1210. $this->iFileId = $aParams['id'];
  1211. $this->oStorage = BxDolStorage::getObjectInstance($aParams['storage']);
  1212. $this->aFile = false;
  1213. if ($this->oStorage)
  1214. $this->aFile = $this->oStorage->getFile($this->iFileId);
  1215. }
  1216. function getImmediateError()
  1217. {
  1218. if (!$this->iFileId)
  1219. return BX_DOL_STORAGE_ERR_NO_FILE;
  1220. if (!$this->oStorage)
  1221. return BX_DOL_STORAGE_ERR_ENGINE_GET;
  1222. if (!$this->aFile)
  1223. return BX_DOL_STORAGE_ERR_NO_FILE;
  1224. return BX_DOL_STORAGE_ERR_OK;
  1225. }
  1226. function save($path)
  1227. {
  1228. $s = bx_file_get_contents ($this->oStorage->getFileUrlById($this->iFileId));
  1229. if (!$s)
  1230. return false;
  1231. return file_put_contents($path, $s) ? true : false;
  1232. }
  1233. function getName()
  1234. {
  1235. return $this->aFile['file_name'];
  1236. }
  1237. function getSize()
  1238. {
  1239. return $this->aFile['size'];
  1240. }
  1241. }
  1242. /** @} */