Projet

Général

Profil

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

root / htmltest / sites / all / modules / imce / inc / imce.page.inc @ a5572547

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', 'text/' . ($jsop == 'upload' ? 'html' : 'javascript') . '; 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['#attributes']['enctype'] = 'multipart/form-data';
148
  $form['#action'] = $imce['url'];
149
  return $form;
150
}
151

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
351
}
352

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

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

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

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

    
375
}
376

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

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

    
392
  return $processed;
393
}
394

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

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

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

    
434
  return TRUE;
435
}
436

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
562
  return $file;
563
}
564

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

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

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

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

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

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

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

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

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

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

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

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

    
753
  return FALSE;
754
}
755

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

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

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

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

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

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

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

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

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

    
859
  return FALSE;
860
}
861

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

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

    
872
  return TRUE;
873
}
874

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

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

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

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

    
912
  return $info;
913
}
914

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

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

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

    
936
  return FALSE;
937
}
938

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

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

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

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

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

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

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

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

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

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

    
983
    $path = $diruri . $file;
984

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

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

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

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

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

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

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

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

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

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