BxDolStorage.php 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551
  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. // store file to storage engine
  425. $sLocalId = $this->genRandName();
  426. $sPath = $this->genPath($sLocalId, $this->_aObject['levels']);
  427. $sRemoteNamePath = $this->genRemoteNamePath ($sPath, $sLocalId, $sExt);
  428. if (!$this->addFileToEngine($sTmpFile, $sLocalId, $oHelper->getName(), $isPrivate, $iProfileId)) {
  429. unlink($sTmpFile);
  430. $this->setErrorCode(BX_DOL_STORAGE_ERR_ENGINE_ADD);
  431. return false;
  432. }
  433. unlink($sTmpFile);
  434. // add record in db
  435. $iTime = time();
  436. $iSize = $oHelper->getSize();
  437. $bFileAdded = $this->_oDb->addFile($iProfileId, $sLocalId, $sRemoteNamePath, $oHelper->getName(), $sMimeType, $sExt, $iSize, $iTime, $isPrivate, $aAdditionalFields);
  438. $iId = $this->_oDb->lastId();
  439. if (!$bFileAdded || !$iId) {
  440. $this->deleteFileFromEngine($sPath . $sLocalId, $isPrivate);
  441. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  442. return false;
  443. }
  444. // after upload callback + triggers update
  445. if (!$this->onFileAdded (array(
  446. 'id' => $iId,
  447. 'profile_id' => $iProfileId,
  448. 'content_id' => $iContentId,
  449. 'remote_id' => $sLocalId,
  450. 'path' => $sPath . $sLocalId,
  451. 'file_name' => $oHelper->getName(),
  452. 'mime_type' => $sMimeType,
  453. 'size' => $iSize,
  454. 'private' => $isPrivate ? 1 : 0,
  455. ))) {
  456. $this->deleteFileFromEngine($sPath . $sLocalId, $isPrivate);
  457. $this->_oDb->deleteFile($iId);
  458. return false;
  459. }
  460. return $iId;
  461. }
  462. /**
  463. * convert default multiple files array into more logical one
  464. */
  465. public function convertMultipleFilesArray($aFiles)
  466. {
  467. if (!is_array($aFiles) || !is_array($aFiles['name']))
  468. return false;
  469. $aRet = array ();
  470. foreach ($aFiles['name'] as $i => $sName) {
  471. foreach ($aFiles as $sKey => $r) {
  472. if (!$aFiles['name'][$i])
  473. break;
  474. $aRet[$i][$sKey] = $aFiles[$sKey][$i];
  475. }
  476. }
  477. return $aRet;
  478. }
  479. /**
  480. * the same as storeFile, but it tries to do it directly from uploaded file
  481. */
  482. public function storeFileFromForm($aFile, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  483. {
  484. return $this->storeFile('Form', array('file' => $aFile), false, $isPrivate, $iProfileId, $iContentId);
  485. }
  486. /**
  487. * the same as storeFile, but it tries to do it directly from HTML5 file upload method
  488. */
  489. public function storeFileFromXhr($sName, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  490. {
  491. return $this->storeFile('Xhr', array('name' => $sName), false, $isPrivate, $iProfileId, $iContentId);
  492. }
  493. /**
  494. * the same as storeFile, but it tries to do it directly from local file
  495. */
  496. public function storeFileFromPath($sPath, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  497. {
  498. return $this->storeFile('Path', array('path' => $sPath), false, $isPrivate, $iProfileId, $iContentId);
  499. }
  500. /**
  501. * the same as storeFileFromPath, but it tries to do it from URL
  502. */
  503. public function storeFileFromUrl($sUrl, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  504. {
  505. return $this->storeFile('Url', array('url' => $sUrl), false, $isPrivate, $iProfileId, $iContentId);
  506. }
  507. /**
  508. * the same as storeFile, but it tries to do it directly from the same or another storage by file id
  509. * @param $aParams['id'] - file ID in the storage
  510. * @param $aParams['storage'] - the storage name
  511. */
  512. public function storeFileFromStorage($aParams, $isPrivate = true, $iProfileId = 0, $iContentId = 0)
  513. {
  514. if (!isset($aParams['id']) || !(int)$aParams['id'])
  515. $aParams['id'] = 0;
  516. if (!isset($aParams['storage']))
  517. $aParams['storage'] = $this->_aObject['object'];
  518. return $this->storeFile('Storage', $aParams, false, $isPrivate, $iProfileId, $iContentId = 0);
  519. }
  520. /**
  521. * Delete file by file id.
  522. */
  523. public function deleteFile($iFileId, $iProfileId = 0)
  524. {
  525. $aFile = $this->_oDb->getFileById ($iFileId);
  526. if (!$aFile) {
  527. $this->setErrorCode(BX_DOL_STORAGE_ERR_FILE_NOT_FOUND);
  528. return false;
  529. }
  530. if (!$this->onBeforeFileDelete ($aFile, $iProfileId)) {
  531. return false;
  532. }
  533. if (!$this->deleteFileFromEngine($aFile['path'], $aFile['private'])) {
  534. return false;
  535. }
  536. $aGhost = $this->_oDb->getGhost($aFile['id']);
  537. if (!$this->_oDb->deleteFile($aFile['id'])) {
  538. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  539. return false;
  540. }
  541. if (!$this->onFileDeleted ($aFile, $iProfileId, $aGhost)) {
  542. return false;
  543. }
  544. return true;
  545. }
  546. /**
  547. * Queue file(s) for deletion. File(s) will be deleted later upon cron call (usually every minute).
  548. * @param $mixedFileId file id or array of file ids.
  549. * @return number of queued files
  550. */
  551. public function queueFilesForDeletion($mixedFileId)
  552. {
  553. if (!is_array($mixedFileId))
  554. $mixedFileId = array ($mixedFileId);
  555. bx_import('BxDolForm');
  556. $oChecker = new BxDolFormCheckerHelper();
  557. return $this->_oDb->queueFilesForDeletion (array_unique($oChecker->passInt($mixedFileId)));
  558. }
  559. /**
  560. * Queue file(s) for deletion by getting neccesary files from ghosts table by profile id and content id
  561. * @param $iProfileId profile id associated with files
  562. * @param $iContentId content id associated with files, or false if to check by profile id only
  563. * @return number of queued files
  564. */
  565. public function queueFilesForDeletionFromGhosts($iProfileId, $iContentId = false)
  566. {
  567. $aFiles = $this->getGhosts ($iProfileId, $iContentId);
  568. return $this->queueFiles($aFiles);
  569. }
  570. /**
  571. * Queue file(s) for deletion of the whole storage object
  572. * @return number of queued files
  573. */
  574. public function queueFilesForDeletionFromObject()
  575. {
  576. $aFiles = $this->getFiles (false);
  577. return $this->queueFiles($aFiles);
  578. }
  579. /**
  580. * Download file.
  581. * @param array $aFile downloading file info.
  582. * @param boolean $bForceDownloadDialog if downloading to a local file system first is required and/or send the outout as attachment rather than inline.
  583. */
  584. public function download ($aFile, $sToken = false, $bForceDownloadDialog = 'auto')
  585. {
  586. $bRet = true;
  587. bx_alert($this->_aObject['object'], 'file_downloaded', $aFile['id'], bx_get_logged_profile_id(), array(
  588. 'profile_ip' => getVisitorIP(),
  589. 'file_info' => $aFile,
  590. 'return_value' => &$bRet
  591. ));
  592. return $bRet;
  593. }
  594. /**
  595. * Set file private or public.
  596. */
  597. public function setFilePrivate($iFileId, $isPrivate = true)
  598. {
  599. if (!$this->_oDb->modifyFilePrivate ($iFileId, $isPrivate)) {
  600. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  601. return false;
  602. }
  603. return true;
  604. }
  605. /**
  606. * Get file url.
  607. * @param $sRemoteId file remote id
  608. * @return file url or false on error
  609. */
  610. public function getFileUrlByRemoteId($sRemoteId)
  611. {
  612. $aFile = $this->_oDb->getFileByRemoteId($sRemoteId);
  613. if (!$aFile) {
  614. $this->setErrorCode(BX_DOL_STORAGE_ERR_FILE_NOT_FOUND);
  615. return false;
  616. }
  617. return $this->getFileUrlById($aFile['id']);
  618. }
  619. /**
  620. * Get file url.
  621. * @param $iFileId file id
  622. * @return file url or false on error
  623. */
  624. public function getFileUrlById($iFileId) { }
  625. /**
  626. * Get file info array by file id.
  627. * @param $iFileId file id
  628. * @return array
  629. */
  630. public function getFile($iFileId)
  631. {
  632. $a = $this->_oDb->getFileById($iFileId);
  633. if (!$a) return false;
  634. // update custom fields for previously uploaded files
  635. if (!defined('BX_DOL_STORAGE_CUSTOM_FIELDS_UPDATE_SKIP') && isset($this->_aParams['fields']) && is_array($this->_aParams['fields'])) {
  636. foreach ($this->_aParams['fields'] as $sField => $mixedMethod) {
  637. if ($a[$sField])
  638. continue;
  639. $sFileUrl = $this->getFileUrlById($iFileId);
  640. if (is_string($mixedMethod) && method_exists($this, $mixedMethod)) {
  641. $a[$sField] = $this->$mixedMethod($sFileUrl, $a['mime_type'], $a['ext'], $this);
  642. }
  643. elseif (is_array($mixedMethod) && isset($mixedMethod['module']) && isset($mixedMethod['method'])) {
  644. $mixedMethod['params'] = array($sFileUrl, $a['mime_type'], $a['ext'], $this);
  645. $a[$sField] = call_user_func_array('bx_srv', array($mixedMethod['module'], $mixedMethod['method'], $mixedMethod['params'], isset($mixedMethod['class']) ? $mixedMethod['class'] : 'Module'));
  646. }
  647. if ($a[$sField])
  648. $this->_oDb->modifyCustomField($iFileId, $sField, $a[$sField], false);
  649. }
  650. }
  651. return $a;
  652. }
  653. /**
  654. * Get ghost file info array by file id.
  655. * @param $iFileId file id
  656. * @return array
  657. */
  658. public function getGhost($iFileId)
  659. {
  660. return $this->_oDb->getGhost($iFileId);
  661. }
  662. /**
  663. * check if file is private or public
  664. * @param $iFileId file id
  665. * @return boolean
  666. */
  667. public function isFilePrivate($iFileId)
  668. {
  669. $aFile = $this->getFile ($iFileId);
  670. return $aFile['private'] ? true : false;
  671. }
  672. /**
  673. * Call this function after saving/associate just uploaded file id, so file is not orphaned/ghost.
  674. * Ghost files appear on download form automaticaly during next upload,
  675. * for example if file was uploaded but was not submitted for some reason.
  676. * This mechanism ensure that the file is not lost.
  677. * @param $mixedFileIds array of file ids or just one file id
  678. * @param $iProfileId profile id
  679. * @param return number of deleted ghost files
  680. */
  681. public function afterUploadCleanup($mixedFileIds, $iProfileId, $iContentId = false)
  682. {
  683. return $this->_oDb->deleteGhosts($mixedFileIds, $iProfileId, $iContentId);
  684. }
  685. /**
  686. * Get ghost/orphaned files for particular user.
  687. * @param $iProfileId profile id
  688. * @param $iContentId content id, or false to not consider content id at all
  689. * @param $isCheckAllAccountProfiles get all files associated with all account profiles
  690. * @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
  691. * @return array of arrays
  692. */
  693. public function getGhosts($iProfileId, $iContentId = false, $isCheckAllAccountProfiles = false, $isAdmin = false)
  694. {
  695. if ($isCheckAllAccountProfiles && ($oProfile = BxDolProfile::getInstance($iProfileId))) {
  696. $oAccount = $oProfile->getAccountObject();
  697. $aProfiles = $oAccount->getProfilesIds(false, false);
  698. return $this->_oDb->getGhosts($aProfiles, $iContentId, $isAdmin);
  699. }
  700. return $this->_oDb->getGhosts($iProfileId, $iContentId, $isAdmin);
  701. }
  702. /**
  703. * Reorder ghost/orphaned files for particular content/user.
  704. * @param $iProfileId profile id
  705. * @param $iContentId content id, or false to not consider content id at all
  706. * @param $aGhosts an ordered list of ghost/orphaned files' IDs.
  707. * @return boolean result of operation
  708. */
  709. public function reorderGhosts($iProfileId, $iContentId, $aGhosts)
  710. {
  711. $bResult = true;
  712. $iGhosts = count($aGhosts);
  713. for($i = 0; $i < $iGhosts; $i++)
  714. $bResult &= $this->_oDb->updateGhostOrder($iProfileId, $iContentId, (int)$aGhosts[$i], $i);
  715. return $bResult;
  716. }
  717. /**
  718. * Update ghosts' content id.
  719. * @param $mixedFileIds array of file ids or just one file id
  720. * @param $iProfileId profile id
  721. * @param $iContentId content id
  722. * @param $isAdmin if true, then don't check files ownership
  723. * @return true on success or false otherwise
  724. */
  725. public function updateGhostsContentId($mixedFileIds, $iProfileId, $iContentId, $isAdmin = false)
  726. {
  727. $aProfiles = array();
  728. if ($oProfile = BxDolProfile::getInstance($iProfileId)) {
  729. $oAccount = $oProfile->getAccountObject();
  730. $aProfiles = $oAccount->getProfilesIds(false);
  731. }
  732. return $this->_oDb->updateGhostsContentId($mixedFileIds, $iProfileId, $iContentId, $aProfiles, $isAdmin);
  733. }
  734. /**
  735. * Get files list for particular user.
  736. * @param $iProfileId profile id
  737. * @return array of arrays
  738. */
  739. public function getFiles($iProfileId)
  740. {
  741. return $this->_oDb->getFiles($iProfileId);
  742. }
  743. /**
  744. * Get all files in the storage
  745. */
  746. public function getFilesAll($iStart = 0, $iPerPage = 1000)
  747. {
  748. return $this->_oDb->getFilesAll($iStart, $iPerPage);
  749. }
  750. /**
  751. * Get readable representation of restrictions by file extentions.
  752. * @param $iProfileId profile id
  753. * @return string
  754. */
  755. public function getRestrictionsTextExtensions ($iProfileId)
  756. {
  757. switch ($this->_aObject['ext_mode']) {
  758. case 'allow-deny':
  759. if (!$this->_aObject['ext_allow'])
  760. return _t('_sys_storage_restriction_ext_all_denied');
  761. return _t('_sys_storage_restriction_ext_allowed', _t_format_extensions($this->_aObject['ext_allow']));
  762. case 'deny-allow':
  763. if (!$this->_aObject['ext_deny'])
  764. return _t('_sys_storage_restriction_ext_all_allowed');
  765. return _t('_sys_storage_restriction_ext_denied', _t_format_extensions($this->_aObject['ext_deny']));
  766. default:
  767. return _t('_sys_storage_restriction_ext_all_denied');
  768. }
  769. }
  770. /**
  771. * @return list of allowed extensions, if ext_mode = 'allow-deny', returns false otherwise.
  772. */
  773. public function getAllowedExtensions ()
  774. {
  775. if ('allow-deny' == $this->_aObject['ext_mode'])
  776. return _t_format_extensions($this->_aObject['ext_allow']);
  777. return null;
  778. }
  779. /**
  780. * Get readable representation of restrictions by file size.
  781. * @param $iProfileId profile id
  782. * @return string
  783. */
  784. public function getRestrictionsTextFileSize ($iProfileId)
  785. {
  786. return _t('_sys_storage_restriction_size', _t_format_size($this->getMaxUploadFileSize($iProfileId)));
  787. }
  788. /**
  789. * Get readable representation of all restrictions.
  790. * @param $iProfileId profile id
  791. * @return array of strings
  792. */
  793. public function getRestrictionsTextArray ($iProfileId)
  794. {
  795. $aTypes = array('Extensions', 'FileSize');
  796. $aRet = array();
  797. foreach ($aTypes as $sType) {
  798. $sFunc = 'getRestrictionsText' . $sType;
  799. $s = $this->$sFunc ($iProfileId);
  800. if ($s)
  801. $aRet[] = $s;
  802. }
  803. return $aRet;
  804. }
  805. /**
  806. * Reread available mimetypes from particular file.
  807. * It clears 'sys_storage_mime_types' table and fill it with data form provided file.
  808. * The format of file is: mime/type _space_or_tab_ extentions_sperated_by_space.
  809. * Usually the file is mime.types file from apache or /etc/mime.types from unix systems.
  810. * @param $sFile file to read mime types from
  811. * @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.
  812. */
  813. public function reloadMimeTypesFromFile ($sFile)
  814. {
  815. $sResult = '';
  816. /*
  817. * These mime types must be manually added/replaced if they aren't defined in the mime type file
  818. *
  819. text/x-php php
  820. text/x-coffeescript coffee
  821. text/x-common-lisp lsp lisp
  822. text/x-diff diff
  823. text/x-go go
  824. text/x-java java
  825. text/x-lua lua
  826. text/x-perl pl prl perl
  827. text/x-python py
  828. text/nginx nginx
  829. text/x-ini ini
  830. text/x-ruby rb
  831. text/x-sass sass
  832. text/x-sh bash sh
  833. text/x-swift swift
  834. text/x-vb vb
  835. text/vbscript vbs
  836. text/x-vue vue
  837. text/x-yaml yaml
  838. text/x-sql sql
  839. text/x-markdown md
  840. application/xquery xq xquery
  841. application/x-powershell ps1
  842. application/x-aspx aps
  843. application/x-jsp jsp
  844. */
  845. $aIconsFont = array (
  846. 'far file-pdf' => array('pdf'),
  847. 'far file-word' => array('doc', 'docx'),
  848. 'far file-excel' => array('xls', 'xlt', 'xlsx', 'sxc', 'stc', 'ods', 'ots', 'sdc', 'csv', 'dif', 'slk', 'pxl'),
  849. 'far file-powerpoint' => array('ppt', 'pptx', 'sxi', 'sti', 'odp', 'sdp', 'sdd'),
  850. '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'),
  851. 'far file-image' => 'image/',
  852. 'far file-video' => 'video/',
  853. 'far file-audio' => 'audio/',
  854. 'far file-alt' => 'text/',
  855. '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'),
  856. );
  857. $aIcons = array (
  858. 'mime-type-psd.svg' => array('psd'),
  859. 'mime-type-png.svg' => array('png'),
  860. 'mime-type-image.svg' => 'image/',
  861. 'mime-type-video.svg' => 'video/',
  862. 'mime-type-audio.svg' => 'audio/',
  863. 'mime-type-presentation.svg' => array('ppt', 'pptx', 'sxi', 'sti', 'odp', 'sdp', 'sdd'),
  864. 'mime-type-spreadsheet.svg' => array('xls', 'xlt', 'xlsx', 'sxc', 'stc', 'ods', 'ots', 'sdc', 'csv', 'dif', 'slk', 'pxl'),
  865. 'mime-type-document.svg' => array('doc', 'docx', 'odt', 'ott', 'sxw', 'stw', 'rtf', 'sdw', 'txt', 'pdb', 'psw', 'pdf'),
  866. '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'),
  867. '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'),
  868. );
  869. $f = fopen ($sFile, 'r');
  870. if (!$f)
  871. return false;
  872. $this->_oDb->clearAllMimeTypes();
  873. while (!feof($f) && ($s = fgets($f, 4096)) !== false) {
  874. $s = trim($s);
  875. if (!$s || '#' == $s[0])
  876. continue;
  877. $a = preg_split ("/[\s\\b]+/", $s, 2);
  878. if (!isset($a[0]) || !isset($a[1]))
  879. continue;
  880. $sMimeType = $a[0];
  881. $aExts = preg_split ("/[\s]+/", $a[1]);
  882. foreach ($aExts as $sExt) {
  883. $sIcon = $this->determineIcon($aIcons, $sExt, $sMimeType);
  884. $sIconFont = $this->determineIcon($aIconsFont, $sExt, $sMimeType);
  885. if (!$this->_oDb->addMimeType($sMimeType, $sExt, $sIcon, $sIconFont))
  886. $sResult .= _t('_Error') . ': ' . $sMimeType . "\t" . $sExt . "\n";
  887. }
  888. }
  889. fclose($f);
  890. if (!$sResult)
  891. $sResult = _t('_Success');
  892. return $sResult;
  893. }
  894. protected function determineIcon($aIcons, $sExt, $sMimeType)
  895. {
  896. foreach ($aIcons as $sIc => $if) {
  897. if (!(is_array($if) && in_array($sExt, $if)) && !(is_string($if) && 0 === strncmp($if, $sMimeType, strlen($if))))
  898. continue;
  899. return $sIc;
  900. }
  901. return false;
  902. }
  903. /**
  904. * Get file extension by file name.
  905. * @param $sFileName file name
  906. * @return file extention string
  907. */
  908. public function getFileExt ($sFileName)
  909. {
  910. return strtolower(pathinfo($sFileName, PATHINFO_EXTENSION));
  911. }
  912. /**
  913. * Get file title by file name, actually file title is file name without extension.
  914. * @param $sFileName file name
  915. * @return file title string
  916. */
  917. public function getFileTitle ($sFileName)
  918. {
  919. return pathinfo($sFileName, PATHINFO_FILENAME);
  920. }
  921. /**
  922. * Get file mime/type by file name.
  923. * @param $sFileName file name
  924. * @return file mime type string
  925. */
  926. public function getMimeTypeByFileName ($sFileName)
  927. {
  928. $sExt = $this->getFileExt($sFileName);
  929. $sMimeType = $this->_oDb->getMimeTypeByExt($sExt);
  930. if (!$sMimeType)
  931. $sMimeType = BX_DOL_STORAGE_DEFAULT_MIME_TYPE;
  932. return $sMimeType;
  933. }
  934. /**
  935. * Get file icon by file name.
  936. * File icon is just icon filename without patch or URL.
  937. * File icons must be located in images/icons directory in your template subfolder.
  938. * @param $sFileName file name
  939. * @return file icon string
  940. */
  941. public function getIconNameByFileName ($sFileName)
  942. {
  943. $sExt = $this->getFileExt($sFileName);
  944. $sIcon = $this->_oDb->getIconByExt($sExt);
  945. if (!$sIcon)
  946. $sIcon = BX_DOL_STORAGE_DEFAULT_ICON;
  947. return $sIcon;
  948. }
  949. /**
  950. * Get file font icon by file name.
  951. * Actually just a class name of icon is returnted.
  952. * @param $sFileName file name
  953. * @return file icon string
  954. */
  955. public function getFontIconNameByFileName ($sFileName)
  956. {
  957. $sExt = $this->getFileExt($sFileName);
  958. $sIcon = $this->_oDb->getIconFontByExt($sExt);
  959. if (!$sIcon)
  960. $sIcon = BX_DOL_STORAGE_DEFAULT_ICON_FONT;
  961. return $sIcon;
  962. }
  963. // ------------ internal functions - events
  964. protected function onBeforeFileAdd ($aFileInfo)
  965. {
  966. if ($aFileInfo['size'] > $this->getMaxUploadFileSize($aFileInfo['profile_id'])) {
  967. $this->setErrorCode(BX_DOL_STORAGE_ERR_FILE_TOO_BIG);
  968. return false;
  969. }
  970. // TODO: check site quota - BX_DOL_STORAGE_ERR_SITE_QUOTA_EXCEEDED
  971. $aObjectQuota = $this->_oDb->getStorageObjectQuota();
  972. if (
  973. ($aObjectQuota['quota_size'] && ($aObjectQuota['current_size'] + $aFileInfo['size'] > $aObjectQuota['quota_size']))
  974. ||
  975. ($aObjectQuota['quota_number'] && ($aObjectQuota['current_number'] + 1 > $aObjectQuota['quota_number']))
  976. ) {
  977. $this->setErrorCode(BX_DOL_STORAGE_ERR_OBJECT_QUOTA_EXCEEDED);
  978. return false;
  979. }
  980. $aUserQuota = $this->_oDb->getUserQuota($aFileInfo['profile_id']);
  981. if (
  982. ($aUserQuota['quota_size'] && ($aUserQuota['current_size'] + $aFileInfo['size'] > $aUserQuota['quota_size']))
  983. ||
  984. ($aUserQuota['quota_number'] && ($aUserQuota['current_number'] + 1 > $aUserQuota['quota_number']))
  985. ) {
  986. $this->setErrorCode(BX_DOL_STORAGE_ERR_USER_QUOTA_EXCEEDED);
  987. return false;
  988. }
  989. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  990. $bRet = true;
  991. bx_alert($this->_aObject['object'], 'before_file_add', 0, $aFileInfo['profile_id'], array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  992. return $bRet;
  993. }
  994. protected function onFileAdded ($aFileInfo)
  995. {
  996. // TODO: update site quota - BX_DOL_STORAGE_ERR_SITE_QUOTA_EXCEEDED
  997. if (!$this->_oDb->updateStorageObjectQuota($aFileInfo['size'], 1)) {
  998. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  999. return false;
  1000. }
  1001. if (!$this->_oDb->updateUserQuota($aFileInfo['profile_id'], $aFileInfo['size'], 1)) {
  1002. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  1003. return false;
  1004. }
  1005. if (!$this->insertGhost ($aFileInfo['id'], $aFileInfo['profile_id'], $aFileInfo['content_id'])) {
  1006. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  1007. return false;
  1008. }
  1009. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  1010. $bRet = true;
  1011. bx_alert($this->_aObject['object'], 'file_added', $aFileInfo['id'], $aFileInfo['profile_id'], array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  1012. return $bRet;
  1013. }
  1014. function insertGhost($iFileId, $iProfileId, $iContentId = 0)
  1015. {
  1016. return $this->_oDb->insertGhosts ($iFileId, $iProfileId, $iContentId);
  1017. }
  1018. function onBeforeFileDelete ($aFileInfo, $iProfileId)
  1019. {
  1020. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  1021. $bRet = true;
  1022. bx_alert($this->_aObject['object'], 'before_file_delete', $aFileInfo['id'], $iProfileId, array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  1023. return $bRet;
  1024. }
  1025. function onFileDeleted ($aFileInfo, $iProfileId, $aGhost = false)
  1026. {
  1027. // TODO: update site quota
  1028. if (!$this->_oDb->updateStorageObjectQuota(-$aFileInfo['size'], -1)) {
  1029. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  1030. return false;
  1031. }
  1032. if (!$this->_oDb->updateUserQuota($aFileInfo['profile_id'], -$aFileInfo['size'], -1)) {
  1033. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  1034. return false;
  1035. }
  1036. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  1037. $bRet = true;
  1038. bx_alert($this->_aObject['object'], 'file_deleted', $aFileInfo['id'], $iProfileId, array('file_info' => $aFileInfo, 'ghost' => $aGhost, 'return_value' => &$bRet));
  1039. return $bRet;
  1040. }
  1041. // ------------ internal functions
  1042. protected function setErrorCode($i)
  1043. {
  1044. return ($this->_iErrorCode = $i);
  1045. }
  1046. protected function genRandName($isCheckForUniq = true)
  1047. {
  1048. $sRandName = strtolower(genRndPwd(32, false));
  1049. if ($isCheckForUniq) {
  1050. $iTries = 10;
  1051. do {
  1052. $aFile = $this->_oDb->getFileByRemoteId($sRandName);
  1053. $bExist = is_array($aFile) && $aFile;
  1054. } while (--$iTries && $bExist);
  1055. }
  1056. return $sRandName;
  1057. }
  1058. protected function genPath($s, $iLevels)
  1059. {
  1060. $sRet = '';
  1061. $i = 1;
  1062. while ($iLevels-- > 0)
  1063. $sRet .= substr($s, 0, $i++) . '/';
  1064. return $sRet;
  1065. }
  1066. protected function genRemoteNamePath ($sPath, $sLocalId, $sExt)
  1067. {
  1068. return $sPath . $sLocalId;
  1069. }
  1070. protected function isValidExt ($sExt)
  1071. {
  1072. switch ($this->_aObject['ext_mode']) {
  1073. case 'allow-deny':
  1074. if ($this->isAllowedExt($sExt))
  1075. return true;
  1076. return false;
  1077. case 'deny-allow':
  1078. if ($this->isDeniedExt($sExt))
  1079. return false;
  1080. return true;
  1081. default:
  1082. return false;
  1083. }
  1084. }
  1085. protected function isAllowedExt ($sExt)
  1086. {
  1087. return $this->isAllowedDeniedExt($sExt, 'ext_allow');
  1088. }
  1089. protected function isDeniedExt ($sExt)
  1090. {
  1091. return $this->isAllowedDeniedExt($sExt, 'ext_deny');
  1092. }
  1093. protected function isAllowedDeniedExt ($sExt, $sExtMode)
  1094. {
  1095. if ('' == $this->_aObject[$sExtMode])
  1096. return false;
  1097. if (!is_array($this->_aObject[$sExtMode]))
  1098. $this->_aObject[$sExtMode] = explode(',', $this->_aObject[$sExtMode]);
  1099. return in_array ($sExt, $this->_aObject[$sExtMode]);
  1100. }
  1101. public function queueFiles($aFiles)
  1102. {
  1103. if (!$aFiles)
  1104. return 0;
  1105. $a = array();
  1106. foreach ($aFiles as $aFile)
  1107. $a[] = $aFile['id'];
  1108. return $this->queueFilesForDeletion($a);
  1109. }
  1110. protected function getFileDuration($sFilePath, $sMimeType, $sExt, $oStorage)
  1111. {
  1112. if (strncmp('video/', $sMimeType, 6) === 0)
  1113. return (int)BxDolTranscoderVideo::getDuration($sFilePath);
  1114. return 0;
  1115. }
  1116. protected function getFileDimensions($sFilePath, $sMimeType, $sExt, $oStorage)
  1117. {
  1118. if (strncmp('image/', $sMimeType, 6) === 0 && $o = BxDolTranscoderImage::getObjectAbstract()) {
  1119. $a = $o->getSize($sFilePath);
  1120. if ($a && isset($a['w']) && isset($a['h']))
  1121. return $a['w'] . 'x' . $a['h'];
  1122. }
  1123. if (strncmp('video/', $sMimeType, 6) === 0 && $o = BxDolTranscoderVideo::getObjectAbstract()) {
  1124. $a = $o->getSize($sFilePath);
  1125. if ($a && isset($a['w']) && isset($a['h']))
  1126. return $a['w'] . 'x' . $a['h'];
  1127. }
  1128. return '';
  1129. }
  1130. }
  1131. /**
  1132. * Handle file uploads via XMLHttpRequest
  1133. */
  1134. class BxDolStorageHelperXhr
  1135. {
  1136. protected $sName;
  1137. function __construct ($aParams)
  1138. {
  1139. $this->sName = $aParams['name'];
  1140. }
  1141. function getImmediateError()
  1142. {
  1143. return BX_DOL_STORAGE_ERR_OK;
  1144. }
  1145. function save($path)
  1146. {
  1147. $input = fopen("php://input", "r");
  1148. $temp = tmpfile();
  1149. $realSize = stream_copy_to_stream($input, $temp);
  1150. fclose($input);
  1151. if (false === $this->getSize() || $realSize != $this->getSize())
  1152. return false;
  1153. $target = fopen($path, "w");
  1154. fseek($temp, 0, SEEK_SET);
  1155. stream_copy_to_stream($temp, $target);
  1156. fclose($target);
  1157. fclose($temp);
  1158. return true;
  1159. }
  1160. function getName()
  1161. {
  1162. return $this->sName;
  1163. }
  1164. function getSize()
  1165. {
  1166. if (isset($_SERVER["CONTENT_LENGTH"]))
  1167. return (int)$_SERVER["CONTENT_LENGTH"];
  1168. else
  1169. return false;
  1170. }
  1171. }
  1172. /**
  1173. * Handle file uploads via regular form post (uses the $_FILES array)
  1174. */
  1175. class BxDolStorageHelperForm
  1176. {
  1177. protected $aFile;
  1178. function __construct ($aParams)
  1179. {
  1180. $this->aFile = $aParams['file'];
  1181. }
  1182. function getImmediateError()
  1183. {
  1184. if (!$this->aFile['size'] || !$this->aFile['tmp_name'])
  1185. return BX_DOL_STORAGE_ERR_NO_FILE;
  1186. if (UPLOAD_ERR_OK != $this->aFile['error'])
  1187. return (int)$this->aFile['error'];
  1188. return BX_DOL_STORAGE_ERR_OK;
  1189. }
  1190. function save($path)
  1191. {
  1192. if (!move_uploaded_file($this->aFile['tmp_name'], $path)){
  1193. return false;
  1194. }
  1195. return true;
  1196. }
  1197. function getName()
  1198. {
  1199. return $this->aFile['name'];
  1200. }
  1201. function getSize()
  1202. {
  1203. return $this->aFile['size'];
  1204. }
  1205. }
  1206. /**
  1207. * Store file from local file path
  1208. */
  1209. class BxDolStorageHelperPath
  1210. {
  1211. protected $sPath;
  1212. function __construct ($aParams)
  1213. {
  1214. $this->sPath = $aParams['path'];
  1215. }
  1216. function getImmediateError()
  1217. {
  1218. if (!$this->sPath || !file_exists($this->sPath))
  1219. return BX_DOL_STORAGE_ERR_NO_FILE;
  1220. return BX_DOL_STORAGE_ERR_OK;
  1221. }
  1222. function save($path)
  1223. {
  1224. if (!copy($this->sPath, $path)) {
  1225. return false;
  1226. }
  1227. return true;
  1228. }
  1229. function getName()
  1230. {
  1231. return pathinfo($this->sPath, PATHINFO_BASENAME);
  1232. }
  1233. function getSize()
  1234. {
  1235. return filesize($this->sPath);
  1236. }
  1237. }
  1238. /**
  1239. * Store file from URL
  1240. */
  1241. class BxDolStorageHelperUrl extends BxDolStorageHelperPath
  1242. {
  1243. protected $aMime2Ext = array (
  1244. 'image/bmp' => 'bmp',
  1245. 'image/gif' => 'gif',
  1246. 'image/jpeg' => 'jpg',
  1247. 'image/pjpeg' => 'jpg',
  1248. 'image/png' => 'png',
  1249. );
  1250. function __construct ($aParams)
  1251. {
  1252. $aParams['path'] = '';
  1253. $sExt = pathinfo(parse_url($aParams['url'], PHP_URL_PATH), PATHINFO_EXTENSION);
  1254. if ($sTmpFilename = tempnam(BX_DIRECTORY_PATH_TMP, '')) {
  1255. $s = '';
  1256. if (!$sExt) {
  1257. $s = @file_get_contents($aParams['url']);
  1258. $oFinfo = new finfo(FILEINFO_MIME_TYPE);
  1259. $sMime = $oFinfo->buffer($s);
  1260. if (isset($this->aMime2Ext[$sMime]))
  1261. $sExt = $this->aMime2Ext[$sMime];
  1262. }
  1263. $aParams['path'] = $sTmpFilename . '.' . $sExt;
  1264. @rename($sTmpFilename, $aParams['path']);
  1265. if ($s) {
  1266. file_put_contents($aParams['path'], $s);
  1267. }
  1268. else {
  1269. $hRead = fopen($aParams['url'], "rb");
  1270. $hWrite = fopen($aParams['path'], "wb");
  1271. if (false !== $hRead && false !== $hWrite) {
  1272. while (!feof($hRead)) {
  1273. $data = fread($hRead, 8192);
  1274. if (false === fwrite($hWrite, $data)) {
  1275. fclose($hWrite);
  1276. file_put_contents($aParams['path'], '');
  1277. break;
  1278. }
  1279. }
  1280. fclose($hRead);
  1281. fclose($hWrite);
  1282. }
  1283. }
  1284. }
  1285. parent::__construct($aParams);
  1286. }
  1287. function getImmediateError()
  1288. {
  1289. $iRet = parent::getImmediateError();
  1290. if (BX_DOL_STORAGE_ERR_OK != $iRet)
  1291. return $iRet;
  1292. return $this->getSize() > 0 ? BX_DOL_STORAGE_ERR_OK : BX_DOL_STORAGE_INVALID_FILE;
  1293. }
  1294. function __destruct()
  1295. {
  1296. @unlink($this->sPath);
  1297. }
  1298. }
  1299. /**
  1300. * Handle file uploads from the same or another storage object
  1301. */
  1302. class BxDolStorageHelperStorage
  1303. {
  1304. protected $iFileId;
  1305. protected $oStorage;
  1306. protected $aFile;
  1307. function __construct ($aParams)
  1308. {
  1309. $this->iFileId = $aParams['id'];
  1310. $this->oStorage = BxDolStorage::getObjectInstance($aParams['storage']);
  1311. $this->aFile = false;
  1312. if ($this->oStorage)
  1313. $this->aFile = $this->oStorage->getFile($this->iFileId);
  1314. }
  1315. function getImmediateError()
  1316. {
  1317. if (!$this->iFileId)
  1318. return BX_DOL_STORAGE_ERR_NO_FILE;
  1319. if (!$this->oStorage)
  1320. return BX_DOL_STORAGE_ERR_ENGINE_GET;
  1321. if (!$this->aFile)
  1322. return BX_DOL_STORAGE_ERR_NO_FILE;
  1323. return BX_DOL_STORAGE_ERR_OK;
  1324. }
  1325. function save($path)
  1326. {
  1327. $s = bx_file_get_contents ($this->oStorage->getFileUrlById($this->iFileId));
  1328. if (!$s)
  1329. return false;
  1330. return file_put_contents($path, $s) ? true : false;
  1331. }
  1332. function getName()
  1333. {
  1334. return $this->aFile['file_name'];
  1335. }
  1336. function getSize()
  1337. {
  1338. return $this->aFile['size'];
  1339. }
  1340. }
  1341. /** @} */