Projet

Général

Profil

Paste
Télécharger (33,9 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / imce / inc / imce.page.inc @ 6eb8d15f

1
<?php
2

    
3
/**
4
 * @file
5
 * Implements the file browser.
6
 */
7

    
8
/**
9
 * q = imce.
10
 */
11
function imce($scheme = NULL) {
12
  module_invoke('admin_menu', 'suppress');//suppress admin_menu
13
  $jsop = isset($_GET['jsop']) ? $_GET['jsop'] : NULL;
14
  drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
15
  print imce_page($GLOBALS['user'], $scheme, $jsop);
16
  exit();
17
}
18

    
19
/**
20
 * q = user/x/imce.
21
 */
22
function imce_user_page($account) {
23
  return theme('imce_user_page', array('account' => $account));
24
}
25

    
26
/**
27
 * Returns the imce page for the specified user and the file scheme.
28
 */
29
function imce_page($user, $scheme = NULL, $jsop = NULL) {
30
  return theme('imce_page', array('content' => imce_content($user, $scheme, $jsop)));
31
}
32

    
33
/**
34
 * Returns the content of the file browser.
35
 */
36
function imce_content($user, $scheme = NULL, $jsop = NULL) {
37

    
38
  //execute ajax calls.
39
  if ($jsop) {
40
    return imce_js($user, $scheme, $jsop);
41
  }
42

    
43
  //initiate configuration profile
44
  if (!$imce = imce_initiate_profile($user, $scheme)) {
45
    return '';
46
  }
47
  imce_process_profile($imce);//get active directory content
48

    
49
  //Before creating the content let's add main files required for imce to function properly.
50
  $path = drupal_get_path('module', 'imce');
51
  drupal_add_js($path . '/js/jquery.form.js');
52
  drupal_add_js($path . '/js/imce.js');
53
  drupal_add_js($path . '/js/imce_extras.js');
54
  drupal_add_css($path . '/css/imce-content.css');
55

    
56
  //process forms.
57
  $imce_ref = array('imce' => &$imce);
58
  $forms = array();
59
  if (!$imce['error']) {
60
    //process file upload.
61
    if (imce_perm_exists($imce, 'upload')) {
62
      $forms[] = drupal_get_form('imce_upload_form', $imce_ref);
63
    }
64
    //process file operations.
65
    $forms[] = drupal_get_form('imce_fileop_form', $imce_ref);
66
  }
67
  $forms = drupal_render($forms);
68

    
69
  //run custom content functions. possible to insert extra forms. content is invisible when js is enabled.
70
  foreach (variable_get('imce_custom_content', array()) as $func => $state) {
71
    if ($state && function_exists($func) && $output = $func($imce)) {
72
      $forms .= $output;
73
    }
74
  }
75

    
76
  $content = theme('imce_content', array(
77
    'tree' => imce_create_tree($imce),
78
    'forms' => $forms,
79
    'imce_ref' => $imce_ref,
80
  ));
81

    
82
  //make necessary changes for js conversion
83
  $imce['dir'] = str_replace('%2F', '/', rawurlencode($imce['dir']));
84
  unset($imce['files'], $imce['name'], $imce['directories'], $imce['subdirectories'], $imce['filesize'], $imce['quota'], $imce['tuquota'], $imce['thumbnails'], $imce['uid'], $imce['usertab']);
85

    
86
  drupal_add_js($imce_ref, 'setting');
87

    
88
  return $content;
89
}
90

    
91
/**
92
 * Ajax operations. q=imce&jsop={op}
93
 */
94
function imce_js($user, $scheme, $jsop = '') {
95
  $response = array();
96

    
97
  //data
98
  if ($imce = imce_initiate_profile($user, $scheme)) {
99
    imce_process_profile($imce);
100
    if (!$imce['error']) {
101
      module_load_include('inc', 'imce', 'inc/imce.js');
102
      if (function_exists($func = 'imce_js_' . $jsop)) {
103
        $response['data'] = $func($imce);
104
      }
105
      // Allow alteration of response.
106
      foreach (variable_get('imce_custom_response', array()) as $func => $state) {
107
        if ($state && function_exists($func)) {
108
          $func($jsop, $response, $imce, $user);
109
        }
110
      }
111
    }
112
  }
113
  //messages
114
  $response['messages'] = drupal_get_messages();
115

    
116
  //disable devel log.
117
  $GLOBALS['devel_shutdown'] = FALSE;
118
  //for upload we must return plain text header.
119
  drupal_add_http_header('Content-Type', (!empty($_POST['html_response']) ? 'text/html' : 'application/json') . '; charset=utf-8');
120
  print drupal_json_encode($response);
121
  exit();
122
}
123

    
124
/**
125
 * Upload form.
126
 */
127
function imce_upload_form($form, &$form_state, $ref) {
128
  $imce =& $ref['imce'];
129
  $form['imce'] = array(
130
    '#type' => 'file',
131
    '#title' => t('File'),
132
    '#size' => 30,
133
  );
134
  if (!empty($imce['thumbnails'])) {
135
    $form['thumbnails'] = array(
136
      '#type' => 'checkboxes',
137
      '#title' => t('Create thumbnails'),
138
      '#options' => imce_thumbnail_options($imce['thumbnails']),
139
    );
140
  }
141
  $form['upload'] = array(
142
    '#type' => 'submit',
143
    '#value' => t('Upload'),
144
    '#submit' => $imce['perm']['upload'] ? array('imce_upload_submit') : NULL,
145
  );
146
  $form = array('fset_upload' => array('#type' => 'fieldset', '#title' => t('Upload file')) + $form);
147
  $form['html_response'] = array('#type' => 'hidden', '#default_value' => '1');
148
  $form['#attributes']['enctype'] = 'multipart/form-data';
149
  $form['#action'] = $imce['url'];
150
  return $form;
151
}
152

    
153
/**
154
 * File operations form.
155
 */
156
function imce_fileop_form($form, &$form_state, $ref) {
157
  $imce =& $ref['imce'];
158
  $form['filenames'] = array(
159
    '#type' => 'textfield',
160
    '#title' => t('Selected files'),
161
    '#maxlength' => $imce['filenum'] ? $imce['filenum']*255 : NULL,
162
  );
163

    
164
  //thumbnail
165
  if (!empty($imce['thumbnails']) && imce_perm_exists($imce, 'thumb')) {
166
    $form['fset_thumb'] = array(
167
      '#type' => 'fieldset',
168
      '#title' => t('Thumbnails'),
169
    ) + imce_thumb_form($imce);
170
  }
171

    
172
  //delete
173
  if (imce_perm_exists($imce, 'delete')) {
174
    $form['fset_delete'] = array(
175
      '#type' => 'fieldset',
176
      '#title' => t('Delete'),
177
    ) + imce_delete_form($imce);
178
  }
179

    
180
  //resize
181
  if (imce_perm_exists($imce, 'resize')) {
182
    $form['fset_resize'] = array(
183
      '#type' => 'fieldset',
184
      '#title' => t('Resize'),
185
    ) + imce_resize_form($imce);
186
  }
187
 
188
  $form['#action'] = $imce['url'];
189
  return $form;
190
}
191

    
192
/**
193
 * Thumbnail form.
194
 */
195
function imce_thumb_form(&$imce) {
196
  $form['thumbnails'] = array(
197
    '#type' => 'checkboxes',
198
    '#title' => t('Thumbnails'),
199
    '#options' => imce_thumbnail_options($imce['thumbnails']),
200
  );
201
  $form['thumb'] = array(
202
    '#type' => 'submit',
203
    '#value' => t('Create thumbnails'),
204
    '#submit' => $imce['perm']['thumb'] ? array('imce_thumb_submit') : NULL,
205
  );
206
  return $form;
207
}
208

    
209
/**
210
 * Delete form.
211
 */
212
function imce_delete_form(&$imce) {
213
  $form['delete'] = array(
214
    '#type' => 'submit',
215
    '#value' => t('Delete'),
216
    '#submit' => $imce['perm']['delete'] ? array('imce_delete_submit') : NULL,
217
  );
218
  return $form;
219
}
220

    
221
/**
222
 * Resizing form.
223
 */
224
function imce_resize_form(&$imce) {
225
  $form['width'] = array(
226
    '#type' => 'textfield',
227
    '#title' => t('Width x Height'),
228
    '#size' => 5,
229
    '#maxlength' => 4,
230
    '#prefix' => '<div class="container-inline">',
231
  );
232
  $form['height'] = array(
233
    '#type' => 'textfield',
234
    '#size' => 5,
235
    '#maxlength' => 4,
236
    '#prefix' => 'x',
237
  );
238
  $form['resize'] = array(
239
    '#type' => 'submit',
240
    '#value' => t('Resize'),
241
    '#submit' => $imce['perm']['resize'] ? array('imce_resize_submit') : NULL,//permission for submission
242
    '#suffix' => '</div>',
243
  );
244
  $form['copy'] = array(
245
    '#type' => 'checkbox',
246
    '#title' => t('Create a new image'),
247
    '#default_value' => 1,
248
  );
249
  return $form;
250
}
251

    
252
/**
253
 * Validate file operations form.
254
 */
255
function imce_fileop_form_validate($form, &$form_state) {
256
  $imce =& $form_state['build_info']['args'][0]['imce'];
257

    
258
  //check if the filenames is empty
259
  if ($form_state['values']['filenames'] == '') {
260
    return form_error($form['filenames'], t('Please select a file.'));
261
  }
262

    
263
  //filenames come separated by colon
264
  $filenames = explode(':', $form_state['values']['filenames']);
265
  $cnt = count($filenames);
266
  //check the number of files.
267
  if ($imce['filenum'] && $cnt > $imce['filenum']) {
268
    return form_error($form['filenames'], t('You are not allowed to operate on more than %num files.', array('%num' => $imce['filenum'])));
269
  }
270

    
271
  //check if there is any illegal choice
272
  for ($i = 0; $i < $cnt; $i++) {
273
    $filenames[$i] = $filename = rawurldecode($filenames[$i]);
274
    if (!isset($imce['files'][$filename])) {
275
      watchdog('imce', 'Illegal choice %choice in !name element.', array('%choice' => $filename, '!name' => t('directory (%dir)', array('%dir' => imce_dir_uri($imce)))), WATCHDOG_ERROR);
276
      return form_error($form['filenames'], t('An illegal choice has been detected. Please contact the site administrator.'));
277
    }
278
  }
279

    
280
  $form_state['values']['filenames'] = $filenames;
281
}
282

    
283
/**
284
 * Submit upload form.
285
 */
286
function imce_upload_submit($form, &$form_state) {
287
  $form_state['redirect'] = FALSE;
288
  $imce =& $form_state['build_info']['args'][0]['imce'];
289
  // Need to provide extension validatior, otherwise file_save_upload uses the default.
290
  $validators['file_validate_extensions'] = array($imce['extensions'] === '*' ? NULL : $imce['extensions']);
291
  $validators['imce_validate_all'] = array(&$imce);
292
  $diruri = imce_dir_uri($imce);
293

    
294
  //save uploaded file.
295
  $replace = variable_get('imce_settings_replace', FILE_EXISTS_RENAME);
296
  if ($file = file_save_upload('imce', $validators, $diruri, $replace)) {
297

    
298
    //core bug #54223.
299
    if ($replace == FILE_EXISTS_RENAME) {
300
      $name = basename($file->uri);
301
      if ($name != $file->filename) {
302
        $file->filename = $name;
303
        drupal_set_message(t('The file has been renamed to %filename.', array('%filename' => $file->filename)));
304
      }
305
    }
306

    
307
    $file->uid = $imce['uid'];//global user may not be the owner.
308
    $file->status = FILE_STATUS_PERMANENT;
309
    file_save($file);
310
    imce_file_register($file);
311
    drupal_set_message(t('%filename has been uploaded.', array('%filename' => $file->filename)));
312

    
313
    //update file list
314
    $img = imce_image_info($file->uri);
315
    $file->width = $img ? $img['width'] : 0;
316
    $file->height = $img ? $img['height'] : 0;
317
    imce_add_file($file, $imce);
318

    
319
    //create thumbnails
320
    if (isset($form_state['values']['thumbnails']) && $img) {
321
      imce_create_thumbnails($file->filename, $imce, $form_state['values']['thumbnails']);
322
    }
323
  }
324
  else {
325
    drupal_set_message(t('Upload failed.'), 'error');
326
  }
327
}
328

    
329
/**
330
 * Submit thumbnail form.
331
 */
332
function imce_thumb_submit($form, &$form_state) {
333
  $form_state['redirect'] = FALSE;
334
  $imce =& $form_state['build_info']['args'][0]['imce'];
335
  //create thumbnails
336
  imce_process_files($form_state['values']['filenames'], $imce, 'imce_create_thumbnails', array($form_state['values']['thumbnails']));
337
}
338

    
339
/**
340
 * Submit delete form.
341
 */
342
function imce_delete_submit($form, &$form_state) {
343
  $form_state['redirect'] = FALSE;
344
  $imce =& $form_state['build_info']['args'][0]['imce'];
345

    
346
  $deleted = imce_process_files($form_state['values']['filenames'], $imce, 'imce_delete_file');
347

    
348
  if (!empty($deleted)) {
349
    drupal_set_message(t('File deletion successful: %files.', array('%files' => utf8_encode(implode(', ', $deleted)))));
350
  }
351

    
352
}
353

    
354
/**
355
 * Submit resize form.
356
 */
357
function imce_resize_submit($form, &$form_state) {
358
  $form_state['redirect'] = FALSE;
359
  $imce =& $form_state['build_info']['args'][0]['imce'];
360

    
361
  //check dimensions
362
  $width = (int) $form_state['values']['width'];
363
  $height = (int) $form_state['values']['height'];
364
  list($maxw, $maxh) = $imce['dimensions'] ? explode('x', $imce['dimensions']) : array(0, 0);
365
  if ($width < 1 || $height < 1 || ($maxw && ($width > $maxw || $height > $maxh))) {
366
    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');
367
    return;
368
  }
369

    
370
  $resized = imce_process_files($form_state['values']['filenames'], $imce, 'imce_resize_image', array($width, $height, $form_state['values']['copy']));
371

    
372
  if (!empty($resized)) {
373
    drupal_set_message(t('File resizing successful: %files.', array('%files' => utf8_encode(implode(', ', $resized)))));
374
  }
375

    
376
}
377

    
378
/**
379
 * Do batch operations on files.
380
 * Used by delete, resize, create thumbnail submissions.
381
 */
382
function imce_process_files($filenames, &$imce, $function, $args = array()) {
383
  $args = array_merge(array('', &$imce), $args);
384
  $processed = array();
385

    
386
  foreach ($filenames as $filename) {
387
    $args[0] = $filename;
388
    if (call_user_func_array($function, $args)) {
389
      $processed[] = $filename;
390
    }
391
  }
392

    
393
  return $processed;
394
}
395

    
396
/**
397
 * Deletes a file in the file list.
398
 */
399
function imce_delete_file($filename, &$imce) {
400
  $uri = imce_dir_uri($imce) . $filename;
401
  if (!imce_delete_filepath($uri)) {
402
    return FALSE;
403
  }
404
  imce_remove_file($filename, $imce);
405
  return TRUE;
406
}
407

    
408
/**
409
 * Deletes a file by uri.
410
 */
411
function imce_delete_filepath($uri) {
412
  $file = file_load_multiple(array(), array('uri' => $uri));
413
  $file = reset($file);
414

    
415
  // File exists in database
416
  if ($file) {
417
    $usage = file_usage_list($file);
418
    $is_imce = isset($usage['imce']);
419
    unset($usage['imce']);
420
    // File is in use by an other module.
421
    if (!empty($usage)) {
422
      drupal_set_message(t('%filename is in use by another application.', array('%filename' => $file->filename)), 'error');
423
      return FALSE;
424
    }
425
    // Force delete file. Prevent running file_usage_list() second time.
426
    if (!file_delete($file, TRUE)) {
427
      return FALSE;
428
    }
429
  }
430
  // Not in db. Probably loaded via ftp.
431
  elseif (!file_unmanaged_delete($uri)) {
432
    return FALSE;
433
  }
434

    
435
  return TRUE;
436
}
437

    
438
/**
439
 * Create all selected thumbnails.
440
 */
441
function imce_create_thumbnails($filename, &$imce, $values) {
442
  $created = array();
443
  foreach ($imce['thumbnails'] as $thumbnail) {
444
    if ($values[$thumbnail['name']] && imce_create_thumbnail($filename, $imce, $thumbnail)) {
445
      $created[] = $thumbnail['name'];
446
    }
447
  }
448
  if (!empty($created)) {
449
  drupal_set_message(t('Thumbnail creation (%thumbnames) successful for %filename.', array('%thumbnames' => implode(', ', $created), '%filename' => utf8_encode($filename))));
450
  }
451
  return $created;
452
}
453

    
454
/**
455
 * Create a thumbnail.
456
 */
457
function imce_create_thumbnail($filename, &$imce, $thumbnail) {
458
  //generate thumbnail name
459
  $name = $thumbnail['prefix'];
460
  if ($thumbnail['suffix'] != '' && $dot = strrpos($filename, '.')) {
461
    $name .= substr($filename, 0, $dot);
462
    $name .= $thumbnail['suffix'];
463
    $name .= substr($filename, $dot);
464
  }
465
  else {
466
    $name .= $filename;
467
  }
468
  //scale the image
469
  list($width, $height) = explode('x', $thumbnail['dimensions']);
470
  return imce_resize_image($filename, $imce, $width, $height, TRUE, $name, variable_get('imce_settings_thumb_method', 'scale_and_crop'));
471
}
472

    
473
/**
474
 * Resize an image in the file list. Also used for thumbnail creation.
475
 */
476
function imce_resize_image($filename, &$imce, $width, $height, $copy = TRUE, $destname = FALSE, $op = 'resize') {
477
  $destdir = imce_dir_uri($imce);
478
  $imguri = $destdir . $filename;
479

    
480
  //check if the file is an image
481
  if (!$imce['files'][$filename]['width'] || !$img = imce_image_info($imguri)) {
482
    drupal_set_message(t('%filename is not an image.', array('%filename' => utf8_encode($filename))), 'error', FALSE);
483
    return FALSE;
484
  }
485

    
486
  if (substr($op, 0, 5) == 'scale' && !($width < $img['width'] || $height < $img['height'])) {
487
    drupal_set_message(t('Scaling up is not allowed.'), 'error', FALSE);
488
    return FALSE;
489
  }
490

    
491
  //create file object
492
  $file = new stdClass();
493
  $file->uri = $destdir . $destname;
494
  if (!$destname || $destname == $filename) {
495
    $file->uri = $copy ? file_create_filename($filename, $destdir) : $imguri;
496
  }
497
  $file->filename = basename($file->uri);
498

    
499
  //check if a file having the same properties exists already.
500
  if (isset($imce['files'][$file->filename])) {
501
    if (($f = $imce['files'][$file->filename]) && $f['width'] == $width && $f['height'] == $height) {
502
      drupal_set_message(t('%filename(%dimensions) already exists.', array('%filename' => utf8_encode($file->filename), '%dimensions' => $width . 'x' . $height)), 'error');
503
      return FALSE;
504
    }
505
  }
506

    
507
  //validate file name
508
  $errors = file_validate_name_length($file);
509
  if (!empty($errors)) {
510
    drupal_set_message($errors[0], 'error');
511
    return FALSE;
512
  }
513

    
514
  //resize image
515
  $image = image_load($imguri);
516
  $function = 'image_' . $op;
517
  if (!$image || !function_exists($function) || !$function($image, $width, $height)) {
518
    drupal_set_message(t('%filename cannot be resized to %dimensions', array('%filename' => utf8_encode($filename), '%dimensions' => $width . 'x' . $height)), 'error', FALSE);
519
    return FALSE;
520
  }
521

    
522
  //copy to a temp file
523
  if (!$tempuri = drupal_tempnam('temporary://', 'imce')) {
524
    return FALSE;
525
  }
526
  register_shutdown_function('file_unmanaged_delete', $tempuri);
527
  if (!image_save($image, $tempuri) || !$image->info) {
528
    return FALSE;
529
  }
530

    
531
  //validate quota
532
  $file->filesize = $image->info['file_size'];
533
  $quotadiff = $file->filename == $filename ? -$imce['files'][$filename]['size'] : 0;
534
  if (!imce_validate_quotas($file, $imce, $quotadiff)) {
535
    return FALSE;
536
  }
537

    
538
  //build the rest of the file object
539
  $file->uid = $imce['uid'];
540
  $file->filemime = $img['mime'];
541
  $file->status = FILE_STATUS_PERMANENT;
542
  $file->timestamp = REQUEST_TIME;
543

    
544
  //copy from temp to file uri
545
  $destination = $file->uri;
546
  $file->uri = $tempuri;
547
  if (!$file = file_copy($file, $destination, FILE_EXISTS_REPLACE)) {
548
    return FALSE;
549
  }
550
  imce_file_register($file);
551

    
552
  //update file list
553
  //if the file was scaled get the new dimensions
554
  if ($op == 'scale') {
555
    $img = imce_image_info($file->uri);
556
    $width = $img['width'];
557
    $height = $img['height'];
558
  }
559
  $file->width = $width;
560
  $file->height = $height;
561
  imce_add_file($file, $imce);
562

    
563
  return $file;
564
}
565

    
566
/**
567
 * Add a new file to the file list.
568
 */
569
function imce_add_file($file, &$imce) {
570
  $imce['dirsize'] += $file->filesize;
571
  if (isset($imce['files'][$file->filename])) {
572
    $imce['dirsize'] -= $imce['files'][$file->filename]['size'];
573
  }
574
  $imce['files'][$file->filename] = array(
575
    'name' => $file->filename,
576
    'size' => $file->filesize,
577
    'width' => $file->width,
578
    'height' => $file->height,
579
    'date' => $file->timestamp
580
  );
581
  if (isset($_GET['jsop'])) {
582
    $add = $imce['files'][$file->filename];
583
    $add['name'] = rawurlencode($file->filename);
584
    $add['fsize'] = format_size($file->filesize);
585
    $add['fdate'] = format_date($file->timestamp, 'short');
586
    $add['id'] = $file->fid;
587
    $imce['added'][] = $add;
588
  }
589
}
590

    
591
/**
592
 * Remove a file from the file list.
593
 */
594
function imce_remove_file($filename, &$imce) {
595
  if (isset($imce['files'][$filename])) {
596
    $imce['dirsize'] -= $imce['files'][$filename]['size'];
597
    unset($imce['files'][$filename]);
598
    if (isset($_GET['jsop'])) {
599
      $imce['removed'][] = rawurlencode($filename);
600
    }
601
  }
602
}
603

    
604
/**
605
 * Validate uploaded file.
606
 */
607
function imce_validate_all($file, $imce) {
608

    
609
  //validate image resolution only if filesize validation passes.
610
  //because user might have uploaded a very big image
611
  //and scaling it may exploit system memory.
612
  $errors = imce_validate_filesize($file, $imce['filesize']);
613
  //image resolution validation
614
  if (empty($errors) && preg_match('/\.(png|gif|jpe?g)$/i', $file->filename)) {
615
    $errors = array_merge($errors, file_validate_image_resolution($file, $imce['dimensions']));
616
  }
617
  //directory quota validation
618
  if ($imce['quota']) {
619
    $errors = array_merge($errors, imce_validate_quota($file, $imce['quota'], $imce['dirsize']));
620
  }
621
  //user quota validation. check it if no errors were thrown.
622
  if (empty($errors) && $imce['tuquota']) {
623
    $errors = imce_validate_tuquota($file, $imce['tuquota'], file_space_used($imce['uid']));
624
  }
625
  return $errors;
626
}
627

    
628
/**
629
 * Validate filesize for maximum allowed file size.
630
 */
631
function imce_validate_filesize($file, $maxsize = 0) {
632
  $errors = array();
633
  if ($maxsize && $file->filesize > $maxsize) {
634
    $errors[] = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size($file->filesize), '%maxsize' => format_size($maxsize)));
635
  }
