Skip to content

Instantly share code, notes, and snippets.

@foxfabi
Created November 3, 2020 14:19
Show Gist options
  • Save foxfabi/c43f54c45418199a057e3c330e164187 to your computer and use it in GitHub Desktop.
Save foxfabi/c43f54c45418199a057e3c330e164187 to your computer and use it in GitHub Desktop.
<?php
/*******************************************************
* Author: Fabian Dennler <fabian.dennler@zli.ch>
* Released: 2020.11.02
*******************************************************
* Checkliste der Anforderungen
* ✔️ Dateisystem verwenden (optional)
* ✔️ Typenfunktionen verwenden
* ✔️ Reguläre Ausdrücke verwenden (optional)
* ✔️ UDF verwenden
* ✔️ Konstrukte zur Iteration und Selektion verwenden
*******************************************************/
// Keywords of images to search
$keywords[] = "abstract";
$keywords[] = "pattern";
// Resolution of wallpaper image
$resolution = "1920x1080";
// Destination filename in same folder
$destination = "wotd.jpg";
/***** DO NOT CHANGE ANYTHING BELOW THIS LINE *****/
// Check if there are at least 2 keywords
if (count($keywords) <= 1) {
notify("error", "Please provide at least 2 keywords");
exit();
}
// Shuffley keywords and extract two of them
shuffle($keywords);
$rand_keys = array_rand($keywords, 2);
$search[] = $keywords[$rand_keys[0]];
$search[] = $keywords[$rand_keys[1]];
// Check if format of resolution is correct
$regex= '/(\d{1,4})x(\d{1,4})$/i';
if (!preg_match($regex, $resolution)) {
notify("error", "Please provide a resolution like '800x600'");
exit();
}
// Check if a filename was provided
if(empty($destination)) {
notify("error", "Please provide a filename for storage");
exit();
}
// Fetch a random image from unsplash
$base_url = "https://source.unsplash.com/random/";
$fetch_url = $base_url . $resolution . "/?" . implode(",", $search);
notify("info", sprintf("Fetching %s", $fetch_url));
$data = file_get_contents($fetch_url);
$image = imagecreatefromstring($data);
if ($image !== false) {
if (imagesy($image) > 0) {
file_put_contents($destination, $data);
notify("info", sprintf("Saved Wallpaper to %s (%d x %d)", $destination, imagesx($image), imagesy($image)));
} else {
notify("error", "Something went terrible wrong!!!");
}
imagedestroy($image);
}
// Colorful CLI output
function notify($type, $message) {
$output = "";
$background['red'] = '41';
$foreground['white'] = '1;37';
$foreground['light_blue'] = '1;34';
if ($type === "error") {
$output .= "\033[" . $foreground['white'] . "m";
$output .= "\033[" . $background['red'] . "m";
} else {
$output .= "\033[" . $foreground['light_blue'] . "m";
}
$output .= $message . "\033[0m";
print $output . PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment