BxDolStorage.php 56 KB

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