636
  return $errors;
637
}
638

    
639
/**
640
 * Validate filesize for directory quota.
641
 */
642
function imce_validate_quota($file, $quota = 0, $currentsize = 0) {
643
  $errors = array();
644
  if ($quota && ($currentsize + $file->filesize) > $quota) {
645
    $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)));
646
  }
647
  return $errors;
648
}
649

    
650
/**
651
 * Validate filesize for total user quota.
652
 */
653
function imce_validate_tuquota($file, $quota = 0, $currentsize = 0) {
654
  $errors = array();
655
  if ($quota && ($currentsize + $file->filesize) > $quota) {
656
    $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)));
657
  }
658
  return $errors;
659
}
660

    
661
/**
662
 * Validate both directory and total user quota. Returns true/false not errors.
663
 */
664
function imce_validate_quotas($file, &$imce, $add = 0) {
665
  $errors = imce_validate_quota($file, $imce['quota'], $imce['dirsize'] + $add);
666
  if (empty($errors) && $imce['tuquota']) {
667
    $errors = imce_validate_tuquota($file, $imce['tuquota'], file_space_used($imce['uid']) + $add);
668
  }
669
  if (!empty($errors)) {
670
    drupal_set_message($errors[0], 'error');
671
    return FALSE;
672
  }
673
  return TRUE;
674
}
675

    
676
/**
677
 * Checks if the file is an image and returns info.
678
 * There are two switchable versions that use image_get_info() and getimagesize()
679
 */
