dd907e0b41274589827c0ee4200bb4fe14a58235
[surrogator.git] / surrogator.php
1 #!/usr/bin/env php
2 <?php
3 /**
4  * Tool to create avatar images in different sizes.
5  *
6  * Part of Surrogator - a simple libravatar avatar image server
7  *
8  * PHP version 5
9  *
10  * @category Tools
11  * @package  Surrogator
12  * @author   Christian Weiske <cweiske@cweiske.de>
13  * @license  http://www.gnu.org/licenses/agpl.html AGPLv3 or later
14  * @link     http://git.cweiske.de/?p=surrogator.git
15  */
16 namespace surrogator;
17 $cfgFile = __DIR__ . '/data/surrogator.config.php';
18 if (!file_exists($cfgFile)) {
19     $cfgFile = '/etc/surrogator.config.php';
20     if (!file_exists($cfgFile)) {
21         logErr(
22             "Configuration file does not exist.\n"
23             . "Copy data/surrogator.config.php.dist to data/surrogator.config.php"
24         );
25         exit(2);
26     }
27 }
28 require $cfgFile;
29
30 array_shift($argv);
31 $files = array();
32 foreach ($argv as $arg) {
33     if ($arg == '-v' || $arg == '--verbose') {
34         ++$logLevel;
35     } else if ($arg == '-vv') {
36         $logLevel += 2;
37     } else if ($arg == '-q' || $arg == '--quiet') {
38         $logLevel = 0;
39     } else if ($arg == '-f' || $arg == '--force') {
40         $forceUpdate = true;
41     } else if ($arg == '-h' || $arg == '--help') {
42         showHelp();
43         exit(4);
44     } else if ($arg == '--version') {
45         echo "surrogator 0.0.1\n";
46         exit();
47     } else if (file_exists($arg)) {
48         $files[] = $arg;
49     } else {
50         logErr('Unknown argument: ' . $arg);
51         exit(3);
52     }
53 }
54
55 /**
56  * Echos the --help screen.
57  *
58  * @return void
59  */
60 function showHelp()
61 {
62     echo <<<HLP
63 Usage: php surrogator.php [options] [filename(s)]
64
65 surrogator - a simple libravatar server
66  Put files in raw/ dir and run surrogator.php to generate different sizes
67
68 Options:
69
70  -h, --help     Show help
71  -v, --verbose  Be verbose (more log messages, also -vv)
72  -q, --quiet    Be quiet (no log messages)
73  -f, --force    Force update of all files
74      --version  Show program version
75
76 filenames       One or several files whose small images shall get generated.
77                 If none given, all will be checked
78
79 HLP;
80 }
81
82 if (!isset($rawDir)) {
83     logErr('$rawDir not set');
84     exit(1);
85 }
86 if (!isset($varDir)) {
87     logErr('$varDir not set');
88     exit(1);
89 }
90 if (!isset($sizes)) {
91     logErr('$sizes not set');
92     exit(1);
93 }
94 if (!isset($maxSize)) {
95     logErr('$maxSize not set');
96     exit(1);
97 }
98 if (!isset($logLevel)) {
99     logErr('$logLevel not set');
100     exit(1);
101 }
102
103
104 if (!is_dir($varDir . '/square')) {
105     log('creating square dir: ' . $varDir . '/square');
106     if (!mkdir($varDir . '/square', 0755, true)) {
107         logErr('cannot create square dir');
108         exit(5);
109     }
110 }
111 log('sizes: ' . implode(', ', $sizes), 2);
112 foreach ($sizes as $size) {
113     if (!is_dir($varDir . '/' . $size)) {
114         log('creating size dir: ' . $varDir . '/' . $size);
115         mkdir($varDir . '/' . $size, 0755);
116     }
117 }
118 if (!file_exists($rawDir . '/mm.png')) {
119     log('mm.png missing, copying it from res/', 2);
120     copy(__DIR__ . '/res/mm.png', $rawDir . '/mm.png');
121 }
122
123 if (count($files)) {
124     $fileInfos = array();
125     foreach ($files as $file) {
126         $fileInfos[] = new \SplFileInfo($file);
127     }
128 } else {
129     $fileInfos = new \RegexIterator(
130         new \DirectoryIterator($rawDir),
131         '#^.+\.(png|jpg)$#'
132     );
133 }
134 foreach ($fileInfos as $fileInfo) {
135     $origPath   = $fileInfo->getPathname();
136     $fileName   = $fileInfo->getFilename();
137     $ext        = strtolower(substr($fileName, strrpos($fileName, '.') + 1));
138     $squarePath = $varDir . '/square/'
139         . substr($fileName, 0, -strlen($ext)) . 'png';
140
141     log('processing ' . $fileName, 1);
142     if (imageUptodate($origPath, $squarePath)) {
143         log(' image up to date', 2);
144         continue;
145     }
146
147     if (!createSquare($origPath, $ext, $squarePath, $maxSize)) {
148         continue;
149     }
150
151     if ($fileName == 'default.png') {
152         $md5 = $sha256 = 'default';
153     } else if ($fileName == 'mm.png') {
154         $md5 = $sha256 = 'mm';
155     } else {
156         list($md5, $sha256) = getHashes($fileName);
157     }
158
159     log(' creating sizes for ' . $fileName, 2);
160     log(' md5:    ' . $md5, 3);
161     log(' sha256: ' . $sha256, 3);
162     $imgSquare = imagecreatefrompng($squarePath);
163     foreach ($sizes as $size) {
164         log(' size ' . $size, 3);
165         $sizePathMd5    = $varDir . '/' . $size . '/' . $md5 . '.png';
166         $sizePathSha256 = $varDir . '/' . $size . '/' . $sha256 . '.png';
167
168         $imgSize = imagecreatetruecolor($size, $size);
169         imagealphablending($imgSize, false);
170         imagefilledrectangle(
171             $imgSize, 0, 0, $size - 1, $size - 1,
172             imagecolorallocatealpha($imgSize, 0, 0, 0, 127)
173         );
174         imagecopyresampled(
175             $imgSize, $imgSquare,
176             0, 0, 0, 0,
177             $size, $size, $maxSize, $maxSize
178         );
179         imagesavealpha($imgSize, true);
180         imagepng($imgSize, $sizePathMd5);
181         imagepng($imgSize, $sizePathSha256);
182         imagedestroy($imgSize);
183
184     }
185     imagedestroy($imgSquare);
186 }
187
188 /**
189  * Create and return md5 and sha256 hashes from a filename.
190  *
191  * @param string $fileName filename without path, e.g. "foo@example.org.png"
192  *
193  * @return array Array with 2 values: md5 and sha256 hash
194  */
195 function getHashes($fileName)
196 {
197     $fileNameNoExt = substr($fileName, 0, -strlen(strrpos($fileName, '.')) - 2);
198     $emailAddress  = trim(strtolower($fileNameNoExt));
199
200     return array(
201         md5($emailAddress), hash('sha256', $emailAddress)
202     );
203 }
204
205 /**
206  * Creates the square image from the given image in maximum size.
207  * Scales the image up or down and makes the non-covered parts transparent.
208  *
209  * @param string  $origPath   Full path to original image
210  * @param string  $ext        File extension ("jpg" or "png")
211  * @param string  $targetPath Full path to target image file
212  * @param integer $maxSize    Maxium image size the server supports
213  *
214  * @return boolean True if all went well, false if there was an error
215  */
216 function createSquare($origPath, $ext, $targetPath, $maxSize)
217 {
218     if ($ext == 'png') {
219         $imgOrig = imagecreatefrompng($origPath);
220     } else if ($ext == 'jpg' || $ext == 'jpeg') {
221         $imgOrig = imagecreatefromjpeg($origPath);
222     } else {
223         //unsupported format
224         return false;
225     }
226
227     if ($imgOrig === false) {
228         logErr('Error loading image file: ' . $origPath);
229         return false;
230     }
231
232     $imgSquare = imagecreatetruecolor($maxSize, $maxSize);
233     imagealphablending($imgSquare, false);
234     imagefilledrectangle(
235         $imgSquare, 0, 0, $maxSize - 1, $maxSize - 1,
236         imagecolorallocatealpha($imgSquare, 0, 0, 0, 127)
237     );
238     imagealphablending($imgSquare, true);
239
240     $oWidth    = imagesx($imgOrig);
241     $oHeight   = imagesy($imgOrig);
242     if ($oWidth > $oHeight) {
243         $flScale = $maxSize / $oWidth;
244     } else {
245         $flScale = $maxSize / $oHeight;
246     }
247     $nWidth  = (int)($oWidth * $flScale);
248     $nHeight = (int)($oHeight * $flScale);
249
250     imagecopyresampled(
251         $imgSquare, $imgOrig,
252         ($maxSize - $nWidth) / 2, ($maxSize - $nHeight) / 2,
253         0, 0,
254         $nWidth, $nHeight,
255         $oWidth, $oHeight
256     );
257
258     imagesavealpha($imgSquare, true);
259     imagepng($imgSquare, $targetPath);
260
261     imagedestroy($imgSquare);
262     imagedestroy($imgOrig);
263     return true;
264 }
265
266 /**
267  * Check if the target file is newer than the source file.
268  *
269  * @param string $sourcePath Full source file path
270  * @param string $targetPath Full target file path
271  *
272  * @return boolean True if target file is newer than the source file
273  */
274 function imageUptodate($sourcePath, $targetPath)
275 {
276     global $forceUpdate;
277     if ($forceUpdate) {
278         return false;
279     }
280     if (!file_exists($targetPath)) {
281         return false;
282     }
283     if (filemtime($sourcePath) > filemtime($targetPath)) {
284         //source newer
285         return false;
286     }
287
288     return true;
289 }
290
291 /**
292  * Write a log message to stdout
293  *
294  * @param string  $msg   Message to write
295  * @param integer $level Log level - 1 is important, 3 is unimportant
296  *
297  * @return void
298  */
299 function log($msg, $level = 1)
300 {
301     global $logLevel;
302     if ($level <= $logLevel) {
303         echo $msg . "\n";
304     }
305 }
306
307 /**
308  * Write an error message to stderr
309  *
310  * @param string $msg Message to write
311  *
312  * @return void
313  */
314 function logErr($msg)
315 {
316     file_put_contents('php://stderr', $msg . "\n");
317 }
318
319 ?>