Example #1
0
 /**
  * Saves a string of comma-separated usernames or IDs to authors table
  *
  * @param   integer  $page_id the id of the page
  * @param   string   $authors string of authors
  * @return  boolean  True if authors successfully saved
  */
 public function updateAuthors($authors = NULL, $page_id = NULL)
 {
     $page_id = $page_id ?: $this->page_id;
     if (!$page_id) {
         $this->setError(Lang::txt("Missing argument (page_id: {$page_id})."));
         return false;
     }
     // Get the list of existing authors
     $ids = $this->getAuthorIds($page_id);
     $auths = array();
     // Turn the comma-separated string of authors into an array and loop through it
     if ($authors) {
         $authArray = explode(',', $authors);
         $authArray = array_map('trim', $authArray);
         foreach ($authArray as $author) {
             // Attempt to load each user
             $targetuser = User::getInstance($author);
             // Ensure we found an account
             if (!is_object($targetuser)) {
                 // No account found for this username/ID
                 // Move on to next record
                 continue;
             }
             // Check if they're already an existing author
             if (in_array($targetuser->get('id'), $ids)) {
                 // Add them to the existing authors array
                 $auths[] = $targetuser->get('id');
                 // Move on to next record
                 continue;
             }
             // Create a new author object and attempt to save the record
             $wpa = new self($this->_db);
             $wpa->page_id = $page_id;
             $wpa->user_id = $targetuser->get('id');
             if ($wpa->check()) {
                 if (!$wpa->store()) {
                     $this->setError($wpa->getError());
                 }
                 // Add them to the existing authors array
                 $auths[] = $targetuser->get('id');
             } else {
                 $this->setError("Error adding page author: (page_id: {$wpa->page_id}, user_id: {$wpa->user_id}).");
             }
         }
     }
     // Loop through the old author list and check for nay entries not in the new list
     // Remove any entries not found in the new list
     foreach ($ids as $id) {
         if (!in_array($id, $auths)) {
             $wpa = new self($this->_db);
             if (!$wpa->removeAuthor($page_id, $id)) {
                 $this->setError($wpa->getError());
             }
         }
     }
     if ($this->getError()) {
         return false;
     }
     return true;
 }