680
if (variable_get('imce_image_get_info', 0)) {
681
  function imce_image_info($file) {
682
    $mimes = array('image/jpeg' => IMAGETYPE_JPEG, 'image/gif'  => IMAGETYPE_GIF, 'image/png'  => IMAGETYPE_PNG);
683
    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']]) ) {
684
      return array('width' => $info['width'], 'height' => $info['height'], 'type' => $mimes[$info['mime_type']], 'mime' => $info['mime_type']);
685
    }
686
    return FALSE;
687
  }
688
}
689
else {
690
  function imce_image_info($file) {
691
    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)) ) {
692
      return array('width' => $info[0], 'height' => $info[1], 'type' => $info[2], 'mime' => $info['mime']);
693
    }
694
    return FALSE;
695
  }
696
}
697

    
698
/**
699
 * Return thumbnails as options to be used in upload form.
700
 */
701
function imce_thumbnail_options($thumbs = array()) {
702
  $options = array();
703
  foreach ($thumbs as $thumb) {
704
    $options[$thumb['name']] = $thumb['name'] . ' (' . $thumb['dimensions'] . ')';
705
  }
706
  return $options;
707
}
708

    
709
/**
710
 * Initiate and return configuration profile for the $user.
711
 */
712
function imce_initiate_profile($user, $scheme = NULL) {
713

    
714
  //check user profile and translate tokens in directory paths and evaluate php paths.
715
  if ($imce = imce_user_profile($user, $scheme)) {
716
    // Allow alteration of raw profile
717
    foreach (variable_get('imce_custom_init', array()) as $func => $state) {
718
      if ($state && function_exists($func)) {
719
        $func($imce, $user);
720
      }
721
    }
722
    imce_process_directories($imce, $user);
723
    if (!empty($imce['directories'])) {
724
      $imce['uid'] = (int) $user->uid;
725
      $imce['url'] = url($_GET['q']);
726
      $imce['clean'] = variable_get('clean_url', 0) == 1;
727
      $imce['absurls'] = variable_get('imce_settings_absurls', 0) == 1;
728
      $imce['furl'] = file_create_url($imce['scheme'] . '://');
729
      $imce['filesize'] *= 1048576;//convert from Mb to byte
730
      $imce['quota'] *= 1048576;
731
      $imce['tuquota'] *= 1048576;
732
      $imce['filenum'] = (int) $imce['filenum'];
733
      //check and set the active directory
734
      if ($info = imce_working_directory($imce)) {
735
        $imce['direct'] = isset($imce['directories'][$info['name']]);
736
        $imce['directories'][$info['name']] = $info;
737
        $imce['dir'] = $info['name'];
738
        $imce['perm'] = $info;//copy permissions of the active directory.
739
        unset($imce['perm']['name']);
740
      }
741
      else {
742
        drupal_set_message(t('Unable to get a working directory for the file browser!'), 'error');
743
        $imce['dir'] = FALSE;
744
        $imce['error'] = TRUE;
745
      }
746
      return $imce;
747
    }
748
    drupal_set_message(t('There is no valid directory specified for the file browser!'), 'error');
749
  }
750
  else {
751
    drupal_set_message(t('You do not have access to any configuration profile to use the file browser!'), 'error');
752
  }
753

    
754
  return FALSE;
755
}
756

    
757
/**
758
 * Get files and folders of the actve directory. Do custom processing.
759
 */
