update readme
[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 foreach (array('mm.png', 'default.png') as $resFile) {
119     if (!file_exists($rawDir . '/' . $resFile)) {
120         log($resFile . ' missing, copying it from res/', 2);
121         copy(__DIR__ . '/res/' . $resFile, $rawDir . '/' . $resFile);
122     }
123 }
124
125 if (count($files)) {
126     $fileInfos = array();
127     foreach ($files as $file) {
128         $fileInfos[] = new \SplFileInfo($file);
129     }
130 } else {
131     $fileInfos = new \RegexIterator(
132         new \DirectoryIterator($rawDir),
133         '#^.+\.(png|jpg)$#'
134     );
135 }
136 foreach ($fileInfos as $fileInfo) {
137     $origPath   = $fileInfo->getPathname();
138     $fileName   = $fileInfo->getFilename();
139     $ext        = strtolower(substr($fileName, strrpos($fileName, '.') + 1));
140     $squarePath = $varDir . '/square/'
141         . substr($fileName, 0, -strlen($ext)) . 'png';
142
143     log('processing ' . $fileName, 1);
144     if (imageUptodate($origPath, $squarePath)) {
145         log(' image up to date', 2);
146         continue;
147     }
148
149     if (!createSquare($origPath, $ext, $squarePath, $maxSize)) {
150         continue;
151     }
152
153     if ($fileName == 'default.png') {
154         $md5 = $sha256 = 'default';
155     } else if ($fileName == 'mm.png') {
156         $md5 = $sha256 = 'mm';
157     } else {
158         list($md5, $sha256) = getHashes($fileName);
159     }
160
161     log(' creating sizes for ' . $fileName, 2);
162     log(' md5:    ' . $md5, 3);
163     log(' sha256: ' . $sha256, 3);
164     $imgSquare = imagecreatefrompng($squarePath);
165     foreach ($sizes as $size) {
166         log(' size ' . $size, 3);
167         $sizePathMd5    = $varDir . '/' . $size . '/' . $md5 . '.png';
168         $sizePathSha256 = $varDir . '/' . $size . '/' . $sha256 . '.png';
169
170         $imgSize = imagecreatetruecolor($size, $size);
171         imagealphablending($imgSize, false);
172         imagefilledrectangle(
173             $imgSize, 0, 0, $size - 1, $size - 1,
174             imagecolorallocatealpha($imgSize, 0, 0, 0, 127)
175         );
176         imagecopyresampled(
177             $imgSize, $imgSquare,
178             0, 0, 0, 0,
179             $size, $size, $maxSize, $maxSize
180         );
181         imagesavealpha($imgSize, true);
182         imagepng($imgSize, $sizePathMd5);
183         imagepng($imgSize, $sizePathSha256);
184         imagedestroy($imgSize);
185
186     }
187     imagedestroy($imgSquare);
188 }
189
190 /**
191  * Create and return md5 and sha256 hashes from a filename.
192  *
193  * @param string $fileName filename without path, e.g. "foo@example.org.png"
194  *
195  * @return array Array with 2 values: md5 and sha256 hash
196  */
197 function getHashes($fileName)
198 {
199     $fileNameNoExt = substr($fileName, 0, -strlen(strrpos($fileName, '.')) - 2);
200     $emailAddress  = trim(strtolower($fileNameNoExt));
201
202     return array(
203         md5($emailAddress), hash('sha256', $emailAddress)
204     );
205 }
206
207 /**
208  * Creates the square image from the given image in maximum size.
209  * Scales the image up or down and makes the non-covered parts transparent.
210  *
211  * @param string  $origPath   Full path to original image
212  * @param string  $ext        File extension ("jpg" or "png")
213  * @param string  $targetPath Full path to target image file
214  * @param integer $maxSize    Maxium image size the server supports
215  *
216  * @return boolean True if all went well, false if there was an error
217  */
218 function createSquare($origPath, $ext, $targetPath, $maxSize)
219 {
220     if ($ext == 'png') {
221         $imgOrig = imagecreatefrompng($origPath);
222     } else if ($ext == 'jpg' || $ext == 'jpeg') {
223         $imgOrig = imagecreatefromjpeg($origPath);
224     } else {
225         //unsupported format
226         return false;
227     }
228
229     if ($imgOrig === false) {
230         logErr('Error loading image file: ' . $origPath);
231         return false;
232     }
233
234     $imgSquare = imagecreatetruecolor($maxSize, $maxSize);
235     imagealphablending($imgSquare, false);
236     imagefilledrectangle(
237         $imgSquare, 0, 0, $maxSize - 1, $maxSize - 1,
238         imagecolorallocatealpha($imgSquare, 0, 0, 0, 127)
239     );
240     imagealphablending($imgSquare, true);
241
242     $oWidth    = imagesx($imgOrig);
243     $oHeight   = imagesy($imgOrig);
244     if ($oWidth > $oHeight) {
245         $flScale = $maxSize / $oWidth;
246     } else {
247         $flScale = $maxSize / $oHeight;
248     }
249     $nWidth  = (int)($oWidth * $flScale);
250     $nHeight = (int)($oHeight * $flScale);
251
252     imagecopyresampled(
253         $imgSquare, $imgOrig,
254         ($maxSize - $nWidth) / 2, ($maxSize - $nHeight) / 2,
255         0, 0,
256         $nWidth, $nHeight,
257         $oWidth, $oHeight
258     );
259
260     imagesavealpha($imgSquare, true);
261     imagepng($imgSquare, $targetPath);
262
263     imagedestroy($imgSquare);
264     imagedestroy($imgOrig);
265     return true;
266 }
267
268 /**
269  * Check if the target file is newer than the source file.
270  *
271  * @param string $sourcePath Full source file path
272  * @param string $targetPath Full target file path
273  *
274  * @return boolean True if target file is newer than the source file
275  */
276 function imageUptodate($sourcePath, $targetPath)
277 {
278     global $forceUpdate;
279     if ($forceUpdate) {
280         return false;
281     }
282     if (!file_exists($targetPath)) {
283         return false;
284     }
285     if (filemtime($sourcePath) > filemtime($targetPath)) {
286         //source newer
287         return false;
288     }
289
290     return true;
291 }
292
293 /**
294  * Write a log message to stdout
295  *
296  * @param string  $msg   Message to write
297  * @param integer $level Log level - 1 is important, 3 is unimportant
298  *
299  * @return void
300  */
301 function log($msg, $level = 1)
302 {
303     global $logLevel;
304     if ($level <= $logLevel) {
305         echo $msg . "\n";
306     }
307 }
308
309 /**
310  * Write an error message to stderr
311  *
312  * @param string $msg Message to write
313  *
314  * @return void
315  */
316 function logErr($msg)
317 {
318     file_put_contents('php://stderr', $msg . "\n");
319 }
320
321 ?>