Elgg  Version 4.3
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 
124  public function getFilestoreSize($prefix = '', $container_guid = 0) {
125  if (!$container_guid) {
127  }
128 
129  return (int) $this->getFilestore()->getSize($prefix, $container_guid);
130  }
131 
138  public function getMimeType() {
139  if ($this->mimetype) {
140  return $this->mimetype;
141  }
142 
143  try {
144  return _elgg_services()->mimetype->getMimeType($this->getFilenameOnFilestore());
145  } catch (ElggInvalidArgumentException $e) {
146  // the file has no file on the filesystem
147  // can happen in tests etc.
148  }
149  return false;
150  }
151 
159  public function setMimeType($mimetype) {
160  return $this->mimetype = $mimetype;
161  }
162 
169  public function getSimpleType() {
170  if (isset($this->simpletype)) {
171  return $this->simpletype;
172  }
173 
174  return _elgg_services()->mimetype->getSimpleType($this->getMimeType() ?: '');
175  }
176 
187  public function open($mode) {
188  if (!$this->getFilename()) {
189  throw new IOException('You must specify a name before opening a file.');
190  }
191 
192  // See if file has already been saved
193  // seek on datastore, parameters and name?
194  // Sanity check
195  if (
196  ($mode != 'read') &&
197  ($mode != 'write') &&
198  ($mode != 'append')
199  ) {
200  throw new InvalidParameterException("Unrecognized file mode '{$mode}'");
201  }
202 
203  // Open the file handle
204  $this->handle = $this->getFilestore()->open($this, $mode);
205 
206  return $this->handle;
207  }
208 
216  public function write($data) {
217  return $this->getFilestore()->write($this->handle, $data);
218  }
219 
228  public function read($length, $offset = 0) {
229  return $this->getFilestore()->read($this->handle, $length, $offset);
230  }
231 
237  public function grabFile() {
238  return $this->getFilestore()->grabFile($this);
239  }
240 
246  public function close() {
247  if ($this->getFilestore()->close($this->handle)) {
248  $this->handle = null;
249 
250  return true;
251  }
252 
253  return false;
254  }
255 
263  public function delete($follow_symlinks = true) {
264  $result = $this->getFilestore()->delete($this, $follow_symlinks);
265 
266  if ($this->getGUID() && $result) {
267  $result = parent::delete();
268  }
269 
270  return $result;
271  }
272 
280  public function seek($position) {
281  $this->getFilestore()->seek($this->handle, $position);
282  }
283 
289  public function tell() {
290  return $this->getFilestore()->tell($this->handle);
291  }
292 
298  public function setModifiedTime() {
299  $filestorename = $this->getFilenameOnFilestore();
300 
301  $modified = touch($filestorename);
302  if ($modified) {
303  clearstatcache(true, $filestorename);
304  } else {
305  elgg_log("Unable to update modified time for {$filestorename}", 'ERROR');
306  }
307 
308  return $modified;
309  }
310 
316  public function getModifiedTime() {
317  return filemtime($this->getFilenameOnFilestore());
318  }
319 
326  public function getSize() {
327  return $this->getFilestore()->getFileSize($this);
328  }
329 
335  public function eof() {
336  return $this->getFilestore()->eof($this->handle);
337  }
338 
344  public function exists() {
345  return $this->getFilestore()->exists($this);
346  }
347 
353  protected function getFilestore() {
354  return _elgg_services()->filestore;
355  }
356 
369  public function transfer($owner_guid, $filename = null) {
370  if (!$owner_guid) {
371  return false;
372  }
373 
374  if (!$this->exists()) {
375  return false;
376  }
377 
378  if (!$filename) {
379  $filename = $this->getFilename();
380  }
381  $filestorename = $this->getFilenameOnFilestore();
382 
383  $this->owner_guid = $owner_guid;
384  $this->setFilename($filename);
385  $this->open('write');
386  $this->close();
387 
388  return rename($filestorename, $this->getFilenameOnFilestore());
389  }
390 
407  public function acceptUploadedFile(UploadedFile $upload) {
408  if (!$upload->isValid()) {
409  return false;
410  }
411 
412  $old_filestorename = '';
413  if ($this->exists()) {
414  $old_filestorename = $this->getFilenameOnFilestore();
415  }
416 
417  $originalfilename = $upload->getClientOriginalName();
418  $this->originalfilename = $originalfilename;
419  if (empty($this->title)) {
420  $this->title = htmlspecialchars($this->originalfilename, ENT_QUOTES, 'UTF-8');
421  }
422 
423  $this->upload_time = time();
424  $prefix = $this->filestore_prefix ?: 'file';
425  $prefix = trim($prefix, '/');
426  $filename = elgg_strtolower("{$prefix}/{$this->upload_time}{$this->originalfilename}");
427  $this->setFilename($filename);
428  $this->filestore_prefix = $prefix;
429 
430  $hook_params = [
431  'file' => $this,
432  'upload' => $upload,
433  ];
434 
435  $uploaded = _elgg_services()->hooks->trigger('upload', 'file', $hook_params);
436  if ($uploaded !== true && $uploaded !== false) {
437  $filestorename = $this->getFilenameOnFilestore();
438  try {
439  $uploaded = $upload->move(pathinfo($filestorename, PATHINFO_DIRNAME), pathinfo($filestorename, PATHINFO_BASENAME));
440  } catch (FileException $ex) {
441  _elgg_services()->logger->error($ex->getMessage());
442  $uploaded = false;
443  }
444  }
445 
446  if ($uploaded) {
447  if ($old_filestorename && $old_filestorename != $this->getFilenameOnFilestore()) {
448  // remove old file
449  unlink($old_filestorename);
450  }
451 
452  try {
453  // try to detect mimetype
454  $mime_type = _elgg_services()->mimetype->getMimeType($this->getFilenameOnFilestore());
455  $this->setMimeType($mime_type);
456  $this->simpletype = _elgg_services()->mimetype->getSimpleType($mime_type);
457  } catch (ElggInvalidArgumentException $e) {
458  // this can fail if the upload hooks returns true, but the file is not present on the filestore
459  // this happens in a unittest
460  }
461  _elgg_services()->events->triggerAfter('upload', 'file', $this);
462  return true;
463  }
464 
465  return false;
466  }
467 
473  public function __sleep() {
474  return array_diff(array_keys(get_object_vars($this)), [
475  // a resource
476  'handle',
477  ]);
478  }
479 
488  public function canDownload($user_guid = 0, $default = true) {
489  return _elgg_services()->userCapabilities->canDownload($this, $user_guid, $default);
490  }
491 
502  public function getDownloadURL($use_cookie = true, $expires = '+2 hours') {
503  $file_svc = new \Elgg\FileService\File();
504  $file_svc->setFile($this);
505  if (!empty($expires)) {
506  $file_svc->setExpires($expires);
507  }
508  $file_svc->setDisposition('attachment');
509  $file_svc->bindSession($use_cookie);
510 
511  $params = [
512  'entity' => $this,
513  ];
514  return _elgg_services()->hooks->trigger('download:url', 'file', $params, $file_svc->getURL());
515  }
516 
528  public function getInlineURL($use_cookie = false, $expires = '') {
529  $file_svc = new \Elgg\FileService\File();
530  $file_svc->setFile($this);
531  if (!empty($expires)) {
532  $file_svc->setExpires($expires);
533  }
534  $file_svc->setDisposition('inline');
535  $file_svc->bindSession($use_cookie);
536 
537  $params = [
538  'entity' => $this,
539  ];
540  return _elgg_services()->hooks->trigger('inline:url', 'file', $params, $file_svc->getURL());
541  }
542 }
$default
Definition: checkbox.php:31
getSize()
Return the size of the file in bytes.
Definition: ElggFile.php:326
$user_guid
Definition: login_as.php:10
$params
Saves global plugin settings.
Definition: save.php:13
$mode
Configure site maintenance mode.
write($data)
Write data.
Definition: ElggFile.php:216
__set($name, $value)
Definition: ElggFile.php:54
An IO Exception, throw when an IO Exception occurs.
Definition: IOException.php:12
if(!$user||!$user->canDelete()) $name
Definition: delete.php:22
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:298
getFilestoreSize($prefix= '', $container_guid=0)
Return the size of the filestore associated with this file.
Definition: ElggFile.php:124
close()
Close the file and commit changes.
Definition: ElggFile.php:246
setFilename($filename)
Set the filename of this file.
Definition: ElggFile.php:85
seek($position)
Seek a position in the file.
Definition: ElggFile.php:280
eof()
Return a boolean value whether the file handle is at the end of the file.
Definition: ElggFile.php:335
exists()
Returns if the file exists.
Definition: ElggFile.php:344
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:169
getGUID()
Returns the guid.
canDownload($user_guid=0, $default=true)
Checks the download permissions for the file.
Definition: ElggFile.php:488
elgg_strtolower()
Wrapper function for mb_strtolower().
Definition: mb_wrapper.php:154
getModifiedTime()
Returns file modification time.
Definition: ElggFile.php:316
$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:237
getFilestore()
Return the system filestore based on dataroot.
Definition: ElggFile.php:353
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:159
getFilename()
Return the filename.
Definition: ElggFile.php:96
read($length, $offset=0)
Read data.
Definition: ElggFile.php:228
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:289
getDownloadURL($use_cookie=true, $expires= '+2 hours')
Returns file&#39;s download URL.
Definition: ElggFile.php:502
acceptUploadedFile(UploadedFile $upload)
Writes contents of the uploaded file to an instance of ElggFile.
Definition: ElggFile.php:407
getMimeType()
Get the mime type of the file.
Definition: ElggFile.php:138
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:528
$filename
_elgg_services()
Get the global service provider.
Definition: elgglib.php:638
$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:369
open($mode)
Open the file with the given mode.
Definition: ElggFile.php:187
__sleep()
Get property names to serialize.
Definition: ElggFile.php:473