file_import.module

Tracking 5.x-1.x branch
  1. drupal
    1. 5 contributions/file_import/file_import.module

Functions & methods

NameDescription
content_type
file_import_access_for_nodeChecks if has acces to import files in node
file_import_admin_settings
file_import_form
file_import_form_submit
file_import_helpImplementation of hook_help().
file_import_menuImplementation of hook_menu().
file_import_permImplementation of hook_perm().
theme_file_import_form
_file_import_settings_check_import_directoryChecks the existence of the directory specified in $form_element.
_file_import_settings_check_output_directory
_file_import_settings_only_with_uploads
_file_import_tab

File

View source
  1. <?php
  2. /**
  3. * Implementation of hook_help().
  4. */
  5. function file_import_help($section = '') {
  6. switch ($section) {
  7. case 'admin/content/file_import':
  8. $output = '<p>'. t("Import multiple files and save them as node attachments. The files will be moved from their default location."). '<br/>'
  9. . t("Searching for files in %dirpath.", array('%dirpath' => realpath(variable_get('file_import_path', '')))) .'</p>';
  10. return $output;
  11. case 'node/'.arg(1).'/file_import':
  12. $output = '<p>'. t("Import multiple files and save them as node attachments. The files will be moved from their default location."). '<br/>'
  13. . t("Searching for files in %dirpath.", array('%dirpath' => realpath(variable_get('file_import_path', '')))) .'</p>';
  14. return $output;
  15. case 'admin/settings/file_import':
  16. return t("Configure the files import module's settings.");
  17. default:
  18. return null;
  19. }
  20. }
  21. /**
  22. * Implementation of hook_perm().
  23. */
  24. function file_import_perm() {
  25. return array('import files');
  26. }
  27. /**
  28. * Implementation of hook_menu().
  29. */
  30. function file_import_menu($may_cache) {
  31. $items = array();
  32. if ($may_cache) {
  33. $items[] = array(
  34. 'path' => 'admin/content/file_import',
  35. 'title' => t('File import'),
  36. 'callback' => 'drupal_get_form',
  37. 'callback arguments' => array('file_import_form'),
  38. 'access' => user_access('import files'),
  39. 'type' => MENU_NORMAL_ITEM,
  40. 'description' => t('Import files from the filesystem.')
  41. );
  42. $items[] = array(
  43. 'path' => 'admin/settings/file_import',
  44. 'title' => t('File import'),
  45. 'callback' => 'drupal_get_form',
  46. 'callback arguments' => array('file_import_admin_settings'),
  47. 'access' => user_access('administer site configuration'),
  48. 'type' => MENU_NORMAL_ITEM,
  49. 'description' => t('Change settings for the File Import module.')
  50. );
  51. $items['file_import/js'] = array(
  52. 'page callback' => 'file_import_js',
  53. 'access arguments' => array('import files'),
  54. 'type' => MENU_CALLBACK,
  55. );
  56. }
  57. else
  58. {
  59. if ((variable_get('file_import_tab', FALSE))&&(arg(0) == 'node' && is_numeric(arg(1)))) {
  60. $node = node_load(arg(1));
  61. if ((file_import_access_for_node($node))&&($node->nid)) {
  62. $items[] = array(
  63. 'path' => 'node/'. arg(1). '/file_import',
  64. 'title' => t('File import'),
  65. 'callback' => 'drupal_get_form',
  66. 'callback arguments' => array('file_import_form'),
  67. 'access' => user_access('import files'),
  68. 'type' => MENU_LOCAL_TASK,
  69. 'weight' => 5);
  70. }
  71. }
  72. }
  73. return $items;
  74. }
  75. function file_import_form() {
  76. $form = array();
  77. $dirpath = variable_get('file_import_output_path', '');
  78. if (!file_check_directory($dirpath)) {
  79. drupal_set_message(t("You need to configure the output directory on the files import module's <a href='!admin-settings-file_import'>settings page</a>.", array('!admin-settings-file_import' => url('admin/settings/file_import'))), 'error');
  80. return $form;
  81. }
  82. $dirpath = variable_get('file_import_path', '');
  83. if (!file_check_directory($dirpath)) {
  84. drupal_set_message(t("You need to configure the import directory on the files import module's <a href='!admin-settings-file_import'>settings page</a>.", array('!admin-settings-file_import' => url('admin/settings/file_import'))), 'error');
  85. return $form;
  86. }
  87. $files = file_scan_directory($dirpath, '.*');
  88. ksort($files);
  89. if ($files) {
  90. // Put the image files into an array for the checkboxes and gather
  91. // additional information like dimensions and filesizes. Make sure that
  92. // there's no 0th element, because a checkbox with a zero value is seen as
  93. // unchecked and won't be imported.
  94. $fields = array('filesize', 'dimensions', 'title', 'node');
  95. foreach ($fields as $field) {
  96. $form['files'][$field][0] = NULL;
  97. }
  98. $filelist = array(0 => NULL);
  99. if ((arg(0)=='node')&&($nid = (arg(1)))){
  100. $only_with_uploads = variable_get("only_with_uploads",TRUE);
  101. if ((is_numeric($nid))&&($n = node_load($nid))&&((!$only_with_uploads) || ($only_with_uploads && variable_get('upload_'. $n->type, 1))))
  102. $default_nid = $n->nid;
  103. else
  104. $default_nid = '';
  105. }
  106. foreach ($files as $file) {
  107. $filelist[] = substr($file->filename, strlen($dirpath) + 1);
  108. $form['files']['filesize'][] = array(
  109. '#type' => 'item',
  110. '#value' => format_size(filesize($file->filename)),
  111. );
  112. $form['files']['title'][] = array(
  113. '#type' => 'textfield',
  114. '#size' => 20,
  115. '#default_value' => basename($file->name),
  116. );
  117. $form['files']['node'][] = array(
  118. '#type' => 'textfield',
  119. '#size' => 20,
  120. '#default_value' => $default_nid,
  121. );
  122. }
  123. // Remove our 0 elements.
  124. unset($filelist[0]);
  125. foreach ($fields as $field) {
  126. $form['files'][$field][0] = NULL;
  127. }
  128. // Put the titles into an array.
  129. $form['files']['title']['#tree'] = TRUE;
  130. $form['files']['node']['#tree'] = TRUE;
  131. // Store a copy of the list into a form value so we can compare it to what
  132. // they submit and not have to worry about files being added or removed from
  133. // the filesystem.
  134. $form['file_list'] = array(
  135. '#type' => 'value',
  136. '#value' => $filelist,
  137. );
  138. $form['import_file'] = array(
  139. '#type' => 'checkboxes',
  140. '#options' => $filelist,
  141. );
  142. // Getting list of node ID's to pot them into the combo box
  143. $types = node_get_types();
  144. $only_with_uploads = variable_get("only_with_uploads",TRUE);
  145. $allowed_types = array();
  146. foreach ($types as $type){
  147. if ((!$only_with_uploads) || ($only_with_uploads && variable_get('upload_'. $type, 1))) {
  148. $allowed_types[] = "'".$type->type."'";
  149. }
  150. }
  151. if ($allowed_types) {
  152. $result = db_query("SELECT nid, title FROM {node} where type in (".implode(',',$allowed_types).") ORDER BY created DESC");
  153. $nids = array();
  154. while ($node = db_fetch_array($result)) {
  155. $nids[$node['nid']] = $node['nid'].' - '.$node['title'];
  156. }
  157. }
  158. $form['node_select'] = array(
  159. '#type' => 'fieldset',
  160. '#title' => t('Target node'),
  161. '#collapsible' => TRUE,
  162. '#collapsed' => FALSE,
  163. '#weight' => -4,
  164. '#attributes' => array('id' => 'target_node'),
  165. '#description' => t('You can set target node to a bunch of selected files at once.').'<br/>'.t(' Select node from list below and press button to set the values.')
  166. );
  167. if ($default_nid) $form['node_select']['#collapsed'] = TRUE;
  168. $form['node_select']['combobox'] = array(
  169. '#type' => 'select',
  170. '#options' => $nids,
  171. '#default_value' => $default_nid,
  172. '#weight' => -4,
  173. '#id' => 'node_select_combo',
  174. '#description' => t('ID - Title'),
  175. );
  176. $form['node_select']['button'] = array(
  177. '#type' => 'button',
  178. '#value' => t('Set for selected rows'),
  179. '#id' => 'node_select_button'
  180. );
  181. $form['edit_titles'] = array(
  182. '#type' => 'fieldset',
  183. '#title' => t('Edit titles'),
  184. '#collapsible' => TRUE,
  185. '#collapsed' => FALSE,
  186. '#weight' => -4,
  187. '#attributes' => array('id' => 'edit_titles'),
  188. );
  189. $form['edit_titles']['clear_titles'] = array(
  190. '#type' => 'button',
  191. '#value' => t('Clear titles'),
  192. '#id' => 'clear_titles',
  193. '#suffix' => '<br/><br/>',
  194. );
  195. $form['edit_titles']['cfl_titles'] = array(
  196. '#type' => 'button',
  197. '#value' => t('Capitalize first letter'),
  198. '#id' => 'cfl_titles',
  199. '#suffix' => '<br/>',
  200. );
  201. $form['edit_titles']['cfla_titles'] = array(
  202. '#type' => 'button',
  203. '#value' => t('Capitalize all words'),
  204. '#id' => 'cfla_titles',
  205. '#suffix' => '<br/><br/>',
  206. );
  207. $form['replace_titles'] = array(
  208. '#type' => 'fieldset',
  209. '#title' => t('RegEx replacement in titles'),
  210. '#collapsible' => TRUE,
  211. '#collapsed' => FALSE,
  212. '#weight' => -4,
  213. '#attributes' => array('id' => 'replace_titles'),
  214. );
  215. $form['replace_titles']['replace_from'] = array(
  216. '#type' => 'textfield',
  217. '#size' => 25,
  218. '#default_value' => '[-_]',
  219. '#description' => t('Replace from'),
  220. );
  221. $form['replace_titles']['replace_to'] = array(
  222. '#type' => 'textfield',
  223. '#size' => 25,
  224. '#default_value' => ' ',
  225. '#description' => t('Replace to'),
  226. );
  227. $form['replace_titles']['replace_titles'] = array(
  228. '#type' => 'button',
  229. '#value' => t('Replace in selected'),
  230. '#id' => 'replace_titles_button',
  231. );
  232. $form['buttons']['submit'] = array(
  233. '#type' => 'submit',
  234. '#value' => t('Import'),
  235. );
  236. }
  237. else {
  238. $form['import_file'] = array(
  239. '#type' => 'item',
  240. '#value' => t('No files in import directory'),
  241. );
  242. }
  243. return $form;
  244. }
  245. function content_type($name) {
  246. // Defines the content type based upon the extension of the file
  247. $contenttype = 'application/octet-stream';
  248. $contenttypes = array( 'html' => 'text/html',
  249. 'htm' => 'text/html',
  250. 'txt' => 'text/plain',
  251. 'gif' => 'image/gif',
  252. 'jpg' => 'image/jpeg',
  253. 'png' => 'image/png',
  254. 'sxw' => 'application/vnd.sun.xml.writer',
  255. 'sxg' => 'application/vnd.sun.xml.writer.global',
  256. 'sxd' => 'application/vnd.sun.xml.draw',
  257. 'sxc' => 'application/vnd.sun.xml.calc',
  258. 'sxi' => 'application/vnd.sun.xml.impress',
  259. 'xls' => 'application/vnd.ms-excel',
  260. 'ppt' => 'application/vnd.ms-powerpoint',
  261. 'doc' => 'application/msword',
  262. 'rtf' => 'text/rtf',
  263. 'zip' => 'application/zip',
  264. 'mp3' => 'audio/mpeg',
  265. 'pdf' => 'application/pdf',
  266. 'tgz' => 'application/x-gzip',
  267. 'gz' => 'application/x-gzip',
  268. 'vcf' => 'text/vcf' );
  269. $name = ereg_replace("§", " ", $name);
  270. foreach ($contenttypes as $type_ext => $type_name) {
  271. if (preg_match ("/$type_ext$/i", $name)) $contenttype = $type_name;
  272. }
  273. return $contenttype;
  274. }
  275. function theme_file_import_form($form) {
  276. $output = '';
  277. if (isset($form['import_file']) && $form['import_file']['#type'] == 'checkboxes') {
  278. $header = array(theme('table_select_header_cell'), t('Name'), t('Size'), t('Title'), t('Target node ID'));
  279. $rows = array();
  280. foreach (element_children($form['import_file']) as $key) {
  281. $filename = $form['import_file'][$key]['#title'];
  282. unset($form['import_file'][$key]['#title']);
  283. $form['import_file'][$key]['#attributes']['checked'] = TRUE;
  284. $rows[] = array(
  285. drupal_render($form['import_file'][$key]),
  286. $filename,
  287. drupal_render($form['files']['filesize'][$key]),
  288. drupal_render($form['files']['title'][$key]),
  289. drupal_render($form['files']['node'][$key]),
  290. );
  291. }
  292. $output .= theme('table', $header, $rows);
  293. }
  294. //javascript for form altering
  295. drupal_add_js(drupal_get_path('module', 'file_import').'/file_import.js');
  296. $inline_script = '<script type="text/javascript"> file_import_form_change(); </script>';
  297. return $output . drupal_render($form). $inline_script;
  298. }
  299. /**
  300. * Checks if has acces to import files in node
  301. */
  302. function file_import_access_for_node($node){
  303. $only_with_uploads = variable_get("only_with_uploads",TRUE);
  304. return (!$only_with_uploads) || ($only_with_uploads && variable_get('upload_'. $node->type, 1));
  305. }
  306. function file_import_form_submit($form_id, $form_values) {
  307. $op = isset($form_values['op']) ? $form_values['op'] : '';
  308. if ($op == t('Import')) {
  309. $dirpath = variable_get('file_import_path', '');
  310. if (file_check_directory($dirpath)) {
  311. $i = 0;
  312. $list = variable_get('upload_list_default', TRUE);
  313. //array for node objects
  314. $nodes = array();
  315. foreach (array_filter($form_values['import_file']) as $index) {
  316. //current nid
  317. $node_index = $form_values['node'][$index];
  318. if (is_numeric($node_index))
  319. {
  320. //fill aray of objects or skip if something wrong with a node
  321. if ((!$nodes[$node_index])&&($n = node_load($node_index))&&(file_import_access_for_node($n)))
  322. $nodes[$node_index] = $n;
  323. //check if we have that node, if no - skip
  324. if ($nodes[$node_index])
  325. {
  326. $nid = $nodes[$node_index]->nid;
  327. $vid = $nodes[$node_index]->vid;
  328. // try to avoid php's script timeout with a bunch of large files or
  329. // a slow machine
  330. if (!ini_get('safe_mode')) {
  331. set_time_limit(0);
  332. }
  333. $origname = $form_values['file_list'][$index];
  334. $filename = file_check_location($dirpath .'/'. $origname, $dirpath);
  335. $new_filename = variable_get('file_import_output_path', file_directory_path()).'/'. $origname;
  336. //resize images if needed
  337. $info = image_get_info($filename);
  338. if ($info) {
  339. list($width, $height) = explode('x', variable_get('upload_max_resolution', 0));
  340. if ($width && $height) {
  341. $result = image_scale($filename, $filename, $width, $height);
  342. if ($result) {
  343. drupal_set_message(t('The image was resized to fit within the maximum allowed resolution of %resolution pixels.', array('%resolution' => variable_get('upload_max_resolution', 0))));
  344. }
  345. }
  346. }
  347. if (file_move($filename, $new_filename, FILE_EXISTS_RENAME))
  348. {
  349. $fid = db_next_id('{files}_fid'); // best way?
  350. db_query("INSERT INTO {files} (fid, nid, filename, filepath, filemime, filesize) VALUES (%d, %d, '%s', '%s', '%s', %d)",
  351. $fid,
  352. $nid,
  353. $origname,
  354. $filename,
  355. content_type($filename),
  356. filesize($filename));
  357. db_query("INSERT INTO {file_revisions} (fid, vid, description, list) VALUES (%d, %d, '%s', %d)",
  358. $fid,
  359. $vid,
  360. $form_values['title'][$index],
  361. $list);
  362. $i++;
  363. }
  364. }
  365. }
  366. }
  367. // report back on our progress
  368. if ($i) {
  369. drupal_set_message(t('Successfully imported %count', array('%count' => format_plural($i, '1 file', '@count files'))));
  370. }
  371. else {
  372. drupal_set_message(t('No files files were imported.'));
  373. }
  374. }
  375. }
  376. }
  377. function file_import_admin_settings() {
  378. $form['file_import_path'] = array(
  379. '#type' => 'textfield',
  380. '#title' => t('Import path'),
  381. '#default_value' => variable_get('file_import_path', file_directory_path() .'/import'),
  382. '#after_build' => array('_file_import_settings_check_import_directory'),
  383. '#description' => t("The directory to import files from. Drupal will need to have write access to this directory so we can move the file.") .'<br />'
  384. . t("<strong>Note:</strong> a path begining with a <kbd>/</kbd> indicates the path is relative to the server's root, not the website's root. One starting without a <kbd>/</kbd> specifies a path relative to Drupal's root. For example: <kbd>/tmp/image</kbd> would be the temp directory off the root while <kbd>tmp/image</kbd> would be inside Drupal's directory."),
  385. '#required' => TRUE,
  386. );
  387. $form['file_import_output_path'] = array(
  388. '#type' => 'textfield',
  389. '#title' => t('Output path'),
  390. '#default_value' => variable_get('file_import_output_path', file_directory_path()),
  391. '#after_build' => array('_file_import_settings_check_output_directory'),
  392. '#description' => t("The directory to output files to. Drupal will need to have write access to this directory so we can move the file.") .'<br />'
  393. . t("<strong>Note:</strong> a path begining with a <kbd>/</kbd> indicates the path is relative to the server's root, not the website's root. One starting without a <kbd>/</kbd> specifies a path relative to Drupal's root. For example: <kbd>/tmp/image</kbd> would be the temp directory off the root while <kbd>tmp/image</kbd> would be inside Drupal's directory."),
  394. '#required' => TRUE,
  395. );
  396. $form['files_only_with_uploads'] = array(
  397. '#type' => 'checkbox',
  398. '#title' => t('Import to nodes which has permission to contain files only'),
  399. '#after_build' => array('_file_import_settings_only_with_uploads'),
  400. '#default_value' => variable_get('only_with_uploads', TRUE),
  401. );
  402. $form['file_import_tab'] = array(
  403. '#type' => 'checkbox',
  404. '#title' => t('Display tab on node pages'),
  405. '#after_build' => array('_file_import_tab'),
  406. '#default_value' => variable_get('file_import_tab', FALSE),
  407. );
  408. return system_settings_form($form);
  409. }
  410. /**
  411. * Checks the existence of the directory specified in $form_element.
  412. *
  413. * @param $form_element
  414. * The form element containing the name of the directory to check.
  415. * @see system_check_directory()
  416. */
  417. function _file_import_settings_check_import_directory($form_element) {
  418. $import_dir = $form_element['#value'];
  419. file_check_directory($import_dir, 0, $form_element['#parents'][0]);
  420. $files_dir = file_create_path(variable_get('files_default_path', 'files'));
  421. if (realpath($import_dir) == realpath($files_dir)) {
  422. form_set_error($form_element['#parents'][0], t("You can't import from the files module's directory. The import deletes the original files so you would just be asking for trouble."));
  423. }
  424. return $form_element;
  425. }
  426. function _file_import_settings_check_output_directory($form_element) {
  427. $output_dir = $form_element['#value'];
  428. file_check_directory($output_dir, 0, $form_element['#parents'][0]);
  429. return $form_element;
  430. }
  431. function _file_import_settings_only_with_uploads($form_element) {
  432. variable_set('only_with_uploads', $form_element['#value']);
  433. return $form_element;
  434. }
  435. function _file_import_tab($form_element) {
  436. variable_set('file_import_tab', $form_element['#value']);
  437. return $form_element;
  438. }