760
function imce_process_profile(&$imce) {
761
  //get directory content. do a custom scan if it is set
762
  $scan = ($scan = variable_get('imce_custom_scan', '')) && function_exists($scan) ? $scan : 'imce_scan_directory';
763
  $imce += $scan($imce['dir'], $imce);
764

    
765
  //run custom process functions
766
  foreach (variable_get('imce_custom_process', array()) as $func => $state) {
767
    if ($state && function_exists($func)) {
768
      $func($imce);
769
    }
770
  }
771

    
772
  //set subdirectories
773
  if (!$imce['error'] && !imce_subdirectories_accessible($imce)) {
774
    $imce['subdirectories'] = array();
775
  }
776
}
777

    
778
/**
779
 * Translate tokens and evaluate php in directory names.
780
 * Convert directories into an associative array (dirname => info)
781
 */
782
function imce_process_directories(&$imce, $user) {
783
  $directories = $imce['directories'];
784
  $paths = array();
785
  $translate = array('%uid' => $user->uid);
786

    
787
  foreach ($directories as $directory) {
788
    if (substr($directory['name'], 0, 4) == 'php:') {
789
      $directory['name'] = eval(substr($directory['name'], 4));
790
     //php may return an array of directories
791
      if (is_array($directory['name'])) {
792
        foreach ($directory['name'] as $name) {
793
          $paths[$name] = array('name' => $name) + $directory;
794
        }
795
        continue;
796
      }
797
    }
798
    else {
799
      $directory['name'] = strtr($directory['name'], $translate);
800
    }
801
    if ($directory['name']) {
802
      $paths[$directory['name']] = $directory;
803
    }
804
  }
805

    
806
  $imce['directories'] = $paths;
807
}
808

    
809
/**
810
 * Return an avaliable directory for the profile.
811
 */
