Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
namespace core_badges;
18
 
19
/**
20
 * Information on PNG file chunks can be found at http://www.w3.org/TR/PNG/#11Chunks
21
 * Some other info on PNG that I used http://garethrees.org/2007/11/14/pngcrush/
22
 *
23
 * Example of use:
24
 * $png = new png_metadata_handler('file.png');
25
 *
26
 * if ($png->check_chunks("tEXt", "openbadge")) {
27
 *     $newcontents = $png->add_chunks("tEXt", "openbadge", 'http://some.public.url/to.your.assertion.file');
28
 * }
29
 *
30
 * file_put_contents('file.png', $newcontents);
31
 */
32
 
33
/**
34
 * Baking badges - PNG metadata handler.
35
 *
36
 * @package    core_badges
37
 * @copyright  2012 onwards Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
38
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39
 * @author     Yuliya Bozhko <yuliya.bozhko@totaralms.com>
40
 */
41
class png_metadata_handler
42
{
43
    /** @var string File content as a string */
44
    private string $_contents;
45
    /** @var int Length of the image file */
46
    private int $_size;
47
    /** @var array Variable for storing parsed chunks */
48
    private array $_chunks;
49
 
50
    /**
51
     * Prepares file for handling metadata.
52
     * Verifies that this file is a valid PNG file.
53
     * Unpacks file chunks and reads them into an array.
54
     *
55
     * @param string $contents File content as a string
56
     */
57
    public function __construct(string $contents) {
58
        $this->_contents = $contents;
59
        $png_signature = pack("C8", 137, 80, 78, 71, 13, 10, 26, 10);
60
 
61
        // Read 8 bytes of PNG header and verify.
62
        $header = substr($this->_contents, 0, 8);
63
 
64
        if ($header != $png_signature) {
65
            debugging('This is not a valid PNG image');
66
        }
67
 
68
        $this->_size = strlen($this->_contents);
69
 
70
        $this->_chunks = array();
71
 
72
        // Skip 8 bytes of IHDR image header.
73
        $position = 8;
74
        do {
75
            $chunk = @unpack('Nsize/a4type', substr($this->_contents, $position, 8));
76
            $this->_chunks[$chunk['type']][] = substr($this->_contents, $position + 8, $chunk['size']);
77
 
78
            // Skip 12 bytes chunk overhead.
79
            $position += $chunk['size'] + 12;
80
        } while ($position < $this->_size);
81
    }
82
 
83
    /**
84
     * Checks if a key already exists in the chunk of said type.
85
     * We need to avoid writing same keyword into file chunks.
86
     *
87
     * @param string $type Chunk type, like iTXt, tEXt, etc.
88
     * @param string $check Keyword that needs to be checked.
89
     *
90
     * @return boolean (true|false) True if file is safe to write this keyword, false otherwise.
91
     */
92
    public function check_chunks(string $type, string $check): bool {
93
        if (array_key_exists($type, $this->_chunks)) {
94
            foreach (array_keys($this->_chunks[$type]) as $typekey) {
95
                list($key, $data) = explode("\0", $this->_chunks[$type][$typekey]);
96
 
97
                if (strcmp($key, $check) == 0) {
98
                    debugging('Key "' . $check . '" already exists in "' . $type . '" chunk.');
99
                    return false;
100
                }
101
            }
102
        }
103
        return true;
104
    }
105
 
106
    /**
107
     * Adds a chunk with keyword and data to the file content.
108
     * Chunk is added to the end of the file, before IEND image trailer.
109
     *
110
     * @param string $type Chunk type, like iTXt, tEXt, etc.
111
     * @param string $key Keyword that needs to be added.
112
     * @param string $value Currently an assertion URL that is added to an image metadata.
113
     *
114
     * @return string $result File content with a new chunk as a string. Can be used in file_put_contents() to write to a file.
115
     * @throws \moodle_exception when unsupported chunk type is defined.
116
     */
117
    public function add_chunks(string $type, string $key, string $value): string {
118
        if (strlen($key) > 79) {
119
            debugging('Key is too big');
120
        }
121
 
122
        $dataparts = [];
123
        if ($type === 'iTXt') {
124
            // International textual data (iTXt).
125
            // Keyword:             1-79 bytes (character string).
126
            $dataparts[] = $key;
127
            // Null separator:      1 byte.
128
            $dataparts[] = "\x00";
129
            // Compression flag:    1 byte
130
            // A value of 0 means no compression.
131
            $dataparts[] = "\x00";
132
            // Compression method:  1 byte
133
            // If compression is disabled, the method should also be 0.
134
            $dataparts[] = "\x00";
135
            // Language tag:        0 or more bytes (character string)
136
            // When there is no language specified leave empty.
137
 
138
            // Null separator:      1 byte.
139
            $dataparts[] = "\x00";
140
            // Translated keyword:  0 or more bytes
141
            // When there is no translation specified, leave empty.
142
 
143
            // Null separator:      1 byte.
144
            $dataparts[] = "\x00";
145
            // Text:                0 or more bytes.
146
            $dataparts[] = $value;
147
        } else if ($type === 'tEXt') {
148
            // Textual data (tEXt).
149
            // Keyword:             1-79 bytes (character string).
150
            $dataparts[] = $key;
151
            // Null separator:      1 byte.
152
            $dataparts[] = "\0";
153
            // Text:                n bytes (character string).
154
            $dataparts[] = $value;
155
        } else {
156
            throw new \moodle_exception('Unsupported chunk type: ' . $type);
157
        }
158
 
159
        $data = implode($dataparts);
160
 
161
        $crc = pack("N", crc32($type . $data));
162
        $len = pack("N", strlen($data));
163
 
164
        // Chunk format: length + type + data + CRC.
165
        // CRC is a CRC-32 computed over the chunk type and chunk data.
166
        $newchunk = $len . $type . $data . $crc;
167
        $this->_chunks[$type] = $data;
168
 
169
        $result = substr($this->_contents, 0, $this->_size - 12)
170
                . $newchunk
171
                . substr($this->_contents, $this->_size - 12, 12);
172
 
173
        return $result;
174
    }
175
}