+
+ /**
+ * Delete gallery and drawings that are not within HTML content of pages or page revisions.
+ * Checks based off of only the image name.
+ * Could be much improved to be more specific but kept it generic for now to be safe.
+ *
+ * Returns the path of the images that would be/have been deleted.
+ * @param bool $checkRevisions
+ * @param bool $dryRun
+ * @param array $types
+ * @return array
+ */
+ public function deleteUnusedImages($checkRevisions = true, $dryRun = true, $types = ['gallery', 'drawio'])
+ {
+ $types = array_intersect($types, ['gallery', 'drawio']);
+ $deletedPaths = [];
+
+ $this->image->newQuery()->whereIn('type', $types)
+ ->chunk(1000, function($images) use ($types, $checkRevisions, &$deletedPaths, $dryRun) {
+ foreach ($images as $image) {
+ $searchQuery = '%' . basename($image->path) . '%';
+ $inPage = DB::table('pages')
+ ->where('html', 'like', $searchQuery)->count() > 0;
+ $inRevision = false;
+ if ($checkRevisions) {
+ $inRevision = DB::table('page_revisions')
+ ->where('html', 'like', $searchQuery)->count() > 0;
+ }
+
+ if (!$inPage && !$inRevision) {
+ $deletedPaths[] = $image->path;
+ if (!$dryRun) {
+ $this->destroy($image);
+ }
+ }
+ }
+ });
+ return $deletedPaths;
+ }
+
+ /**
+ * Convert a image URI to a Base64 encoded string.
+ * Attempts to find locally via set storage method first.
+ * @param string $uri
+ * @return null|string
+ * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
+ */
+ public function imageUriToBase64(string $uri)
+ {
+ $isLocal = strpos(trim($uri), 'http') !== 0;
+
+ // Attempt to find local files even if url not absolute
+ $base = baseUrl('/');
+ if (!$isLocal && strpos($uri, $base) === 0) {
+ $isLocal = true;
+ $uri = str_replace($base, '', $uri);
+ }
+
+ $imageData = null;
+
+ if ($isLocal) {
+ $uri = trim($uri, '/');
+ $storage = $this->getStorage();
+ if ($storage->exists($uri)) {
+ $imageData = $storage->get($uri);
+ }
+ } else {
+ try {
+ $ch = curl_init();
+ curl_setopt_array($ch, [CURLOPT_URL => $uri, CURLOPT_RETURNTRANSFER => 1, CURLOPT_CONNECTTIMEOUT => 5]);
+ $imageData = curl_exec($ch);
+ $err = curl_error($ch);
+ curl_close($ch);
+ if ($err) {
+ throw new \Exception("Image fetch failed, Received error: " . $err);
+ }
+ } catch (\Exception $e) {
+ }
+ }
+
+ if ($imageData === null) {
+ return null;
+ }
+
+ return 'data:image/' . pathinfo($uri, PATHINFO_EXTENSION) . ';base64,' . base64_encode($imageData);
+ }
+