812
function imce_working_directory(&$imce) {
813
  //Do not use session if there is only one directory assigned.
814
  $sess = TRUE;
815
  if (count($imce['directories']) < 2) {
816
    $perms = reset($imce['directories']);
817
    if (!isset($perms['subnav']) || !$perms['subnav']) {
818
      $sess = FALSE;
819
    }
820
  }
821
  //check GET.
822
  if (isset($_GET['dir'])) {
823
    if ($info = imce_directory_info($_GET['dir'], $imce)) {
824
      if (imce_check_directory($_GET['dir'], $imce)) {
825
        if ($sess) {
826
          $_SESSION['imce_directory'] = rawurlencode($info['name']);
827
        }
828
      }
829
      else {
830
        $info = FALSE;
831
      }
832
    }
833
    else {
834
      imce_inaccessible_directory($_GET['dir'], $imce);
835
    }
836
    return $info;
837
  }
838

    
839
  //check session
840
  if ($sess && isset($_SESSION['imce_directory'])) {
841
    $dirname = rawurldecode($_SESSION['imce_directory']);
842
    if ($info = imce_directory_info($dirname, $imce)) {
843
      if (imce_check_directory($dirname, $imce)) {
844
        return $info;
845
      }
846
    }
847
  }
848

    
849
  //or the whole list.
850
  foreach ($imce['directories'] as $dirname => $info) {
851
    $dirname = (string) $dirname;
852
    if (imce_check_directory($dirname, $imce)) {
853
      if ($sess) {
854
        $_SESSION['imce_directory'] = rawurlencode($dirname);
855
      }
856
      return $info;
857
    }
858
  }
859

    
860
  return FALSE;
861
}
862

    
863
/**
864
 * Create a writable directory(any level) under file system directory.
865
 */
