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