BxDolStorage.php 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  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. /*
  723. * These mime types must be manually added/replaced if they aren't defined in the mime type file
  724. *
  725. text/x-php php
  726. text/x-coffeescript coffee
  727. text/x-common-lisp lsp lisp
  728. text/x-diff diff
  729. text/x-go go
  730. text/x-java java
  731. text/x-lua lua
  732. text/x-perl pl prl perl
  733. text/x-python py
  734. text/nginx nginx
  735. text/x-ini ini
  736. text/x-ruby rb
  737. text/x-sass sass
  738. text/x-sh bash sh
  739. text/x-swift swift
  740. text/x-vb vb
  741. text/vbscript vbs
  742. text/x-vue vue
  743. text/x-yaml yaml
  744. text/x-sql sql
  745. text/x-markdown md
  746. application/xquery xq xquery
  747. application/x-powershell ps1
  748. application/x-aspx aps
  749. application/x-jsp jsp
  750. */
  751. $aIconsFont = array (
  752. 'file-pdf-o' => array('pdf'),
  753. 'file-word-o' => array('doc', 'docx'),
  754. 'file-excel-o' => array('xls', 'xlt', 'xlsx', 'sxc', 'stc', 'ods', 'ots', 'sdc', 'csv', 'dif', 'slk', 'pxl'),
  755. 'file-powerpoint-o' => array('ppt', 'pptx', 'sxi', 'sti', 'odp', 'sdp', 'sdd'),
  756. 'file-code-o' => 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'),
  757. 'file-image-o' => 'image/',
  758. 'file-video-o' => 'video/',
  759. 'file-audio-o' => 'audio/',
  760. 'file-text-o' => 'text/',
  761. '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'),
  762. );
  763. $aIcons = array (
  764. 'mime-type-psd.png' => array('psd'),
  765. 'mime-type-png.png' => array('png'),
  766. 'mime-type-image.png' => 'image/',
  767. 'mime-type-video.png' => 'video/',
  768. 'mime-type-audio.png' => 'audio/',
  769. 'mime-type-presentation.png' => array('ppt', 'pptx', 'sxi', 'sti', 'odp', 'sdp', 'sdd'),
  770. 'mime-type-spreadsheet.png' => array('xls', 'xlt', 'xlsx', 'sxc', 'stc', 'ods', 'ots', 'sdc', 'csv', 'dif', 'slk', 'pxl'),
  771. 'mime-type-document.png' => array('doc', 'docx', 'odt', 'ott', 'sxw', 'stw', 'rtf', 'sdw', 'txt', 'pdb', 'psw', 'pdf'),
  772. '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'),
  773. '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'),
  774. );
  775. $f = fopen ($sFile, 'r');
  776. if (!$f)
  777. return false;
  778. $this->_oDb->clearAllMimeTypes();
  779. while (!feof($f) && ($s = fgets($f, 4096)) !== false) {
  780. $s = trim($s);
  781. if (!$s || '#' == $s[0])
  782. continue;
  783. $a = preg_split ("/[\s\\b]+/", $s, 2);
  784. if (!isset($a[0]) || !isset($a[1]))
  785. continue;
  786. $sMimeType = $a[0];
  787. $aExts = preg_split ("/[\s]+/", $a[1]);
  788. foreach ($aExts as $sExt) {
  789. $sIcon = $this->determineIcon($aIcons, $sExt, $sMimeType);
  790. $sIconFont = $this->determineIcon($aIconsFont, $sExt, $sMimeType);
  791. if (!$this->_oDb->addMimeType($sMimeType, $sExt, $sIcon, $sIconFont))
  792. $sResult .= _t('_Error') . ': ' . $sMimeType . "\t" . $sExt . "\n";
  793. }
  794. }
  795. fclose($f);
  796. if (!$sResult)
  797. $sResult = _t('_Success');
  798. return $sResult;
  799. }
  800. protected function determineIcon($aIcons, $sExt, $sMimeType)
  801. {
  802. foreach ($aIcons as $sIc => $if) {
  803. if (!(is_array($if) && in_array($sExt, $if)) && !(is_string($if) && 0 === strncmp($if, $sMimeType, strlen($if))))
  804. continue;
  805. return $sIc;
  806. }
  807. return false;
  808. }
  809. /**
  810. * Get file extension by file name.
  811. * @param $sFileName file name
  812. * @return file extention string
  813. */
  814. public function getFileExt ($sFileName)
  815. {
  816. return strtolower(pathinfo($sFileName, PATHINFO_EXTENSION));
  817. }
  818. /**
  819. * Get file title by file name, actually file title is file name without extension.
  820. * @param $sFileName file name
  821. * @return file title string
  822. */
  823. public function getFileTitle ($sFileName)
  824. {
  825. return pathinfo($sFileName, PATHINFO_FILENAME);
  826. }
  827. /**
  828. * Get file mime/type by file name.
  829. * @param $sFileName file name
  830. * @return file mime type string
  831. */
  832. public function getMimeTypeByFileName ($sFileName)
  833. {
  834. $sExt = $this->getFileExt($sFileName);
  835. $sMimeType = $this->_oDb->getMimeTypeByExt($sExt);
  836. if (!$sMimeType)
  837. $sMimeType = BX_DOL_STORAGE_DEFAULT_MIME_TYPE;
  838. return $sMimeType;
  839. }
  840. /**
  841. * Get file icon by file name.
  842. * File icon is just icon filename without patch or URL.
  843. * File icons must be located in images/icons directory in your template subfolder.
  844. * @param $sFileName file name
  845. * @return file icon string
  846. */
  847. public function getIconNameByFileName ($sFileName)
  848. {
  849. $sExt = $this->getFileExt($sFileName);
  850. $sIcon = $this->_oDb->getIconByExt($sExt);
  851. if (!$sIcon)
  852. $sIcon = BX_DOL_STORAGE_DEFAULT_ICON;
  853. return $sIcon;
  854. }
  855. /**
  856. * Get file font icon by file name.
  857. * Actually just a class name of icon is returnted.
  858. * @param $sFileName file name
  859. * @return file icon string
  860. */
  861. public function getFontIconNameByFileName ($sFileName)
  862. {
  863. $sExt = $this->getFileExt($sFileName);
  864. $sIcon = $this->_oDb->getIconFontByExt($sExt);
  865. if (!$sIcon)
  866. $sIcon = BX_DOL_STORAGE_DEFAULT_ICON_FONT;
  867. return $sIcon;
  868. }
  869. // ------------ internal functions - events
  870. protected function onBeforeFileAdd ($aFileInfo)
  871. {
  872. if ($aFileInfo['size'] > $this->getMaxUploadFileSize($aFileInfo['profile_id'])) {
  873. $this->setErrorCode(BX_DOL_STORAGE_ERR_FILE_TOO_BIG);
  874. return false;
  875. }
  876. // TODO: check site quota - BX_DOL_STORAGE_ERR_SITE_QUOTA_EXCEEDED
  877. $aObjectQuota = $this->_oDb->getStorageObjectQuota();
  878. if (
  879. ($aObjectQuota['quota_size'] && ($aObjectQuota['current_size'] + $aFileInfo['size'] > $aObjectQuota['quota_size']))
  880. ||
  881. ($aObjectQuota['quota_number'] && ($aObjectQuota['current_number'] + 1 > $aObjectQuota['quota_number']))
  882. ) {
  883. $this->setErrorCode(BX_DOL_STORAGE_ERR_OBJECT_QUOTA_EXCEEDED);
  884. return false;
  885. }
  886. $aUserQuota = $this->_oDb->getUserQuota($aFileInfo['profile_id']);
  887. if (
  888. ($aUserQuota['quota_size'] && ($aUserQuota['current_size'] + $aFileInfo['size'] > $aUserQuota['quota_size']))
  889. ||
  890. ($aUserQuota['quota_number'] && ($aUserQuota['current_number'] + 1 > $aUserQuota['quota_number']))
  891. ) {
  892. $this->setErrorCode(BX_DOL_STORAGE_ERR_USER_QUOTA_EXCEEDED);
  893. return false;
  894. }
  895. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  896. $bRet = true;
  897. bx_alert($this->_aObject['object'], 'before_file_add', 0, $aFileInfo['profile_id'], array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  898. return $bRet;
  899. }
  900. protected function onFileAdded ($aFileInfo)
  901. {
  902. // TODO: update site quota - BX_DOL_STORAGE_ERR_SITE_QUOTA_EXCEEDED
  903. if (!$this->_oDb->updateStorageObjectQuota($aFileInfo['size'], 1)) {
  904. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  905. return false;
  906. }
  907. if (!$this->_oDb->updateUserQuota($aFileInfo['profile_id'], $aFileInfo['size'], 1)) {
  908. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  909. return false;
  910. }
  911. if (!$this->insertGhost ($aFileInfo['id'], $aFileInfo['profile_id'], $aFileInfo['content_id'])) {
  912. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  913. return false;
  914. }
  915. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  916. $bRet = true;
  917. bx_alert($this->_aObject['object'], 'file_added', $aFileInfo['id'], $aFileInfo['profile_id'], array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  918. return $bRet;
  919. }
  920. function insertGhost($iFileId, $iProfileId, $iContentId = 0)
  921. {
  922. return $this->_oDb->insertGhosts ($iFileId, $iProfileId, $iContentId);
  923. }
  924. function onBeforeFileDelete ($aFileInfo, $iProfileId)
  925. {
  926. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  927. $bRet = true;
  928. bx_alert($this->_aObject['object'], 'before_file_delete', $aFileInfo['id'], $iProfileId, array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  929. return $bRet;
  930. }
  931. function onFileDeleted ($aFileInfo, $iProfileId, $aGhost = false)
  932. {
  933. // TODO: update site quota
  934. if (!$this->_oDb->updateStorageObjectQuota(-$aFileInfo['size'], -1)) {
  935. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  936. return false;
  937. }
  938. if (!$this->_oDb->updateUserQuota($aFileInfo['profile_id'], -$aFileInfo['size'], -1)) {
  939. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  940. return false;
  941. }
  942. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  943. $bRet = true;
  944. bx_alert($this->_aObject['object'], 'file_deleted', $aFileInfo['id'], $iProfileId, array('file_info' => $aFileInfo, 'ghost' => $aGhost, 'return_value' => &$bRet));
  945. return $bRet;
  946. }
  947. // ------------ internal functions
  948. protected function setErrorCode($i)
  949. {
  950. return ($this->_iErrorCode = $i);
  951. }
  952. protected function genRandName($isCheckForUniq = true)
  953. {
  954. $sRandName = strtolower(genRndPwd(32, false));
  955. if ($isCheckForUniq) {
  956. $iTries = 10;
  957. do {
  958. $aFile = $this->_oDb->getFileByRemoteId($sRandName);
  959. $bExist = is_array($aFile) && $aFile;
  960. } while (--$iTries && $bExist);
  961. }
  962. return $sRandName;
  963. }
  964. protected function genPath($s, $iLevels)
  965. {
  966. $sRet = '';
  967. $i = 1;
  968. while ($iLevels-- > 0)
  969. $sRet .= substr($s, 0, $i++) . '/';
  970. return $sRet;
  971. }
  972. protected function genRemoteNamePath ($sPath, $sLocalId, $sExt)
  973. {
  974. return $sPath . $sLocalId;
  975. }
  976. protected function isValidExt ($sExt)
  977. {
  978. switch ($this->_aObject['ext_mode']) {
  979. case 'allow-deny':
  980. if ($this->isAllowedExt($sExt))
  981. return true;
  982. return false;
  983. case 'deny-allow':
  984. if ($this->isDeniedExt($sExt))
  985. return false;
  986. return true;
  987. default:
  988. return false;
  989. }
  990. }
  991. protected function isAllowedExt ($sExt)
  992. {
  993. return $this->isAllowedDeniedExt($sExt, 'ext_allow');
  994. }
  995. protected function isDeniedExt ($sExt)
  996. {
  997. return $this->isAllowedDeniedExt($sExt, 'ext_deny');
  998. }
  999. protected function isAllowedDeniedExt ($sExt, $sExtMode)
  1000. {
  1001. if ('' == $this->_aObject[$sExtMode])
  1002. return false;
  1003. if (!is_array($this->_aObject[$sExtMode]))
  1004. $this->_aObject[$sExtMode] = explode(',', $this->_aObject[$sExtMode]);
  1005. return in_array ($sExt, $this->_aObject[$sExtMode]);
  1006. }
  1007. protected function queueFiles($aFiles)
  1008. {
  1009. if (!$aFiles)
  1010. return 0;
  1011. $a = array();
  1012. foreach ($aFiles as $aFile)
  1013. $a[] = $aFile['id'];
  1014. return $this->queueFilesForDeletion($a);
  1015. }
  1016. }
  1017. /**
  1018. * Handle file uploads via XMLHttpRequest
  1019. */
  1020. class BxDolStorageHelperXhr
  1021. {
  1022. protected $sName;
  1023. function __construct ($aParams)
  1024. {
  1025. $this->sName = $aParams['name'];
  1026. }
  1027. function getImmediateError()
  1028. {
  1029. return BX_DOL_STORAGE_ERR_OK;
  1030. }
  1031. function save($path)
  1032. {
  1033. $input = fopen("php://input", "r");
  1034. $temp = tmpfile();
  1035. $realSize = stream_copy_to_stream($input, $temp);
  1036. fclose($input);
  1037. if (false === $this->getSize() || $realSize != $this->getSize())
  1038. return false;
  1039. $target = fopen($path, "w");
  1040. fseek($temp, 0, SEEK_SET);
  1041. stream_copy_to_stream($temp, $target);
  1042. fclose($target);
  1043. fclose($temp);
  1044. return true;
  1045. }
  1046. function getName()
  1047. {
  1048. return $this->sName;
  1049. }
  1050. function getSize()
  1051. {
  1052. if (isset($_SERVER["CONTENT_LENGTH"]))
  1053. return (int)$_SERVER["CONTENT_LENGTH"];
  1054. else
  1055. return false;
  1056. }
  1057. }
  1058. /**
  1059. * Handle file uploads via regular form post (uses the $_FILES array)
  1060. */
  1061. class BxDolStorageHelperForm
  1062. {
  1063. protected $aFile;
  1064. function __construct ($aParams)
  1065. {
  1066. $this->aFile = $aParams['file'];
  1067. }
  1068. function getImmediateError()
  1069. {
  1070. if (!$this->aFile['size'] || !$this->aFile['tmp_name'])
  1071. return BX_DOL_STORAGE_ERR_NO_FILE;
  1072. if (UPLOAD_ERR_OK != $this->aFile['error'])
  1073. return (int)$this->aFile['error'];
  1074. return BX_DOL_STORAGE_ERR_OK;
  1075. }
  1076. function save($path)
  1077. {
  1078. if (!move_uploaded_file($this->aFile['tmp_name'], $path)){
  1079. return false;
  1080. }
  1081. return true;
  1082. }
  1083. function getName()
  1084. {
  1085. return $this->aFile['name'];
  1086. }
  1087. function getSize()
  1088. {
  1089. return $this->aFile['size'];
  1090. }
  1091. }
  1092. /**
  1093. * Store file from local file path
  1094. */
  1095. class BxDolStorageHelperPath
  1096. {
  1097. protected $sPath;
  1098. function __construct ($aParams)
  1099. {
  1100. $this->sPath = $aParams['path'];
  1101. }
  1102. function getImmediateError()
  1103. {
  1104. if (!$this->sPath || !file_exists($this->sPath))
  1105. return BX_DOL_STORAGE_ERR_NO_FILE;
  1106. return BX_DOL_STORAGE_ERR_OK;
  1107. }
  1108. function save($path)
  1109. {
  1110. if (!copy($this->sPath, $path)) {
  1111. return false;
  1112. }
  1113. return true;
  1114. }
  1115. function getName()
  1116. {
  1117. return pathinfo($this->sPath, PATHINFO_BASENAME);
  1118. }
  1119. function getSize()
  1120. {
  1121. return filesize($this->sPath);
  1122. }
  1123. }
  1124. /**
  1125. * Store file from URL
  1126. */
  1127. class BxDolStorageHelperUrl extends BxDolStorageHelperPath
  1128. {
  1129. protected $aMime2Ext = array (
  1130. 'image/bmp' => 'bmp',
  1131. 'image/gif' => 'gif',
  1132. 'image/jpeg' => 'jpg',
  1133. 'image/pjpeg' => 'jpg',
  1134. 'image/png' => 'png',
  1135. );
  1136. function __construct ($aParams)
  1137. {
  1138. $aParams['path'] = '';
  1139. $sExt = pathinfo(parse_url($aParams['url'], PHP_URL_PATH), PATHINFO_EXTENSION);
  1140. if ($sTmpFilename = tempnam(BX_DIRECTORY_PATH_TMP, '')) {
  1141. $s = '';
  1142. if (!$sExt) {
  1143. $s = file_get_contents($aParams['url']);
  1144. $oFinfo = new finfo(FILEINFO_MIME_TYPE);
  1145. $sMime = $oFinfo->buffer($s);
  1146. if (isset($this->aMime2Ext[$sMime]))
  1147. $sExt = $this->aMime2Ext[$sMime];
  1148. }
  1149. $aParams['path'] = $sTmpFilename . '.' . $sExt;
  1150. @rename($sTmpFilename, $aParams['path']);
  1151. if ($s || $s = bx_file_get_contents ($aParams['url']))
  1152. file_put_contents($aParams['path'], $s);
  1153. }
  1154. parent::__construct($aParams);
  1155. }
  1156. function getImmediateError()
  1157. {
  1158. $iRet = parent::getImmediateError();
  1159. if (BX_DOL_STORAGE_ERR_OK != $iRet)
  1160. return $iRet;
  1161. return $this->getSize() > 0 ? BX_DOL_STORAGE_ERR_OK : BX_DOL_STORAGE_INVALID_FILE;
  1162. }
  1163. function __destruct()
  1164. {
  1165. @unlink($this->sPath);
  1166. }
  1167. }
  1168. /**
  1169. * Handle file uploads from the same or another storage object
  1170. */
  1171. class BxDolStorageHelperStorage
  1172. {
  1173. protected $iFileId;
  1174. protected $oStorage;
  1175. protected $aFile;
  1176. function __construct ($aParams)
  1177. {
  1178. $this->iFileId = $aParams['id'];
  1179. $this->oStorage = BxDolStorage::getObjectInstance($aParams['storage']);
  1180. $this->aFile = false;
  1181. if ($this->oStorage)
  1182. $this->aFile = $this->oStorage->getFile($this->iFileId);
  1183. }
  1184. function getImmediateError()
  1185. {
  1186. if (!$this->iFileId)
  1187. return BX_DOL_STORAGE_ERR_NO_FILE;
  1188. if (!$this->oStorage)
  1189. return BX_DOL_STORAGE_ERR_ENGINE_GET;
  1190. if (!$this->aFile)
  1191. return BX_DOL_STORAGE_ERR_NO_FILE;
  1192. return BX_DOL_STORAGE_ERR_OK;
  1193. }
  1194. function save($path)
  1195. {
  1196. $s = bx_file_get_contents ($this->oStorage->getFileUrlById($this->iFileId));
  1197. if (!$s)
  1198. return false;
  1199. return file_put_contents($path, $s) ? true : false;
  1200. }
  1201. function getName()
  1202. {
  1203. return $this->aFile['file_name'];
  1204. }
  1205. function getSize()
  1206. {
  1207. return $this->aFile['size'];
  1208. }
  1209. }
  1210. /** @} */