BxDolStorage.php 58 KB

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