Elgg  Version 3.0
ElggFile.php
Go to the documentation of this file.
1 <?php
2 
6 
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 
58  public function setFilename($name) {
59  $this->filename = $name;
60  }
61 
67  public function getFilename() {
68  return $this->filename;
69  }
70 
77  public function getFilenameOnFilestore() {
78  return $this->getFilestore()->getFilenameOnFilestore($this);
79  }
80 
89  public function getFilestoreSize($prefix = '', $container_guid = 0) {
90  if (!$container_guid) {
92  }
93  // @todo add getSize() to \ElggFilestore
94  return (int) $this->getFilestore()->getSize($prefix, $container_guid);
95  }
96 
103  public function getMimeType() {
104  if ($this->mimetype) {
105  return $this->mimetype;
106  }
107  return $this->detectMimeType();
108  }
109 
117  public function setMimeType($mimetype) {
118  return $this->mimetype = $mimetype;
119  }
120 
133  public function detectMimeType($file = null, $default = null) {
134  $class = __CLASS__;
135  if (!$file && isset($this) && $this instanceof $class) {
136  $file = $this->getFilenameOnFilestore();
137  }
138 
139  if (!is_readable($file)) {
140  return false;
141  }
142 
143  $mime = $default;
144 
145  $detected = (new MimeTypeDetector())->tryStrategies($file);
146  if ($detected) {
147  $mime = $detected;
148  }
149 
150  $original_filename = isset($this) && $this instanceof $class ? $this->originalfilename : basename($file);
151  $params = [
152  'filename' => $file,
153  'original_filename' => $original_filename, // @see file upload action
154  'default' => $default,
155  ];
156  return _elgg_services()->hooks->trigger('mime_type', 'file', $params, $mime);
157  }
158 
166  public function getSimpleType() {
167  if (isset($this->simpletype)) {
168  return $this->simpletype;
169  }
170  $mime_type = $this->getMimeType();
171  return elgg_get_file_simple_type($mime_type);
172  }
173 
181  public function setDescription($description) {
182  $this->description = $description;
183  }
184 
195  public function open($mode) {
196  if (!$this->getFilename()) {
197  throw new IOException("You must specify a name before opening a file.");
198  }
199 
200  // See if file has already been saved
201  // seek on datastore, parameters and name?
202  // Sanity check
203  if (
204  ($mode != "read") &&
205  ($mode != "write") &&
206  ($mode != "append")
207  ) {
208  $msg = "Unrecognized file mode '" . $mode . "'";
209  throw new InvalidParameterException($msg);
210  }
211 
212  // Open the file handle
213  $this->handle = $this->getFilestore()->open($this, $mode);
214 
215  return $this->handle;
216  }
217 
225  public function write($data) {
226  return $this->getFilestore()->write($this->handle, $data);
227  }
228 
237  public function read($length, $offset = 0) {
238  return $this->getFilestore()->read($this->handle, $length, $offset);
239  }
240 
246  public function grabFile() {
247  return $this->getFilestore()->grabFile($this);
248  }
249 
255  public function close() {
256  if ($this->getFilestore()->close($this->handle)) {
257  $this->handle = null;
258 
259  return true;
260  }
261 
262  return false;
263  }
264 
271  public function delete($follow_symlinks = true) {
272  $result = $this->getFilestore()->delete($this, $follow_symlinks);
273 
274  if ($this->getGUID() && $result) {
275  $result = parent::delete();
276  }
277 
278  return $result;
279  }
280 
288  public function seek($position) {
289  // @todo add seek() to \ElggFilestore
290  $this->getFilestore()->seek($this->handle, $position);
291  }
292 
298  public function tell() {
299  return $this->getFilestore()->tell($this->handle);
300  }
301 
306  public function setModifiedTime() {
307  $filestorename = $this->getFilenameOnFilestore();
308  $modified = touch($filestorename);
309  if ($modified) {
310  clearstatcache(true, $filestorename);
311  } else {
312  elgg_log("Unable to update modified time for $filestorename", 'ERROR');
313  }
314  return $modified;
315  }
316 
321  public function getModifiedTime() {
322  return filemtime($this->getFilenameOnFilestore());
323  }
324 
331  public function getSize() {
332  return $this->getFilestore()->getFileSize($this);
333  }
334 
340  public function eof() {
341  return $this->getFilestore()->eof($this->handle);
342  }
343 
349  public function exists() {
350  return $this->getFilestore()->exists($this);
351  }
352 
358  protected function getFilestore() {
359  return _elgg_services()->filestore;
360  }
361 
373  public function transfer($owner_guid, $filename = null) {
374  if (!$owner_guid) {
375  return false;
376  }
377 
378  if (!$this->exists()) {
379  return false;
380  }
381 
382  if (!$filename) {
383  $filename = $this->getFilename();
384  }
385  $filestorename = $this->getFilenameOnFilestore();
386 
387  $this->owner_guid = $owner_guid;
388  $this->setFilename($filename);
389  $this->open('write');
390  $this->close();
391 
392  return rename($filestorename, $this->getFilenameOnFilestore());
393  }
394 
410  public function acceptUploadedFile(UploadedFile $upload) {
411  if (!$upload->isValid()) {
412  return false;
413  }
414 
415  $old_filestorename = '';
416  if ($this->exists()) {
417  $old_filestorename = $this->getFilenameOnFilestore();
418  }
419 
420  $originalfilename = $upload->getClientOriginalName();
421  $this->originalfilename = $originalfilename;
422  if (empty($this->title)) {
423  $this->title = htmlspecialchars($this->originalfilename, ENT_QUOTES, 'UTF-8');
424  }
425 
426  $this->upload_time = time();
427  $prefix = $this->filestore_prefix ?: 'file';
428  $prefix = trim($prefix, '/');
429  $filename = elgg_strtolower("$prefix/{$this->upload_time}{$this->originalfilename}");
430  $this->setFilename($filename);
431  $this->filestore_prefix = $prefix;
432 
433  $hook_params = [
434  'file' => $this,
435  'upload' => $upload,
436  ];
437 
438  $uploaded = _elgg_services()->hooks->trigger('upload', 'file', $hook_params);
439  if ($uploaded !== true && $uploaded !== false) {
440  $filestorename = $this->getFilenameOnFilestore();
441  try {
442  $uploaded = $upload->move(pathinfo($filestorename, PATHINFO_DIRNAME), pathinfo($filestorename, PATHINFO_BASENAME));
443  } catch (FileException $ex) {
444  _elgg_services()->logger->error($ex->getMessage());
445  $uploaded = false;
446  }
447  }
448 
449  if ($uploaded) {
450  if ($old_filestorename && $old_filestorename != $this->getFilenameOnFilestore()) {
451  // remove old file
452  unlink($old_filestorename);
453  }
454  $mime_type = $this->detectMimeType(null, $upload->getClientMimeType());
455  $this->setMimeType($mime_type);
456  $this->simpletype = elgg_get_file_simple_type($mime_type);
457  _elgg_services()->events->triggerAfter('upload', 'file', $this);
458  return true;
459  }
460 
461  return false;
462  }
463 
469  public function __sleep() {
470  return array_diff(array_keys(get_object_vars($this)), [
471  // a resource
472  'handle',
473  ]);
474  }
475 
484  public function canDownload($user_guid = 0, $default = true) {
485  return _elgg_services()->userCapabilities->canDownload($this, $user_guid, $default);
486  }
487 
498  public function getDownloadURL($use_cookie = true, $expires = '+2 hours') {
499 
500  $file_svc = new \Elgg\FileService\File();
501  $file_svc->setFile($this);
502  $file_svc->setExpires($expires);
503  $file_svc->setDisposition('attachment');
504  $file_svc->bindSession($use_cookie);
505  $url = $file_svc->getURL();
506 
507  $params = [
508  'entity' => $this,
509  ];
510 
511  return _elgg_services()->hooks->trigger('download:url', 'file', $params, $url);
512  }
513 
525  public function getInlineURL($use_cookie = false, $expires = '') {
526  $file_svc = new \Elgg\FileService\File();
527  $file_svc->setFile($this);
528  if (!empty($expires)) {
529  $file_svc->setExpires($expires);
530  }
531  $file_svc->setDisposition('inline');
532  $file_svc->bindSession($use_cookie);
533  $url = $file_svc->getURL();
534 
535  $params = [
536  'entity' => $this,
537  ];
538 
539  return _elgg_services()->hooks->trigger('inline:url', 'file', $params, $url);
540  }
541 
542 }
setDescription($description)
Set the optional file description.
Definition: ElggFile.php:181
getSize()
Return the size of the file in bytes.
Definition: ElggFile.php:331
if(!$user||!$user->canDelete()) $name
Definition: delete.php:22
if(!array_key_exists($filename, $text_files)) $file
$params
Saves global plugin settings.
Definition: save.php:13
$mode
Configure site maintenance mode.
write($data)
Write data.
Definition: ElggFile.php:225
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:306
getFilestoreSize($prefix= '', $container_guid=0)
Return the size of the filestore associated with this file.
Definition: ElggFile.php:89
close()
Close the file and commit changes.
Definition: ElggFile.php:255
seek($position)
Seek a position in the file.
Definition: ElggFile.php:288
eof()
Return a boolean value whether the file handle is at the end of the file.
Definition: ElggFile.php:340
exists()
Returns if the file exists.
Definition: ElggFile.php:349
if(elgg_trigger_plugin_hook('usersettings:save', 'user', $hooks_params, true)) foreach($request->validation() ->all() as $item) $data
Definition: save.php:57
if(!$count) $offset
Definition: pagination.php:26
getSimpleType()
Get the simple type of the file.
Definition: ElggFile.php:166
getGUID()
Returns the guid.
canDownload($user_guid=0, $default=true)
Checks the download permissions for the file.
Definition: ElggFile.php:484
elgg_strtolower()
Wrapper function for mb_strtolower().
Definition: mb_wrapper.php:174
getModifiedTime()
Returns file modification time.
Definition: ElggFile.php:321
$position
Definition: move.php:7
getFilenameOnFilestore()
Return the filename of this file as it is/will be stored on the filestore, which may be different to ...
Definition: ElggFile.php:77
grabFile()
Gets the full contents of this file.
Definition: ElggFile.php:246
getFilestore()
Return the system filestore based on dataroot.
Definition: ElggFile.php:358
$user_guid
Validate a user.
Definition: validate.php:6
initializeAttributes()
Set subtype to &#39;file&#39;.
Definition: ElggFile.php:45
$owner_guid
if(!$site) if(!($site instanceof ElggSite)) $site description
setMimeType($mimetype)
Set the mime type of the file.
Definition: ElggFile.php:117
$class
Definition: field.php:29
getFilename()
Return the filename.
Definition: ElggFile.php:67
detectMimeType($file=null, $default=null)
Detects mime types based on filename or actual file.
Definition: ElggFile.php:133
read($length, $offset=0)
Read data.
Definition: ElggFile.php:237
elgg_log($message, $level=\Psr\Log\LogLevel::NOTICE)
Log a message.
Definition: elgglib.php:786
tell()
Return the current position of the file.
Definition: ElggFile.php:298
$url
Definition: default.php:33
getDownloadURL($use_cookie=true, $expires= '+2 hours')
Returns file&#39;s download URL.
Definition: ElggFile.php:498
acceptUploadedFile(UploadedFile $upload)
Writes contents of the uploaded file to an instance of ElggFile.
Definition: ElggFile.php:410
getMimeType()
Get the mime type of the file.
Definition: ElggFile.php:103
$default
Definition: checkbox.php:35
Detect the MIME type of a file.
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:525
$filename
setFilename($name)
Set the filename of this file.
Definition: ElggFile.php:58
_elgg_services()
Get the global service provider.
Definition: elgglib.php:1292
$container_guid
if(elgg_view_exists("plugins/{$plugin_id}/settings")) $description
Definition: full.php:179
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:373
open($mode)
Open the file with the given mode.
Definition: ElggFile.php:195
elgg_get_file_simple_type($mime_type)
Returns the category of a file from its MIME type.
Definition: filestore.php:123
__sleep()
Get property names to serialize.
Definition: ElggFile.php:469
$comment owner_guid
Definition: save.php:45