PageRenderTime 66ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/core/file_api.php

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