file_example.module 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. <?php
  2. /**
  3. * @file
  4. * Examples demonstrating the Drupal File API (and Stream Wrappers).
  5. */
  6. /**
  7. * @defgroup file_example Example: Files
  8. * @ingroup examples
  9. * @{
  10. * Examples demonstrating the Drupal File API (and Stream Wrappers).
  11. *
  12. * The File Example module is a part of the Examples for Developers Project
  13. * and provides various Drupal File API Examples. You can download and
  14. * experiment with this code at the
  15. * @link http://drupal.org/project/examples Examples for Developers project page. @endlink
  16. *
  17. * See @link http://drupal.org/node/555118 Drupal File API @endlink for handbook
  18. * documentation on the File API and
  19. * @link file File summary on api.drupal.org @endlink for the function summary.
  20. */
  21. /**
  22. * Implements hook_menu().
  23. *
  24. * Set up the URLs (menu entries) for the file examples.
  25. */
  26. function file_example_menu() {
  27. $items = array();
  28. $items['examples/file_example'] = array(
  29. 'title' => 'File Example',
  30. 'page callback' => 'file_example_intro',
  31. 'access callback' => TRUE,
  32. 'expanded' => TRUE,
  33. );
  34. $items['examples/file_example/fileapi'] = array(
  35. 'title' => 'Use File API to read/write a file',
  36. 'page callback' => 'drupal_get_form',
  37. 'access arguments' => array('use file example'),
  38. 'page arguments' => array('file_example_readwrite'),
  39. );
  40. $items['examples/file_example/access_session'] = array(
  41. 'page callback' => 'file_example_session_contents',
  42. 'access arguments' => array('use file example'),
  43. 'type' => MENU_CALLBACK,
  44. );
  45. return $items;
  46. }
  47. /**
  48. * Implements hook_permission().
  49. */
  50. function file_example_permission() {
  51. return array(
  52. 'use file example' => array(
  53. 'title' => t('Use the examples in the File Example module'),
  54. ),
  55. );
  56. }
  57. /**
  58. * A simple introduction to the workings of this module.
  59. */
  60. function file_example_intro() {
  61. $markup = t('The file example module provides a form and code to demonstrate the Drupal 7 file api. Experiment with the form, and then look at the submit handlers in the code to understand the file api.');
  62. return array('#markup' => $markup);
  63. }
  64. /**
  65. * Form builder function.
  66. *
  67. * A simple form that allows creation of a file, managed or unmanaged. It
  68. * also allows reading/deleting a file and creation of a directory.
  69. */
  70. function file_example_readwrite($form, &$form_state) {
  71. if (empty($_SESSION['file_example_default_file'])) {
  72. $_SESSION['file_example_default_file'] = 'session://drupal.txt';
  73. }
  74. $default_file = $_SESSION['file_example_default_file'];
  75. if (empty($_SESSION['file_example_default_directory'])) {
  76. $_SESSION['file_example_default_directory'] = 'session://directory1';
  77. }
  78. $default_directory = $_SESSION['file_example_default_directory'];
  79. $form['write_file'] = array(
  80. '#type' => 'fieldset',
  81. '#title' => t('Write to a file'),
  82. );
  83. $form['write_file']['write_contents'] = array(
  84. '#type' => 'textfield',
  85. '#title' => t('Enter something you would like to write to a file') . ' ' . date('m'),
  86. '#default_value' => t('Put some text here or just use this text'),
  87. );
  88. $form['write_file']['destination'] = array(
  89. '#type' => 'textfield',
  90. '#default_value' => $default_file,
  91. '#title' => t('Optional: Enter the streamwrapper saying where it should be written'),
  92. '#description' => t('This may be public://some_dir/test_file.txt or private://another_dir/some_file.txt, for example. If you include a directory, it must already exist. The default is "public://". Since this example supports session://, you can also use something like session://somefile.txt.'),
  93. );
  94. $form['write_file']['managed_submit'] = array(
  95. '#type' => 'submit',
  96. '#value' => t('Write managed file'),
  97. '#submit' => array('file_example_managed_write_submit'),
  98. );
  99. $form['write_file']['unmanaged_submit'] = array(
  100. '#type' => 'submit',
  101. '#value' => t('Write unmanaged file'),
  102. '#submit' => array('file_example_unmanaged_write_submit'),
  103. );
  104. $form['write_file']['unmanaged_php'] = array(
  105. '#type' => 'submit',
  106. '#value' => t('Unmanaged using PHP'),
  107. '#submit' => array('file_example_unmanaged_php_submit'),
  108. );
  109. $form['fileops'] = array(
  110. '#type' => 'fieldset',
  111. '#title' => t('Read from a file'),
  112. );
  113. $form['fileops']['fileops_file'] = array(
  114. '#type' => 'textfield',
  115. '#default_value' => $default_file,
  116. '#title' => t('Enter the URI of a file'),
  117. '#description' => t('This must be a stream-type description like public://some_file.txt or http://drupal.org or private://another_file.txt or (for this example) session://yet_another_file.txt.'),
  118. );
  119. $form['fileops']['read_submit'] = array(
  120. '#type' => 'submit',
  121. '#value' => t('Read the file and store it locally'),
  122. '#submit' => array('file_example_read_submit'),
  123. );
  124. $form['fileops']['delete_submit'] = array(
  125. '#type' => 'submit',
  126. '#value' => t('Delete file'),
  127. '#submit' => array('file_example_delete_submit'),
  128. );
  129. $form['fileops']['check_submit'] = array(
  130. '#type' => 'submit',
  131. '#value' => t('Check to see if file exists'),
  132. '#submit' => array('file_example_file_check_exists_submit'),
  133. );
  134. $form['directory'] = array(
  135. '#type' => 'fieldset',
  136. '#title' => t('Create or prepare a directory'),
  137. );
  138. $form['directory']['directory_name'] = array(
  139. '#type' => 'textfield',
  140. '#title' => t('Directory to create/prepare/delete'),
  141. '#default_value' => $default_directory,
  142. '#description' => t('This is a directory as in public://some/directory or private://another/dir.'),
  143. );
  144. $form['directory']['create_directory'] = array(
  145. '#type' => 'submit',
  146. '#value' => t('Create directory'),
  147. '#submit' => array('file_example_create_directory_submit'),
  148. );
  149. $form['directory']['delete_directory'] = array(
  150. '#type' => 'submit',
  151. '#value' => t('Delete directory'),
  152. '#submit' => array('file_example_delete_directory_submit'),
  153. );
  154. $form['directory']['check_directory'] = array(
  155. '#type' => 'submit',
  156. '#value' => t('Check to see if directory exists'),
  157. '#submit' => array('file_example_check_directory_submit'),
  158. );
  159. $form['debug'] = array(
  160. '#type' => 'fieldset',
  161. '#title' => t('Debugging'),
  162. );
  163. $form['debug']['show_raw_session'] = array(
  164. '#type' => 'submit',
  165. '#value' => t('Show raw $_SESSION contents'),
  166. '#submit' => array('file_example_show_session_contents_submit'),
  167. );
  168. return $form;
  169. }
  170. /**
  171. * Submit handler to write a managed file.
  172. *
  173. * The key functions used here are:
  174. * - file_save_data(), which takes a buffer and saves it to a named file and
  175. * also creates a tracking record in the database and returns a file object.
  176. * In this function we use FILE_EXISTS_RENAME (the default) as the argument,
  177. * which means that if there's an existing file, create a new non-colliding
  178. * filename and use it.
  179. * - file_create_url(), which converts a URI in the form public://junk.txt or
  180. * private://something/test.txt into a URL like
  181. * http://example.com/sites/default/files/junk.txt.
  182. */
  183. function file_example_managed_write_submit($form, &$form_state) {
  184. $data = $form_state['values']['write_contents'];
  185. $uri = !empty($form_state['values']['destination']) ? $form_state['values']['destination'] : NULL;
  186. // Managed operations work with a file object.
  187. $file_object = file_save_data($data, $uri, FILE_EXISTS_RENAME);
  188. if (!empty($file_object)) {
  189. $url = file_create_url($file_object->uri);
  190. $_SESSION['file_example_default_file'] = $file_object->uri;
  191. drupal_set_message(
  192. t('Saved managed file: %file to destination %destination (accessible via !url, actual uri=<span id="uri">@uri</span>)',
  193. array(
  194. '%file' => print_r($file_object, TRUE),
  195. '%destination' => $uri, '@uri' => $file_object->uri,
  196. '!url' => l(t('this URL'), $url),
  197. )
  198. )
  199. );
  200. }
  201. else {
  202. drupal_set_message(t('Failed to save the managed file'), 'error');
  203. }
  204. }
  205. /**
  206. * Submit handler to write an unmanaged file.
  207. *
  208. * The key functions used here are:
  209. * - file_unmanaged_save_data(), which takes a buffer and saves it to a named
  210. * file, but does not create any kind of tracking record in the database.
  211. * This example uses FILE_EXISTS_REPLACE for the third argument, meaning
  212. * that if there's an existing file at this location, it should be replaced.
  213. * - file_create_url(), which converts a URI in the form public://junk.txt or
  214. * private://something/test.txt into a URL like
  215. * http://example.com/sites/default/files/junk.txt.
  216. */
  217. function file_example_unmanaged_write_submit($form, &$form_state) {
  218. $data = $form_state['values']['write_contents'];
  219. $destination = !empty($form_state['values']['destination']) ? $form_state['values']['destination'] : NULL;
  220. // With the unmanaged file we just get a filename back.
  221. $filename = file_unmanaged_save_data($data, $destination, FILE_EXISTS_REPLACE);
  222. if ($filename) {
  223. $url = file_create_url($filename);
  224. $_SESSION['file_example_default_file'] = $filename;
  225. drupal_set_message(
  226. t('Saved file as %filename (accessible via !url, uri=<span id="uri">@uri</span>)',
  227. array(
  228. '%filename' => $filename,
  229. '@uri' => $filename,
  230. '!url' => l(t('this URL'), $url),
  231. )
  232. )
  233. );
  234. }
  235. else {
  236. drupal_set_message(t('Failed to save the file'), 'error');
  237. }
  238. }
  239. /**
  240. * Submit handler to write an unmanaged file using plain PHP functions.
  241. *
  242. * The key functions used here are:
  243. * - file_unmanaged_save_data(), which takes a buffer and saves it to a named
  244. * file, but does not create any kind of tracking record in the database.
  245. * - file_create_url(), which converts a URI in the form public://junk.txt or
  246. * private://something/test.txt into a URL like
  247. * http://example.com/sites/default/files/junk.txt.
  248. * - drupal_tempnam() generates a temporary filename for use.
  249. */
  250. function file_example_unmanaged_php_submit($form, &$form_state) {
  251. $data = $form_state['values']['write_contents'];
  252. $destination = !empty($form_state['values']['destination']) ? $form_state['values']['destination'] : NULL;
  253. if (empty($destination)) {
  254. // If no destination has been provided, use a generated name.
  255. $destination = drupal_tempnam('public://', 'file');
  256. }
  257. // With all traditional PHP functions we can use the stream wrapper notation
  258. // for a file as well.
  259. $fp = fopen($destination, 'w');
  260. // To demonstrate the fact that everything is based on streams, we'll do
  261. // multiple 5-character writes to put this to the file. We could easily
  262. // (and far more conveniently) write it in a single statement with
  263. // fwrite($fp, $data).
  264. $length = strlen($data);
  265. $write_size = 5;
  266. for ($i = 0; $i < $length; $i += $write_size) {
  267. $result = fwrite($fp, substr($data, $i, $write_size));
  268. if ($result === FALSE) {
  269. drupal_set_message(t('Failed writing to the file %file', array('%file' => $destination)), 'error');
  270. fclose($fp);
  271. return;
  272. }
  273. }
  274. $url = file_create_url($destination);
  275. $_SESSION['file_example_default_file'] = $destination;
  276. drupal_set_message(
  277. t('Saved file as %filename (accessible via !url, uri=<span id="uri">@uri</span>)',
  278. array(
  279. '%filename' => $destination,
  280. '@uri' => $destination,
  281. '!url' => l(t('this URL'), $url),
  282. )
  283. )
  284. );
  285. }
  286. /**
  287. * Submit handler for reading a stream wrapper.
  288. *
  289. * Drupal now has full support for PHP's stream wrappers, which means that
  290. * instead of the traditional use of all the file functions
  291. * ($fp = fopen("/tmp/some_file.txt");) far more sophisticated and generalized
  292. * (and extensible) things can be opened as if they were files. Drupal itself
  293. * provides the public:// and private:// schemes for handling public and
  294. * private files. PHP provides file:// (the default) and http://, so that a
  295. * URL can be read or written (as in a POST) as if it were a file. In addition,
  296. * new schemes can be provided for custom applications, as will be demonstrated
  297. * below.
  298. *
  299. * Here we take the stream wrapper provided in the form. We grab the
  300. * contents with file_get_contents(). Notice that's it's as simple as that:
  301. * file_get_contents("http://example.com") or
  302. * file_get_contents("public://somefile.txt") just works. Although it's
  303. * not necessary, we use file_unmanaged_save_data() to save this file locally
  304. * and then find a local URL for it by using file_create_url().
  305. */
  306. function file_example_read_submit($form, &$form_state) {
  307. $uri = $form_state['values']['fileops_file'];
  308. if (!is_file($uri)) {
  309. drupal_set_message(t('The file %uri does not exist', array('%uri' => $uri)), 'error');
  310. return;
  311. }
  312. // Make a working filename to save this by stripping off the (possible)
  313. // file portion of the streamwrapper. If it's an evil file extension,
  314. // file_munge_filename() will neuter it.
  315. $filename = file_munge_filename(preg_replace('@^.*/@', '', $uri), '', TRUE);
  316. $buffer = file_get_contents($uri);
  317. if ($buffer) {
  318. $sourcename = file_unmanaged_save_data($buffer, 'public://' . $filename);
  319. if ($sourcename) {
  320. $url = file_create_url($sourcename);
  321. $_SESSION['file_example_default_file'] = $sourcename;
  322. drupal_set_message(
  323. t('The file was read and copied to %filename which is accessible at !url',
  324. array(
  325. '%filename' => $sourcename,
  326. '!url' => l($url, $url),
  327. )
  328. )
  329. );
  330. }
  331. else {
  332. drupal_set_message(t('Failed to save the file'));
  333. }
  334. }
  335. else {
  336. // We failed to get the contents of the requested file.
  337. drupal_set_message(t('Failed to retrieve the file %file', array('%file' => $uri)));
  338. }
  339. }
  340. /**
  341. * Submit handler to delete a file.
  342. */
  343. function file_example_delete_submit($form, &$form_state) {
  344. $uri = $form_state['values']['fileops_file'];
  345. // Since we don't know if the file is managed or not, look in the database
  346. // to see. Normally, code would be working with either managed or unmanaged
  347. // files, so this is not a typical situation.
  348. $file_object = file_example_get_managed_file($uri);
  349. // If a managed file, use file_delete().
  350. if (!empty($file_object)) {
  351. $result = file_delete($file_object);
  352. if ($result !== TRUE) {
  353. drupal_set_message(t('Failed deleting managed file %uri. Result was %result',
  354. array(
  355. '%uri' => $uri,
  356. '%result' => print_r($result, TRUE),
  357. )
  358. ), 'error');
  359. }
  360. else {
  361. drupal_set_message(t('Successfully deleted managed file %uri', array('%uri' => $uri)));
  362. $_SESSION['file_example_default_file'] = $uri;
  363. }
  364. }
  365. // Else use file_unmanaged_delete().
  366. else {
  367. $result = file_unmanaged_delete($uri);
  368. if ($result !== TRUE) {
  369. drupal_set_message(t('Failed deleting unmanaged file %uri', array('%uri' => $uri, 'error')));
  370. }
  371. else {
  372. drupal_set_message(t('Successfully deleted unmanaged file %uri', array('%uri' => $uri)));
  373. $_SESSION['file_example_default_file'] = $uri;
  374. }
  375. }
  376. }
  377. /**
  378. * Submit handler to check existence of a file.
  379. */
  380. function file_example_file_check_exists_submit($form, &$form_state) {
  381. $uri = $form_state['values']['fileops_file'];
  382. if (is_file($uri)) {
  383. drupal_set_message(t('The file %uri exists.', array('%uri' => $uri)));
  384. }
  385. else {
  386. drupal_set_message(t('The file %uri does not exist.', array('%uri' => $uri)));
  387. }
  388. }
  389. /**
  390. * Submit handler for directory creation.
  391. *
  392. * Here we create a directory and set proper permissions on it using
  393. * file_prepare_directory().
  394. */
  395. function file_example_create_directory_submit($form, &$form_state) {
  396. $directory = $form_state['values']['directory_name'];
  397. // The options passed to file_prepare_directory are a bitmask, so we can
  398. // specify either FILE_MODIFY_PERMISSIONS (set permissions on the directory),
  399. // FILE_CREATE_DIRECTORY, or both together:
  400. // FILE_MODIFY_PERMISSIONS | FILE_CREATE_DIRECTORY.
  401. // FILE_MODIFY_PERMISSIONS will set the permissions of the directory by
  402. // by default to 0755, or to the value of the variable 'file_chmod_directory'.
  403. if (!file_prepare_directory($directory, FILE_MODIFY_PERMISSIONS | FILE_CREATE_DIRECTORY)) {
  404. drupal_set_message(t('Failed to create %directory.', array('%directory' => $directory)), 'error');
  405. }
  406. else {
  407. drupal_set_message(t('Directory %directory is ready for use.', array('%directory' => $directory)));
  408. $_SESSION['file_example_default_directory'] = $directory;
  409. }
  410. }
  411. /**
  412. * Submit handler for directory deletion.
  413. *
  414. * @see file_unmanaged_delete_recursive()
  415. */
  416. function file_example_delete_directory_submit($form, &$form_state) {
  417. $directory = $form_state['values']['directory_name'];
  418. $result = file_unmanaged_delete_recursive($directory);
  419. if (!$result) {
  420. drupal_set_message(t('Failed to delete %directory.', array('%directory' => $directory)), 'error');
  421. }
  422. else {
  423. drupal_set_message(t('Recursively deleted directory %directory.', array('%directory' => $directory)));
  424. $_SESSION['file_example_default_directory'] = $directory;
  425. }
  426. }
  427. /**
  428. * Submit handler to test directory existence.
  429. *
  430. * This actually just checks to see if the directory is writable
  431. *
  432. * @param array $form
  433. * FormAPI form.
  434. * @param array $form_state
  435. * FormAPI form state.
  436. */
  437. function file_example_check_directory_submit($form, &$form_state) {
  438. $directory = $form_state['values']['directory_name'];
  439. $result = is_dir($directory);
  440. if (!$result) {
  441. drupal_set_message(t('Directory %directory does not exist.', array('%directory' => $directory)));
  442. }
  443. else {
  444. drupal_set_message(t('Directory %directory exists.', array('%directory' => $directory)));
  445. }
  446. }
  447. /**
  448. * Utility submit function to show the contents of $_SESSION.
  449. */
  450. function file_example_show_session_contents_submit($form, &$form_state) {
  451. // If the devel module is installed, use it's nicer message format.
  452. if (module_exists('devel')) {
  453. dsm($_SESSION['file_example'], t('Entire $_SESSION["file_example"]'));
  454. }
  455. else {
  456. drupal_set_message('<pre>' . print_r($_SESSION['file_example'], TRUE) . '</pre>');
  457. }
  458. }
  459. /**
  460. * Utility function to check for and return a managed file.
  461. *
  462. * In this demonstration code we don't necessarily know if a file is managed
  463. * or not, so often need to check to do the correct behavior. Normal code
  464. * would not have to do this, as it would be working with either managed or
  465. * unmanaged files.
  466. *
  467. * @param string $uri
  468. * The URI of the file, like public://test.txt.
  469. */
  470. function file_example_get_managed_file($uri) {
  471. $fid = db_query('SELECT fid FROM {file_managed} WHERE uri = :uri', array(':uri' => $uri))->fetchField();
  472. if (!empty($fid)) {
  473. $file_object = file_load($fid);
  474. return $file_object;
  475. }
  476. return FALSE;
  477. }
  478. /**
  479. * Implements hook_stream_wrappers().
  480. *
  481. * hook_stream_wrappers() is Drupal's way of exposing the class that PHP will
  482. * use to provide a new stream wrapper class. In this case, we'll expose the
  483. * 'session' scheme, so a file reference like "session://example/example.txt"
  484. * is readable and writable as a location in the $_SESSION variable.
  485. *
  486. * @see FileExampleSessionStreamWrapper
  487. */
  488. function file_example_stream_wrappers() {
  489. $wrappers = array(
  490. 'session' => array(
  491. 'name' => t('Example: $_SESSION variable storage'),
  492. 'class' => 'FileExampleSessionStreamWrapper',
  493. 'description' => t('Store files in the $_SESSION variable as an example.'),
  494. ),
  495. );
  496. return $wrappers;
  497. }
  498. /**
  499. * Show the contents of a session file.
  500. *
  501. * This page callback function is called by the Menu API for the path
  502. * examples/file_example/access_session. Any extra path elements
  503. * beyond this are considered to be the session path. E.g.:
  504. * examples/file_example/access_session/foo/bar.txt would be the
  505. * equivalent of session://foo/bar.txt, which will map into
  506. * $_SESSION as keys: $_SESSION['foo']['bar.txt']
  507. *
  508. * Menu API will pass in additional path elements as function arguments. You
  509. * can obtain these with func_get_args().
  510. *
  511. * @return string
  512. * A message containing the contents of the session file.
  513. *
  514. * @see file_get_contents()
  515. */
  516. function file_example_session_contents() {
  517. $path_components = func_get_args();
  518. $session_path = 'session://' . implode('/', $path_components);
  519. $content = file_get_contents($session_path);
  520. if ($content !== FALSE) {
  521. return t('Contents of @path :',
  522. array('@path' => check_plain($session_path))) . ' ' .
  523. print_r($content, TRUE);
  524. }
  525. return t('Unable to load contents of: @path',
  526. array('@path' => check_plain($session_path)));
  527. }
  528. /**
  529. * @} End of "defgroup file_example".
  530. */