Elgg  Version 2.3
filestore.php
Go to the documentation of this file.
1 <?php
2 
11 
20 function get_dir_size($dir, $total_size = 0) {
21  $handle = @opendir($dir);
22  while ($file = @readdir($handle)) {
23  if (in_array($file, array('.', '..'))) {
24  continue;
25  }
26  if (is_dir($dir . $file)) {
27  $total_size = get_dir_size($dir . $file . "/", $total_size);
28  } else {
29  $total_size += filesize($dir . $file);
30  }
31  }
32  @closedir($handle);
33 
34  return($total_size);
35 }
36 
47  elgg_deprecated_notice(__FUNCTION__ . ' has been deprecated and will be removed', '2.3');
49  $input = array_shift($inputs);
50  if (!$input || !$input->isValid()) {
51  return false;
52  }
53  return file_get_contents($input->getPathname());
54 }
55 
81 function elgg_save_resized_image($source, $destination = null, array $params = array()) {
82  return _elgg_services()->imageService->resize($source, $destination, $params);
83 }
84 
100 function get_resized_image_from_uploaded_file($input_name, $maxwidth, $maxheight,
101  $square = false, $upscale = false) {
102 
103  elgg_deprecated_notice(__FUNCTION__ . ' has been deprecated. Use elgg_save_resized_image()', '2.3');
104 
105  $files = _elgg_services()->request->files;
106  if (!$files->has($input_name)) {
107  return false;
108  }
109 
110  $file = $files->get($input_name);
111  if (empty($file)) {
112  // a file input was provided but no file uploaded
113  return false;
114  }
115  if ($file->getError() !== 0) {
116  return false;
117  }
118 
119  return get_resized_image_from_existing_file($file->getPathname(), $maxwidth, $maxheight, $square, 0, 0, 0, 0, $upscale);
120 }
121 
143 function get_resized_image_from_existing_file($input_name, $maxwidth, $maxheight,
144  $square = false, $x1 = 0, $y1 = 0, $x2 = 0, $y2 = 0, $upscale = false) {
145 
146  elgg_deprecated_notice(__FUNCTION__ . ' has been deprecated. Use elgg_save_resized_image()', '2.3');
147 
148  if (!is_readable($input_name)) {
149  return false;
150  }
151 
152  // we will write resized image to a temporary file and then delete it
153  // need to add a valid image extension otherwise resizing fails
154  $tmp_filename = tempnam(sys_get_temp_dir(), 'icon_resize');
155 
156  $params = [
157  'w' => $maxwidth,
158  'h' => $maxheight,
159  'x1' => $x1,
160  'y1' => $y1,
161  'x2' => $x2,
162  'y2' => $y2,
163  'square' => $square,
164  'upscale' => $upscale,
165  ];
166 
167  $image_bytes = false;
168  if (elgg_save_resized_image($input_name, $tmp_filename, $params)) {
169  $image_bytes = file_get_contents($tmp_filename);
170  }
171 
172  unlink($tmp_filename);
173 
174  return $image_bytes;
175 }
176 
193 function get_image_resize_parameters($width, $height, array $params = []) {
194 
195  elgg_deprecated_notice(__FUNCTION__ . ' has been deprecated and will be removed from public API', '2.3');
196 
197  try {
198  $params['w'] = elgg_extract('maxwidth', $params);
199  $params['h'] = elgg_extract('maxheight', $params);
200  unset($params['maxwidth']);
201  unset($params['maxheight']);
202  $params = _elgg_services()->imageService->normalizeResizeParameters($width, $height, $params);
203  return [
204  'newwidth' => $params['w'],
205  'newheight' => $params['h'],
206  'selectionwidth' => $params['x2'] - $params['x1'],
207  'selectionheight' => $params['y2'] - $params['y1'],
208  'xoffset' => $params['x1'],
209  'yoffset' => $params['y1'],
210  ];
211  } catch (\LogicException $ex) {
212  elgg_log($ex->getMessage(), 'ERROR');
213  return false;
214  }
215 }
216 
224 function file_delete($guid) {
226  if (!$file || !$file->canEdit()) {
227  return false;
228  }
229 
230  $thumbnail = $file->thumbnail;
231  $smallthumb = $file->smallthumb;
232  $largethumb = $file->largethumb;
233  if ($thumbnail) {
234  $delfile = new \ElggFile();
235  $delfile->owner_guid = $file->owner_guid;
236  $delfile->setFilename($thumbnail);
237  $delfile->delete();
238  }
239  if ($smallthumb) {
240  $delfile = new \ElggFile();
241  $delfile->owner_guid = $file->owner_guid;
242  $delfile->setFilename($smallthumb);
243  $delfile->delete();
244  }
245  if ($largethumb) {
246  $delfile = new \ElggFile();
247  $delfile->owner_guid = $file->owner_guid;
248  $delfile->setFilename($largethumb);
249  $delfile->delete();
250  }
251 
252  return $file->delete();
253 }
254 
262 function delete_directory($directory) {
263  // sanity check: must be a directory
264  if (!$handle = opendir($directory)) {
265  return false;
266  }
267 
268  // loop through all files
269  while (($file = readdir($handle)) !== false) {
270  if (in_array($file, array('.', '..'))) {
271  continue;
272  }
273 
274  $path = "$directory/$file";
275  if (is_dir($path)) {
276  // recurse down through directory
277  if (!delete_directory($path)) {
278  return false;
279  }
280  } else {
281  // delete file
282  unlink($path);
283  }
284  }
285 
286  // remove empty directory
287  closedir($handle);
288  return rmdir($directory);
289 }
290 
307  $dir = new \Elgg\EntityDirLocator($entity->guid);
308  $file_path = elgg_get_config('dataroot') . $dir;
309  if (file_exists($file_path)) {
310  delete_directory($file_path);
311  }
312 }
313 
316 
324  elgg_deprecated_notice(__FUNCTION__ . ' is deprecated.', '2.1');
325 
326  return $GLOBALS['DEFAULT_FILE_STORE'];
327 }
328 
337 function set_default_filestore(\ElggFilestore $filestore) {
338  elgg_deprecated_notice(__FUNCTION__ . ' is deprecated.', '2.1');
339 
340  $GLOBALS['DEFAULT_FILE_STORE'] = $filestore;
341  return true;
342 }
343 
352 function elgg_get_file_simple_type($mime_type) {
353  $params = array('mime_type' => $mime_type);
354  return elgg_trigger_plugin_hook('simple_type', 'file', $params, 'general');
355 }
356 
364  global $CONFIG;
365 
366  // Now register a default filestore
367  if (isset($CONFIG->dataroot)) {
368  $GLOBALS['DEFAULT_FILE_STORE'] = new \ElggDiskFilestore($CONFIG->dataroot);
369  }
370 }
371 
379 
380  // Fix MIME type detection for Microsoft zipped formats
381  elgg_register_plugin_hook_handler('mime_type', 'file', '_elgg_filestore_detect_mimetype');
382 
383  // Parse category of file from MIME type
384  elgg_register_plugin_hook_handler('simple_type', 'file', '_elgg_filestore_parse_simpletype');
385 
386  // Unit testing
387  elgg_register_plugin_hook_handler('unit_test', 'system', '_elgg_filestore_test');
388 
389  // Handler for serving embedded icons
390  elgg_register_page_handler('serve-icon', '_elgg_filestore_serve_icon_handler');
391 
392  // Touch entity icons if entity access id has changed
393  elgg_register_event_handler('update:after', 'object', '_elgg_filestore_touch_icons');
394  elgg_register_event_handler('update:after', 'group', '_elgg_filestore_touch_icons');
395 
396  // Move entity icons if entity owner has changed
397  elgg_register_event_handler('update:after', 'object', '_elgg_filestore_move_icons');
398  elgg_register_event_handler('update:after', 'group', '_elgg_filestore_move_icons');
399 }
400 
412 function _elgg_filestore_detect_mimetype($hook, $type, $mime_type, $params) {
413 
414  $original_filename = elgg_extract('original_filename', $params);
415  $ext = pathinfo($original_filename, PATHINFO_EXTENSION);
416 
417  return (new \Elgg\Filesystem\MimeTypeDetector())->fixDetectionErrors($mime_type, $ext);
418 }
419 
431 function _elgg_filestore_parse_simpletype($hook, $type, $simple_type, $params) {
432 
433  $mime_type = elgg_extract('mime_type', $params);
434 
435  switch ($mime_type) {
436  case "application/msword":
437  case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
438  case "application/pdf":
439  return "document";
440 
441  case "application/ogg":
442  return "audio";
443  }
444 
445  if (preg_match('~^(audio|image|video)/~', $mime_type, $m)) {
446  return $m[1];
447  }
448  if (0 === strpos($mime_type, 'text/') || false !== strpos($mime_type, 'opendocument')) {
449  return "document";
450  }
451 
452  // unrecognized MIME
453  return $simple_type;
454 }
455 
466 function _elgg_filestore_test($hook, $type, $value) {
467  global $CONFIG;
468  $value[] = "{$CONFIG->path}engine/tests/ElggCoreFilestoreTest.php";
469  return $value;
470 }
471 
482 function elgg_get_download_url(\ElggFile $file, $use_cookie = true, $expires = '+2 hours') {
483  $file_svc = new Elgg\FileService\File();
484  $file_svc->setFile($file);
485  $file_svc->setExpires($expires);
486  $file_svc->setDisposition('attachment');
487  $file_svc->bindSession($use_cookie);
488  return $file_svc->getURL();
489 }
490 
502 function elgg_get_inline_url(\ElggFile $file, $use_cookie = false, $expires = '') {
503  $file_svc = new Elgg\FileService\File();
504  $file_svc->setFile($file);
505  if ($expires) {
506  $file_svc->setExpires($expires);
507  }
508  $file_svc->setDisposition('inline');
509  $file_svc->bindSession($use_cookie);
510  return $file_svc->getURL();
511 }
512 
526  return elgg_normalize_url("serve-icon/$entity->guid/$size");
527 }
528 
538  $response = _elgg_services()->iconService->handleServeIconRequest();
539  $response->send();
540  exit;
541 }
542 
553  $original_attributes = $entity->getOriginalAttributes();
554  if (!array_key_exists('access_id', $original_attributes)) {
555  return;
556  }
557  if ($entity instanceof \ElggFile) {
558  // we touch the file to invalidate any previously generated download URLs
559  $entity->setModifiedTime();
560  }
561  $sizes = array_keys(elgg_get_icon_sizes($entity->getType(), $entity->getSubtype()));
562  foreach ($sizes as $size) {
563  $icon = $entity->getIcon($size);
564  if ($icon->exists()) {
565  $icon->setModifiedTime();
566  }
567  }
568 }
569 
587 
588  $original_attributes = $entity->getOriginalAttributes();
589  if (empty($original_attributes['owner_guid'])) {
590  return;
591  }
592 
593  $previous_owner_guid = $original_attributes['owner_guid'];
594  $new_owner_guid = $entity->owner_guid;
595 
596  $sizes = elgg_get_icon_sizes($entity->getType(), $entity->getSubtype());
597 
598  foreach ($sizes as $size => $opts) {
599  $new_icon = $entity->getIcon($size);
600  if ($new_icon->owner_guid == $entity->guid) {
601  // we do not need to update icons that are owned by the entity itself
602  continue;
603  }
604 
605  if ($new_icon->owner_guid != $new_owner_guid) {
606  // a plugin implements some custom logic
607  continue;
608  }
609 
610  $old_icon = new \ElggIcon();
611  $old_icon->owner_guid = $previous_owner_guid;
612  $old_icon->setFilename($new_icon->getFilename());
613  if (!$old_icon->exists()) {
614  // there is no icon to move
615  continue;
616  }
617 
618  if ($new_icon->exists()) {
619  // there is already a new icon
620  // just removing the old one
621  $old_icon->delete();
622  elgg_log("Entity $entity->guid has been transferred to a new owner but an icon was "
623  . "left behind under {$old_icon->getFilenameOnFilestore()}. "
624  . "Old icon has been deleted", 'NOTICE');
625  continue;
626  }
627 
628  $old_icon->transfer($new_icon->owner_guid, $new_icon->getFilename());
629  elgg_log("Entity $entity->guid has been transferred to a new owner. "
630  . "Icon was moved from {$old_icon->getFilenameOnFilestore()} to {$new_icon->getFilenameOnFilestore()}.", 'NOTICE');
631  }
632 }
633 
641  return _elgg_services()->uploads->getUploadedFiles($input_name);
642 }
643 
644 return function(\Elgg\EventsService $events, \Elgg\HooksRegistrationService $hooks) {
645  $events->registerHandler('boot', 'system', '_elgg_filestore_boot', 100);
646  $events->registerHandler('init', 'system', '_elgg_filestore_init', 100);
647 };
_elgg_filestore_boot()
Bootstraps the default filestore at "boot, system" event.
Definition: filestore.php:363
elgg_get_config($name, $site_guid=0)
Get an Elgg configuration value.
_elgg_filestore_serve_icon_handler()
Handler for /serve-icon resources /serve-icon/<entity_guid>/<size>
Definition: filestore.php:537
if(!array_key_exists($filename, $text_files)) $file
$m
Definition: metadata.php:11
File service.
Definition: File.php:12
elgg_normalize_url($url)
Definition: output.php:280
if(!$owner||!($owner instanceof ElggUser)||!$owner->canEdit()) $input
Definition: edit.php:19
$DEFAULT_FILE_STORE
Variable holding the default datastore.
Definition: filestore.php:315
elgg_get_icon_sizes($entity_type=null, $entity_subtype=null, $type= 'icon')
Returns a configuration array of icon sizes.
elgg_get_download_url(\ElggFile $file, $use_cookie=true, $expires= '+2 hours')
Returns file&#39;s download URL.
Definition: filestore.php:482
$input_name
Definition: item.php:14
elgg_get_embed_url(\ElggEntity $entity, $size)
Returns a URL suitable for embedding entity&#39;s icon in a text editor.
Definition: filestore.php:525
$path
Definition: details.php:88
$value
Definition: longtext.php:42
get_dir_size($dir, $total_size=0)
Get the size of the specified directory.
Definition: filestore.php:20
_elgg_filestore_parse_simpletype($hook, $type, $simple_type, $params)
Parse a file category of file from a MIME type.
Definition: filestore.php:431
$guid
Removes an admin notice.
elgg_register_plugin_hook_handler($hook, $type, $callback, $priority=500)
Definition: elgglib.php:740
elgg_get_uploaded_files($input_name)
Returns an array of uploaded file objects regardless of upload status/errors.
Definition: filestore.php:640
get_default_filestore()
Return the default filestore.
Definition: filestore.php:323
if(!$owner) $icon
Definition: default.php:16
$params
Definition: login.php:72
get_resized_image_from_existing_file($input_name, $maxwidth, $maxheight, $square=false, $x1=0, $y1=0, $x2=0, $y2=0, $upscale=false)
Gets the jpeg contents of the resized version of an already uploaded image (Returns false if the file...
Definition: filestore.php:143
elgg_get_inline_url(\ElggFile $file, $use_cookie=false, $expires= '')
Returns file&#39;s URL for inline display Suitable for displaying cacheable resources, such as user avatars.
Definition: filestore.php:502
Save menu items.
get_uploaded_file($input_name)
Get the contents of an uploaded file.
Definition: filestore.php:46
global $CONFIG
elgg_trigger_plugin_hook($hook, $type, $params=null, $returnvalue=null)
Definition: elgglib.php:826
elgg_register_page_handler($identifier, $function)
Registers a page handler for a particular identifier.
Definition: pagehandler.php:34
elgg_deprecated_notice($msg, $dep_version, $backtrace_level=1)
Log a notice about deprecated use of a function, view, etc.
Definition: elgglib.php:1098
elgg global
Pointer to the global context.
Definition: elgglib.js:12
_elgg_services(\Elgg\Di\ServiceProvider $services=null)
Get the global service provider.
Definition: autoloader.php:17
file_delete($guid)
Delete an file.
Definition: filestore.php:224
elgg_extract($key, $array, $default=null, $strict=true)
Checks for $array[$key] and returns its value if it exists, else returns $default.
Definition: elgglib.php:1375
_elgg_filestore_move_icons($event, $type, $entity)
Listen to entity ownership changes and update icon ownership by moving icons to their new owner&#39;s dir...
Definition: filestore.php:586
elgg_register_event_handler($event, $object_type, $callback, $priority=500)
Definition: elgglib.php:550
elgg_log($message, $level= 'NOTICE')
Display or log a message.
Definition: elgglib.php:1028
elgg_save_resized_image($source, $destination=null, array $params=array())
Crops and resizes an image.
Definition: filestore.php:81
$size
Definition: default.php:20
_elgg_filestore_detect_mimetype($hook, $type, $mime_type, $params)
Fix MIME type detection for Microsoft zipped formats.
Definition: filestore.php:412
$entity
Definition: delete.php:7
get_resized_image_from_uploaded_file($input_name, $maxwidth, $maxheight, $square=false, $upscale=false)
Gets the jpeg contents of the resized version of an uploaded image (Returns false if the uploaded fil...
Definition: filestore.php:100
exit
Definition: autoloader.php:34
delete_directory($directory)
Delete a directory and all its contents.
Definition: filestore.php:262
set_default_filestore(\ElggFilestore $filestore)
Set the default filestore for the system.
Definition: filestore.php:337
foreach($resources as $id=> $href) if(!empty($resources_html)) $files
Definition: details.php:141
_elgg_filestore_init()
Register file-related handlers on "init, system" event.
Definition: filestore.php:378
http free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:5
_elgg_filestore_test($hook, $type, $value)
Unit tests for files.
Definition: filestore.php:466
_elgg_clear_entity_files($entity)
Removes all entity files.
Definition: filestore.php:306
elgg_get_file_simple_type($mime_type)
Returns the category of a file from its MIME type.
Definition: filestore.php:352
get_image_resize_parameters($width, $height, array $params=[])
Calculate the parameters for resizing an image.
Definition: filestore.php:193
get_entity($guid)
Loads and returns an entity object from a guid.
Definition: entities.php:204
_elgg_filestore_touch_icons($event, $type, $entity)
Reset icon URLs if access_id has changed.
Definition: filestore.php:552
if(!$display_name) $type
Definition: delete.php:27