866
function imce_check_directory($dirname, $imce) {
867
  $diruri = imce_dir_uri($imce, $dirname);
868

    
869
  if (!imce_reg_dir($dirname) || !file_prepare_directory($diruri, FILE_CREATE_DIRECTORY)) {
870
    return imce_inaccessible_directory($dirname, $imce);
871
  }
872

    
873
  return TRUE;
874
}
875

    
876
/**
877
 * Generate and log a directory access error.
878
 */
879
function imce_inaccessible_directory($dirname, $imce) {
880
  if (is_string($dirname)) {
881
    $dirname = utf8_encode($dirname);
882
    $diruri = imce_dir_uri($imce, $dirname);
883
    drupal_set_message(t('Directory %dirname is not accessible.', array('%dirname' => $dirname)), 'error');
884
    watchdog('imce', 'Access to %directory was denied.', array('%directory' => $diruri), WATCHDOG_ERROR);
885
  }
886
  return FALSE;
887
}
888

    
889
/**
890
 * Return the permissions for a directory that is accessed directly or indirectly.
891
 * A child of a predefined directory in the directory list takes its parent's properties.
892
 * If it has multiple parents, it gets the properties of the latter in the list.
893
 */
894
function imce_directory_info($dirname, $imce) {
895

    
896
  if (isset($imce['directories'][$dirname])) {
897
    return $imce['directories'][$dirname];
898
  }
899

    
900
  $info = FALSE;
901
  if (imce_reg_dir($dirname)) {
902
    $diruri = imce_dir_uri($imce, $dirname);
903
    if (file_prepare_directory($diruri)) {
904
      foreach ($imce['directories'] as $name => $prop) {
905
        if ($prop['subnav'] && ($name === '.' || strpos($dirname . '/', $name . '/') === 0)) {
906
          $info = $prop;
907
          $info['name'] = $dirname;
908
        }
909
      }
910
    }
911
  }
912

    
913
  return $info;
914
}
915

    
916
/**
917
 * Detect if the subdirectories are accessible through any directory(not just the current one) in the list.
918
 */
