BxDolStorage.php 59 KB

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