PageRenderTime 58ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/core/file_api.php

https://github.com/markkimsal/mantisbt
PHP | 979 lines | 713 code | 82 blank | 184 comment | 97 complexity | 34cd589b73b4006e36147430162577fd MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. # MantisBT - A PHP based bugtracking system
  3. # MantisBT is free software: you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation, either version 2 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # MantisBT is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with MantisBT. If not, see <http://www.gnu.org/licenses/>.
  15. /**
  16. * File API
  17. *
  18. * @package CoreAPI
  19. * @subpackage FileAPI
  20. * @copyright Copyright (C) 2000 - 2002 Kenzaburo Ito - kenito@300baud.org
  21. * @copyright Copyright (C) 2002 - 2010 MantisBT Team - mantisbt-dev@lists.sourceforge.net
  22. * @link http://www.mantisbt.org
  23. *
  24. * @uses access_api.php
  25. * @uses authentication_api.php
  26. * @uses bug_api.php
  27. * @uses config_api.php
  28. * @uses constant_inc.php
  29. * @uses database_api.php
  30. * @uses gpc_api.php
  31. * @uses helper_api.php
  32. * @uses history_api.php
  33. * @uses project_api.php
  34. * @uses utility_api.php
  35. */
  36. require_api( 'access_api.php' );
  37. require_api( 'authentication_api.php' );
  38. require_api( 'bug_api.php' );
  39. require_api( 'config_api.php' );
  40. require_api( 'constant_inc.php' );
  41. require_api( 'database_api.php' );
  42. require_api( 'gpc_api.php' );
  43. require_api( 'helper_api.php' );
  44. require_api( 'history_api.php' );
  45. require_api( 'project_api.php' );
  46. require_api( 'utility_api.php' );
  47. $g_cache_file_count = array();
  48. # ## File API ###
  49. # Gets the filename without the bug id prefix.
  50. function file_get_display_name( $p_filename ) {
  51. $t_array = explode( '-', $p_filename, 2 );
  52. # Check if it's a project document filename (doc-0000000-filename)
  53. # or a bug attachment filename (0000000-filename)
  54. # for newer filenames, the filename in schema is correct.
  55. # This is important to handle filenames with '-'s properly
  56. $t_doc_match = '/^' . config_get( 'document_files_prefix' ) . '-\d{7}-/';
  57. $t_name = preg_split( $t_doc_match, $p_filename );
  58. if( isset( $t_name[1] ) ) {
  59. return $t_name[1];
  60. } else {
  61. $t_bug_match = '/^\d{7}-/';
  62. $t_name = preg_split( $t_bug_match, $p_filename );
  63. if( isset( $t_name[1] ) ) {
  64. return $t_name[1];
  65. } else {
  66. return $p_filename;
  67. }
  68. }
  69. }
  70. # Check the number of attachments a bug has (if any)
  71. function file_bug_attachment_count( $p_bug_id ) {
  72. global $g_cache_file_count;
  73. $c_bug_id = db_prepare_int( $p_bug_id );
  74. $t_bug_file_table = db_get_table( 'bug_file' );
  75. # First check if we have a cache hit
  76. if( isset( $g_cache_file_count[$p_bug_id] ) ) {
  77. return $g_cache_file_count[$p_bug_id];
  78. }
  79. # If there is no cache hit, check if there is anything in
  80. # the cache. If the cache isn't empty and we didn't have
  81. # a hit, then there are not attachments for this bug.
  82. if( count( $g_cache_file_count ) > 0 ) {
  83. return 0;
  84. }
  85. # Otherwise build the cache and return the attachment count
  86. # for the given bug (if any).
  87. $query = "SELECT bug_id, COUNT(bug_id) AS attachments
  88. FROM $t_bug_file_table
  89. GROUP BY bug_id";
  90. $result = db_query_bound( $query );
  91. $t_file_count = 0;
  92. while( $row = db_fetch_array( $result ) ) {
  93. $g_cache_file_count[$row['bug_id']] = $row['attachments'];
  94. if( $p_bug_id == $row['bug_id'] ) {
  95. $t_file_count = $row['attachments'];
  96. }
  97. }
  98. # If no attachments are present, mark the cache to avoid
  99. # repeated queries for this.
  100. if( count( $g_cache_file_count ) == 0 ) {
  101. $g_cache_file_count['_no_files_'] = -1;
  102. }
  103. return $t_file_count;
  104. }
  105. # Check if a specific bug has attachments
  106. function file_bug_has_attachments( $p_bug_id ) {
  107. if( file_bug_attachment_count( $p_bug_id ) > 0 ) {
  108. return true;
  109. } else {
  110. return false;
  111. }
  112. }
  113. # Check if the current user can view attachments for the specified bug.
  114. function file_can_view_bug_attachments( $p_bug_id ) {
  115. $t_reported_by_me = bug_is_user_reporter( $p_bug_id, auth_get_current_user_id() );
  116. $t_can_view = access_has_bug_level( config_get( 'view_attachments_threshold' ), $p_bug_id );
  117. /** @todo Fix this to be readable */
  118. $t_can_view = $t_can_view || ( $t_reported_by_me && config_get( 'allow_view_own_attachments' ) );
  119. return $t_can_view;
  120. }
  121. # Check if the current user can download attachments for the specified bug.
  122. function file_can_download_bug_attachments( $p_bug_id ) {
  123. $t_reported_by_me = bug_is_user_reporter( $p_bug_id, auth_get_current_user_id() );
  124. $t_can_download = access_has_bug_level( config_get( 'download_attachments_threshold' ), $p_bug_id );
  125. /** @todo Fix this to be readable */
  126. $t_can_download = $t_can_download || ( $t_reported_by_me && config_get( 'allow_download_own_attachments' ) );
  127. return $t_can_download;
  128. }
  129. # Check if the current user can delete attachments from the specified bug.
  130. function file_can_delete_bug_attachments( $p_bug_id ) {
  131. if( bug_is_readonly( $p_bug_id ) ) {
  132. return false;
  133. }
  134. $t_reported_by_me = bug_is_user_reporter( $p_bug_id, auth_get_current_user_id() );
  135. $t_can_download = access_has_bug_level( config_get( 'delete_attachments_threshold' ), $p_bug_id );
  136. /** @todo Fix this to be readable */
  137. $t_can_download = $t_can_download || ( $t_reported_by_me && config_get( 'allow_delete_own_attachments' ) );
  138. return $t_can_download;
  139. }
  140. # Get icon corresponding to the specified filename
  141. # returns an associative array with "url" and "alt" text.
  142. function file_get_icon_url( $p_display_filename ) {
  143. $t_file_type_icons = config_get( 'file_type_icons' );
  144. $ext = utf8_strtolower( file_get_extension( $p_display_filename ) );
  145. if( is_blank( $ext ) || !isset( $t_file_type_icons[$ext] ) ) {
  146. $ext = '?';
  147. }
  148. $t_name = $t_file_type_icons[$ext];
  149. return array( 'url' => config_get( 'icon_path' ) . 'fileicons/' . $t_name, 'alt' => $ext );
  150. }
  151. /**
  152. * Combines a path and a file name making sure that the separator exists.
  153. *
  154. * @param string $p_path The path.
  155. * @param string $p_filename The file name.
  156. *
  157. * @return The combined full path.
  158. */
  159. function file_path_combine( $p_path, $p_filename ) {
  160. $t_path = $p_path;
  161. if ( utf8_substr( $t_path, -1 ) != '/' && utf8_substr( $t_path, -1 ) != '\\' ) {
  162. $t_path .= DIRECTORY_SEPARATOR;
  163. }
  164. $t_path .= $p_filename;
  165. return $t_path;
  166. }
  167. /**
  168. * Nomalizes the disk file path based on the following algorithm:
  169. * 1. If disk file exists, then return as is.
  170. * 2. If not, and a project path is available, then check with that, if exists return it.
  171. * 3. If not, then use default upload path, then check with that, if exists return it.
  172. * 4. If disk file doesn't include a path, then return expected path based on project path or default path.
  173. * 5. Otherwise return as is.
  174. *
  175. * @param string $p_diskfile The disk file (full path or just filename).
  176. * @param integer The project id - shouldn't be 0 (ALL_PROJECTS).
  177. * @return The normalized full path.
  178. */
  179. function file_normalize_attachment_path( $p_diskfile, $p_project_id ) {
  180. if ( file_exists( $p_diskfile ) ) {
  181. return $p_diskfile;
  182. }
  183. $t_basename = basename( $p_diskfile );
  184. $t_expected_file_path = '';
  185. if ( $p_project_id != ALL_PROJECTS ) {
  186. $t_path = project_get_field( $p_project_id, 'file_path' );
  187. if ( !is_blank( $t_path ) ) {
  188. $t_diskfile = file_path_combine( $t_path, $t_basename );
  189. if ( file_exists( $t_diskfile ) ) {
  190. return $t_diskfile;
  191. }
  192. // if we don't find the file, then this is the path we want to return.
  193. $t_expected_file_path = $t_diskfile;
  194. }
  195. }
  196. $t_path = config_get( 'absolute_path_default_upload_folder' );
  197. if ( !is_blank( $t_path ) ) {
  198. $t_diskfile = file_path_combine( $t_path, $t_basename );
  199. if ( file_exists( $t_diskfile ) ) {
  200. return $t_diskfile;
  201. }
  202. // if the expected path not set to project directory, then set it to default directory.
  203. if ( is_blank( $t_expected_file_path ) ) {
  204. $t_expected_file_path = $t_diskfile;
  205. }
  206. }
  207. // if diskfile doesn't include a path, then use the expected filename.
  208. if ( ( strstr( $p_diskfile, DIRECTORY_SEPARATOR ) === false ||
  209. strstr( $p_diskfile, '\\' ) === false ) &&
  210. !is_blank( $t_expected_file_path ) ) {
  211. return $t_expected_file_path;
  212. }
  213. // otherwise return as is.
  214. return $p_diskfile;
  215. }
  216. # --------------------
  217. # Gets an array of attachments that are visible to the currently logged in user.
  218. # Each element of the array contains the following:
  219. # display_name - The attachment display name (i.e. file name dot extension)
  220. # size - The attachment size in bytes.
  221. # date_added - The date where the attachment was added.
  222. # can_download - true: logged in user has access to download the attachment, false: otherwise.
  223. # diskfile - The name of the file on disk. Typically this is a hash without an extension.
  224. # download_url - The download URL for the attachment (only set if can_download is true).
  225. # exists - Applicable for DISK attachments. true: file exists, otherwise false.
  226. # can_delete - The logged in user can delete the attachments.
  227. # preview - true: the attachment should be previewable, otherwise false.
  228. # type - Can be "image", "text" or empty for other types.
  229. # alt - The alternate text to be associated with the icon.
  230. # icon - array with icon information, contains 'url' and 'alt' elements.
  231. function file_get_visible_attachments( $p_bug_id ) {
  232. $t_attachment_rows = bug_get_attachments( $p_bug_id );
  233. $t_visible_attachments = array();
  234. $t_attachments_count = count( $t_attachment_rows );
  235. if( $t_attachments_count === 0 ) {
  236. return $t_visible_attachments;
  237. }
  238. $t_attachments = array();
  239. $t_can_download = file_can_download_bug_attachments( $p_bug_id );
  240. $t_can_delete = file_can_delete_bug_attachments( $p_bug_id );
  241. $t_preview_text_ext = config_get( 'preview_text_extensions' );
  242. $t_preview_image_ext = config_get( 'preview_image_extensions' );
  243. $image_previewed = false;
  244. for( $i = 0;$i < $t_attachments_count;$i++ ) {
  245. $t_row = $t_attachment_rows[$i];
  246. $t_id = $t_row['id'];
  247. $t_filename = $t_row['filename'];
  248. $t_filesize = $t_row['filesize'];
  249. $t_diskfile = file_normalize_attachment_path( $t_row['diskfile'], bug_get_field( $p_bug_id, 'project_id' ) );
  250. $t_date_added = $t_row['date_added'];
  251. $t_attachment = array();
  252. $t_attachment['id'] = $t_id;
  253. $t_attachment['display_name'] = file_get_display_name( $t_filename );
  254. $t_attachment['size'] = $t_filesize;
  255. $t_attachment['date_added'] = $t_date_added;
  256. $t_attachment['can_download'] = $t_can_download;
  257. $t_attachment['diskfile'] = $t_diskfile;
  258. if( $t_can_download ) {
  259. $t_attachment['download_url'] = "file_download.php?file_id=$t_id&type=bug";
  260. }
  261. if( $image_previewed ) {
  262. $image_previewed = false;
  263. }
  264. $t_attachment['exists'] = config_get( 'file_upload_method' ) != DISK || file_exists( $t_diskfile );
  265. $t_attachment['icon'] = file_get_icon_url( $t_attachment['display_name'] );
  266. $t_attachment['can_delete'] = $t_can_delete;
  267. $t_attachment['preview'] = false;
  268. $t_attachment['type'] = '';
  269. $t_ext = strtolower( file_get_extension( $t_attachment['display_name'] ) );
  270. $t_attachment['alt'] = $t_ext;
  271. if ( $t_attachment['exists'] && $t_can_download && $t_filesize != 0 && $t_filesize <= config_get( 'preview_attachments_inline_max_size' ) ) {
  272. if ( in_array( $t_ext, $t_preview_text_ext, true ) ) {
  273. $t_attachment['preview'] = true;
  274. $t_attachment['type'] = 'text';
  275. } else if ( in_array( $t_ext, $t_preview_image_ext, true ) ) {
  276. $t_attachment['preview'] = true;
  277. $t_attachment['type'] = 'image';
  278. }
  279. }
  280. $t_attachments[] = $t_attachment;
  281. }
  282. return $t_attachments;
  283. }
  284. # delete all files that are associated with the given bug
  285. function file_delete_attachments( $p_bug_id ) {
  286. $c_bug_id = db_prepare_int( $p_bug_id );
  287. $t_bug_file_table = db_get_table( 'bug_file' );
  288. $t_method = config_get( 'file_upload_method' );
  289. # Delete files from disk
  290. $query = "SELECT diskfile, filename
  291. FROM $t_bug_file_table
  292. WHERE bug_id=" . db_param();
  293. $result = db_query_bound( $query, Array( $c_bug_id ) );
  294. $file_count = db_num_rows( $result );
  295. if( 0 == $file_count ) {
  296. return true;
  297. }
  298. if(( DISK == $t_method ) || ( FTP == $t_method ) ) {
  299. # there may be more than one file
  300. $ftp = 0;
  301. if( FTP == $t_method ) {
  302. $ftp = file_ftp_connect();
  303. }
  304. for( $i = 0;$i < $file_count;$i++ ) {
  305. $row = db_fetch_array( $result );
  306. $t_local_diskfile = file_normalize_attachment_path( $row['diskfile'], bug_get_field( $p_bug_id, 'project_id' ) );
  307. file_delete_local( $t_local_diskfile );
  308. if( FTP == $t_method ) {
  309. file_ftp_delete( $ftp, $row['diskfile'] );
  310. }
  311. }
  312. if( FTP == $t_method ) {
  313. file_ftp_disconnect( $ftp );
  314. }
  315. }
  316. # Delete the corresponding db records
  317. $query = "DELETE FROM $t_bug_file_table
  318. WHERE bug_id=" . db_param();
  319. $result = db_query_bound( $query, Array( $c_bug_id ) );
  320. # db_query errors on failure so:
  321. return true;
  322. }
  323. function file_delete_project_files( $p_project_id ) {
  324. $t_project_file_table = db_get_table( 'project_file' );
  325. $t_method = config_get( 'file_upload_method' );
  326. # Delete the file physically (if stored via DISK or FTP)
  327. if(( DISK == $t_method ) || ( FTP == $t_method ) ) {
  328. # Delete files from disk
  329. $query = "SELECT diskfile, filename
  330. FROM $t_project_file_table
  331. WHERE project_id=" . db_param();
  332. $result = db_query_bound( $query, array( (int) $p_project_id ) );
  333. $file_count = db_num_rows( $result );
  334. $ftp = 0;
  335. if( FTP == $t_method ) {
  336. $ftp = file_ftp_connect();
  337. }
  338. for( $i = 0;$i < $file_count;$i++ ) {
  339. $row = db_fetch_array( $result );
  340. $t_local_diskfile = file_normalize_attachment_path( $row['diskfile'], $p_project_id );
  341. file_delete_local( $t_local_diskfile );
  342. if( FTP == $t_method ) {
  343. file_ftp_delete( $ftp, $row['diskfile'] );
  344. }
  345. }
  346. if( FTP == $t_method ) {
  347. file_ftp_disconnect( $ftp );
  348. }
  349. }
  350. # Delete the corresponding db records
  351. $query = "DELETE FROM $t_project_file_table
  352. WHERE project_id=" . db_param();
  353. $result = db_query_bound( $query, Array( (int) $p_project_id ) );
  354. }
  355. # Delete all cached files that are older than configured number of days.
  356. function file_ftp_cache_cleanup() {
  357. }
  358. # Connect to ftp server using configured server address, user name, and password.
  359. function file_ftp_connect() {
  360. $conn_id = ftp_connect( config_get( 'file_upload_ftp_server' ) );
  361. $login_result = ftp_login( $conn_id, config_get( 'file_upload_ftp_user' ), config_get( 'file_upload_ftp_pass' ) );
  362. if(( !$conn_id ) || ( !$login_result ) ) {
  363. trigger_error( ERROR_FTP_CONNECT_ERROR, ERROR );
  364. }
  365. return $conn_id;
  366. }
  367. # Put a file to the ftp server.
  368. function file_ftp_put( $p_conn_id, $p_remote_filename, $p_local_filename ) {
  369. helper_begin_long_process();
  370. $upload = ftp_put( $p_conn_id, $p_remote_filename, $p_local_filename, FTP_BINARY );
  371. }
  372. # Get a file from the ftp server.
  373. function file_ftp_get( $p_conn_id, $p_local_filename, $p_remote_filename ) {
  374. helper_begin_long_process();
  375. $download = ftp_get( $p_conn_id, $p_local_filename, $p_remote_filename, FTP_BINARY );
  376. }
  377. # Delete a file from the ftp server
  378. function file_ftp_delete( $p_conn_id, $p_filename ) {
  379. @ftp_delete( $p_conn_id, $p_filename );
  380. }
  381. # Disconnect from the ftp server
  382. function file_ftp_disconnect( $p_conn_id ) {
  383. ftp_quit( $p_conn_id );
  384. }
  385. # Delete a local file even if it is read-only.
  386. function file_delete_local( $p_filename ) {
  387. if( file_exists( $p_filename ) ) {
  388. chmod( $p_filename, 0775 );
  389. unlink( $p_filename );
  390. }
  391. }
  392. # Return the specified field value
  393. function file_get_field( $p_file_id, $p_field_name, $p_table = 'bug' ) {
  394. $c_field_name = db_prepare_string( $p_field_name );
  395. $t_bug_file_table = db_get_table( $p_table . '_file' );
  396. # get info
  397. $query = "SELECT $c_field_name
  398. FROM $t_bug_file_table
  399. WHERE id=" . db_param();
  400. $result = db_query_bound( $query, Array( (int) $p_file_id ), 1 );
  401. return db_result( $result );
  402. }
  403. function file_delete( $p_file_id, $p_table = 'bug' ) {
  404. $t_upload_method = config_get( 'file_upload_method' );
  405. $c_file_id = db_prepare_int( $p_file_id );
  406. $t_filename = file_get_field( $p_file_id, 'filename', $p_table );
  407. $t_diskfile = file_get_field( $p_file_id, 'diskfile', $p_table );
  408. if ( $p_table == 'bug' ) {
  409. $t_bug_id = file_get_field( $p_file_id, 'bug_id', $p_table );
  410. $t_project_id = bug_get_field( $t_bug_id, 'project_id' );
  411. } else {
  412. $t_project_id = file_get_field( $p_file_id, 'project_id', $p_table );
  413. }
  414. if(( DISK == $t_upload_method ) || ( FTP == $t_upload_method ) ) {
  415. if( FTP == $t_upload_method ) {
  416. $ftp = file_ftp_connect();
  417. file_ftp_delete( $ftp, $t_diskfile );
  418. file_ftp_disconnect( $ftp );
  419. }
  420. $t_local_disk_file = file_normalize_attachment_path( $t_diskfile, $t_project_id );
  421. if ( file_exists( $t_local_disk_file ) ) {
  422. file_delete_local( $t_local_disk_file );
  423. }
  424. }
  425. if( 'bug' == $p_table ) {
  426. # log file deletion
  427. history_log_event_special( $t_bug_id, FILE_DELETED, file_get_display_name( $t_filename ) );
  428. }
  429. $t_file_table = db_get_table( $p_table . '_file' );
  430. $query = "DELETE FROM $t_file_table
  431. WHERE id=" . db_param();
  432. db_query_bound( $query, Array( $c_file_id ) );
  433. return true;
  434. }
  435. # File type check
  436. function file_type_check( $p_file_name ) {
  437. $t_allowed_files = config_get( 'allowed_files' );
  438. $t_disallowed_files = config_get( 'disallowed_files' );;
  439. # grab extension
  440. $t_extension = file_get_extension( $p_file_name );
  441. # check against disallowed files
  442. $t_disallowed_arr = explode( ',', $t_disallowed_files );
  443. foreach( $t_disallowed_arr as $t_val ) {
  444. if( 0 == strcasecmp( $t_val, $t_extension ) ) {
  445. return false;
  446. }
  447. }
  448. # if the allowed list is note populated then the file must be allowed
  449. if( is_blank( $t_allowed_files ) ) {
  450. return true;
  451. }
  452. # check against allowed files
  453. $t_allowed_arr = explode( ',', $t_allowed_files );
  454. foreach( $t_allowed_arr as $t_val ) {
  455. if( 0 == strcasecmp( $t_val, $t_extension ) ) {
  456. return true;
  457. }
  458. }
  459. return false;
  460. }
  461. # clean file name by removing sensitive characters and replacing them with underscores
  462. function file_clean_name( $p_filename ) {
  463. return preg_replace( '/[\/*?"<>|\\ :&]/', "_", $p_filename );
  464. }
  465. # Generate a string to use as the identifier for the file
  466. # It is not guaranteed to be unique and should be checked
  467. # The string returned should be 32 characters in length
  468. function file_generate_name( $p_seed ) {
  469. return md5( $p_seed . time() );
  470. }
  471. # Generate a UNIQUE string to use as the identifier for the file
  472. # The string returned should be 64 characters in length
  473. function file_generate_unique_name( $p_seed, $p_filepath ) {
  474. do {
  475. $t_string = file_generate_name( $p_seed );
  476. }
  477. while( !diskfile_is_name_unique( $t_string, $p_filepath ) );
  478. return $t_string;
  479. }
  480. # Return true if the diskfile name identifier is unique, false otherwise
  481. function diskfile_is_name_unique( $p_name, $p_filepath ) {
  482. $t_file_table = db_get_table( 'bug_file' );
  483. $c_name = $p_filepath . $p_name;
  484. $query = "SELECT COUNT(*)
  485. FROM $t_file_table
  486. WHERE diskfile=" . db_param();
  487. $result = db_query_bound( $query, Array( $c_name ) );
  488. $t_count = db_result( $result );
  489. if( $t_count > 0 ) {
  490. return false;
  491. } else {
  492. return true;
  493. }
  494. }
  495. # Return true if the file name identifier is unique, false otherwise
  496. function file_is_name_unique( $p_name, $p_bug_id ) {
  497. $t_file_table = db_get_table( 'bug_file' );
  498. $query = "SELECT COUNT(*)
  499. FROM $t_file_table
  500. WHERE filename=" . db_param() . " AND bug_id=" . db_param();
  501. $result = db_query_bound( $query, Array( $p_name, $p_bug_id ) );
  502. $t_count = db_result( $result );
  503. if( $t_count > 0 ) {
  504. return false;
  505. } else {
  506. return true;
  507. }
  508. }
  509. /**
  510. * Add a file to the system using the configured storage method
  511. *
  512. * @param integer $p_bug_id the bug id
  513. * @param array $p_file the uploaded file info, as retrieved from gpc_get_file()
  514. * @param string $p_table table ('bug' or 'doc')
  515. * @param string $p_title file title
  516. * @param string $p_desc file description
  517. * @param int $p_user_id user id
  518. * @param int $p_date_added date added
  519. * @param bool $p_skip_bug_update skip bug last modification update (useful when importing bug attachments)
  520. */
  521. function file_add( $p_bug_id, $p_file, $p_table = 'bug', $p_title = '', $p_desc = '', $p_user_id = null, $p_date_added = 0, $p_skip_bug_update = false ) {
  522. file_ensure_uploaded( $p_file );
  523. $t_file_name = $p_file['name'];
  524. $t_tmp_file = $p_file['tmp_name'];
  525. $c_date_added = $p_date_added <= 0 ? db_now() : db_prepare_int( $p_date_added );
  526. if( !file_type_check( $t_file_name ) ) {
  527. trigger_error( ERROR_FILE_NOT_ALLOWED, ERROR );
  528. }
  529. if( !file_is_name_unique( $t_file_name, $p_bug_id ) ) {
  530. trigger_error( ERROR_DUPLICATE_FILE, ERROR );
  531. }
  532. if( 'bug' == $p_table ) {
  533. $t_project_id = bug_get_field( $p_bug_id, 'project_id' );
  534. $t_bug_id = bug_format_id( $p_bug_id );
  535. } else {
  536. $t_project_id = helper_get_current_project();
  537. $t_bug_id = 0;
  538. }
  539. if( $p_user_id === null ) {
  540. $c_user_id = auth_get_current_user_id();
  541. } else {
  542. $c_user_id = (int)$p_user_id;
  543. }
  544. # prepare variables for insertion
  545. $c_bug_id = db_prepare_int( $p_bug_id );
  546. $c_project_id = db_prepare_int( $t_project_id );
  547. $c_file_type = db_prepare_string( $p_file['type'] );
  548. $c_title = db_prepare_string( $p_title );
  549. $c_desc = db_prepare_string( $p_desc );
  550. if( $t_project_id == ALL_PROJECTS ) {
  551. $t_file_path = config_get( 'absolute_path_default_upload_folder' );
  552. } else {
  553. $t_file_path = project_get_field( $t_project_id, 'file_path' );
  554. if( $t_file_path == '' ) {
  555. $t_file_path = config_get( 'absolute_path_default_upload_folder' );
  556. }
  557. }
  558. $c_file_path = db_prepare_string( $t_file_path );
  559. $c_new_file_name = db_prepare_string( $t_file_name );
  560. $t_file_hash = ( 'bug' == $p_table ) ? $t_bug_id : config_get( 'document_files_prefix' ) . '-' . $t_project_id;
  561. $t_unique_name = file_generate_unique_name( $t_file_hash . '-' . $t_file_name, $t_file_path );
  562. $t_disk_file_name = $t_file_path . $t_unique_name;
  563. $c_unique_name = db_prepare_string( $t_unique_name );
  564. $t_file_size = filesize( $t_tmp_file );
  565. if( 0 == $t_file_size ) {
  566. trigger_error( ERROR_FILE_NO_UPLOAD_FAILURE, ERROR );
  567. }
  568. $t_max_file_size = (int) min( ini_get_number( 'upload_max_filesize' ), ini_get_number( 'post_max_size' ), config_get( 'max_file_size' ) );
  569. if( $t_file_size > $t_max_file_size ) {
  570. trigger_error( ERROR_FILE_TOO_BIG, ERROR );
  571. }
  572. $c_file_size = db_prepare_int( $t_file_size );
  573. $t_method = config_get( 'file_upload_method' );
  574. switch( $t_method ) {
  575. case FTP:
  576. case DISK:
  577. file_ensure_valid_upload_path( $t_file_path );
  578. if( !file_exists( $t_disk_file_name ) ) {
  579. if( FTP == $t_method ) {
  580. $conn_id = file_ftp_connect();
  581. file_ftp_put( $conn_id, $t_disk_file_name, $t_tmp_file );
  582. file_ftp_disconnect( $conn_id );
  583. }
  584. if( !move_uploaded_file( $t_tmp_file, $t_disk_file_name ) ) {
  585. trigger_error( FILE_MOVE_FAILED, ERROR );
  586. }
  587. chmod( $t_disk_file_name, config_get( 'attachments_file_permissions' ) );
  588. $c_content = "''";
  589. } else {
  590. trigger_error( ERROR_FILE_DUPLICATE, ERROR );
  591. }
  592. break;
  593. case DATABASE:
  594. $c_content = db_prepare_binary_string( fread( fopen( $t_tmp_file, 'rb' ), $t_file_size ) );
  595. break;
  596. default:
  597. trigger_error( ERROR_GENERIC, ERROR );
  598. }
  599. $t_file_table = db_get_table( $p_table . '_file' );
  600. $c_id = ( 'bug' == $p_table ) ? $c_bug_id : $c_project_id;
  601. $query = "INSERT INTO $t_file_table
  602. (" . $p_table . "_id, title, description, diskfile, filename, folder, filesize, file_type, date_added, content, user_id)
  603. VALUES
  604. ($c_id, '$c_title', '$c_desc', '$c_unique_name', '$c_new_file_name', '$c_file_path', $c_file_size, '$c_file_type', '" . $c_date_added . "', $c_content, $c_user_id)";
  605. db_query( $query );
  606. if( 'bug' == $p_table ) {
  607. # updated the last_updated date
  608. if ( !$p_skip_bug_update ) {
  609. $result = bug_update_date( $p_bug_id );
  610. }
  611. # log new bug
  612. history_log_event_special( $p_bug_id, FILE_ADDED, $t_file_name );
  613. }
  614. }
  615. # --------------------
  616. # Return true if file uploading is enabled (in our config and PHP's),
  617. # false otherwise
  618. function file_is_uploading_enabled() {
  619. if( ini_get_bool( 'file_uploads' ) && ( ON == config_get( 'allow_file_upload' ) ) ) {
  620. return true;
  621. } else {
  622. return false;
  623. }
  624. }
  625. # Check if the user can upload files for this project
  626. # return true if they can, false otherwise
  627. # the project defaults to the current project and the user to the current user
  628. function file_allow_project_upload( $p_project_id = null, $p_user_id = null ) {
  629. if( null === $p_project_id ) {
  630. $p_project_id = helper_get_current_project();
  631. }
  632. if( null === $p_user_id ) {
  633. $p_user_id = auth_get_current_user_id();
  634. }
  635. return( file_is_uploading_enabled() && ( access_has_project_level( config_get( 'upload_project_file_threshold' ), $p_project_id, $p_user_id ) ) );
  636. }
  637. # --------------------
  638. # Check if the user can upload files for this bug
  639. # return true if they can, false otherwise
  640. # the user defaults to the current user
  641. #
  642. # if the bug null (the default) we answer whether the user can
  643. # upload a file to a new bug in the current project
  644. function file_allow_bug_upload( $p_bug_id = null, $p_user_id = null ) {
  645. if( null === $p_user_id ) {
  646. $p_user_id = auth_get_current_user_id();
  647. }
  648. # If uploads are disbled just return false
  649. if( !file_is_uploading_enabled() ) {
  650. return false;
  651. }
  652. if( null === $p_bug_id ) {
  653. # new bug
  654. $t_project_id = helper_get_current_project();
  655. # the user must be the reporter if they're reporting a new bug
  656. $t_reporter = true;
  657. } else {
  658. # existing bug
  659. $t_project_id = bug_get_field( $p_bug_id, 'project_id' );
  660. # check if the user is the reporter of the bug
  661. $t_reporter = bug_is_user_reporter( $p_bug_id, $p_user_id );
  662. }
  663. # *** If we ever wanted to have a per-project setting enabling file
  664. # uploads, we'd want to check it here before exempting the reporter
  665. if( $t_reporter && ( ON == config_get( 'allow_reporter_upload' ) ) ) {
  666. return true;
  667. }
  668. # Check the access level against the config setting
  669. return access_has_project_level( config_get( 'upload_bug_file_threshold' ), $t_project_id, $p_user_id );
  670. }
  671. # --------------------
  672. # checks whether the specified upload path exists and is writable
  673. function file_ensure_valid_upload_path( $p_upload_path ) {
  674. if( !file_exists( $p_upload_path ) || !is_dir( $p_upload_path ) || !is_writable( $p_upload_path ) || !is_readable( $p_upload_path ) ) {
  675. trigger_error( ERROR_FILE_INVALID_UPLOAD_PATH, ERROR );
  676. }
  677. }
  678. /**
  679. * Ensure a file was uploaded
  680. *
  681. * This function perform various checks for determining if the upload
  682. * was successful
  683. *
  684. * @param array $p_file the uploaded file info, as retrieved from gpc_get_file()
  685. */
  686. function file_ensure_uploaded( $p_file ) {
  687. switch( $p_file['error'] ) {
  688. case UPLOAD_ERR_INI_SIZE:
  689. case UPLOAD_ERR_FORM_SIZE:
  690. trigger_error( ERROR_FILE_TOO_BIG, ERROR );
  691. break;
  692. case UPLOAD_ERR_PARTIAL:
  693. case UPLOAD_ERR_NO_FILE:
  694. trigger_error( ERROR_FILE_NO_UPLOAD_FAILURE, ERROR );
  695. break;
  696. default:
  697. break;
  698. }
  699. if(( '' == $p_file['tmp_name'] ) || ( '' == $p_file['name'] ) ) {
  700. trigger_error( ERROR_FILE_NO_UPLOAD_FAILURE, ERROR );
  701. }
  702. if( !is_readable( $p_file['tmp_name'] ) ) {
  703. trigger_error( ERROR_UPLOAD_FAILURE, ERROR );
  704. }
  705. }
  706. # Get extension given the filename or its full path.
  707. function file_get_extension( $p_filename ) {
  708. $t_extension = '';
  709. $t_basename = $p_filename;
  710. if( utf8_strpos( $t_basename, '/' ) !== false ) {
  711. // Note that we can't use end(explode(...)) on a single line because
  712. // end() expects a reference to a variable and thus we first need to
  713. // copy the result of explode() into a variable that end() can modify.
  714. $t_components = explode( '/', $t_basename );
  715. $t_basename = end( $t_components );
  716. }
  717. if( utf8_strpos( $t_basename, '\\' ) !== false ) {
  718. $t_components = explode( '\\', $t_basename );
  719. $t_basename = end( $t_components );
  720. }
  721. if( utf8_strpos( $t_basename, '.' ) !== false ) {
  722. $t_components = explode( '.', $t_basename );
  723. $t_extension = end( $t_components );
  724. }
  725. return $t_extension;
  726. }
  727. /**
  728. * Get file content
  729. *
  730. * @param int $p_file_id file id
  731. * @param string $p_type file type (either 'bug' or 'doc')
  732. * @return array|bool array containing file type and content or false on failure to retrieve file
  733. */
  734. function file_get_content( $p_file_id, $p_type = 'bug' ) {
  735. # we handle the case where the file is attached to a bug
  736. # or attached to a project as a project doc.
  737. $query = '';
  738. switch ( $p_type ) {
  739. case 'bug':
  740. $t_bug_file_table = db_get_table( 'mantis_bug_file_table' );
  741. $query = "SELECT *
  742. FROM $t_bug_file_table
  743. WHERE id=" . db_param();
  744. break;
  745. case 'doc':
  746. $t_project_file_table = db_get_table( 'mantis_project_file_table' );
  747. $query = "SELECT *
  748. FROM $t_project_file_table
  749. WHERE id=" . db_param();
  750. break;
  751. default:
  752. return false;
  753. }
  754. $result = db_query_bound( $query, Array( $p_file_id ) );
  755. $row = db_fetch_array( $result );
  756. if ( $f_type == 'bug' ) {
  757. $t_project_id = bug_get_field( $row['bug_id'], 'project_id' );
  758. } else {
  759. $t_project_id = $row['bug_id'];
  760. }
  761. # If finfo is available (always true for PHP >= 5.3.0) we can use it to determine the MIME type of files
  762. $finfo_available = false;
  763. if ( class_exists( 'finfo' ) ) {
  764. $t_info_file = config_get( 'fileinfo_magic_db_file' );
  765. if ( is_blank( $t_info_file ) ) {
  766. $finfo = new finfo( FILEINFO_MIME );
  767. } else {
  768. $finfo = new finfo( FILEINFO_MIME, $t_info_file );
  769. }
  770. if ( $finfo ) {
  771. $finfo_available = true;
  772. }
  773. }
  774. $t_content_type = $row['file_type'];
  775. switch ( config_get( 'file_upload_method' ) ) {
  776. case DISK:
  777. $t_local_disk_file = file_normalize_attachment_path( $row['diskfile'], $t_project_id );
  778. if ( file_exists( $t_local_disk_file ) ) {
  779. if ( $finfo_available ) {
  780. $t_file_info_type = $finfo->file( $t_local_disk_file );
  781. if ( $t_file_info_type !== false ) {
  782. $t_content_type = $t_file_info_type;
  783. }
  784. }
  785. return array( 'type' => $t_content_type, 'content' => file_get_contents( $t_local_disk_file ) );
  786. }
  787. break;
  788. case FTP:
  789. $t_local_disk_file = file_normalize_attachment_path( $row['diskfile'], $t_project_id );
  790. if ( !file_exists( $t_local_disk_file ) ) {
  791. $ftp = file_ftp_connect();
  792. file_ftp_get ( $ftp, $t_local_disk_file, $row['diskfile'] );
  793. file_ftp_disconnect( $ftp );
  794. }
  795. if ( $finfo_available ) {
  796. $t_file_info_type = $finfo->file( $t_local_disk_file );
  797. if ( $t_file_info_type !== false ) {
  798. $t_content_type = $t_file_info_type;
  799. }
  800. }
  801. return array( 'type' => $t_content_type, 'content' => file_get_contents( $t_local_disk_file ) );
  802. break;
  803. default:
  804. if ( $finfo_available ) {
  805. $t_file_info_type = $finfo->buffer( $row['content'] );
  806. if ( $t_file_info_type !== false ) {
  807. $t_content_type = $t_file_info_type;
  808. }
  809. }
  810. return array( 'type' => $t_content_type, 'content' => $row['content'] );
  811. break;
  812. }
  813. }