919
function imce_subdirectories_accessible(&$imce) {
920

    
921
  if (!empty($imce['subdirectories'])) {
922
    if (!empty($imce['perm']['subnav'])) {
923
      return TRUE;
924
    }
925
    //checking only the first one is sufficient.
926
    $dirname = ($imce['dir'] == '.' ? '' : $imce['dir'] . '/') . $imce['subdirectories'][0];
927

    
928
    //check if any setting is applicable for this subdirectory through any directory in the list.
929
    foreach ($imce['directories'] as $name => $info) {
930
      $name = (string) $name;
931
      if ($info['subnav'] && $dirname != $name && ($name == '.' || strpos($dirname . '/', $name . '/') === 0)) {
932
        return TRUE;
933
      }
934
    }
935
  }
936

    
937
  return FALSE;
938
}
939

    
940
/**
941
 * Check if a permission is given to at least one directory in the list.
942
 */
943
function imce_perm_exists(&$imce, $perm) {
944
  static $perms = array();
945

    
946
  if (isset($perms[$perm])) {
947
    return $perms[$perm];
948
  }
949

    
950
  if (isset($imce['perm'][$perm]) && $imce['perm'][$perm]) {
951
    return $perms[$perm] = TRUE;
952
  }
953

    
954
  foreach ($imce['directories'] as $name => $info) {
955
    if (isset($info[$perm]) && $info[$perm]) {
956
      return $perms[$perm] = TRUE;
957
    }
958
  }
959

    
960
  return $perms[$perm] = FALSE;
961
}
962

    
963
/**
964
 * Scan directory and return file list, subdirectories, and total size.
965
 */
966
function imce_scan_directory($dirname, $imce) {
967

    
968
  $directory = array('dirsize' => 0, 'files' => array(), 'subdirectories' => array(), 'error' => FALSE);
969
  $diruri = imce_dir_uri($imce, $dirname);
970

    
971
  if (!is_string($dirname) || $dirname == '' || !$handle = opendir($diruri)) {
972
    imce_inaccessible_directory($dirname, $imce);
973
    $directory['error'] = TRUE;
974
    return $directory;
975
  }
976

    
977
  while (($file = readdir($handle)) !== FALSE) {
978

    
979
    // Do not include dot files and folders
980
    if (substr($file, 0, 1) === '.') {
981
      continue;
982
    }
983

    
984
    $path = $diruri . $file;
985

    
986
    if (is_dir($path)) {
987
      $directory['subdirectories'][] = $file;
988
      continue;
989
    }
990

    
991
    $width = $height = 0;
992
    if ($img = imce_image_info($path)) {
993
      $width = $img['width'];
994
      $height = $img['height'];
995
    }
996
    $size = filesize($path);
997
    $date = filemtime($path);
998
    $directory['files'][$file] = array(
999
      'name' => $file,
1000
      'size' => $size,
1001
      'width' => $width,
1002
      'height' => $height,
1003
      'date' => $date
1004
    );
1005
    $directory['dirsize'] += $size;
1006
  }
1007

    
1008
  closedir($handle);
1009
  sort($directory['subdirectories']);
1010
  return $directory;
1011
}
1012

    
1013
/**
1014
 * Create directory tree.
1015
 */
