BxDolStorage.php 55 KB

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