imce.page.inc 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  1. <?php
  2. /**
  3. * @file
  4. * Implements the file browser.
  5. */
  6. /**
  7. * q = imce.
  8. */
  9. function imce($scheme = NULL) {
  10. module_invoke('admin_menu', 'suppress');//suppress admin_menu
  11. $jsop = isset($_GET['jsop']) ? $_GET['jsop'] : NULL;
  12. drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
  13. print imce_page($GLOBALS['user'], $scheme, $jsop);
  14. exit();
  15. }
  16. /**
  17. * q = user/x/imce.
  18. */
  19. function imce_user_page($account) {
  20. return theme('imce_user_page', array('account' => $account));
  21. }
  22. /**
  23. * Returns the imce page for the specified user and the file scheme.
  24. */
  25. function imce_page($user, $scheme = NULL, $jsop = NULL) {
  26. return theme('imce_page', array('content' => imce_content($user, $scheme, $jsop)));
  27. }
  28. /**
  29. * Returns the content of the file browser.
  30. */
  31. function imce_content($user, $scheme = NULL, $jsop = NULL) {
  32. //execute ajax calls.
  33. if ($jsop) {
  34. return imce_js($user, $scheme, $jsop);
  35. }
  36. //initiate configuration profile
  37. if (!$imce = imce_initiate_profile($user, $scheme)) {
  38. return '';
  39. }
  40. imce_process_profile($imce);//get active directory content
  41. //Before creating the content let's add main files required for imce to function properly.
  42. $path = drupal_get_path('module', 'imce');
  43. drupal_add_js($path . '/js/jquery.form.js');
  44. drupal_add_js($path . '/js/imce.js');
  45. drupal_add_js($path . '/js/imce_extras.js');
  46. drupal_add_css($path . '/css/imce-content.css');
  47. //process forms.
  48. $imce_ref = array('imce' => &$imce);
  49. $forms = array();
  50. if (!$imce['error']) {
  51. //process file upload.
  52. if (imce_perm_exists($imce, 'upload')) {
  53. $forms[] = drupal_get_form('imce_upload_form', $imce_ref);
  54. }
  55. //process file operations.
  56. $forms[] = drupal_get_form('imce_fileop_form', $imce_ref);
  57. }
  58. $forms = drupal_render($forms);
  59. //run custom content functions. possible to insert extra forms. content is invisible when js is enabled.
  60. foreach (variable_get('imce_custom_content', array()) as $func => $state) {
  61. if ($state && function_exists($func) && $output = $func($imce)) {
  62. $forms .= $output;
  63. }
  64. }
  65. $content = theme('imce_content', array(
  66. 'tree' => imce_create_tree($imce),
  67. 'forms' => $forms,
  68. 'imce_ref' => $imce_ref,
  69. ));
  70. //make necessary changes for js conversion
  71. $imce['dir'] = str_replace('%2F', '/', rawurlencode($imce['dir']));
  72. unset($imce['files'], $imce['name'], $imce['directories'], $imce['subdirectories'], $imce['filesize'], $imce['quota'], $imce['tuquota'], $imce['thumbnails'], $imce['uid'], $imce['usertab']);
  73. drupal_add_js($imce_ref, 'setting');
  74. return $content;
  75. }
  76. /**
  77. * Ajax operations. q=imce&jsop={op}
  78. */
  79. function imce_js($user, $scheme, $jsop = '') {
  80. $response = array();
  81. //data
  82. if ($imce = imce_initiate_profile($user, $scheme)) {
  83. imce_process_profile($imce);
  84. if (!$imce['error']) {
  85. module_load_include('inc', 'imce', 'inc/imce.js');
  86. if (function_exists($func = 'imce_js_' . $jsop)) {
  87. $response['data'] = $func($imce);
  88. }
  89. // Allow alteration of response.
  90. foreach (variable_get('imce_custom_response', array()) as $func => $state) {
  91. if ($state && function_exists($func)) {
  92. $func($jsop, $response, $imce, $user);
  93. }
  94. }
  95. }
  96. }
  97. //messages
  98. $response['messages'] = drupal_get_messages();
  99. //disable devel log.
  100. $GLOBALS['devel_shutdown'] = FALSE;
  101. //for upload we must return plain text header.
  102. drupal_add_http_header('Content-Type', (!empty($_POST['html_response']) ? 'text/html' : 'application/json') . '; charset=utf-8');
  103. print drupal_json_encode($response);
  104. exit();
  105. }
  106. /**
  107. * Upload form.
  108. */
  109. function imce_upload_form($form, &$form_state, $ref) {
  110. $imce =& $ref['imce'];
  111. $form['imce'] = array(
  112. '#type' => 'file',
  113. '#title' => t('File'),
  114. '#size' => 30,
  115. );
  116. if (!empty($imce['thumbnails'])) {
  117. $form['thumbnails'] = array(
  118. '#type' => 'checkboxes',
  119. '#title' => t('Create thumbnails'),
  120. '#options' => imce_thumbnail_options($imce['thumbnails']),
  121. );
  122. }
  123. $form['upload'] = array(
  124. '#type' => 'submit',
  125. '#value' => t('Upload'),
  126. '#submit' => $imce['perm']['upload'] ? array('imce_upload_submit') : NULL,
  127. );
  128. $form = array('fset_upload' => array('#type' => 'fieldset', '#title' => t('Upload file')) + $form);
  129. $form['html_response'] = array('#type' => 'hidden', '#default_value' => '1');
  130. $form['#attributes']['enctype'] = 'multipart/form-data';
  131. $form['#action'] = $imce['url'];
  132. return $form;
  133. }
  134. /**
  135. * File operations form.
  136. */
  137. function imce_fileop_form($form, &$form_state, $ref) {
  138. $imce =& $ref['imce'];
  139. $form['filenames'] = array(
  140. '#type' => 'textfield',
  141. '#title' => t('Selected files'),
  142. '#maxlength' => $imce['filenum'] ? $imce['filenum']*255 : NULL,
  143. );
  144. //thumbnail
  145. if (!empty($imce['thumbnails']) && imce_perm_exists($imce, 'thumb')) {
  146. $form['fset_thumb'] = array(
  147. '#type' => 'fieldset',
  148. '#title' => t('Thumbnails'),
  149. ) + imce_thumb_form($imce);
  150. }
  151. //delete
  152. if (imce_perm_exists($imce, 'delete')) {
  153. $form['fset_delete'] = array(
  154. '#type' => 'fieldset',
  155. '#title' => t('Delete'),
  156. ) + imce_delete_form($imce);
  157. }
  158. //resize
  159. if (imce_perm_exists($imce, 'resize')) {
  160. $form['fset_resize'] = array(
  161. '#type' => 'fieldset',
  162. '#title' => t('Resize'),
  163. ) + imce_resize_form($imce);
  164. }
  165. $form['#action'] = $imce['url'];
  166. return $form;
  167. }
  168. /**
  169. * Thumbnail form.
  170. */
  171. function imce_thumb_form(&$imce) {
  172. $form['thumbnails'] = array(
  173. '#type' => 'checkboxes',
  174. '#title' => t('Thumbnails'),
  175. '#options' => imce_thumbnail_options($imce['thumbnails']),
  176. );
  177. $form['thumb'] = array(
  178. '#type' => 'submit',
  179. '#value' => t('Create thumbnails'),
  180. '#submit' => $imce['perm']['thumb'] ? array('imce_thumb_submit') : NULL,
  181. );
  182. return $form;
  183. }
  184. /**
  185. * Delete form.
  186. */
  187. function imce_delete_form(&$imce) {
  188. $form['delete'] = array(
  189. '#type' => 'submit',
  190. '#value' => t('Delete'),
  191. '#submit' => $imce['perm']['delete'] ? array('imce_delete_submit') : NULL,
  192. );
  193. return $form;
  194. }
  195. /**
  196. * Resizing form.
  197. */
  198. function imce_resize_form(&$imce) {
  199. $form['width'] = array(
  200. '#type' => 'textfield',
  201. '#title' => t('Width x Height'),
  202. '#size' => 5,
  203. '#maxlength' => 4,
  204. '#prefix' => '<div class="container-inline">',
  205. );
  206. $form['height'] = array(
  207. '#type' => 'textfield',
  208. '#size' => 5,
  209. '#maxlength' => 4,
  210. '#prefix' => 'x',
  211. );
  212. $form['resize'] = array(
  213. '#type' => 'submit',
  214. '#value' => t('Resize'),
  215. '#submit' => $imce['perm']['resize'] ? array('imce_resize_submit') : NULL,//permission for submission
  216. '#suffix' => '</div>',
  217. );
  218. $form['copy'] = array(
  219. '#type' => 'checkbox',
  220. '#title' => t('Create a new image'),
  221. '#default_value' => 1,
  222. );
  223. return $form;
  224. }
  225. /**
  226. * Validate file operations form.
  227. */
  228. function imce_fileop_form_validate($form, &$form_state) {
  229. $imce =& $form_state['build_info']['args'][0]['imce'];
  230. //check if the filenames is empty
  231. if ($form_state['values']['filenames'] == '') {
  232. return form_error($form['filenames'], t('Please select a file.'));
  233. }
  234. //filenames come separated by colon
  235. $filenames = explode(':', $form_state['values']['filenames']);
  236. $cnt = count($filenames);
  237. //check the number of files.
  238. if ($imce['filenum'] && $cnt > $imce['filenum']) {
  239. return form_error($form['filenames'], t('You are not allowed to operate on more than %num files.', array('%num' => $imce['filenum'])));
  240. }
  241. //check if there is any illegal choice
  242. for ($i = 0; $i < $cnt; $i++) {
  243. $filenames[$i] = $filename = rawurldecode($filenames[$i]);
  244. if (!isset($imce['files'][$filename])) {
  245. watchdog('imce', 'Illegal choice %choice in !name element.', array('%choice' => $filename, '!name' => t('directory (%dir)', array('%dir' => imce_dir_uri($imce)))), WATCHDOG_ERROR);
  246. return form_error($form['filenames'], t('An illegal choice has been detected. Please contact the site administrator.'));
  247. }
  248. }
  249. $form_state['values']['filenames'] = $filenames;
  250. }
  251. /**
  252. * Submit upload form.
  253. */
  254. function imce_upload_submit($form, &$form_state) {
  255. $form_state['redirect'] = FALSE;
  256. $imce =& $form_state['build_info']['args'][0]['imce'];
  257. // Need to provide extension validatior, otherwise file_save_upload uses the default.
  258. $validators['file_validate_extensions'] = array($imce['extensions'] === '*' ? NULL : $imce['extensions']);
  259. $validators['imce_validate_all'] = array(&$imce);
  260. $diruri = imce_dir_uri($imce);
  261. //save uploaded file.
  262. $replace = variable_get('imce_settings_replace', FILE_EXISTS_RENAME);
  263. if ($file = file_save_upload('imce', $validators, $diruri, $replace)) {
  264. //core bug #54223.
  265. if ($replace == FILE_EXISTS_RENAME) {
  266. $name = drupal_basename($file->uri);
  267. if ($name != $file->filename) {
  268. $file->filename = $name;
  269. drupal_set_message(t('The file has been renamed to %filename.', array('%filename' => $file->filename)));
  270. }
  271. }
  272. $file->uid = $imce['uid'];//global user may not be the owner.
  273. $file->status = FILE_STATUS_PERMANENT;
  274. file_save($file);
  275. imce_file_register($file);
  276. drupal_set_message(t('%filename has been uploaded.', array('%filename' => $file->filename)));
  277. //update file list
  278. $img = imce_image_info($file->uri);
  279. $file->width = $img ? $img['width'] : 0;
  280. $file->height = $img ? $img['height'] : 0;
  281. imce_add_file($file, $imce);
  282. //create thumbnails
  283. if (isset($form_state['values']['thumbnails']) && $img) {
  284. imce_create_thumbnails($file->filename, $imce, $form_state['values']['thumbnails']);
  285. }
  286. }
  287. else {
  288. drupal_set_message(t('Upload failed.'), 'error');
  289. }
  290. }
  291. /**
  292. * Submit thumbnail form.
  293. */
  294. function imce_thumb_submit($form, &$form_state) {
  295. $form_state['redirect'] = FALSE;
  296. $imce =& $form_state['build_info']['args'][0]['imce'];
  297. //create thumbnails
  298. imce_process_files($form_state['values']['filenames'], $imce, 'imce_create_thumbnails', array($form_state['values']['thumbnails']));
  299. }
  300. /**
  301. * Submit delete form.
  302. */
  303. function imce_delete_submit($form, &$form_state) {
  304. $form_state['redirect'] = FALSE;
  305. $imce =& $form_state['build_info']['args'][0]['imce'];
  306. $deleted = imce_process_files($form_state['values']['filenames'], $imce, 'imce_delete_file');
  307. if (!empty($deleted)) {
  308. drupal_set_message(t('File deletion successful: %files.', array('%files' => utf8_encode(implode(', ', $deleted)))));
  309. }
  310. }
  311. /**
  312. * Submit resize form.
  313. */
  314. function imce_resize_submit($form, &$form_state) {
  315. $form_state['redirect'] = FALSE;
  316. $imce =& $form_state['build_info']['args'][0]['imce'];
  317. //check dimensions
  318. $width = (int) $form_state['values']['width'];
  319. $height = (int) $form_state['values']['height'];
  320. list($maxw, $maxh) = $imce['dimensions'] ? explode('x', $imce['dimensions']) : array(0, 0);
  321. if ($width < 1 || $height < 1 || ($maxw && ($width > $maxw || $height > $maxh))) {
  322. drupal_set_message(t('Please specify dimensions within the allowed range that is from 1x1 to @dimensions.', array('@dimensions' => $imce['dimensions'] ? $imce['dimensions'] : t('unlimited'))), 'error');
  323. return;
  324. }
  325. $resized = imce_process_files($form_state['values']['filenames'], $imce, 'imce_resize_image', array($width, $height, $form_state['values']['copy']));
  326. if (!empty($resized)) {
  327. drupal_set_message(t('File resizing successful: %files.', array('%files' => utf8_encode(implode(', ', $resized)))));
  328. }
  329. }
  330. /**
  331. * Do batch operations on files.
  332. * Used by delete, resize, create thumbnail submissions.
  333. */
  334. function imce_process_files($filenames, &$imce, $function, $args = array()) {
  335. $args = array_merge(array('', &$imce), $args);
  336. $processed = array();
  337. foreach ($filenames as $filename) {
  338. $args[0] = $filename;
  339. if (call_user_func_array($function, $args)) {
  340. $processed[] = $filename;
  341. }
  342. }
  343. return $processed;
  344. }
  345. /**
  346. * Deletes a file in the file list.
  347. */
  348. function imce_delete_file($filename, &$imce) {
  349. $uri = imce_dir_uri($imce) . $filename;
  350. if (!imce_delete_filepath($uri)) {
  351. return FALSE;
  352. }
  353. imce_remove_file($filename, $imce);
  354. return TRUE;
  355. }
  356. /**
  357. * Deletes a file by uri.
  358. */
  359. function imce_delete_filepath($uri) {
  360. $file = file_load_multiple(array(), array('uri' => $uri));
  361. $file = reset($file);
  362. // File exists in database
  363. if ($file) {
  364. $usage = file_usage_list($file);
  365. $is_imce = isset($usage['imce']);
  366. unset($usage['imce']);
  367. // File is in use by an other module.
  368. if (!empty($usage)) {
  369. drupal_set_message(t('%filename is in use by another application.', array('%filename' => $file->filename)), 'error');
  370. return FALSE;
  371. }
  372. // Force delete file. Prevent running file_usage_list() second time.
  373. if (!file_delete($file, TRUE)) {
  374. return FALSE;
  375. }
  376. }
  377. // Not in db. Probably loaded via ftp.
  378. elseif (!file_unmanaged_delete($uri)) {
  379. return FALSE;
  380. }
  381. return TRUE;
  382. }
  383. /**
  384. * Create all selected thumbnails.
  385. */
  386. function imce_create_thumbnails($filename, &$imce, $values) {
  387. $created = array();
  388. foreach ($imce['thumbnails'] as $thumbnail) {
  389. if ($values[$thumbnail['name']] && imce_create_thumbnail($filename, $imce, $thumbnail)) {
  390. $created[] = $thumbnail['name'];
  391. }
  392. }
  393. if (!empty($created)) {
  394. drupal_set_message(t('Thumbnail creation (%thumbnames) successful for %filename.', array('%thumbnames' => implode(', ', $created), '%filename' => utf8_encode($filename))));
  395. }
  396. return $created;
  397. }
  398. /**
  399. * Create a thumbnail.
  400. */
  401. function imce_create_thumbnail($filename, &$imce, $thumbnail) {
  402. //generate thumbnail name
  403. $name = $thumbnail['prefix'];
  404. if ($thumbnail['suffix'] != '' && $dot = strrpos($filename, '.')) {
  405. $name .= substr($filename, 0, $dot);
  406. $name .= $thumbnail['suffix'];
  407. $name .= substr($filename, $dot);
  408. }
  409. else {
  410. $name .= $filename;
  411. }
  412. //scale the image
  413. list($width, $height) = explode('x', $thumbnail['dimensions']);
  414. return imce_resize_image($filename, $imce, $width, $height, TRUE, $name, variable_get('imce_settings_thumb_method', 'scale_and_crop'));
  415. }
  416. /**
  417. * Resize an image in the file list. Also used for thumbnail creation.
  418. */
  419. function imce_resize_image($filename, &$imce, $width, $height, $copy = TRUE, $destname = FALSE, $op = 'resize') {
  420. $destdir = imce_dir_uri($imce);
  421. $imguri = $destdir . $filename;
  422. //check if the file is an image
  423. if (!$imce['files'][$filename]['width'] || !$img = imce_image_info($imguri)) {
  424. drupal_set_message(t('%filename is not an image.', array('%filename' => utf8_encode($filename))), 'error', FALSE);
  425. return FALSE;
  426. }
  427. if (substr($op, 0, 5) == 'scale' && !($width < $img['width'] || $height < $img['height'])) {
  428. drupal_set_message(t('Scaling up is not allowed.'), 'error', FALSE);
  429. return FALSE;
  430. }
  431. //create file object
  432. $file = new stdClass();
  433. $file->uri = $destdir . $destname;
  434. if (!$destname || $destname == $filename) {
  435. $file->uri = $copy ? file_create_filename($filename, $destdir) : $imguri;
  436. }
  437. $file->filename = drupal_basename($file->uri);
  438. //check if a file having the same properties exists already.
  439. if (isset($imce['files'][$file->filename])) {
  440. if (($f = $imce['files'][$file->filename]) && $f['width'] == $width && $f['height'] == $height) {
  441. drupal_set_message(t('%filename(%dimensions) already exists.', array('%filename' => utf8_encode($file->filename), '%dimensions' => $width . 'x' . $height)), 'error');
  442. return FALSE;
  443. }
  444. }
  445. //validate file name
  446. $errors = file_validate_name_length($file);
  447. if (!empty($errors)) {
  448. drupal_set_message($errors[0], 'error');
  449. return FALSE;
  450. }
  451. //resize image
  452. $image = image_load($imguri);
  453. $function = 'image_' . $op;
  454. if (!$image || !function_exists($function) || !$function($image, $width, $height)) {
  455. drupal_set_message(t('%filename cannot be resized to %dimensions', array('%filename' => utf8_encode($filename), '%dimensions' => $width . 'x' . $height)), 'error', FALSE);
  456. return FALSE;
  457. }
  458. //copy to a temp file
  459. if (!$tempuri = drupal_tempnam('temporary://', 'imce')) {
  460. return FALSE;
  461. }
  462. register_shutdown_function('file_unmanaged_delete', $tempuri);
  463. if (!image_save($image, $tempuri) || !$image->info) {
  464. return FALSE;
  465. }
  466. //validate quota
  467. $file->filesize = $image->info['file_size'];
  468. $quotadiff = $file->filename == $filename ? -$imce['files'][$filename]['size'] : 0;
  469. if (!imce_validate_quotas($file, $imce, $quotadiff)) {
  470. return FALSE;
  471. }
  472. //build the rest of the file object
  473. $file->uid = $imce['uid'];
  474. $file->filemime = $img['mime'];
  475. $file->status = FILE_STATUS_PERMANENT;
  476. $file->timestamp = REQUEST_TIME;
  477. //copy from temp to file uri
  478. $destination = $file->uri;
  479. $file->uri = $tempuri;
  480. if (!$file = file_copy($file, $destination, FILE_EXISTS_REPLACE)) {
  481. return FALSE;
  482. }
  483. imce_file_register($file);
  484. //update file list
  485. //if the file was scaled get the new dimensions
  486. if ($op == 'scale') {
  487. $img = imce_image_info($file->uri);
  488. $width = $img['width'];
  489. $height = $img['height'];
  490. }
  491. $file->width = $width;
  492. $file->height = $height;
  493. imce_add_file($file, $imce);
  494. return $file;
  495. }
  496. /**
  497. * Add a new file to the file list.
  498. */
  499. function imce_add_file($file, &$imce) {
  500. $imce['dirsize'] += $file->filesize;
  501. if (isset($imce['files'][$file->filename])) {
  502. $imce['dirsize'] -= $imce['files'][$file->filename]['size'];
  503. }
  504. $imce['files'][$file->filename] = array(
  505. 'name' => $file->filename,
  506. 'size' => $file->filesize,
  507. 'width' => $file->width,
  508. 'height' => $file->height,
  509. 'date' => $file->timestamp
  510. );
  511. if (isset($_GET['jsop'])) {
  512. $add = $imce['files'][$file->filename];
  513. $add['name'] = rawurlencode($file->filename);
  514. $add['fsize'] = format_size($file->filesize);
  515. $add['fdate'] = format_date($file->timestamp, 'short');
  516. $add['id'] = $file->fid;
  517. $imce['added'][] = $add;
  518. }
  519. }
  520. /**
  521. * Remove a file from the file list.
  522. */
  523. function imce_remove_file($filename, &$imce) {
  524. if (isset($imce['files'][$filename])) {
  525. $imce['dirsize'] -= $imce['files'][$filename]['size'];
  526. unset($imce['files'][$filename]);
  527. if (isset($_GET['jsop'])) {
  528. $imce['removed'][] = rawurlencode($filename);
  529. }
  530. }
  531. }
  532. /**
  533. * Validate uploaded file.
  534. */
  535. function imce_validate_all($file, $imce) {
  536. //validate image resolution only if filesize validation passes.
  537. //because user might have uploaded a very big image
  538. //and scaling it may exploit system memory.
  539. $errors = imce_validate_filesize($file, $imce['filesize']);
  540. //image resolution validation
  541. if (empty($errors) && preg_match('/\.(png|gif|jpe?g)$/i', $file->filename)) {
  542. $errors = array_merge($errors, file_validate_image_resolution($file, $imce['dimensions']));
  543. }
  544. //directory quota validation
  545. if ($imce['quota']) {
  546. $errors = array_merge($errors, imce_validate_quota($file, $imce['quota'], $imce['dirsize']));
  547. }
  548. //user quota validation. check it if no errors were thrown.
  549. if (empty($errors) && $imce['tuquota']) {
  550. $errors = imce_validate_tuquota($file, $imce['tuquota'], file_space_used($imce['uid']));
  551. }
  552. return $errors;
  553. }
  554. /**
  555. * Validate filesize for maximum allowed file size.
  556. */
  557. function imce_validate_filesize($file, $maxsize = 0) {
  558. $errors = array();
  559. if ($maxsize && $file->filesize > $maxsize) {
  560. $errors[] = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size($file->filesize), '%maxsize' => format_size($maxsize)));
  561. }
  562. return $errors;
  563. }
  564. /**
  565. * Validate filesize for directory quota.
  566. */
  567. function imce_validate_quota($file, $quota = 0, $currentsize = 0) {
  568. $errors = array();
  569. if ($quota && ($currentsize + $file->filesize) > $quota) {
  570. $errors[] = t('%filename is %filesize which would exceed your directory quota. You are currently using %size of %total_quota.', array('%size' => format_size($currentsize), '%total_quota' => format_size($quota), '%filesize' => format_size($file->filesize), '%filename' => utf8_encode($file->filename)));
  571. }
  572. return $errors;
  573. }
  574. /**
  575. * Validate filesize for total user quota.
  576. */
  577. function imce_validate_tuquota($file, $quota = 0, $currentsize = 0) {
  578. $errors = array();
  579. if ($quota && ($currentsize + $file->filesize) > $quota) {
  580. $errors[] = t('%filename is %filesize which would exceed your total user quota. You are currently using %size of %total_quota.', array('%size' => format_size($currentsize), '%total_quota' => format_size($quota), '%filesize' => format_size($file->filesize), '%filename' => utf8_encode($file->filename)));
  581. }
  582. return $errors;
  583. }
  584. /**
  585. * Validate both directory and total user quota. Returns true/false not errors.
  586. */
  587. function imce_validate_quotas($file, &$imce, $add = 0) {
  588. $errors = imce_validate_quota($file, $imce['quota'], $imce['dirsize'] + $add);
  589. if (empty($errors) && $imce['tuquota']) {
  590. $errors = imce_validate_tuquota($file, $imce['tuquota'], file_space_used($imce['uid']) + $add);
  591. }
  592. if (!empty($errors)) {
  593. drupal_set_message($errors[0], 'error');
  594. return FALSE;
  595. }
  596. return TRUE;
  597. }
  598. /**
  599. * Checks if the file is an image and returns info.
  600. * There are two switchable versions that use image_get_info() and getimagesize()
  601. */
  602. if (variable_get('imce_image_get_info', 0)) {
  603. function imce_image_info($file) {
  604. $mimes = array('image/jpeg' => IMAGETYPE_JPEG, 'image/gif' => IMAGETYPE_GIF, 'image/png' => IMAGETYPE_PNG);
  605. if (is_file($file) && ($dot = strrpos($file, '.')) && in_array(strtolower(substr($file, $dot+1)), array('jpg', 'jpeg', 'gif', 'png')) && ($info = @image_get_info($file)) && isset($mimes[$info['mime_type']]) ) {
  606. return array('width' => $info['width'], 'height' => $info['height'], 'type' => $mimes[$info['mime_type']], 'mime' => $info['mime_type']);
  607. }
  608. return FALSE;
  609. }
  610. }
  611. else {
  612. function imce_image_info($file) {
  613. if (is_file($file) && ($dot = strrpos($file, '.')) && in_array(strtolower(substr($file, $dot+1)), array('jpg', 'jpeg', 'gif', 'png')) && ($info = @getimagesize($file)) && in_array($info[2], array(IMAGETYPE_JPEG, IMAGETYPE_GIF, IMAGETYPE_PNG)) ) {
  614. return array('width' => $info[0], 'height' => $info[1], 'type' => $info[2], 'mime' => $info['mime']);
  615. }
  616. return FALSE;
  617. }
  618. }
  619. /**
  620. * Return thumbnails as options to be used in upload form.
  621. */
  622. function imce_thumbnail_options($thumbs = array()) {
  623. $options = array();
  624. foreach ($thumbs as $thumb) {
  625. $options[$thumb['name']] = $thumb['name'] . ' (' . $thumb['dimensions'] . ')';
  626. }
  627. return $options;
  628. }
  629. /**
  630. * Initiate and return configuration profile for the $user.
  631. */
  632. function imce_initiate_profile($user, $scheme = NULL) {
  633. //check user profile and translate tokens in directory paths and evaluate php paths.
  634. if ($imce = imce_user_profile($user, $scheme)) {
  635. // Allow alteration of raw profile
  636. foreach (variable_get('imce_custom_init', array()) as $func => $state) {
  637. if ($state && function_exists($func)) {
  638. $func($imce, $user);
  639. }
  640. }
  641. imce_process_directories($imce, $user);
  642. if (!empty($imce['directories'])) {
  643. $imce['uid'] = (int) $user->uid;
  644. $imce['url'] = url($_GET['q']);
  645. $imce['clean'] = variable_get('clean_url', 0) == 1;
  646. $imce['absurls'] = variable_get('imce_settings_absurls', 0) == 1;
  647. $imce['furl'] = file_create_url($imce['scheme'] . '://');
  648. $imce['filesize'] *= 1048576;//convert from Mb to byte
  649. $imce['quota'] *= 1048576;
  650. $imce['tuquota'] *= 1048576;
  651. $imce['filenum'] = (int) $imce['filenum'];
  652. //check and set the active directory
  653. if ($info = imce_working_directory($imce)) {
  654. $imce['direct'] = isset($imce['directories'][$info['name']]);
  655. $imce['directories'][$info['name']] = $info;
  656. $imce['dir'] = $info['name'];
  657. $imce['perm'] = $info;//copy permissions of the active directory.
  658. unset($imce['perm']['name']);
  659. }
  660. else {
  661. drupal_set_message(t('Unable to get a working directory for the file browser!'), 'error');
  662. $imce['dir'] = FALSE;
  663. $imce['error'] = TRUE;
  664. }
  665. return $imce;
  666. }
  667. drupal_set_message(t('There is no valid directory specified for the file browser!'), 'error');
  668. }
  669. else {
  670. drupal_set_message(t('You do not have access to any configuration profile to use the file browser!'), 'error');
  671. }
  672. return FALSE;
  673. }
  674. /**
  675. * Get files and folders of the actve directory. Do custom processing.
  676. */
  677. function imce_process_profile(&$imce) {
  678. //get directory content. do a custom scan if it is set
  679. $scan = ($scan = variable_get('imce_custom_scan', '')) && function_exists($scan) ? $scan : 'imce_scan_directory';
  680. $imce += $scan($imce['dir'], $imce);
  681. //run custom process functions
  682. foreach (variable_get('imce_custom_process', array()) as $func => $state) {
  683. if ($state && function_exists($func)) {
  684. $func($imce);
  685. }
  686. }
  687. //set subdirectories
  688. if (!$imce['error'] && !imce_subdirectories_accessible($imce)) {
  689. $imce['subdirectories'] = array();
  690. }
  691. }
  692. /**
  693. * Translate tokens and evaluate php in directory names.
  694. * Convert directories into an associative array (dirname => info)
  695. */
  696. function imce_process_directories(&$imce, $user) {
  697. $directories = $imce['directories'];
  698. $paths = array();
  699. $translate = array('%uid' => $user->uid);
  700. foreach ($directories as $directory) {
  701. if (substr($directory['name'], 0, 4) == 'php:') {
  702. $directory['name'] = eval(substr($directory['name'], 4));
  703. //php may return an array of directories
  704. if (is_array($directory['name'])) {
  705. foreach ($directory['name'] as $name) {
  706. $paths[$name] = array('name' => $name) + $directory;
  707. }
  708. continue;
  709. }
  710. }
  711. else {
  712. $directory['name'] = strtr($directory['name'], $translate);
  713. }
  714. if ($directory['name']) {
  715. $paths[$directory['name']] = $directory;
  716. }
  717. }
  718. $imce['directories'] = $paths;
  719. }
  720. /**
  721. * Return an available directory for the profile.
  722. */
  723. function imce_working_directory(&$imce) {
  724. //Do not use session if there is only one directory assigned.
  725. $sess = TRUE;
  726. if (count($imce['directories']) < 2) {
  727. $perms = reset($imce['directories']);
  728. if (!isset($perms['subnav']) || !$perms['subnav']) {
  729. $sess = FALSE;
  730. }
  731. }
  732. //check GET.
  733. if (isset($_GET['dir'])) {
  734. if ($info = imce_directory_info($_GET['dir'], $imce)) {
  735. if (imce_check_directory($_GET['dir'], $imce)) {
  736. if ($sess) {
  737. $_SESSION['imce_directory'] = rawurlencode($info['name']);
  738. }
  739. }
  740. else {
  741. $info = FALSE;
  742. }
  743. }
  744. else {
  745. imce_inaccessible_directory($_GET['dir'], $imce);
  746. }
  747. return $info;
  748. }
  749. //check session
  750. if ($sess && isset($_SESSION['imce_directory'])) {
  751. $dirname = rawurldecode($_SESSION['imce_directory']);
  752. if ($info = imce_directory_info($dirname, $imce)) {
  753. if (imce_check_directory($dirname, $imce)) {
  754. return $info;
  755. }
  756. }
  757. }
  758. //or the whole list.
  759. foreach ($imce['directories'] as $dirname => $info) {
  760. $dirname = (string) $dirname;
  761. if (imce_check_directory($dirname, $imce)) {
  762. if ($sess) {
  763. $_SESSION['imce_directory'] = rawurlencode($dirname);
  764. }
  765. return $info;
  766. }
  767. }
  768. return FALSE;
  769. }
  770. /**
  771. * Create a writable directory(any level) under file system directory.
  772. */
  773. function imce_check_directory($dirname, $imce) {
  774. $diruri = imce_dir_uri($imce, $dirname);
  775. if (!imce_reg_dir($dirname) || !file_prepare_directory($diruri, FILE_CREATE_DIRECTORY)) {
  776. return imce_inaccessible_directory($dirname, $imce);
  777. }
  778. return TRUE;
  779. }
  780. /**
  781. * Generate and log a directory access error.
  782. */
  783. function imce_inaccessible_directory($dirname, $imce) {
  784. if (is_string($dirname)) {
  785. $dirname = utf8_encode($dirname);
  786. $diruri = imce_dir_uri($imce, $dirname);
  787. drupal_set_message(t('Directory %dirname is not accessible.', array('%dirname' => $dirname)), 'error');
  788. watchdog('imce', 'Access to %directory was denied.', array('%directory' => $diruri), WATCHDOG_ERROR);
  789. }
  790. return FALSE;
  791. }
  792. /**
  793. * Return the permissions for a directory that is accessed directly or indirectly.
  794. * A child of a predefined directory in the directory list takes its parent's properties.
  795. * If it has multiple parents, it gets the properties of the latter in the list.
  796. */
  797. function imce_directory_info($dirname, $imce) {
  798. if (isset($imce['directories'][$dirname])) {
  799. return $imce['directories'][$dirname];
  800. }
  801. $info = FALSE;
  802. if (imce_reg_dir($dirname)) {
  803. $diruri = imce_dir_uri($imce, $dirname);
  804. if (file_prepare_directory($diruri)) {
  805. foreach ($imce['directories'] as $name => $prop) {
  806. if ($prop['subnav'] && ($name === '.' || strpos($dirname . '/', $name . '/') === 0)) {
  807. $info = $prop;
  808. $info['name'] = $dirname;
  809. }
  810. }
  811. }
  812. }
  813. return $info;
  814. }
  815. /**
  816. * Detect if the subdirectories are accessible through any directory(not just the current one) in the list.
  817. */
  818. function imce_subdirectories_accessible(&$imce) {
  819. if (!empty($imce['subdirectories'])) {
  820. if (!empty($imce['perm']['subnav'])) {
  821. return TRUE;
  822. }
  823. //checking only the first one is sufficient.
  824. $dirname = reset($imce['subdirectories']);
  825. if ($imce['dir'] !== '.') {
  826. $dirname = $imce['dir'] . '/' . $dirname;
  827. }
  828. //check if any setting is applicable for this subdirectory through any directory in the list.
  829. foreach ($imce['directories'] as $name => $info) {
  830. $name = (string) $name;
  831. if ($info['subnav'] && $dirname != $name && ($name == '.' || strpos($dirname . '/', $name . '/') === 0)) {
  832. return TRUE;
  833. }
  834. }
  835. }
  836. return FALSE;
  837. }
  838. /**
  839. * Check if a permission is given to at least one directory in the list.
  840. */
  841. function imce_perm_exists(&$imce, $perm) {
  842. static $perms = array();
  843. if (isset($perms[$perm])) {
  844. return $perms[$perm];
  845. }
  846. if (isset($imce['perm'][$perm]) && $imce['perm'][$perm]) {
  847. return $perms[$perm] = TRUE;
  848. }
  849. foreach ($imce['directories'] as $name => $info) {
  850. if (isset($info[$perm]) && $info[$perm]) {
  851. return $perms[$perm] = TRUE;
  852. }
  853. }
  854. return $perms[$perm] = FALSE;
  855. }
  856. /**
  857. * Scan directory and return file list, subdirectories, and total size.
  858. */
  859. function imce_scan_directory($dirname, $imce) {
  860. $directory = array('dirsize' => 0, 'files' => array(), 'subdirectories' => array(), 'error' => FALSE);
  861. $diruri = imce_dir_uri($imce, $dirname);
  862. if (!is_string($dirname) || $dirname == '' || !$handle = opendir($diruri)) {
  863. imce_inaccessible_directory($dirname, $imce);
  864. $directory['error'] = TRUE;
  865. return $directory;
  866. }
  867. while (($file = readdir($handle)) !== FALSE) {
  868. // Do not include dot files and folders
  869. if (substr($file, 0, 1) === '.') {
  870. continue;
  871. }
  872. $path = $diruri . $file;
  873. if (is_dir($path)) {
  874. $directory['subdirectories'][] = $file;
  875. continue;
  876. }
  877. $width = $height = 0;
  878. if ($img = imce_image_info($path)) {
  879. $width = $img['width'];
  880. $height = $img['height'];
  881. }
  882. $size = filesize($path);
  883. $date = filemtime($path);
  884. $directory['files'][$file] = array(
  885. 'name' => $file,
  886. 'size' => $size,
  887. 'width' => $width,
  888. 'height' => $height,
  889. 'date' => $date
  890. );
  891. $directory['dirsize'] += $size;
  892. }
  893. closedir($handle);
  894. sort($directory['subdirectories']);
  895. return $directory;
  896. }
  897. /**
  898. * Create directory tree.
  899. */
  900. function imce_create_tree(&$imce) {
  901. $paths = array();
  902. //rearrange paths as arg0=>arg1=>...
  903. foreach ($imce['directories'] as $path => $arr) {
  904. $tmp =& $paths;
  905. if ($path != '.') {
  906. $args = explode('/', $path);
  907. foreach ($args as $arg) {
  908. if (!isset($tmp[$arg])) {
  909. $tmp[$arg] = array();
  910. }
  911. $tmp =& $tmp[$arg];
  912. }
  913. $tmp[':access:'] = TRUE;
  914. }
  915. if ("$path" == $imce['dir']) {
  916. $tmp[':active:'] = TRUE;
  917. foreach ($imce['subdirectories'] as $arg) {
  918. $tmp[$arg][':access:'] = TRUE;
  919. }
  920. }
  921. }
  922. //set root branch
  923. $root = theme('imce_root_text', array('imce_ref' => array('imce' => &$imce)));
  924. $q = $imce['clean'] ? '?' : '&';
  925. if (isset($imce['directories']['.'])) {
  926. $root = '<a href="' . $imce['url'] . $q . 'dir=." title="." class="folder' . ($imce['dir'] == '.' ? ' active' : '') . '">' . $root . '</a>';
  927. }
  928. else {
  929. $root = '<a title="." class="folder disabled">' . $root . '</a>';
  930. }
  931. return $root . imce_tree_html($imce, $paths, $q);
  932. }
  933. /**
  934. * Return tree html.
  935. * This is not themable because it is complex and needs to be in a proper format for js processing.
  936. */
  937. function imce_tree_html(&$imce, $paths, $q = '?', $prefix = '', $eprefix = '') {
  938. unset($paths[':access:'], $paths[':active:']);
  939. $html = '';
  940. foreach ($paths as $arg => $children) {
  941. $path = $prefix . $arg;
  942. $earg = rawurlencode($arg);
  943. $epath = $eprefix . $earg;
  944. if (isset($children[':access:']) || imce_directory_info($path, $imce)) {
  945. $a = '<a href="' . $imce['url'] . $q . 'dir=' . $epath . '" title="' . $epath . '" class="folder' . (isset($children[':active:']) ? ' active' : '') . '">' . $earg . '</a>';
  946. }
  947. else {
  948. $a = '<a title="' . $epath . '" class="folder disabled">' . $earg . '</a>';
  949. }
  950. $ul = imce_tree_html($imce, $children, $q, $path . '/', $epath . '/');
  951. $class = $ul ? ' class="expanded"' : (isset($children[':active:']) ? ' class="leaf"' : '');
  952. $html .= '<li' . $class . '>' . $a . $ul . '</li>';
  953. }
  954. if ($html) {
  955. $html = '<ul>' . $html . '</ul>';
  956. }
  957. return $html;
  958. }
  959. /**
  960. * Return the uri of the active directory
  961. */
  962. function imce_dir_uri($imce, $dir = NULL) {
  963. if (!isset($dir)) {
  964. $dir = $imce['dir'];
  965. }
  966. $target = $dir === '.' ? '' : $dir;
  967. $uri = $imce['scheme'] . '://' . $target;
  968. // Uri is already normalized. Call alterers.
  969. drupal_alter('file_stream_wrapper_uri_normalize', $uri, $imce['scheme'], $target);
  970. // Add the slash
  971. if (substr($uri, -1) !== '/') {
  972. $uri .= '/';
  973. }
  974. return $uri;
  975. }
  976. /**
  977. * Returns the text for the root directory in a directory tree.
  978. */
  979. function theme_imce_root_text($variables) {
  980. //$imce = &$variables['imce_ref']['imce'];
  981. return '&lt;' . t('root') . '&gt;';
  982. }
  983. /**
  984. * Returns the html for user's file browser tab.
  985. */
  986. function theme_imce_user_page($variables) {
  987. global $user;
  988. $account = $variables['account'];
  989. $options = array();
  990. //switch to account's active folder
  991. if ($user->uid == 1 && $account->uid != 1) {
  992. $imce = imce_initiate_profile($account);
  993. $options['query'] = array('dir' => $imce['dir']);
  994. }
  995. return '<iframe src="' . url('imce', $options) . '" frameborder="0" style="border: 1px solid #eee; width: 99%; height: 520px" class="imce-frame"></iframe>';
  996. }
  997. /**
  998. * Registers the file as an IMCE file.
  999. */
  1000. function imce_file_register($file) {
  1001. if (!db_query("SELECT 1 FROM {file_usage} WHERE module = 'imce' AND fid = :fid", array(':fid' => $file->fid))->fetchField()) {
  1002. file_usage_add($file, 'imce', 'file', $file->fid);
  1003. }
  1004. }