BxDolStorage.php 59 KB

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