Jake Vanderwerf
4 hours ago 88d9e0e2b7997eb0c96dc737082c91b4e3f7ca6e
inc/managers/queue/executors/UploadExecutor.php
@@ -7,7 +7,8 @@
use JVBase\meta\Meta;
use Exception;
use JVBase\registrar\Registrar;
use JVBase\utility\Features;
use JVBase\base\Site;
use WP_Error;
if (!defined('ABSPATH')) {
   exit;
@@ -209,7 +210,43 @@
      }
      if (!empty($data['field_name'])) {
         $this->saveToMeta($data, $uploadResults);
         if ($data['field_name'] === 'timeline_gallery') {
            $registrar = Registrar::getInstance($data['content']);
            if ($registrar) {
               switch ($registrar->getType()) {
                  case 'post':
                     $meta = Meta::forPost($data['item_id']);
                     break;
                  case 'term':
                     $meta = Meta::forTerm($data['item_id']);
                     break;
                  case 'user':
                     $meta = Meta::forUser($data['item_id']);
                     break;
                  default:
                     $meta = false;
               }
               if ($meta) {
                  $title = $meta->get('post_title');
                  $current = $meta->get('number');
                  $i = empty($current) ? 1 : $current + 1;
                  foreach ($data['upload_ids'] as $uploadID) {
                     if (!array_key_exists($uploadID, $uploadResults)) {
                        continue;
                     }
                     $imgID = $uploadResults[$uploadID]['attachment_id'] ?? false;
                     if (!$imgID) {
                        continue;
                     }
                     $this->createTimelinePoint($imgID, $data['item_id'], $data['user'], $data['content'], $title, $i);
                     $i++;
                  }
               }
            }
         } else {
            $this->saveToMeta($data, $uploadResults);
         }
      }
      $progress->advance(1);
@@ -220,6 +257,25 @@
      );
   }
      protected function createTimelinePoint(int $imgID, int $parentID, int $user, string $postType, string $baseTitle, int $index):int|WP_Error
      {
         $title = $baseTitle.' - Treatment #'.$index;
         $args = [
            'post_type'    => jvbCheckBase($postType),
            'post_author'  => $user,
            'post_status'  => 'draft',
            'post_parent'  => $parentID,
            'post_title'   => $title,
            'post_name'    => sanitize_title($title)
         ];
         $child = wp_insert_post($args);
         if ($child && !is_wp_error($child)) {
            set_post_thumbnail($child, $imgID);
         }
         return $child;
      }
   /**
    * Process metadata updates for attachments
    */
@@ -232,6 +288,7 @@
      error_log('Processing Meta Update with data: '.print_r($data, true));
      foreach ($data as $uploadId => $info) {
         if (!is_array($info)) {
            error_log('Not an array for processing meta update: '.print_r($info, true));
            continue;
         }
         $success = true;
@@ -257,8 +314,6 @@
               continue;
            }
            $this->applyMeta($attachmentId, $info);
            $updatedCount++;
            $progress->advance(1);
@@ -269,10 +324,11 @@
            $errors[] = $e->getMessage();
         }
         if ($success) {
         if ($success && $attachmentId) {
            $postID = wp_get_post_parent_id($attachmentId);
            if ($postID && !in_array($postID, $postsAttachedTo)){
               $postsAttachedTo[] = $postID;
               //TODO: is there a better way?
            }
         }
@@ -538,7 +594,7 @@
               'post_author'  => $user,
               'post_status'  => 'draft',
               'post_title'   => $title,
               'post_slug'    => sanitize_title($title),
               'post_name'    => sanitize_title($title),
               'post_excerpt' => $excerpt
            ];
@@ -582,12 +638,10 @@
               foreach($childPosts as $i => $imgID) {
                  $treatment = $i + 1;
                  $args ['post_title'] = $title.' - Treatment #'.$treatment;
                  $child = wp_insert_post($args);
                  if ($child && !is_wp_error($child)) {
                     $createdChildren = $child;
                  $child = $this->createTimelinePoint($imgID, $parent, $args['post_author'], $args['post_type'], $title, $treatment);
                  if ($child && !is_wp_error($child) && $child> 0 ) {
                     $createdChildren[] = $child;
                     $usedUploads[] = $imgID;
                     set_post_thumbnail($child, $imgID);
                  }
               }
            }
@@ -627,14 +681,7 @@
   private function updateTimelineMetadata(int $parentId): void
   {
      // Get all child posts
      $children = get_children([
         'post_parent' => $parentId,
         'post_type' => get_post_type($parentId),
         'post_status' => ['publish', 'draft'],
         'orderby' => 'date',
         'order' => 'DESC',
         'fields' => 'ids'
      ]);
      $children = jvbTimelinePoints($parentId, get_post_type($parentId), ['any']);
      // Count includes parent + children
      $number = count($children) + 1;
@@ -650,24 +697,40 @@
   private function applyMeta(int $attachmentId, array $metadata): void
   {
      if (array_key_exists('image-alt-text', $metadata)) {
         update_post_meta($attachmentId, '_wp_attachment_image_alt', sanitize_text_field($metadata['image-alt-text']));
      }
      $postUpdates = [];
      foreach ($metadata as $key => $value) {
         //Remove the image_data| from the  meta's group formatting
         $base = 'image_data|';
         $key = str_replace($base, '', $key);
         if ($key === 'image-alt-text') {
            error_log('Updating Image Alt Text: '.print_r($value, true));
            update_post_meta($attachmentId, '_wp_attachment_image_alt', sanitize_text_field($value));
            continue;
         }
      if (array_key_exists('image-title', $metadata)) {
         $postUpdates['post_title'] = sanitize_text_field($metadata['image-title']);
         $k = match ($key) {
            'image-title'  => 'post_title',
            'image-caption' => 'post_excerpt',
            'image-description' => 'post_content',
            default => false
         };
         if (!$k) {
            error_log('No matching key for '.$key.' with value: '.print_r($value, true));
            continue;
         }
         $v = match ($key) {
            'image-title'  => sanitize_text_field($value),
            default        => sanitize_textarea_field($value)
         };
         $postUpdates[$k] = $v;
      }
      if (array_key_exists('image-caption', $metadata)) {
         $postUpdates['post_excerpt'] = sanitize_textarea_field($metadata['image-caption']);
      }
      if (array_key_exists('image-description', $metadata)) {
         $postUpdates['post_excerpt']= sanitize_textarea_field($metadata['image-caption']);
      }
      if (!empty($postUpdates)){
         $postUpdates['ID'] = $attachmentId;
         $postUpdates['post_type'] = 'attachment';
         error_log('Updating Image post with data: '.print_r($postUpdates, true));
         wp_update_post($postUpdates);
      }
   }