Elgg  Version 4.x
ElggFile.php
Go to the documentation of this file.
1 <?php
2 
9 
32 class ElggFile extends ElggObject {
33 
38  private $handle;
39 
45  protected function initializeAttributes() {
46  parent::initializeAttributes();
47 
48  $this->attributes['subtype'] = 'file';
49  }
50 
54  public function __set($name, $value) {
55  switch ($name) {
56  case 'filename':
57  // ensure sanitization
58  $this->setFilename($value);
59  return;
60  }
61 
62  parent::__set($name, $value);
63  }
64 
68  public function __get($name) {
69  switch ($name) {
70  case 'filename':
71  // ensure sanitization
72  return $this->getFilename();
73  }
74 
75  return parent::__get($name);
76  }
77 
85  public function setFilename($filename) {
86  $filename = ltrim(Paths::sanitize($filename, false), '/');
87 
88  parent::__set('filename', $filename);
89  }
90 
96  public function getFilename() {
97  $filename = parent::__get('filename');
98  if (empty($filename)) {
99  return '';
100  }
101 
102  return ltrim(Paths::sanitize($filename, false), '/');
103  }
104 
111  public function getFilenameOnFilestore() {
112  return $this->getFilestore()->getFilenameOnFilestore($this);
113  }
114 
123  public function getFilestoreSize($prefix = '', $container_guid = 0) {
124  if (!$container_guid) {
126  }
127 
128  return (int) $this->getFilestore()->getSize($prefix, $container_guid);
129  }
130 
137  public function getMimeType() {
138  if ($this->mimetype) {
139  return $this->mimetype;
140  }
141 
142  try {
143  return _elgg_services()->mimetype->getMimeType($this->getFilenameOnFilestore());
144  } catch (ElggInvalidArgumentException $e) {
145  // the file has no file on the filesystem
146  // can happen in tests etc.
147  }
148  return false;
149  }
150 
158  public function setMimeType($mimetype) {
159  return $this->mimetype = $mimetype;
160  }
161 
168  public function getSimpleType() {
169  if (isset($this->simpletype)) {
170  return $this->simpletype;
171  }
172 
173  return _elgg_services()->mimetype->getSimpleType($this->getMimeType() ?: '');
174  }
175 
186  public function open($mode) {
187  if (!$this->getFilename()) {
188  throw new IOException('You must specify a name before opening a file.');
189  }
190 
191  // See if file has already been saved
192  // seek on datastore, parameters and name?
193  // Sanity check
194  if (
195  ($mode != 'read') &&
196  ($mode != 'write') &&
197  ($mode != 'append')
198  ) {
199  throw new InvalidParameterException("Unrecognized file mode '{$mode}'");
200  }
201 
202  // Open the file handle
203  $this->handle = $this->getFilestore()->open($this, $mode);
204 
205  return $this->handle;
206  }
207 
215  public function write($data) {
216  return $this->getFilestore()->write($this->handle, $data);
217  }
218 
227  public function read($length, $offset = 0) {
228  return $this->getFilestore()->read($this->handle, $length, $offset);
229  }
230 
236  public function grabFile() {
237  return $this->getFilestore()->grabFile($this);
238  }
239 
245  public function close() {
246  if ($this->getFilestore()->close($this->handle)) {
247  $this->handle = null;
248 
249  return true;
250  }
251 
252  return false;
253  }
254 
262  public function delete($follow_symlinks = true) {
263  $result = $this->getFilestore()->delete($this, $follow_symlinks);
264 
265  if ($this->getGUID() && $result) {
266  $result = parent::delete();
267  }
268 
269  return $result;
270  }
271 
279  public function seek($position) {
280  $this->getFilestore()->seek($this->handle, $position);
281  }
282 
288  public function tell() {
289  return $this->getFilestore()->tell($this->handle);
290  }
291 
297  public function setModifiedTime() {
298  $filestorename = $this->getFilenameOnFilestore();
299 
300  $modified = touch($filestorename);
301  if ($modified) {
302  clearstatcache(true, $filestorename);
303  } else {
304  elgg_log("Unable to update modified time for {$filestorename}", 'ERROR');
305  }
306 
307  return $modified;
308  }
309 
315  public function getModifiedTime() {
316  return filemtime($this->getFilenameOnFilestore());
317  }
318 
325  public function getSize() {
326  return $this->getFilestore()->getFileSize($this);
327  }
328 
334  public function eof() {
335  return $this->getFilestore()->eof($this->handle);
336  }
337 
343  public function exists() {
344  return $this->getFilestore()->exists($this);
345  }
346 
352  protected function getFilestore() {
353  return _elgg_services()->filestore;
354  }
355 
368  public function transfer($owner_guid, $filename = null) {
369  if (!$owner_guid) {
370  return false;
371  }
372 
373  if (!$this->exists()) {
374  return false;
375  }
376 
377  if (!$filename) {
378  $filename = $this->getFilename();
379  }
380  $filestorename = $this->getFilenameOnFilestore();
381 
382  $this->owner_guid = $owner_guid;
383  $this->setFilename($filename);
384  $this->open('write');
385  $this->close();
386 
387  return rename($filestorename, $this->getFilenameOnFilestore());
388  }
389 
406  public function acceptUploadedFile(UploadedFile $upload) {
407  if (!$upload->isValid()) {
408  return false;
409  }
410 
411  $old_filestorename = '';
412  if ($this->exists()) {
413  $old_filestorename = $this->getFilenameOnFilestore();
414  }
415 
416  $originalfilename = $upload->getClientOriginalName();
417  $this->originalfilename = $originalfilename;
418  if (empty($this->title)) {
419  $this->title = htmlspecialchars($this->originalfilename, ENT_QUOTES, 'UTF-8');
420  }
421 
422  $this->upload_time = time();
423  $prefix = $this->filestore_prefix ?: 'file';
424  $prefix = trim($prefix, '/');
425  $filename = elgg_strtolower("{$prefix}/{$this->upload_time}{$this->originalfilename}");
426  $this->setFilename($filename);
427  $this->filestore_prefix = $prefix;
428 
429  $hook_params = [
430  'file' => $this,
431  'upload' => $upload,
432  ];
433 
434  $uploaded = _elgg_services()->hooks->trigger('upload', 'file', $hook_params);
435  if ($uploaded !== true && $uploaded !== false) {
436  $filestorename = $this->getFilenameOnFilestore();
437  try {
438  $uploaded = $upload->move(pathinfo($filestorename, PATHINFO_DIRNAME), pathinfo($filestorename, PATHINFO_BASENAME));
439  } catch (FileException $ex) {
440  _elgg_services()->logger->error($ex->getMessage());
441  $uploaded = false;
442  }
443  }
444 
445  if ($uploaded) {
446  if ($old_filestorename && $old_filestorename != $this->getFilenameOnFilestore()) {
447  // remove old file
448  unlink($old_filestorename);
449  }
450 
451  try {
452  // try to detect mimetype
453  $mime_type = _elgg_services()->mimetype->getMimeType($this->getFilenameOnFilestore());
454  $this->setMimeType($mime_type);
455  $this->simpletype = _elgg_services()->mimetype->getSimpleType($mime_type);
456  } catch (ElggInvalidArgumentException $e) {
457  // this can fail if the upload hooks returns true, but the file is not present on the filestore
458  // this happens in a unittest
459  }
460  _elgg_services()->events->triggerAfter('upload', 'file', $this);
461  return true;
462  }
463 
464  return false;
465  }
466 
472  public function __sleep() {
473  return array_diff(array_keys(get_object_vars($this)), [
474  // a resource
475  'handle',
476  ]);
477  }
478 
487  public function canDownload($user_guid = 0, $default = true) {
488  return _elgg_services()->userCapabilities->canDownload($this, $user_guid, $default);
489  }
490 
501  public function getDownloadURL($use_cookie = true, $expires = '+2 hours') {
502  $file_svc = new \Elgg\FileService\File();
503  $file_svc->setFile($this);
504  if (!empty($expires)) {
505  $file_svc->setExpires($expires);
506  }
507  $file_svc->setDisposition('attachment');
508  $file_svc->bindSession($use_cookie);
509 
510  $params = [
511  'entity' => $this,
512  ];
513  return _elgg_services()->hooks->trigger('download:url', 'file', $params, $file_svc->getURL());
514  }
515 
527  public function getInlineURL($use_cookie = false, $expires = '') {
528  $file_svc = new \Elgg\FileService\File();
529  $file_svc->setFile($this);
530  if (!empty($expires)) {
531  $file_svc->setExpires($expires);
532  }
533  $file_svc->setDisposition('inline');
534  $file_svc->bindSession($use_cookie);
535 
536  $params = [
537  'entity' => $this,
538  ];
539  return _elgg_services()->hooks->trigger('inline:url', 'file', $params, $file_svc->getURL());
540  }
541 }
$default
Definition: checkbox.php:31
getSize()
Return the size of the file in bytes.
Definition: ElggFile.php:325
$user_guid
Definition: login_as.php:10
if(!$user||!$user->canDelete()) $name
Definition: delete.php:22
$params
Saves global plugin settings.
Definition: save.php:13
$mode
Configure site maintenance mode.
write($data)
Write data.
Definition: ElggFile.php:215
__set($name, $value)
Definition: ElggFile.php:54
An IO Exception, throw when an IO Exception occurs.
Definition: IOException.php:12
if(!$item instanceof ElggEntity) $length
Definition: excerpt.php:16
setModifiedTime()
Updates modification time of the file and clears stats cache for the file.
Definition: ElggFile.php:297
getFilestoreSize($prefix= '', $container_guid=0)
Return the size of the filestore associated with this file.
Definition: ElggFile.php:123
close()
Close the file and commit changes.
Definition: ElggFile.php:245
setFilename($filename)
Set the filename of this file.
Definition: ElggFile.php:85
seek($position)
Seek a position in the file.
Definition: ElggFile.php:279
eof()
Return a boolean value whether the file handle is at the end of the file.
Definition: ElggFile.php:334
exists()
Returns if the file exists.
Definition: ElggFile.php:343
if(elgg_trigger_plugin_hook('usersettings:save', 'user', $hooks_params, true)) foreach($request->validation() ->all() as $item) $data
Definition: save.php:53
if(!$count) $offset
Definition: pagination.php:26
getSimpleType()
Get the simple type of the file.
Definition: ElggFile.php:168
getGUID()
Returns the guid.
canDownload($user_guid=0, $default=true)
Checks the download permissions for the file.
Definition: ElggFile.php:487
elgg_strtolower()
Wrapper function for mb_strtolower().
Definition: mb_wrapper.php:154
getModifiedTime()
Returns file modification time.
Definition: ElggFile.php:315
$position
Definition: move.php:7
__get($name)
Definition: ElggFile.php:68
$value
Definition: generic.php:51
getFilenameOnFilestore()
Return the filename of this file as it is/will be stored on the filestore, which may be different to ...
Definition: ElggFile.php:111
grabFile()
Gets the full contents of this file.
Definition: ElggFile.php:236
getFilestore()
Return the system filestore based on dataroot.
Definition: ElggFile.php:352
initializeAttributes()
Set subtype to &#39;file&#39;.
Definition: ElggFile.php:45
$owner_guid
setMimeType($mimetype)
Set the mime type of the file.
Definition: ElggFile.php:158
getFilename()
Return the filename.
Definition: ElggFile.php:96
read($length, $offset=0)
Read data.
Definition: ElggFile.php:227
elgg_log($message, $level=\Psr\Log\LogLevel::NOTICE)
Log a message.
Definition: elgglib.php:399
tell()
Return the current position of the file.
Definition: ElggFile.php:288
getDownloadURL($use_cookie=true, $expires= '+2 hours')
Returns file&#39;s download URL.
Definition: ElggFile.php:501
acceptUploadedFile(UploadedFile $upload)
Writes contents of the uploaded file to an instance of ElggFile.
Definition: ElggFile.php:406
getMimeType()
Get the mime type of the file.
Definition: ElggFile.php:137
getInlineURL($use_cookie=false, $expires= '')
Returns file&#39;s URL for inline display Suitable for displaying cacheable resources, such as user avatars.
Definition: ElggFile.php:527
$filename
_elgg_services()
Get the global service provider.
Definition: elgglib.php:777
$container_guid
transfer($owner_guid, $filename=null)
Transfer a file to a new owner and sets a new filename, copies file contents to a new location...
Definition: ElggFile.php:368
open($mode)
Open the file with the given mode.
Definition: ElggFile.php:186
__sleep()
Get property names to serialize.
Definition: ElggFile.php:472