BxDolStorage.php 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514
  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. // update custom fields for previously uploaded files
  624. if (!defined('BX_DOL_STORAGE_CUSTOM_FIELDS_UPDATE_SKIP') && isset($this->_aParams['fields']) && is_array($this->_aParams['fields'])) {
  625. foreach ($this->_aParams['fields'] as $sField => $mixedMethod) {
  626. if ($a[$sField])
  627. continue;
  628. $sFileUrl = $this->getFileUrlById($iFileId);
  629. if (is_string($mixedMethod) && method_exists($this, $mixedMethod)) {
  630. $a[$sField] = $this->$mixedMethod($sFileUrl, $a['mime_type'], $a['ext'], $this);
  631. }
  632. elseif (is_array($mixedMethod) && isset($mixedMethod['module']) && isset($mixedMethod['method'])) {
  633. $mixedMethod['params'] = array($sFileUrl, $a['mime_type'], $a['ext'], $this);
  634. $a[$sField] = call_user_func_array('bx_srv', array($mixedMethod['module'], $mixedMethod['method'], $mixedMethod['params'], isset($mixedMethod['class']) ? $mixedMethod['class'] : 'Module'));
  635. }
  636. if ($a[$sField])
  637. $this->_oDb->modifyCustomField($iFileId, $sField, $a[$sField], false);
  638. }
  639. }
  640. return $a;
  641. }
  642. /**
  643. * Get ghost file info array by file id.
  644. * @param $iFileId file id
  645. * @return array
  646. */
  647. public function getGhost($iFileId)
  648. {
  649. return $this->_oDb->getGhost($iFileId);
  650. }
  651. /**
  652. * check if file is private or public
  653. * @param $iFileId file id
  654. * @return boolean
  655. */
  656. public function isFilePrivate($iFileId)
  657. {
  658. $aFile = $this->getFile ($iFileId);
  659. return $aFile['private'] ? true : false;
  660. }
  661. /**
  662. * Call this function after saving/associate just uploaded file id, so file is not orphaned/ghost.
  663. * Ghost files appear on download form automaticaly during next upload,
  664. * for example if file was uploaded but was not submitted for some reason.
  665. * This mechanism ensure that the file is not lost.
  666. * @param $mixedFileIds array of file ids or just one file id
  667. * @param $iProfileId profile id
  668. * @param return number of deleted ghost files
  669. */
  670. public function afterUploadCleanup($mixedFileIds, $iProfileId, $iContentId = false)
  671. {
  672. return $this->_oDb->deleteGhosts($mixedFileIds, $iProfileId, $iContentId);
  673. }
  674. /**
  675. * Get ghost/orphaned files for particular user.
  676. * @param $iProfileId profile id
  677. * @param $iContentId content id, or false to not consider content id at all
  678. * @param $isCheckAllAccountProfiles get all files associated with all account profiles
  679. * @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
  680. * @return array of arrays
  681. */
  682. public function getGhosts($iProfileId, $iContentId = false, $isCheckAllAccountProfiles = false, $isAdmin = false)
  683. {
  684. if ($isCheckAllAccountProfiles && ($oProfile = BxDolProfile::getInstance($iProfileId))) {
  685. $oAccount = $oProfile->getAccountObject();
  686. $aProfiles = $oAccount->getProfilesIds(false, false);
  687. return $this->_oDb->getGhosts($aProfiles, $iContentId, $isAdmin);
  688. }
  689. return $this->_oDb->getGhosts($iProfileId, $iContentId, $isAdmin);
  690. }
  691. /**
  692. * Update ghosts' content id.
  693. * @param $mixedFileIds array of file ids or just one file id
  694. * @param $iProfileId profile id
  695. * @param $iContentId content id
  696. * @param $isAdmin if true, then don't check files ownership
  697. * @return true on success or false otherwise
  698. */
  699. public function updateGhostsContentId($mixedFileIds, $iProfileId, $iContentId, $isAdmin = false)
  700. {
  701. $aProfiles = array();
  702. if ($oProfile = BxDolProfile::getInstance($iProfileId)) {
  703. $oAccount = $oProfile->getAccountObject();
  704. $aProfiles = $oAccount->getProfilesIds(false);
  705. }
  706. return $this->_oDb->updateGhostsContentId($mixedFileIds, $iProfileId, $iContentId, $aProfiles, $isAdmin);
  707. }
  708. /**
  709. * Get files list for particular user.
  710. * @param $iProfileId profile id
  711. * @return array of arrays
  712. */
  713. public function getFiles($iProfileId)
  714. {
  715. return $this->_oDb->getFiles($iProfileId);
  716. }
  717. /**
  718. * Get all files in the storage
  719. */
  720. public function getFilesAll($iStart = 0, $iPerPage = 1000)
  721. {
  722. return $this->_oDb->getFilesAll($iStart, $iPerPage);
  723. }
  724. /**
  725. * Get readable representation of restrictions by file extentions.
  726. * @param $iProfileId profile id
  727. * @return string
  728. */
  729. public function getRestrictionsTextExtensions ($iProfileId)
  730. {
  731. switch ($this->_aObject['ext_mode']) {
  732. case 'allow-deny':
  733. if (!$this->_aObject['ext_allow'])
  734. return _t('_sys_storage_restriction_ext_all_denied');
  735. return _t('_sys_storage_restriction_ext_allowed', _t_format_extensions($this->_aObject['ext_allow']));
  736. case 'deny-allow':
  737. if (!$this->_aObject['ext_deny'])
  738. return _t('_sys_storage_restriction_ext_all_allowed');
  739. return _t('_sys_storage_restriction_ext_denied', _t_format_extensions($this->_aObject['ext_deny']));
  740. default:
  741. return _t('_sys_storage_restriction_ext_all_denied');
  742. }
  743. }
  744. /**
  745. * @return list of allowed extensions, if ext_mode = 'allow-deny', returns false otherwise.
  746. */
  747. public function getAllowedExtensions ()
  748. {
  749. if ('allow-deny' == $this->_aObject['ext_mode'])
  750. return _t_format_extensions($this->_aObject['ext_allow']);
  751. return null;
  752. }
  753. /**
  754. * Get readable representation of restrictions by file size.
  755. * @param $iProfileId profile id
  756. * @return string
  757. */
  758. public function getRestrictionsTextFileSize ($iProfileId)
  759. {
  760. return _t('_sys_storage_restriction_size', _t_format_size($this->getMaxUploadFileSize($iProfileId)));
  761. }
  762. /**
  763. * Get readable representation of all restrictions.
  764. * @param $iProfileId profile id
  765. * @return array of strings
  766. */
  767. public function getRestrictionsTextArray ($iProfileId)
  768. {
  769. $aTypes = array('Extensions', 'FileSize');
  770. $aRet = array();
  771. foreach ($aTypes as $sType) {
  772. $sFunc = 'getRestrictionsText' . $sType;
  773. $s = $this->$sFunc ($iProfileId);
  774. if ($s)
  775. $aRet[] = $s;
  776. }
  777. return $aRet;
  778. }
  779. /**
  780. * Reread available mimetypes from particular file.
  781. * It clears 'sys_storage_mime_types' table and fill it with data form provided file.
  782. * The format of file is: mime/type _space_or_tab_ extentions_sperated_by_space.
  783. * Usually the file is mime.types file from apache or /etc/mime.types from unix systems.
  784. * @param $sFile file to read mime types from
  785. * @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.
  786. */
  787. public function reloadMimeTypesFromFile ($sFile)
  788. {
  789. $sResult = '';
  790. /*
  791. * These mime types must be manually added/replaced if they aren't defined in the mime type file
  792. *
  793. text/x-php php
  794. text/x-coffeescript coffee
  795. text/x-common-lisp lsp lisp
  796. text/x-diff diff
  797. text/x-go go
  798. text/x-java java
  799. text/x-lua lua
  800. text/x-perl pl prl perl
  801. text/x-python py
  802. text/nginx nginx
  803. text/x-ini ini
  804. text/x-ruby rb
  805. text/x-sass sass
  806. text/x-sh bash sh
  807. text/x-swift swift
  808. text/x-vb vb
  809. text/vbscript vbs
  810. text/x-vue vue
  811. text/x-yaml yaml
  812. text/x-sql sql
  813. text/x-markdown md
  814. application/xquery xq xquery
  815. application/x-powershell ps1
  816. application/x-aspx aps
  817. application/x-jsp jsp
  818. */
  819. $aIconsFont = array (
  820. 'far file-pdf' => array('pdf'),
  821. 'far file-word' => array('doc', 'docx'),
  822. 'far file-excel' => array('xls', 'xlt', 'xlsx', 'sxc', 'stc', 'ods', 'ots', 'sdc', 'csv', 'dif', 'slk', 'pxl'),
  823. 'far file-powerpoint' => array('ppt', 'pptx', 'sxi', 'sti', 'odp', 'sdp', 'sdd'),
  824. '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'),
  825. 'far file-image' => 'image/',
  826. 'far file-video' => 'video/',
  827. 'far file-audio' => 'audio/',
  828. 'far file-alt' => 'text/',
  829. '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'),
  830. );
  831. $aIcons = array (
  832. 'mime-type-psd.png' => array('psd'),
  833. 'mime-type-png.png' => array('png'),
  834. 'mime-type-image.png' => 'image/',
  835. 'mime-type-video.png' => 'video/',
  836. 'mime-type-audio.png' => 'audio/',
  837. 'mime-type-presentation.png' => array('ppt', 'pptx', 'sxi', 'sti', 'odp', 'sdp', 'sdd'),
  838. 'mime-type-spreadsheet.png' => array('xls', 'xlt', 'xlsx', 'sxc', 'stc', 'ods', 'ots', 'sdc', 'csv', 'dif', 'slk', 'pxl'),
  839. 'mime-type-document.png' => array('doc', 'docx', 'odt', 'ott', 'sxw', 'stw', 'rtf', 'sdw', 'txt', 'pdb', 'psw', 'pdf'),
  840. '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'),
  841. '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'),
  842. );
  843. $f = fopen ($sFile, 'r');
  844. if (!$f)
  845. return false;
  846. $this->_oDb->clearAllMimeTypes();
  847. while (!feof($f) && ($s = fgets($f, 4096)) !== false) {
  848. $s = trim($s);
  849. if (!$s || '#' == $s[0])
  850. continue;
  851. $a = preg_split ("/[\s\\b]+/", $s, 2);
  852. if (!isset($a[0]) || !isset($a[1]))
  853. continue;
  854. $sMimeType = $a[0];
  855. $aExts = preg_split ("/[\s]+/", $a[1]);
  856. foreach ($aExts as $sExt) {
  857. $sIcon = $this->determineIcon($aIcons, $sExt, $sMimeType);
  858. $sIconFont = $this->determineIcon($aIconsFont, $sExt, $sMimeType);
  859. if (!$this->_oDb->addMimeType($sMimeType, $sExt, $sIcon, $sIconFont))
  860. $sResult .= _t('_Error') . ': ' . $sMimeType . "\t" . $sExt . "\n";
  861. }
  862. }
  863. fclose($f);
  864. if (!$sResult)
  865. $sResult = _t('_Success');
  866. return $sResult;
  867. }
  868. protected function determineIcon($aIcons, $sExt, $sMimeType)
  869. {
  870. foreach ($aIcons as $sIc => $if) {
  871. if (!(is_array($if) && in_array($sExt, $if)) && !(is_string($if) && 0 === strncmp($if, $sMimeType, strlen($if))))
  872. continue;
  873. return $sIc;
  874. }
  875. return false;
  876. }
  877. /**
  878. * Get file extension by file name.
  879. * @param $sFileName file name
  880. * @return file extention string
  881. */
  882. public function getFileExt ($sFileName)
  883. {
  884. return strtolower(pathinfo($sFileName, PATHINFO_EXTENSION));
  885. }
  886. /**
  887. * Get file title by file name, actually file title is file name without extension.
  888. * @param $sFileName file name
  889. * @return file title string
  890. */
  891. public function getFileTitle ($sFileName)
  892. {
  893. return pathinfo($sFileName, PATHINFO_FILENAME);
  894. }
  895. /**
  896. * Get file mime/type by file name.
  897. * @param $sFileName file name
  898. * @return file mime type string
  899. */
  900. public function getMimeTypeByFileName ($sFileName)
  901. {
  902. $sExt = $this->getFileExt($sFileName);
  903. $sMimeType = $this->_oDb->getMimeTypeByExt($sExt);
  904. if (!$sMimeType)
  905. $sMimeType = BX_DOL_STORAGE_DEFAULT_MIME_TYPE;
  906. return $sMimeType;
  907. }
  908. /**
  909. * Get file icon by file name.
  910. * File icon is just icon filename without patch or URL.
  911. * File icons must be located in images/icons directory in your template subfolder.
  912. * @param $sFileName file name
  913. * @return file icon string
  914. */
  915. public function getIconNameByFileName ($sFileName)
  916. {
  917. $sExt = $this->getFileExt($sFileName);
  918. $sIcon = $this->_oDb->getIconByExt($sExt);
  919. if (!$sIcon)
  920. $sIcon = BX_DOL_STORAGE_DEFAULT_ICON;
  921. return $sIcon;
  922. }
  923. /**
  924. * Get file font icon by file name.
  925. * Actually just a class name of icon is returnted.
  926. * @param $sFileName file name
  927. * @return file icon string
  928. */
  929. public function getFontIconNameByFileName ($sFileName)
  930. {
  931. $sExt = $this->getFileExt($sFileName);
  932. $sIcon = $this->_oDb->getIconFontByExt($sExt);
  933. if (!$sIcon)
  934. $sIcon = BX_DOL_STORAGE_DEFAULT_ICON_FONT;
  935. return $sIcon;
  936. }
  937. // ------------ internal functions - events
  938. protected function onBeforeFileAdd ($aFileInfo)
  939. {
  940. if ($aFileInfo['size'] > $this->getMaxUploadFileSize($aFileInfo['profile_id'])) {
  941. $this->setErrorCode(BX_DOL_STORAGE_ERR_FILE_TOO_BIG);
  942. return false;
  943. }
  944. // TODO: check site quota - BX_DOL_STORAGE_ERR_SITE_QUOTA_EXCEEDED
  945. $aObjectQuota = $this->_oDb->getStorageObjectQuota();
  946. if (
  947. ($aObjectQuota['quota_size'] && ($aObjectQuota['current_size'] + $aFileInfo['size'] > $aObjectQuota['quota_size']))
  948. ||
  949. ($aObjectQuota['quota_number'] && ($aObjectQuota['current_number'] + 1 > $aObjectQuota['quota_number']))
  950. ) {
  951. $this->setErrorCode(BX_DOL_STORAGE_ERR_OBJECT_QUOTA_EXCEEDED);
  952. return false;
  953. }
  954. $aUserQuota = $this->_oDb->getUserQuota($aFileInfo['profile_id']);
  955. if (
  956. ($aUserQuota['quota_size'] && ($aUserQuota['current_size'] + $aFileInfo['size'] > $aUserQuota['quota_size']))
  957. ||
  958. ($aUserQuota['quota_number'] && ($aUserQuota['current_number'] + 1 > $aUserQuota['quota_number']))
  959. ) {
  960. $this->setErrorCode(BX_DOL_STORAGE_ERR_USER_QUOTA_EXCEEDED);
  961. return false;
  962. }
  963. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  964. $bRet = true;
  965. bx_alert($this->_aObject['object'], 'before_file_add', 0, $aFileInfo['profile_id'], array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  966. return $bRet;
  967. }
  968. protected function onFileAdded ($aFileInfo)
  969. {
  970. // TODO: update site quota - BX_DOL_STORAGE_ERR_SITE_QUOTA_EXCEEDED
  971. if (!$this->_oDb->updateStorageObjectQuota($aFileInfo['size'], 1)) {
  972. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  973. return false;
  974. }
  975. if (!$this->_oDb->updateUserQuota($aFileInfo['profile_id'], $aFileInfo['size'], 1)) {
  976. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  977. return false;
  978. }
  979. if (!$this->insertGhost ($aFileInfo['id'], $aFileInfo['profile_id'], $aFileInfo['content_id'])) {
  980. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  981. return false;
  982. }
  983. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  984. $bRet = true;
  985. bx_alert($this->_aObject['object'], 'file_added', $aFileInfo['id'], $aFileInfo['profile_id'], array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  986. return $bRet;
  987. }
  988. function insertGhost($iFileId, $iProfileId, $iContentId = 0)
  989. {
  990. return $this->_oDb->insertGhosts ($iFileId, $iProfileId, $iContentId);
  991. }
  992. function onBeforeFileDelete ($aFileInfo, $iProfileId)
  993. {
  994. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  995. $bRet = true;
  996. bx_alert($this->_aObject['object'], 'before_file_delete', $aFileInfo['id'], $iProfileId, array('file_info' => $aFileInfo, 'return_value' => &$bRet));
  997. return $bRet;
  998. }
  999. function onFileDeleted ($aFileInfo, $iProfileId, $aGhost = false)
  1000. {
  1001. // TODO: update site quota
  1002. if (!$this->_oDb->updateStorageObjectQuota(-$aFileInfo['size'], -1)) {
  1003. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  1004. return false;
  1005. }
  1006. if (!$this->_oDb->updateUserQuota($aFileInfo['profile_id'], -$aFileInfo['size'], -1)) {
  1007. $this->setErrorCode(BX_DOL_STORAGE_ERR_DB);
  1008. return false;
  1009. }
  1010. $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
  1011. $bRet = true;
  1012. bx_alert($this->_aObject['object'], 'file_deleted', $aFileInfo['id'], $iProfileId, array('file_info' => $aFileInfo, 'ghost' => $aGhost, 'return_value' => &$bRet));
  1013. return $bRet;
  1014. }
  1015. // ------------ internal functions
  1016. protected function setErrorCode($i)
  1017. {
  1018. return ($this->_iErrorCode = $i);
  1019. }
  1020. protected function genRandName($isCheckForUniq = true)
  1021. {
  1022. $sRandName = strtolower(genRndPwd(32, false));
  1023. if ($isCheckForUniq) {
  1024. $iTries = 10;
  1025. do {
  1026. $aFile = $this->_oDb->getFileByRemoteId($sRandName);
  1027. $bExist = is_array($aFile) && $aFile;
  1028. } while (--$iTries && $bExist);
  1029. }
  1030. return $sRandName;
  1031. }
  1032. protected function genPath($s, $iLevels)
  1033. {
  1034. $sRet = '';
  1035. $i = 1;
  1036. while ($iLevels-- > 0)
  1037. $sRet .= substr($s, 0, $i++) . '/';
  1038. return $sRet;
  1039. }
  1040. protected function genRemoteNamePath ($sPath, $sLocalId, $sExt)
  1041. {
  1042. return $sPath . $sLocalId;
  1043. }
  1044. protected function isValidExt ($sExt)
  1045. {
  1046. switch ($this->_aObject['ext_mode']) {
  1047. case 'allow-deny':
  1048. if ($this->isAllowedExt($sExt))
  1049. return true;
  1050. return false;
  1051. case 'deny-allow':
  1052. if ($this->isDeniedExt($sExt))
  1053. return false;
  1054. return true;
  1055. default:
  1056. return false;
  1057. }
  1058. }
  1059. protected function isAllowedExt ($sExt)
  1060. {
  1061. return $this->isAllowedDeniedExt($sExt, 'ext_allow');
  1062. }
  1063. protected function isDeniedExt ($sExt)
  1064. {
  1065. return $this->isAllowedDeniedExt($sExt, 'ext_deny');
  1066. }
  1067. protected function isAllowedDeniedExt ($sExt, $sExtMode)
  1068. {
  1069. if ('' == $this->_aObject[$sExtMode])
  1070. return false;
  1071. if (!is_array($this->_aObject[$sExtMode]))
  1072. $this->_aObject[$sExtMode] = explode(',', $this->_aObject[$sExtMode]);
  1073. return in_array ($sExt, $this->_aObject[$sExtMode]);
  1074. }
  1075. protected function queueFiles($aFiles)
  1076. {
  1077. if (!$aFiles)
  1078. return 0;
  1079. $a = array();
  1080. foreach ($aFiles as $aFile)
  1081. $a[] = $aFile['id'];
  1082. return $this->queueFilesForDeletion($a);
  1083. }
  1084. protected function getFileDuration($sFilePath, $sMimeType, $sExt, $oStorage)
  1085. {
  1086. if (strncmp('video/', $sMimeType, 6) === 0)
  1087. return (int)BxDolTranscoderVideo::getDuration($sFilePath);
  1088. return 0;
  1089. }
  1090. protected function getFileDimensions($sFilePath, $sMimeType, $sExt, $oStorage)
  1091. {
  1092. if (strncmp('video/', $sMimeType, 6) === 0 && $o = BxDolTranscoderVideo::getObjectVideoAbstract()) {
  1093. $a = $o->getVideoSize($sFilePath);
  1094. if ($a && isset($a['w']) && isset($a['h']))
  1095. return $a['w'] . 'x' . $a['h'];
  1096. }
  1097. return '';
  1098. }
  1099. }
  1100. /**
  1101. * Handle file uploads via XMLHttpRequest
  1102. */
  1103. class BxDolStorageHelperXhr
  1104. {
  1105. protected $sName;
  1106. function __construct ($aParams)
  1107. {
  1108. $this->sName = $aParams['name'];
  1109. }
  1110. function getImmediateError()
  1111. {
  1112. return BX_DOL_STORAGE_ERR_OK;
  1113. }
  1114. function save($path)
  1115. {
  1116. $input = fopen("php://input", "r");
  1117. $temp = tmpfile();
  1118. $realSize = stream_copy_to_stream($input, $temp);
  1119. fclose($input);
  1120. if (false === $this->getSize() || $realSize != $this->getSize())
  1121. return false;
  1122. $target = fopen($path, "w");
  1123. fseek($temp, 0, SEEK_SET);
  1124. stream_copy_to_stream($temp, $target);
  1125. fclose($target);
  1126. fclose($temp);
  1127. return true;
  1128. }
  1129. function getName()
  1130. {
  1131. return $this->sName;
  1132. }
  1133. function getSize()
  1134. {
  1135. if (isset($_SERVER["CONTENT_LENGTH"]))
  1136. return (int)$_SERVER["CONTENT_LENGTH"];
  1137. else
  1138. return false;
  1139. }
  1140. }
  1141. /**
  1142. * Handle file uploads via regular form post (uses the $_FILES array)
  1143. */
  1144. class BxDolStorageHelperForm
  1145. {
  1146. protected $aFile;
  1147. function __construct ($aParams)
  1148. {
  1149. $this->aFile = $aParams['file'];
  1150. }
  1151. function getImmediateError()
  1152. {
  1153. if (!$this->aFile['size'] || !$this->aFile['tmp_name'])
  1154. return BX_DOL_STORAGE_ERR_NO_FILE;
  1155. if (UPLOAD_ERR_OK != $this->aFile['error'])
  1156. return (int)$this->aFile['error'];
  1157. return BX_DOL_STORAGE_ERR_OK;
  1158. }
  1159. function save($path)
  1160. {
  1161. if (!move_uploaded_file($this->aFile['tmp_name'], $path)){
  1162. return false;
  1163. }
  1164. return true;
  1165. }
  1166. function getName()
  1167. {
  1168. return $this->aFile['name'];
  1169. }
  1170. function getSize()
  1171. {
  1172. return $this->aFile['size'];
  1173. }
  1174. }
  1175. /**
  1176. * Store file from local file path
  1177. */
  1178. class BxDolStorageHelperPath
  1179. {
  1180. protected $sPath;
  1181. function __construct ($aParams)
  1182. {
  1183. $this->sPath = $aParams['path'];
  1184. }
  1185. function getImmediateError()
  1186. {
  1187. if (!$this->sPath || !file_exists($this->sPath))
  1188. return BX_DOL_STORAGE_ERR_NO_FILE;
  1189. return BX_DOL_STORAGE_ERR_OK;
  1190. }
  1191. function save($path)
  1192. {
  1193. if (!copy($this->sPath, $path)) {
  1194. return false;
  1195. }
  1196. return true;
  1197. }
  1198. function getName()
  1199. {
  1200. return pathinfo($this->sPath, PATHINFO_BASENAME);
  1201. }
  1202. function getSize()
  1203. {
  1204. return filesize($this->sPath);
  1205. }
  1206. }
  1207. /**
  1208. * Store file from URL
  1209. */
  1210. class BxDolStorageHelperUrl extends BxDolStorageHelperPath
  1211. {
  1212. protected $aMime2Ext = array (
  1213. 'image/bmp' => 'bmp',
  1214. 'image/gif' => 'gif',
  1215. 'image/jpeg' => 'jpg',
  1216. 'image/pjpeg' => 'jpg',
  1217. 'image/png' => 'png',
  1218. );
  1219. function __construct ($aParams)
  1220. {
  1221. $aParams['path'] = '';
  1222. $sExt = pathinfo(parse_url($aParams['url'], PHP_URL_PATH), PATHINFO_EXTENSION);
  1223. if ($sTmpFilename = tempnam(BX_DIRECTORY_PATH_TMP, '')) {
  1224. $s = '';
  1225. if (!$sExt) {
  1226. $s = @file_get_contents($aParams['url']);
  1227. $oFinfo = new finfo(FILEINFO_MIME_TYPE);
  1228. $sMime = $oFinfo->buffer($s);
  1229. if (isset($this->aMime2Ext[$sMime]))
  1230. $sExt = $this->aMime2Ext[$sMime];
  1231. }
  1232. $aParams['path'] = $sTmpFilename . '.' . $sExt;
  1233. @rename($sTmpFilename, $aParams['path']);
  1234. if ($s) {
  1235. file_put_contents($aParams['path'], $s);
  1236. }
  1237. else {
  1238. $hRead = fopen($aParams['url'], "rb");
  1239. $hWrite = fopen($aParams['path'], "wb");
  1240. if (false !== $hRead && false !== $hWrite) {
  1241. while (!feof($hRead)) {
  1242. $data = fread($hRead, 8192);
  1243. if (false === fwrite($hWrite, $data)) {
  1244. fclose($hWrite);
  1245. file_put_contents($aParams['path'], '');
  1246. break;
  1247. }
  1248. }
  1249. fclose($hRead);
  1250. fclose($hWrite);
  1251. }
  1252. }
  1253. }
  1254. parent::__construct($aParams);
  1255. }
  1256. function getImmediateError()
  1257. {
  1258. $iRet = parent::getImmediateError();
  1259. if (BX_DOL_STORAGE_ERR_OK != $iRet)
  1260. return $iRet;
  1261. return $this->getSize() > 0 ? BX_DOL_STORAGE_ERR_OK : BX_DOL_STORAGE_INVALID_FILE;
  1262. }
  1263. function __destruct()
  1264. {
  1265. @unlink($this->sPath);
  1266. }
  1267. }
  1268. /**
  1269. * Handle file uploads from the same or another storage object
  1270. */
  1271. class BxDolStorageHelperStorage
  1272. {
  1273. protected $iFileId;
  1274. protected $oStorage;
  1275. protected $aFile;
  1276. function __construct ($aParams)
  1277. {
  1278. $this->iFileId = $aParams['id'];
  1279. $this->oStorage = BxDolStorage::getObjectInstance($aParams['storage']);
  1280. $this->aFile = false;
  1281. if ($this->oStorage)
  1282. $this->aFile = $this->oStorage->getFile($this->iFileId);
  1283. }
  1284. function getImmediateError()
  1285. {
  1286. if (!$this->iFileId)
  1287. return BX_DOL_STORAGE_ERR_NO_FILE;
  1288. if (!$this->oStorage)
  1289. return BX_DOL_STORAGE_ERR_ENGINE_GET;
  1290. if (!$this->aFile)
  1291. return BX_DOL_STORAGE_ERR_NO_FILE;
  1292. return BX_DOL_STORAGE_ERR_OK;
  1293. }
  1294. function save($path)
  1295. {
  1296. $s = bx_file_get_contents ($this->oStorage->getFileUrlById($this->iFileId));
  1297. if (!$s)
  1298. return false;
  1299. return file_put_contents($path, $s) ? true : false;
  1300. }
  1301. function getName()
  1302. {
  1303. return $this->aFile['file_name'];
  1304. }
  1305. function getSize()
  1306. {
  1307. return $this->aFile['size'];
  1308. }
  1309. }
  1310. /** @} */