1<?php
2
3namespace dokuwiki\Remote\Response;
4
5use dokuwiki\ChangeLog\MediaChangeLog;
6
7/**
8 * Represents a single media revision in the wiki.
9 */
10class Media extends ApiResponse
11{
12    /** @var string The media ID */
13    public $id;
14    /** @var int The media revision aka last modified timestamp */
15    public $revision;
16    /** @var int The page size in bytes */
17    public $size;
18    /** @var int The current user's permissions for this file */
19    public $permission;
20    /** @var bool Wether this is an image file */
21    public $isimage;
22    /** @var string MD5 sum over the file's content (if available and requested) */
23    public $hash;
24    /** @var string The author of this page revision (if available and requested) */
25    public $author;
26
27    /** @var string The file path to this media revision */
28    protected $file;
29
30    /**
31     * Media constructor.
32     *
33     * @param string $id The media ID
34     * @param int $revision The media revision aka last modified timestamp
35     * @param int $mtime The media revision aka last modified timestamp
36     * @param int|null $size The page size in bytes
37     * @param int|null $perms The current user's permissions for this file
38     * @param bool|null $isimage Wether this is an image file
39     * @param string $hash MD5 sum over the file's content
40     */
41    public function __construct(
42        $id,
43        $revision = 0,
44        $mtime = 0,
45        $size = null,
46        $perms = null,
47        $isimage = null,
48        $hash = '',
49        $author = ''
50    ) {
51        $this->id = $id;
52        $this->file = mediaFN($this->id, $revision);
53        $this->revision = $revision ?: $mtime ?: filemtime($this->file);
54        $this->size = $size ?? filesize($this->file);
55        $this->permission = $perms ?? auth_quickaclcheck($this->id);
56        ;
57        $this->isimage = (bool)($isimage ?? preg_match("/\.(jpe?g|gif|png)$/", $id));
58        $this->hash = $hash;
59        $this->author = $author;
60    }
61
62    /**
63     * Calculate the hash for this page
64     *
65     * This is a heavy operation and should only be called when needed.
66     */
67    public function calculateHash()
68    {
69        $this->hash = md5(io_readFile($this->file, false));
70    }
71
72    /**
73     * Retrieve the author of this page
74     */
75    public function retrieveAuthor()
76    {
77        $pagelog = new MediaChangeLog($this->id, 1024);
78        $info = $pagelog->getRevisionInfo($this->revision);
79        $this->author = is_array($info) ? ($info['user'] ?: $info['ip']) : '';
80    }
81
82    /** @inheritdoc */
83    public function __toString()
84    {
85        return $this->id . '@' . $this->revision;
86    }
87}
88