BxDolStorage.php 48 KB

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