1016
function imce_create_tree(&$imce) {
1017
  $paths = array();
1018
  //rearrange paths as arg0=>arg1=>...
1019
  foreach ($imce['directories'] as $path => $arr) {
1020
    $tmp =& $paths;
1021
    if ($path != '.') {
1022
      $args = explode('/', $path);
1023
      foreach ($args as $arg) {
1024
        if (!isset($tmp[$arg])) {
1025
          $tmp[$arg] = array();
1026
        }
1027
        $tmp =& $tmp[$arg];
1028
      }
1029
      $tmp[':access:'] = TRUE;
1030
    }
1031
    if ("$path" == $imce['dir']) {
1032
      $tmp[':active:'] = TRUE;
1033
      foreach ($imce['subdirectories'] as $arg) {
1034
        $tmp[$arg][':access:'] = TRUE;
1035
      }
1036
    }
1037
  }
1038
  //set root branch
1039
  $root = theme('imce_root_text', array('imce_ref' => array('imce' => &$imce)));
1040
  $q = $imce['clean'] ? '?' : '&';
1041
  if (isset($imce['directories']['.'])) {
1042
    $root = '<a href="' . $imce['url'] . $q . 'dir=." title="." class="folder' . ($imce['dir'] == '.' ? ' active' : '') . '">' . $root . '</a>';
1043
  }
1044
  else {
1045
    $root = '<a title="." class="folder disabled">' . $root . '</a>';
1046
  }
1047

    
1048
  return $root . imce_tree_html($imce, $paths, $q);
1049
}
1050

    
1051
/**
1052
 * Return tree html.
1053
 * This is not themable because it is complex and needs to be in a proper format for js processing.
1054
 */
1055
function imce_tree_html(&$imce, $paths, $q = '?', $prefix = '', $eprefix = '') {
1056
  unset($paths[':access:'], $paths[':active:']);
1057
  $html = '';
1058
  foreach ($paths as $arg => $children) {
1059
    $path = $prefix . $arg;
1060
    $earg = rawurlencode($arg);
1061
    $epath = $eprefix . $earg;
1062
    if (isset($children[':access:']) || imce_directory_info($path, $imce)) {
1063
      $a = '<a href="' . $imce['url'] . $q . 'dir=' . $epath . '" title="' . $epath . '" class="folder' . (isset($children[':active:']) ? ' active' : '') . '">' . $earg . '</a>';
1064
    }
1065
    else {
1066
      $a = '<a title="' . $epath . '" class="folder disabled">' . $earg . '</a>';
1067
    }
1068
    $ul = imce_tree_html($imce, $children, $q, $path . '/', $epath . '/');
1069
    $class = $ul ? ' class="expanded"' : (isset($children[':active:']) ? ' class="leaf"' : '');
1070
    $html .= '<li' . $class . '>' . $a . $ul . '</li>';
1071
  }
1072
  if ($html) {
1073
    $html = '<ul>' . $html . '</ul>';
1074
  }
1075
  return $html;
1076
}
1077

    
1078
/**
1079
 * Return the uri of the active directory
1080
 */
1081
function imce_dir_uri($imce, $dir = NULL) {
1082
  if (!isset($dir)) {
1083
    $dir = $imce['dir'];
1084
  }
1085
  return $imce['scheme'] . '://' . ($dir == '.' ? '' : $dir . '/');
1086
}
1087

    
1088
/**
1089
 * Returns the text for the root directory in a directory tree.
1090
 */
1091
function theme_imce_root_text($variables) {
1092
  //$imce = &$variables['imce_ref']['imce'];
1093
  return '&lt;' . t('root') . '&gt;';
1094
}
1095

    
1096
/**
1097
 * Returns the html for user's file browser tab.
1098
 */
1099
function theme_imce_user_page($variables) {
1100
  global $user;
1101
  $account = $variables['account'];
1102
  $options = array();
1103
  //switch to account's active folder
1104
  if ($user->uid == 1 && $account->uid != 1) {
1105
    $imce = imce_initiate_profile($account);
1106
    $options['query'] = array('dir' => $imce['dir']);
1107
  }
1108
  return '<iframe src="' . url('imce', $options) . '" frameborder="0" style="border: 1px solid #eee; width: 99%; height: 520px" class="imce-frame"></iframe>';
1109
}
1110

    
1111
/**
1112
 * Registers the file as an IMCE file.
1113
 */
1114
function imce_file_register($file) {
1115
  if (!db_query("SELECT 1 FROM {file_usage} WHERE module = 'imce' AND fid = :fid", array(':fid' => $file->fid))->fetchField()) {
1116
    file_usage_add($file, 'imce', 'file', $file->fid);
1117
  }
1118
}