public function testInvalidCharset()
 {
     $this->markTestSkipped();
     $db = Propel::getDB(BookPeer::DATABASE_NAME);
     if ($db instanceof DBSQLite) {
         $this->markTestSkipped();
     }
     $a = new Author();
     $a->setFirstName("Б.");
     $a->setLastName("АКУНИН");
     $a->save();
     $authorNameWindows1251 = iconv("utf-8", "windows-1251", $a->getLastName());
     $a->setLastName($authorNameWindows1251);
     // Different databases seem to handle invalid data differently (no surprise, I guess...)
     if ($db instanceof DBPostgres) {
         try {
             $a->save();
             $this->fail("Expected an exception when saving non-UTF8 data to database.");
         } catch (Exception $x) {
             print $x;
         }
     } else {
         // No exception is thrown by MySQL ... (others need to be tested still)
         $a->save();
         $a->reload();
         $this->assertEquals("", $a->getLastName(), "Expected last_name to be empty (after inserting invalid charset data)");
     }
 }
Example #2
0
    public function testToStringUsesDefaultStringFormat()
    {
        $author = new Author();
        $author->setFirstName('John');
        $author->setLastName('Doe');
        $expected = <<<EOF
Id: null
FirstName: John
LastName: Doe
Email: null
Age: null

EOF;
        $this->assertEquals($expected, (string) $author, 'generated __toString() uses default string format and exportTo()');
        $publisher = new Publisher();
        $publisher->setId(345345);
        $publisher->setName('Peguinoo');
        $expected = <<<EOF
<?xml version="1.0" encoding="UTF-8"?>
<data>
  <Id>345345</Id>
  <Name><![CDATA[Peguinoo]]></Name>
</data>

EOF;
        $this->assertEquals($expected, (string) $publisher, 'generated __toString() uses default string format and exportTo()');
    }
 function runAuthorInsertion($i)
 {
     $author = new Author();
     $author->setFirstName('John' . $i);
     $author->setLastName('Doe' . $i);
     $author->save($this->con);
     $this->authors[] = $author->getId();
 }
Example #4
0
 public function lol()
 {
     $author = new Author();
     $author->setFirstName('Jane' . rand(1, 100));
     $author->setLastName('Austen' . rand(1, 100));
     $author->save();
     return $author;
 }
 function authorInsertion($firstName, $lastName)
 {
     $author = new \Author();
     $author->setFirstName($firstName);
     $author->setLastName($lastName);
     $author->save();
     return $author;
 }
Example #6
0
 function testSetLastName()
 {
     //Arrange
     $first_name = "J.K.";
     $last_name = "Rowling";
     $test_author = new Author($first_name, $last_name);
     //Act
     $test_author->setLastName("Rowling");
     $result = $test_author->getLastName();
     //Assert
     $this->assertEquals("Rowling", $result);
 }
 function runAuthorInsertion($i)
 {
     $author = new Author();
     $author->setFirstName('John' . $i);
     $author->setLastName('Doe' . $i);
     $this->session->persist($author);
     $this->authors[] = $author;
     $this->i++;
     if ($this->i >= 500) {
         $this->commit();
         $this->beginTransaction();
     }
 }
 public function testFromArray()
 {
     $author = new Author();
     $author->setFirstName('Jane');
     $author->setLastName('Austen');
     $author->save();
     $books = array(array('Title' => 'Mansfield Park', 'AuthorId' => $author->getId()), array('Title' => 'Pride And PRejudice', 'AuthorId' => $author->getId()));
     $col = new PropelObjectCollection();
     $col->setModel('Book');
     $col->fromArray($books);
     $col->save();
     $nbBooks = PropelQuery::from('Book')->count();
     $this->assertEquals(6, $nbBooks);
     $booksByJane = PropelQuery::from('Book b')->join('b.Author a')->where('a.LastName = ?', 'Austen')->count();
     $this->assertEquals(2, $booksByJane);
 }
 /**
  * Primary key should differ
  */
 public function testSavedObjectCreatesDifferentHashForIdenticalObjects()
 {
     $book1 = new Book();
     $book1->setTitle('Foo5');
     $book1->setISBN('1234');
     $author1 = new Author();
     $author1->setFirstName('JAne');
     $author1->setLastName('JAne');
     $author1->addBook($book1);
     $author1->save();
     $author2 = new Author();
     $author2->setFirstName('JAne');
     $author2->setLastName('JAne');
     $author2->addBook($book1);
     $author2->save();
     $this->assertNotEquals($author1->hashCode(), $author2->hashCode());
 }
 public function testSerializeObjectWithCollections()
 {
     $book1 = new Book();
     $book1->setTitle('Foo5');
     $book1->setISBN('1234');
     $book2 = new Book();
     $book2->setTitle('Foo6');
     $book2->setISBN('1234');
     $author = new Author();
     $author->setFirstName('JAne');
     $author->setLastName('JAne');
     $author->addBook($book1);
     $author->addBook($book2);
     $author->save();
     $a = clone $author;
     $sa = serialize($a);
     $author->clearAllReferences();
     $this->assertEquals($author, unserialize($sa));
 }
 protected function setUp()
 {
     parent::setUp();
     $publisher = new Publisher();
     $publisher->setId(1234);
     $publisher->setName('Penguin');
     $author = new Author();
     $author->setId(5678);
     $author->setFirstName('George');
     $author->setLastName('Byron');
     $book = new Book();
     $book->setId(9012);
     $book->setTitle('Don Juan');
     $book->setISBN('0140422161');
     $book->setPrice(12.99);
     $book->setAuthor($author);
     $book->setPublisher($publisher);
     $this->book = $book;
 }
 public function setUp()
 {
     parent::setUp();
     $a = new Author();
     $a->setFirstName("Douglas");
     $a->setLastName("Adams");
     $b1 = new Book();
     $b1->setTitle("The Hitchhikers Guide To The Galaxy");
     $a->addBook($b1);
     $b2 = new Book();
     $b2->setTitle("The Restaurant At The End Of The Universe");
     $a->addBook($b2);
     $a->save();
     $this->author = $a;
     $this->books = array($b1, $b2);
     Propel::enableInstancePooling();
     // Clear author instance pool so the object would be fetched from the database
     AuthorPeer::clearInstancePool();
 }
Example #13
0
$can_save = false;
if ($id > -1 && strlen($first_name) > 0 && strlen($last_name) > 0) {
    $can_save = true;
}
if ($can_save) {
    $author = new Author();
    if ($id > 0) {
        $author = new Author($id);
        $isNewAuthor = false;
    } else {
        $author->create(array('first_name' => $first_name, 'last_name' => $last_name));
        $isNewAuthor = true;
    }
    $uploadFileSpecified = isset($_FILES['file']) && isset($_FILES['file']['name']) && !empty($_FILES['file']['name']);
    $author->setFirstName($first_name);
    $author->setLastName($last_name);
    $author->commit();
    // Reset types
    $types = Input::Get('type', 'array', array());
    AuthorAssignedType::ResetAuthorAssignedTypes($author->getId());
    foreach ($types as $type) {
        $author->setType($type);
    }
    $author->setSkype(Input::Get('skype'));
    $author->setJabber(Input::Get('jabber'));
    $author->setAim(Input::Get('aim'));
    $author->setEmail(Input::Get('email'));
    $authorBiography = array();
    $authorBiography['biography'] = Input::Get("txt_biography", "string");
    $authorBiography['language'] = Input::Get("lang", "int", 0);
    $authorBiography['first_name'] = Input::Get("lang_first_name");
 public function testNestedTransactionForceRollBack()
 {
     $con = Propel::getConnection(BookPeer::DATABASE_NAME);
     $driver = $con->getAttribute(PDO::ATTR_DRIVER_NAME);
     // main transaction
     $con->beginTransaction();
     $a = new Author();
     $a->setFirstName('Test');
     $a->setLastName('User');
     $a->save($con);
     $authorId = $a->getId();
     // nested transaction
     $con->beginTransaction();
     $a2 = new Author();
     $a2->setFirstName('Test2');
     $a2->setLastName('User2');
     $a2->save($con);
     $authorId2 = $a2->getId();
     // force rollback
     $con->forceRollback();
     $this->assertEquals(0, $con->getNestedTransactionCount(), 'nested transaction is null after nested transaction forced rollback');
     $this->assertFalse($con->isInTransaction(), 'PropelPDO is not in transaction after nested transaction force rollback');
     AuthorPeer::clearInstancePool();
     $at = AuthorPeer::retrieveByPK($authorId);
     $this->assertNull($at, "Rolled back transaction is not persisted in database");
     $at2 = AuthorPeer::retrieveByPK($authorId2);
     $this->assertNull($at2, "Forced Rolled back nested transaction is not persisted in database");
 }
Example #15
0
 /**
  * Save changes to article.
  * @param $request PKPRequest
  * @return int the article ID
  */
 function execute(&$request)
 {
     $articleDao =& DAORegistry::getDAO('ArticleDAO');
     $authorDao =& DAORegistry::getDAO('AuthorDAO');
     $sectionDao =& DAORegistry::getDAO('SectionDAO');
     $citationDao =& DAORegistry::getDAO('CitationDAO');
     /* @var $citationDao CitationDAO */
     $article =& $this->article;
     // Retrieve the previous citation list for comparison.
     $previousRawCitationList = $article->getCitations();
     // Update article
     $article->setTitle($this->getData('title'), null);
     // Localized
     $section =& $sectionDao->getSection($article->getSectionId());
     $article->setAbstract($this->getData('abstract'), null);
     // Localized
     import('classes.file.PublicFileManager');
     $publicFileManager = new PublicFileManager();
     if ($publicFileManager->uploadedFileExists(COVER_PAGE_IMAGE_NAME)) {
         $journal = Request::getJournal();
         $originalFileName = $publicFileManager->getUploadedFileName(COVER_PAGE_IMAGE_NAME);
         $type = $publicFileManager->getUploadedFileType(COVER_PAGE_IMAGE_NAME);
         $newFileName = 'cover_article_' . $this->article->getId() . '_' . $this->getFormLocale() . $publicFileManager->getImageExtension($type);
         $publicFileManager->uploadJournalFile($journal->getId(), COVER_PAGE_IMAGE_NAME, $newFileName);
         $article->setOriginalFileName($publicFileManager->truncateFileName($originalFileName, 127), $this->getFormLocale());
         $article->setFileName($newFileName, $this->getFormLocale());
         // Store the image dimensions.
         list($width, $height) = getimagesize($publicFileManager->getJournalFilesPath($journal->getId()) . '/' . $newFileName);
         $article->setWidth($width, $this->getFormLocale());
         $article->setHeight($height, $this->getFormLocale());
     }
     $article->setCoverPageAltText($this->getData('coverPageAltText'), null);
     // Localized
     $showCoverPage = array_map(create_function('$arrayElement', 'return (int)$arrayElement;'), (array) $this->getData('showCoverPage'));
     foreach (array_keys($this->getData('coverPageAltText')) as $locale) {
         if (!array_key_exists($locale, $showCoverPage)) {
             $showCoverPage[$locale] = 0;
         }
     }
     $article->setShowCoverPage($showCoverPage, null);
     // Localized
     $hideCoverPageToc = array_map(create_function('$arrayElement', 'return (int)$arrayElement;'), (array) $this->getData('hideCoverPageToc'));
     foreach (array_keys($this->getData('coverPageAltText')) as $locale) {
         if (!array_key_exists($locale, $hideCoverPageToc)) {
             $hideCoverPageToc[$locale] = 0;
         }
     }
     $article->setHideCoverPageToc($hideCoverPageToc, null);
     // Localized
     $hideCoverPageAbstract = array_map(create_function('$arrayElement', 'return (int)$arrayElement;'), (array) $this->getData('hideCoverPageAbstract'));
     foreach (array_keys($this->getData('coverPageAltText')) as $locale) {
         if (!array_key_exists($locale, $hideCoverPageAbstract)) {
             $hideCoverPageAbstract[$locale] = 0;
         }
     }
     $article->setHideCoverPageAbstract($hideCoverPageAbstract, null);
     // Localized
     $article->setDiscipline($this->getData('discipline'), null);
     // Localized
     $article->setSubjectClass($this->getData('subjectClass'), null);
     // Localized
     $article->setSubject($this->getData('subject'), null);
     // Localized
     $article->setCoverageGeo($this->getData('coverageGeo'), null);
     // Localized
     $article->setCoverageChron($this->getData('coverageChron'), null);
     // Localized
     $article->setCoverageSample($this->getData('coverageSample'), null);
     // Localized
     $article->setType($this->getData('type'), null);
     // Localized
     $article->setLanguage($this->getData('language'));
     // Localized
     $article->setSponsor($this->getData('sponsor'), null);
     // Localized
     $article->setCitations($this->getData('citations'));
     if ($this->isEditor) {
         $article->setHideAuthor($this->getData('hideAuthor') ? $this->getData('hideAuthor') : 0);
     }
     // consider the additional field names from the public identifer plugins
     import('classes.plugins.PubIdPluginHelper');
     $pubIdPluginHelper = new PubIdPluginHelper();
     $pubIdPluginHelper->execute($this, $article);
     // Update authors
     $authors = $this->getData('authors');
     for ($i = 0, $count = count($authors); $i < $count; $i++) {
         if ($authors[$i]['authorId'] > 0) {
             // Update an existing author
             $author =& $authorDao->getAuthor($authors[$i]['authorId'], $article->getId());
             $isExistingAuthor = true;
         } else {
             // Create a new author
             if (checkPhpVersion('5.0.0')) {
                 // *5488* PHP4 Requires explicit instantiation-by-reference
                 $author = new Author();
             } else {
                 $author =& new Author();
             }
             $isExistingAuthor = false;
         }
         if ($author != null) {
             $author->setSubmissionId($article->getId());
             $author->setFirstName($authors[$i]['firstName']);
             $author->setMiddleName($authors[$i]['middleName']);
             $author->setLastName($authors[$i]['lastName']);
             $author->setAffiliation($authors[$i]['affiliation'], null);
             // Localized
             $author->setCountry($authors[$i]['country']);
             $author->setEmail($authors[$i]['email']);
             $author->setData('orcid', $authors[$i]['orcid']);
             $author->setUrl($authors[$i]['url']);
             if (array_key_exists('competingInterests', $authors[$i])) {
                 $author->setCompetingInterests($authors[$i]['competingInterests'], null);
                 // Localized
             }
             $author->setBiography($authors[$i]['biography'], null);
             // Localized
             $author->setPrimaryContact($this->getData('primaryContact') == $i ? 1 : 0);
             $author->setSequence($authors[$i]['seq']);
             HookRegistry::call('Submission::Form::MetadataForm::Execute', array(&$author, &$authors[$i]));
             if ($isExistingAuthor) {
                 $authorDao->updateAuthor($author);
             } else {
                 $authorDao->insertAuthor($author);
             }
             unset($author);
         }
     }
     // Remove deleted authors
     $deletedAuthors = preg_split('/:/', $this->getData('deletedAuthors'), -1, PREG_SPLIT_NO_EMPTY);
     for ($i = 0, $count = count($deletedAuthors); $i < $count; $i++) {
         $authorDao->deleteAuthorById($deletedAuthors[$i], $article->getId());
     }
     if ($this->isEditor) {
         $article->setCopyrightHolder($this->getData('copyrightHolder'), null);
         $article->setCopyrightYear($this->getData('copyrightYear'));
         $article->setLicenseURL($this->getData('licenseURL'));
     }
     parent::execute();
     // Save the article
     $articleDao->updateArticle($article);
     // Update search index
     import('classes.search.ArticleSearchIndex');
     $articleSearchIndex = new ArticleSearchIndex();
     $articleSearchIndex->articleMetadataChanged($article);
     $articleSearchIndex->articleChangesFinished();
     // Update references list if it changed.
     $rawCitationList = $article->getCitations();
     if ($previousRawCitationList != $rawCitationList) {
         $citationDao->importCitations($request, ASSOC_TYPE_ARTICLE, $article->getId(), $rawCitationList);
     }
     return $article->getId();
 }
 public function testSetterOneToManyReplacesOldObjectsByNewObjects()
 {
     // Ensure no data
     BookQuery::create()->deleteAll();
     AuthorQuery::create()->deleteAll();
     $books = new PropelObjectCollection();
     foreach (array('foo', 'bar') as $title) {
         $b = new Book();
         $b->setTitle($title);
         $b->setIsbn('12354');
         $books[] = $b;
     }
     $a = new Author();
     $a->setFirstName('Foo');
     $a->setLastName('Bar');
     $a->setBooks($books);
     $a->save();
     $books = $a->getBooks();
     $this->assertEquals('foo', $books[0]->getTitle());
     $this->assertEquals('bar', $books[1]->getTitle());
     $books = new PropelObjectCollection();
     foreach (array('bam', 'bom') as $title) {
         $b = new Book();
         $b->setTitle($title);
         $b->setIsbn('1235');
         $books[] = $b;
     }
     $a->setBooks($books);
     $a->save();
     $books = $a->getBooks();
     $this->assertEquals('bam', $books[0]->getTitle());
     $this->assertEquals('bom', $books[1]->getTitle());
     $this->assertEquals(1, AuthorQuery::create()->count());
     // the replaced book are still there because the PK is not required
     $this->assertEquals(4, BookQuery::create()->count());
 }
Example #17
0
 function handleAuthorNode(&$conference, &$schedConf, &$authorNode, &$track, &$paper, &$errors)
 {
     $errors = array();
     $conferenceSupportedLocales = array_keys($conference->getSupportedLocaleNames());
     // => conference locales must be set up before
     $conferencePrimaryLocale = $conference->getPrimaryLocale();
     $author = new Author();
     if ($node = $authorNode->getChildByName('firstname')) {
         $author->setFirstName($node->getValue());
     }
     if ($node = $authorNode->getChildByName('middlename')) {
         $author->setMiddleName($node->getValue());
     }
     if ($node = $authorNode->getChildByName('lastname')) {
         $author->setLastName($node->getValue());
     }
     if ($node = $authorNode->getChildByName('affiliation')) {
         $author->setAffiliation($node->getValue());
     }
     if ($node = $authorNode->getChildByName('country')) {
         $author->setCountry($node->getValue());
     }
     if ($node = $authorNode->getChildByName('email')) {
         $author->setEmail($node->getValue());
     }
     if ($node = $authorNode->getChildByName('url')) {
         $author->setUrl($node->getValue());
     }
     for ($index = 0; $node = $authorNode->getChildByName('biography', $index); $index++) {
         $locale = $node->getAttribute('locale');
         if ($locale == '') {
             $locale = $conferencePrimaryLocale;
         } elseif (!in_array($locale, $conferenceSupportedLocales)) {
             $errors[] = array('plugins.importexport.native.import.error.paperAuthorBiographyLocaleUnsupported', array('authorFullName' => $author->getFullName(), 'paperTitle' => $paper->getLocalizedTitle(), 'locale' => $locale));
             return false;
         }
         $author->setBiography($node->getValue(), $locale);
     }
     $author->setPrimaryContact($authorNode->getAttribute('primary_contact') === 'true' ? 1 : 0);
     $paper->addAuthor($author);
     // instead of $author->setSequence($index+1);
     return true;
 }
 /**
  * Save changes to article.
  * @param $request Request
  * @return int the article ID
  */
 function execute()
 {
     $articleDao =& DAORegistry::getDAO('ArticleDAO');
     $authorDao =& DAORegistry::getDAO('AuthorDAO');
     $article =& $this->article;
     // Retrieve the previous citation list for comparison.
     $previousRawCitationList = $article->getCitations();
     // Update article
     $article->setTitle($this->getData('title'), null);
     // Localized
     $article->setAbstract($this->getData('abstract'), null);
     // Localized
     $article->setDiscipline($this->getData('discipline'), null);
     // Localized
     $article->setSubjectClass($this->getData('subjectClass'), null);
     // Localized
     $article->setSubject($this->getData('subject'), null);
     // Localized
     $article->setCoverageGeo($this->getData('coverageGeo'), null);
     // Localized
     $article->setCoverageChron($this->getData('coverageChron'), null);
     // Localized
     $article->setCoverageSample($this->getData('coverageSample'), null);
     // Localized
     $article->setType($this->getData('type'), null);
     // Localized
     $article->setLanguage($this->getData('language'));
     $article->setSponsor($this->getData('sponsor'), null);
     // Localized
     $article->setCitations($this->getData('citations'));
     if ($article->getSubmissionProgress() <= $this->step) {
         $article->stampStatusModified();
         $article->setSubmissionProgress($this->step + 1);
     }
     // Update authors
     $authors = $this->getData('authors');
     for ($i = 0, $count = count($authors); $i < $count; $i++) {
         if ($authors[$i]['authorId'] > 0) {
             // Update an existing author
             $author =& $authorDao->getAuthor($authors[$i]['authorId'], $article->getId());
             $isExistingAuthor = true;
         } else {
             // Create a new author
             $author = new Author();
             $isExistingAuthor = false;
         }
         if ($author != null) {
             $author->setSubmissionId($article->getId());
             $author->setFirstName($authors[$i]['firstName']);
             $author->setMiddleName($authors[$i]['middleName']);
             $author->setLastName($authors[$i]['lastName']);
             $author->setAffiliation($authors[$i]['affiliation'], null);
             $author->setCountry($authors[$i]['country']);
             $author->setEmail($authors[$i]['email']);
             $author->setData('orcid', $authors[$i]['orcid']);
             $author->setUrl($authors[$i]['url']);
             if (array_key_exists('competingInterests', $authors[$i])) {
                 $author->setCompetingInterests($authors[$i]['competingInterests'], null);
             }
             $author->setBiography($authors[$i]['biography'], null);
             $author->setPrimaryContact($this->getData('primaryContact') == $i ? 1 : 0);
             $author->setSequence($authors[$i]['seq']);
             HookRegistry::call('Author::Form::Submit::AuthorSubmitStep3Form::Execute', array(&$author, &$authors[$i]));
             if ($isExistingAuthor) {
                 $authorDao->updateAuthor($author);
             } else {
                 $authorDao->insertAuthor($author);
             }
         }
         unset($author);
     }
     // Remove deleted authors
     $deletedAuthors = preg_split('/:/', $this->getData('deletedAuthors'), -1, PREG_SPLIT_NO_EMPTY);
     for ($i = 0, $count = count($deletedAuthors); $i < $count; $i++) {
         $authorDao->deleteAuthorById($deletedAuthors[$i], $article->getId());
     }
     parent::execute();
     // Save the article
     $articleDao->updateArticle($article);
     // Update references list if it changed.
     $citationDao =& DAORegistry::getDAO('CitationDAO');
     $rawCitationList = $article->getCitations();
     if ($previousRawCitationList != $rawCitationList) {
         $citationDao->importCitations($this->request, ASSOC_TYPE_ARTICLE, $article->getId(), $rawCitationList);
     }
     return $this->articleId;
 }
 public function testFindOneWithDuplicateRelation()
 {
     EssayPeer::doDeleteAll();
     $auth1 = new Author();
     $auth1->setFirstName('John');
     $auth1->setLastName('Doe');
     $auth1->save();
     $auth2 = new Author();
     $auth2->setFirstName('Jack');
     $auth2->setLastName('Sparrow');
     $auth2->save();
     $essay = new Essay();
     $essay->setTitle('Foo');
     $essay->setFirstAuthor($auth1->getId());
     $essay->setSecondAuthor($auth2->getId());
     $essay->save();
     AuthorPeer::clearInstancePool();
     EssayPeer::clearInstancePool();
     $c = new ModelCriteria('bookstore', 'Essay');
     $c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND);
     $c->join('Essay.AuthorRelatedByFirstAuthor');
     $c->with('AuthorRelatedByFirstAuthor');
     $c->where('Essay.Title = ?', 'Foo');
     $c->limit(1);
     $con = Propel::getConnection(BookPeer::DATABASE_NAME);
     $essays = $c->find($con);
     foreach ($essays as $essay) {
         break;
     }
     $count = $con->getQueryCount();
     $this->assertEquals($essay->getTitle(), 'Foo', 'Main object is correctly hydrated');
     $firstAuthor = $essay->getAuthorRelatedByFirstAuthor();
     $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query');
     $this->assertEquals($firstAuthor->getFirstName(), 'John', 'Related object is correctly hydrated');
     $secondAuthor = $essay->getAuthorRelatedBySecondAuthor();
     $this->assertEquals($count + 1, $con->getQueryCount(), 'with() does not hydrate objects not in with');
 }
Example #20
0
 /**
  * Save settings.
  */
 function execute()
 {
     $articleDao = DAORegistry::getDAO('ArticleDAO');
     $signoffDao = DAORegistry::getDAO('SignoffDAO');
     $sectionEditorSubmissionDao = DAORegistry::getDAO('SectionEditorSubmissionDAO');
     $application = PKPApplication::getApplication();
     $request = $this->request;
     $user = $request->getUser();
     $router = $request->getRouter();
     $journal = $router->getContext($request);
     $article = $articleDao->newDataObject();
     $article->setLocale($journal->getPrimaryLocale());
     // FIXME in bug #5543
     $article->setUserId($user->getId());
     $article->setJournalId($journal->getId());
     $article->setSectionId($this->getData('sectionId'));
     $article->setLanguage($this->getData('language'));
     $article->setTitle($this->getData('title'), null);
     // Localized
     $article->setAbstract($this->getData('abstract'), null);
     // Localized
     $article->setDiscipline($this->getData('discipline'), null);
     // Localized
     $article->setSubjectClass($this->getData('subjectClass'), null);
     // Localized
     $article->setSubject($this->getData('subject'), null);
     // Localized
     $article->setCoverageGeo($this->getData('coverageGeo'), null);
     // Localized
     $article->setCoverageChron($this->getData('coverageChron'), null);
     // Localized
     $article->setCoverageSample($this->getData('coverageSample'), null);
     // Localized
     $article->setType($this->getData('type'), null);
     // Localized
     $article->setSponsor($this->getData('sponsor'), null);
     // Localized
     $article->setCitations($this->getData('citations'));
     $article->setPages($this->getData('pages'));
     // Set some default values so the ArticleDAO doesn't complain when adding this article
     $article->setDateSubmitted(Core::getCurrentDate());
     $article->setStatus(STATUS_PUBLISHED);
     $article->setSubmissionProgress(0);
     $article->stampStatusModified();
     $article->setCurrentRound(1);
     $article->setFastTracked(1);
     $article->setHideAuthor(0);
     $article->setCommentsStatus(0);
     // Insert the article to get it's ID
     $articleDao->insertObject($article);
     $articleId = $article->getId();
     // Add authors
     $authors = $this->getData('authors');
     for ($i = 0, $count = count($authors); $i < $count; $i++) {
         if ($authors[$i]['authorId'] > 0) {
             // Update an existing author
             $author =& $authorDao->getAuthor($authors[$i]['authorId'], $articleId);
             $isExistingAuthor = true;
         } else {
             // Create a new author
             $author = new Author();
             $isExistingAuthor = false;
         }
         if ($author != null) {
             $author->setSubmissionId($articleId);
             $author->setFirstName($authors[$i]['firstName']);
             $author->setMiddleName($authors[$i]['middleName']);
             $author->setLastName($authors[$i]['lastName']);
             if (array_key_exists('affiliation', $authors[$i])) {
                 $author->setAffiliation($authors[$i]['affiliation'], null);
             }
             $author->setCountry($authors[$i]['country']);
             $author->setEmail($authors[$i]['email']);
             $author->setUrl($authors[$i]['url']);
             if (array_key_exists('competingInterests', $authors[$i])) {
                 $author->setCompetingInterests($authors[$i]['competingInterests'], null);
             }
             $author->setBiography($authors[$i]['biography'], null);
             $author->setPrimaryContact($this->getData('primaryContact') == $i ? 1 : 0);
             $author->setSequence($authors[$i]['seq']);
             if ($isExistingAuthor == false) {
                 $authorDao = DAORegistry::getDAO('AuthorDAO');
                 /* @var $authorDao AuthorDAO */
                 $authorDao->insertObject($author);
             }
         }
     }
     // Add the submission files as galleys
     import('lib.pkp.classes.file.TemporaryFileManager');
     import('classes.file.ArticleFileManager');
     $tempFileIds = $this->getData('tempFileId');
     $temporaryFileManager = new TemporaryFileManager();
     $articleFileManager = new ArticleFileManager($articleId);
     $designatedPrimary = false;
     foreach (array_keys($tempFileIds) as $locale) {
         $temporaryFile = $temporaryFileManager->getFile($tempFileIds[$locale], $user->getId());
         $fileId = null;
         if ($temporaryFile) {
             $fileId = $articleFileManager->temporaryFileToArticleFile($temporaryFile, SUBMISSION_FILE_SUBMISSION);
             $fileType = $temporaryFile->getFileType();
             if (strstr($fileType, 'html')) {
                 import('classes.article.ArticleHTMLGalley');
                 $galley = new ArticleHTMLGalley();
             } else {
                 import('classes.article.ArticleGalley');
                 $galley = new ArticleGalley();
             }
             $galley->setArticleId($articleId);
             $galley->setFileId($fileId);
             $galley->setLocale($locale);
             if ($galley->isHTMLGalley()) {
                 $galley->setLabel('HTML');
             } else {
                 if (strstr($fileType, 'pdf')) {
                     $galley->setLabel('PDF');
                 } else {
                     if (strstr($fileType, 'postscript')) {
                         $galley->setLabel('Postscript');
                     } else {
                         if (strstr($fileType, 'xml')) {
                             $galley->setLabel('XML');
                         } else {
                             $galley->setLabel(__('common.untitled'));
                         }
                     }
                 }
             }
             $galleyDao = DAORegistry::getDAO('ArticleGalleyDAO');
             $galleyDao->insertGalley($galley);
             if (!$designatedPrimary) {
                 $article->setSubmissionFileId($fileId);
                 if ($locale == $journal->getPrimaryLocale()) {
                     // Used to make sure that *some* file
                     // is designated Review Version, but
                     // preferrably the primary locale.
                     $designatedPrimary = true;
                 }
             }
         }
         // Update file search index
         import('classes.search.ArticleSearchIndex');
         $articleSearchIndex = new ArticleSearchIndex();
         if (isset($galley)) {
             $articleSearchIndex->articleFileChanged($galley->getArticleId(), SUBMISSION_SEARCH_GALLEY_FILE, $galley->getFileId());
         }
         $articleSearchIndex->articleChangesFinished();
     }
     // Designate this as the review version by default.
     $authorSubmissionDao = DAORegistry::getDAO('AuthorSubmissionDAO');
     $authorSubmission =& $authorSubmissionDao->getAuthorSubmission($articleId);
     import('classes.submission.author.AuthorAction');
     AuthorAction::designateReviewVersion($authorSubmission, true);
     // Accept the submission
     $sectionEditorSubmission =& $sectionEditorSubmissionDao->getSectionEditorSubmission($articleId);
     $articleFileManager = new ArticleFileManager($articleId);
     import('classes.submission.sectionEditor.SectionEditorAction');
     assert(false);
     // FIXME: $decisionLabels missing from call below.
     SectionEditorAction::recordDecision($this->request, $sectionEditorSubmission, SUBMISSION_EDITOR_DECISION_ACCEPT);
     import('classes.author.form.submit.AuthorSubmitForm');
     AuthorSubmitForm::assignEditors($article);
     $articleDao->updateObject($article);
     // Add to end of editing queue
     import('classes.submission.editor.EditorAction');
     if (isset($galley)) {
         EditorAction::expediteSubmission($article, $this->request);
     }
     if ($this->getData('destination') == "issue") {
         // Add to an existing issue
         $issueId = $this->getData('issueId');
         $this->scheduleForPublication($articleId, $issueId);
     }
     // Import the references list.
     $citationDao = DAORegistry::getDAO('CitationDAO');
     $rawCitationList = $article->getCitations();
     $citationDao->importCitations($request, ASSOC_TYPE_ARTICLE, $articleId, $rawCitationList);
     // Index article.
     import('classes.search.ArticleSearchIndex');
     $articleSearchIndex = new ArticleSearchIndex();
     $articleSearchIndex->articleMetadataChanged($article);
     $articleSearchIndex->articleChangesFinished();
 }
 public function testFindWithLeftJoinWithOneToManyAndNullObject()
 {
     BookPeer::clearInstancePool();
     AuthorPeer::clearInstancePool();
     ReviewPeer::clearInstancePool();
     $freud = new Author();
     $freud->setFirstName("Sigmund");
     $freud->setLastName("Freud");
     $freud->save($this->con);
     $c = new ModelCriteria('bookstore', 'Author');
     $c->setFormatter(ModelCriteria::FORMAT_ARRAY);
     $c->add(AuthorPeer::LAST_NAME, 'Freud');
     $c->leftJoinWith('Author.Book');
     $c->leftJoinWith('Book.Review');
     // should not raise a notice
     $authors = $c->find($this->con);
     $this->assertTrue(true);
 }
 function handleAuthorNode(&$journal, &$authorNode, &$issue, &$section, &$article, &$errors)
 {
     $errors = array();
     $journalSupportedLocales = array_keys($journal->getSupportedLocaleNames());
     // => journal locales must be set up before
     $journalPrimaryLocale = $journal->getPrimaryLocale();
     $author = new Author();
     if ($node = $authorNode->getChildByName('firstname')) {
         $author->setFirstName($node->getValue());
     }
     if ($node = $authorNode->getChildByName('middlename')) {
         $author->setMiddleName($node->getValue());
     }
     if ($node = $authorNode->getChildByName('lastname')) {
         $author->setLastName($node->getValue());
     }
     for ($index = 0; $node = $authorNode->getChildByName('affiliation', $index); $index++) {
         $locale = $node->getAttribute('locale');
         if ($locale == '') {
             $locale = $journalPrimaryLocale;
         } elseif (!in_array($locale, $journalSupportedLocales)) {
             $errors[] = array('plugins.importexport.native.import.error.articleAuthorAffiliationLocaleUnsupported', array('authorFullName' => $author->getFullName(), 'articleTitle' => $article->getLocalizedTitle(), 'issueTitle' => $issue->getIssueIdentification(), 'locale' => $locale));
             return false;
         }
         $author->setAffiliation($node->getValue(), $locale);
     }
     if ($node = $authorNode->getChildByName('country')) {
         $author->setCountry($node->getValue());
     }
     if ($node = $authorNode->getChildByName('email')) {
         $author->setEmail($node->getValue());
     }
     if ($node = $authorNode->getChildByName('url')) {
         $author->setUrl($node->getValue());
     }
     for ($index = 0; $node = $authorNode->getChildByName('competing_interests', $index); $index++) {
         $locale = $node->getAttribute('locale');
         if ($locale == '') {
             $locale = $journalPrimaryLocale;
         } elseif (!in_array($locale, $journalSupportedLocales)) {
             $errors[] = array('plugins.importexport.native.import.error.articleAuthorCompetingInterestsLocaleUnsupported', array('authorFullName' => $author->getFullName(), 'articleTitle' => $article->getLocalizedTitle(), 'issueTitle' => $issue->getIssueIdentification(), 'locale' => $locale));
             return false;
         }
         $author->setCompetingInterests($node->getValue(), $locale);
     }
     for ($index = 0; $node = $authorNode->getChildByName('biography', $index); $index++) {
         $locale = $node->getAttribute('locale');
         if ($locale == '') {
             $locale = $journalPrimaryLocale;
         } elseif (!in_array($locale, $journalSupportedLocales)) {
             $errors[] = array('plugins.importexport.native.import.error.articleAuthorBiographyLocaleUnsupported', array('authorFullName' => $author->getFullName(), 'articleTitle' => $article->getLocalizedTitle(), 'issueTitle' => $issue->getIssueIdentification(), 'locale' => $locale));
             return false;
         }
         $author->setBiography($node->getValue(), $locale);
     }
     $author->setPrimaryContact($authorNode->getAttribute('primary_contact') === 'true' ? 1 : 0);
     $article->addAuthor($author);
     // instead of $author->setSequence($index+1);
     return true;
 }
 /**
  * Private function for returning a sample research proposal
  * @param type $approvalNotice
  * @return \SectionEditorSubmission
  */
 private function _createSampleProposal($approvalNotice)
 {
     $institutionDao =& DAORegistry::getDAO('InstitutionDAO');
     $extraFieldDao =& DAORegistry::getDAO('ExtraFieldDAO');
     $sectionDao =& DAORegistry::getDAO('SectionDAO');
     // Create the submission
     import('classes.submission.sectionEditor.SectionEditorSubmission');
     $sectionEditorSubmission = new SectionEditorSubmission();
     $sectionEditorSubmission->setProposalId('2014.76.RV');
     $sectionEditorSubmission->setDateSubmitted('2014-06-13 14:57:17');
     // Create the decision
     import('classes.article.SectionDecision');
     $sectionDecision = new SectionDecision();
     $sectionDecision->setSectionId($sectionDao->getRandomSectionId());
     $reviewTypes = $approvalNotice->getReviewTypesArray();
     if ($reviewTypes[0] != APPROVAL_NOTICE_TYPE_ALL) {
         $sectionDecision->setReviewType($reviewTypes[0]);
     } else {
         $sectionDecision->setReviewType(1);
     }
     $sectionDecision->setRound(2);
     $sectionEditorSubmission->setDecisions(array(0 => $sectionDecision));
     // Create the investigators
     import('classes.article.Author');
     $firstInvestigator = new Author();
     $firstInvestigator->setFirstName('Jane');
     $firstInvestigator->setLastName('Roe');
     $firstInvestigator->setPrimaryContact(1);
     $firstInvestigator->setAffiliation('World Health Organization, Western Pacific Regional Office');
     $coInvestigator1 = new Author();
     $coInvestigator1->setFirstName('John');
     $coInvestigator1->setLastName('Doe');
     $coInvestigator1->setPrimaryContact(0);
     $coInvestigator1->setAffiliation('National Public Health Institution');
     $coInvestigator2 = new Author();
     $coInvestigator2->setFirstName('Marie');
     $coInvestigator2->setMiddleName('Elizabeth');
     $coInvestigator2->setLastName('Watson');
     $coInvestigator2->setPrimaryContact(0);
     $coInvestigator2->setAffiliation('HUYBN');
     $coInvestigator3 = new Author();
     $coInvestigator3->setFirstName('Pascal');
     $coInvestigator3->setLastName('Lavaud');
     $coInvestigator3->setPrimaryContact(0);
     $coInvestigator3->setAffiliation('Cabinet MEDICAL, Avenue Bollée');
     $sectionEditorSubmission->setAuthors(array(0 => $firstInvestigator, 1 => $coInvestigator1, 2 => $coInvestigator2, 3 => $coInvestigator3));
     return $sectionEditorSubmission;
 }
 /**
  * Test for correct reporting of isModified().
  */
 public function testIsModified()
 {
     // 1) Basic test
     $a = new Author();
     $a->setFirstName("John");
     $a->setLastName("Doe");
     $a->setAge(25);
     $this->assertTrue($a->isModified(), "Expected Author to be modified after setting values.");
     $a->save();
     $this->assertFalse($a->isModified(), "Expected Author to be unmodified after saving set values.");
     // 2) Test behavior with setting vars of different types
     // checking setting int col to string val
     $a->setAge('25');
     $this->assertFalse($a->isModified(), "Expected Author to be unmodified after setting int column to string-cast of same value.");
     $a->setFirstName("John2");
     $this->assertTrue($a->isModified(), "Expected Author to be modified after changing string column value.");
     // checking setting string col to int val
     $a->setFirstName("1");
     $a->save();
     $this->assertFalse($a->isModified(), "Expected Author to be unmodified after saving set values.");
     $a->setFirstName(1);
     $this->assertFalse($a->isModified(), "Expected Author to be unmodified after setting string column to int-cast of same value.");
     // 3) Test for appropriate behavior of NULL
     // checking "" -> NULL
     $a->setFirstName("");
     $a->save();
     $this->assertFalse($a->isModified(), "Expected Author to be unmodified after saving set values.");
     $a->setFirstName(null);
     $this->assertTrue($a->isModified(), "Expected Author to be modified after changing empty string column value to NULL.");
     $a->setFirstName("John");
     $a->setAge(0);
     $a->save();
     $this->assertFalse($a->isModified(), "Expected Author to be unmodified after saving set values.");
     $a->setAge(null);
     $this->assertTrue($a->isModified(), "Expected Author to be modified after changing 0-value int column to NULL.");
     $a->save();
     $this->assertFalse($a->isModified(), "Expected Author to be unmodified after saving set values.");
     $a->setAge(0);
     $this->assertTrue($a->isModified(), "Expected Author to be modified after changing NULL-value int column to 0.");
 }
Example #25
0
    /**
     * Retrieve all authors from published papers
     * @param $schedConfId int
     * @return $authors array Author Objects
     */
    function getPublishedPaperAuthors($schedConfId)
    {
        $primaryLocale = AppLocale::getPrimaryLocale();
        $locale = AppLocale::getLocale();
        $authors = array();
        $result =& $this->retrieve('SELECT	aa.*,
				aspl.setting_value AS affiliation_pl,
				asl.setting_value AS affiliation_l
			FROM	authors aa
				LEFT JOIN published_papers pa ON (pa.paper_id = aa.submission_id)
				LEFT JOIN author_settings aspl ON (aspl.author_id = aa.author_id AND aspl.setting_name = ? AND aspl.locale = ?)
				LEFT JOIN author_settings asl ON (asl.author_id = aa.author_id AND asl.setting_name = ? AND asl.locale = ?)
			WHERE	pa.sched_conf_id = ?', array('affiliation', $primaryLocale, 'affiliation', $locale, (int) $schedConfId));
        while (!$result->EOF) {
            $row = $result->GetRowAssoc(false);
            $author = new Author();
            $author->setId($row['author_id']);
            $author->setSubmissionId($row['paper_id']);
            $author->setFirstName($row['first_name']);
            $author->setMiddleName($row['middle_name']);
            $author->setLastName($row['last_name']);
            $author->setAffiliation($row['affiliation_pl'], $primaryLocale);
            $author->setAffiliation($row['affiliation_l'], $locale);
            $author->setEmail($row['email']);
            $author->setBiography($row['biography']);
            $author->setPrimaryContact($row['primary_contact']);
            $author->setSequence($row['seq']);
            $authors[] = $author;
            $result->moveNext();
        }
        $result->Close();
        unset($result);
        return $authors;
    }
Example #26
0
 /**
  * Save author
  * @see Form::execute()
  * @see Form::execute()
  */
 function execute()
 {
     $authorDao = DAORegistry::getDAO('AuthorDAO');
     $submission = $this->getSubmission();
     $author = $this->getAuthor();
     if (!$author) {
         // this is a new submission contributor
         $author = new Author();
         $author->setSubmissionId($submission->getId());
         $existingAuthor = false;
     } else {
         $existingAuthor = true;
         if ($submission->getId() !== $author->getSubmissionId()) {
             fatalError('Invalid author!');
         }
     }
     $author->setFirstName($this->getData('firstName'));
     $author->setMiddleName($this->getData('middleName'));
     $author->setLastName($this->getData('lastName'));
     $author->setSuffix($this->getData('suffix'));
     $author->setAffiliation($this->getData('affiliation'), null);
     // localized
     $author->setCountry($this->getData('country'));
     $author->setEmail($this->getData('email'));
     $author->setUrl($this->getData('userUrl'));
     $author->setOrcid($this->getData('orcid'));
     $author->setUserGroupId($this->getData('userGroupId'));
     $author->setBiography($this->getData('biography'), null);
     // localized
     $author->setPrimaryContact($this->getData('primaryContact') ? true : false);
     $author->setIncludeInBrowse($this->getData('includeInBrowse') ? true : false);
     // in order to be able to use the hook
     parent::execute();
     if ($existingAuthor) {
         $authorDao->updateObject($author);
         $authorId = $author->getId();
     } else {
         $authorId = $authorDao->insertObject($author);
     }
     return $authorId;
 }
Example #27
0
 /**
  * Save changes to article.
  * @param $request PKPRequest
  * @return int the article ID
  */
 function execute(&$request)
 {
     $articleDao =& DAORegistry::getDAO('ArticleDAO');
     $article =& $this->article;
     // Retrieve the previous citation list for comparison.
     $previousRawCitationList = $article->getCitations();
     ///////////////////////////////////////////
     ////////////// Update Authors /////////////
     ///////////////////////////////////////////
     $authors = $this->getData('authors');
     for ($i = 0, $count = count($authors); $i < $count; $i++) {
         if ($authors[$i]['authorId'] > 0) {
             // Update an existing author
             $author =& $article->getAuthor($authors[$i]['authorId']);
             $isExistingAuthor = true;
         } else {
             // Create a new author
             $author = new Author();
             $isExistingAuthor = false;
         }
         if ($author != null) {
             $author->setSubmissionId($article->getId());
             if (isset($authors[$i]['firstName'])) {
                 $author->setFirstName($authors[$i]['firstName']);
             }
             if (isset($authors[$i]['middleName'])) {
                 $author->setMiddleName($authors[$i]['middleName']);
             }
             if (isset($authors[$i]['lastName'])) {
                 $author->setLastName($authors[$i]['lastName']);
             }
             if (isset($authors[$i]['affiliation'])) {
                 $author->setAffiliation($authors[$i]['affiliation']);
             }
             if (isset($authors[$i]['phone'])) {
                 $author->setPhoneNumber($authors[$i]['phone']);
             }
             if (isset($authors[$i]['email'])) {
                 $author->setEmail($authors[$i]['email']);
             }
             $author->setPrimaryContact($this->getData('primaryContact') == $i ? 1 : 0);
             $author->setSequence($authors[$i]['seq']);
             if ($isExistingAuthor == false) {
                 $article->addAuthor($author);
             }
         }
         unset($author);
     }
     // Remove deleted authors
     $deletedAuthors = explode(':', $this->getData('deletedAuthors'));
     for ($i = 0, $count = count($deletedAuthors); $i < $count; $i++) {
         $article->removeAuthor($deletedAuthors[$i]);
     }
     ///////////////////////////////////////////
     //////////// Update Abstract(s) ///////////
     ///////////////////////////////////////////
     import('classes.article.ProposalAbstract');
     $journal = Request::getJournal();
     $abstracts = $this->getData('abstracts');
     foreach ($journal->getSupportedLocaleNames() as $localeKey => $localeValue) {
         if ($abstracts[$localeKey]['abstractId'] > 0) {
             $abstract = $article->getAbstractByLocale($localeKey);
             $isExistingAbstract = true;
         } else {
             $abstract = new ProposalAbstract();
             $isExistingAbstract = false;
         }
         if ($abstract != null) {
             $abstract->setArticleId($article->getId());
             $abstract->setLocale($localeKey);
             $abstract->setScientificTitle($abstracts[$localeKey]['scientificTitle']);
             $abstract->setPublicTitle($abstracts[$localeKey]['publicTitle']);
             $abstract->setBackground($abstracts[$localeKey]['background']);
             $abstract->setObjectives($abstracts[$localeKey]['objectives']);
             $abstract->setStudyMethods($abstracts[$localeKey]['studyMethods']);
             $abstract->setExpectedOutcomes($abstracts[$localeKey]['expectedOutcomes']);
             $abstract->setKeywords($abstracts[$localeKey]['keywords']);
             if ($isExistingAbstract == false) {
                 $article->addAbstract($abstract);
             }
         }
         unset($abstract);
     }
     ///////////////////////////////////////////
     ///////// Update Proposal Details /////////
     ///////////////////////////////////////////
     $proposalDetailsData = $this->getData('proposalDetails');
     import('classes.article.ProposalDetails');
     $proposalDetails = new ProposalDetails();
     $institutionDao =& DAORegistry::getDAO('InstitutionDAO');
     import('classes.journal.Institution');
     $proposalDetails->setArticleId($article->getId());
     $proposalDetails->setStudentResearch($proposalDetailsData['studentInitiatedResearch']);
     $proposalDetails->setStartDate($proposalDetailsData['startDate']);
     $proposalDetails->setEndDate($proposalDetailsData['endDate']);
     if ($proposalDetailsData['keyImplInstitution'] == "OTHER") {
         $institution = new Institution();
         $institution->setInstitutionName($proposalDetailsData['otherInstitutionName']);
         $institution->setInstitutionAcronym($proposalDetailsData['otherInstitutionAcronym']);
         $institution->setInstitutionType($proposalDetailsData['otherInstitutionType']);
         $institution->setInstitutionInternational($proposalDetailsData['international']);
         if ($proposalDetailsData['international'] == INSTITUTION_NATIONAL) {
             $institution->setInstitutionLocation($proposalDetailsData['locationCountry']);
         } elseif ($proposalDetailsData['international'] == INSTITUTION_INTERNATIONAL) {
             $institution->setInstitutionLocation($proposalDetailsData['locationInternational']);
         }
         $institutionId = $institutionDao->insertInstitution($institution);
         $proposalDetails->setKeyImplInstitution($institutionId);
         unset($institution);
     } else {
         $proposalDetails->setKeyImplInstitution($proposalDetailsData['keyImplInstitution']);
     }
     $proposalDetails->setMultiCountryResearch($proposalDetailsData['multiCountryResearch']);
     if ($proposalDetailsData['multiCountryResearch'] == PROPOSAL_DETAIL_YES) {
         $countriesArray = $proposalDetailsData['countries'];
         $countries = implode(",", $countriesArray);
         $proposalDetails->setCountries($countries);
     }
     $proposalDetails->setNationwide($proposalDetailsData['nationwide']);
     if ($proposalDetailsData['nationwide'] != PROPOSAL_DETAIL_YES) {
         $geoAreasArray = $proposalDetailsData['geoAreas'];
         $proposalDetails->setGeoAreasFromArray($geoAreasArray);
     }
     $researchDomainsArray = $proposalDetailsData['researchDomains'];
     $proposalDetails->setResearchDomainsFromArray($researchDomainsArray);
     $researchFieldsArray = $proposalDetailsData['researchFields'];
     foreach ($researchFieldsArray as $i => $field) {
         if ($field == "OTHER") {
             $otherField = $proposalDetailsData['otherResearchField'];
             if ($otherField != "") {
                 $researchFieldsArray[$i] = "Other (" . $otherField . ")";
             }
         }
     }
     $proposalDetails->setResearchFieldsFromArray($researchFieldsArray);
     $proposalDetails->setHumanSubjects($proposalDetailsData['withHumanSubjects']);
     if ($proposalDetailsData['withHumanSubjects'] == PROPOSAL_DETAIL_YES) {
         $proposalTypesArray = $proposalDetailsData['proposalTypes'];
         foreach ($proposalTypesArray as $i => $type) {
             if ($type == "OTHER") {
                 $otherType = $proposalDetailsData['otherProposalType'];
                 if ($otherType != "") {
                     $proposalTypesArray[$i] = "Other (" . $otherType . ")";
                 }
             }
         }
         $proposalDetails->setProposalTypesFromArray($proposalTypesArray);
     }
     $proposalDetails->setDataCollection($proposalDetailsData['dataCollection']);
     if ($proposalDetailsData['reviewedByOtherErc'] == PROPOSAL_DETAIL_YES) {
         $proposalDetails->setCommitteeReviewed($proposalDetailsData['otherErcDecision']);
     } else {
         $proposalDetails->setCommitteeReviewed(PROPOSAL_DETAIL_NO);
     }
     // Update or insert student research
     import('classes.article.StudentResearch');
     $studentResearchInfo = new StudentResearch();
     $studentResearchInfo->setArticleId($article->getId());
     $studentResearchData = $this->getData('studentResearch');
     $studentResearchInfo->setInstitution($studentResearchData['studentInstitution']);
     $studentResearchInfo->setDegree($studentResearchData['academicDegree']);
     $studentResearchInfo->setSupervisorName($studentResearchData['supervisorName']);
     $studentResearchInfo->setSupervisorEmail($studentResearchData['supervisorEmail']);
     $proposalDetails->setStudentResearchInfo($studentResearchInfo);
     $article->setProposalDetails($proposalDetails);
     ///////////////////////////////////////////
     //////// Update Sources of Monetary ///////
     ///////////////////////////////////////////
     $sources = $article->getSources();
     $sourcesData = $this->getData('sources');
     //Remove sources
     foreach ($sources as $source) {
         $isPresent = false;
         foreach ($sourcesData as $sourceData) {
             if (!empty($sourceData['sourceId'])) {
                 if ($source->getSourceId() == $sourceData['sourceId']) {
                     $isPresent = true;
                 }
             }
         }
         if (!$isPresent) {
             $article->removeSource($source->getSourceId());
         }
         unset($source);
     }
     for ($i = 0, $count = count($sourcesData); $i < $count; $i++) {
         if (!empty($sourcesData[$i]['sourceId'])) {
             // Update an existing source
             $source =& $article->getSource($sourcesData[$i]['sourceId']);
             $isExistingSource = true;
         } else {
             // Create a new source
             $source = new ProposalSource();
             $isExistingSource = false;
         }
         if ($source != null) {
             $source->setArticleId($article->getId());
             if ($sourcesData[$i]['institution'] == "OTHER") {
                 $institution = new Institution();
                 $institution->setInstitutionName($sourcesData[$i]['otherInstitutionName']);
                 $institution->setInstitutionAcronym($sourcesData[$i]['otherInstitutionAcronym']);
                 $institution->setInstitutionType($sourcesData[$i]['otherInstitutionType']);
                 $institution->setInstitutionInternational($sourcesData[$i]['international']);
                 if ($sourcesData[$i]['international'] == INSTITUTION_NATIONAL) {
                     $institution->setInstitutionLocation($sourcesData[$i]['locationCountry']);
                 } elseif ($proposalDetailsData['international'] == INSTITUTION_INTERNATIONAL) {
                     $institution->setInstitutionLocation($sourcesData[$i]['locationInternational']);
                 }
                 $institutionId = $institutionDao->insertInstitution($institution);
                 $source->setInstitutionId($institutionId);
                 unset($institution);
             } elseif ($sourcesData[$i]['institution'] == "KII") {
                 $source->setInstitutionId($proposalDetails->getKeyImplInstitution());
             } else {
                 $source->setInstitutionId($sourcesData[$i]['institution']);
             }
             $source->setSourceAmount($sourcesData[$i]['amount']);
             if (!$isExistingSource) {
                 $article->addSource($source);
             }
         }
         unset($source);
     }
     ///////////////////////////////////////////
     ///////////// Risk Assessment /////////////
     ///////////////////////////////////////////
     import('classes.article.RiskAssessment');
     $riskAssessment = new RiskAssessment();
     $riskAssessmentData = $this->getData('riskAssessment');
     $riskAssessment->setArticleId($article->getId());
     $riskAssessment->setIdentityRevealed($riskAssessmentData['identityRevealed']);
     $riskAssessment->setUnableToConsent($riskAssessmentData['unableToConsent']);
     $riskAssessment->setUnder18($riskAssessmentData['under18']);
     $riskAssessment->setDependentRelationship($riskAssessmentData['dependentRelationship']);
     $riskAssessment->setEthnicMinority($riskAssessmentData['ethnicMinority']);
     $riskAssessment->setImpairment($riskAssessmentData['impairment']);
     $riskAssessment->setPregnant($riskAssessmentData['pregnant']);
     $riskAssessment->setNewTreatment($riskAssessmentData['newTreatment']);
     $riskAssessment->setBioSamples($riskAssessmentData['bioSamples']);
     $riskAssessment->setExportHumanTissue($riskAssessmentData['exportHumanTissue']);
     $riskAssessment->setExportReason($riskAssessmentData['exportReason']);
     $riskAssessment->setRadiation($riskAssessmentData['radiation']);
     $riskAssessment->setDistress($riskAssessmentData['distress']);
     $riskAssessment->setInducements($riskAssessmentData['inducements']);
     $riskAssessment->setSensitiveInfo($riskAssessmentData['sensitiveInfo']);
     $riskAssessment->setReproTechnology($riskAssessmentData['reproTechnology']);
     $riskAssessment->setGenetic($riskAssessmentData['genetic']);
     $riskAssessment->setStemCell($riskAssessmentData['stemCell']);
     $riskAssessment->setBiosafety($riskAssessmentData['biosafety']);
     $riskAssessment->setRiskLevel($riskAssessmentData['riskLevel']);
     $riskAssessment->setListRisks($riskAssessmentData['listRisks']);
     $riskAssessment->setHowRisksMinimized($riskAssessmentData['howRisksMinimized']);
     $riskAssessment->setRisksToTeam(isset($riskAssessmentData['risksToTeam']) ? 1 : 0);
     $riskAssessment->setRisksToSubjects(isset($riskAssessmentData['risksToSubjects']) ? 1 : 0);
     $riskAssessment->setRisksToCommunity(isset($riskAssessmentData['risksToCommunity']) ? 1 : 0);
     $riskAssessment->setBenefitsToParticipants(isset($riskAssessmentData['benefitsToParticipants']) ? 1 : 0);
     $riskAssessment->setKnowledgeOnCondition(isset($riskAssessmentData['knowledgeOnCondition']) ? 1 : 0);
     $riskAssessment->setKnowledgeOnDisease(isset($riskAssessmentData['knowledgeOnDisease']) ? 1 : 0);
     $riskAssessment->setMultiInstitutions($riskAssessmentData['multiInstitutions']);
     $riskAssessment->setConflictOfInterest($riskAssessmentData['conflictOfInterest']);
     $article->setRiskAssessment($riskAssessment);
     parent::execute();
     // Save the article
     $articleDao->updateArticle($article);
     // Update references list if it changed.
     $citationDao =& DAORegistry::getDAO('CitationDAO');
     $rawCitationList = $article->getCitations();
     if ($previousRawCitationList != $rawCitationList) {
         $citationDao->importCitations($request, ASSOC_TYPE_ARTICLE, $article->getId(), $rawCitationList);
     }
 }
Example #28
0
 $bk1->setAuthor($auth1);
 $rev1 = new Review();
 $rev1->setReviewDate("08/09/2001");
 // will fail: reviewed_by column required
 $bk1->addReview($rev1);
 $ret2 = $bk1->validate();
 $failures2 = $bk1->getValidationFailures();
 print "Making sure 6 validation messages were returned: ";
 print boolTest(count($failures2) === 3);
 print "Making sure correct columns failed: ";
 print boolTest(array_keys($failures2) === array(AuthorPeer::LAST_NAME, BookPeer::TITLE, ReviewPeer::REVIEWED_BY));
 $bk2 = new Book();
 $bk2->setTitle("12345678901");
 // passes
 $auth2 = new Author();
 $auth2->setLastName("Blah");
 //passes
 $auth2->setEmail("*****@*****.**");
 //passes
 $auth2->setAge(50);
 //passes
 $bk2->setAuthor($auth2);
 $rev2 = new Review();
 $rev2->setReviewedBy("Me!");
 // passes
 $rev2->setStatus("new");
 // passes
 $bk2->addReview($rev2);
 $ret3 = $bk2->validate();
 print "Making sure complex validation can pass: ";
 print boolTest($ret3 === true);
 public function testScenarioUsingQuery()
 {
     // Add publisher records
     // ---------------------
     try {
         $scholastic = new Publisher();
         $scholastic->setName("Scholastic");
         // do not save, will do later to test cascade
         $morrow = new Publisher();
         $morrow->setName("William Morrow");
         $morrow->save();
         $morrow_id = $morrow->getId();
         $penguin = new Publisher();
         $penguin->setName("Penguin");
         $penguin->save();
         $penguin_id = $penguin->getId();
         $vintage = new Publisher();
         $vintage->setName("Vintage");
         $vintage->save();
         $vintage_id = $vintage->getId();
         $this->assertTrue(true, 'Save Publisher records');
     } catch (Exception $e) {
         $this->fail('Save publisher records');
     }
     // Add author records
     // ------------------
     try {
         $rowling = new Author();
         $rowling->setFirstName("J.K.");
         $rowling->setLastName("Rowling");
         // do not save, will do later to test cascade
         $stephenson = new Author();
         $stephenson->setFirstName("Neal");
         $stephenson->setLastName("Stephenson");
         $stephenson->save();
         $stephenson_id = $stephenson->getId();
         $byron = new Author();
         $byron->setFirstName("George");
         $byron->setLastName("Byron");
         $byron->save();
         $byron_id = $byron->getId();
         $grass = new Author();
         $grass->setFirstName("Gunter");
         $grass->setLastName("Grass");
         $grass->save();
         $grass_id = $grass->getId();
         $this->assertTrue(true, 'Save Author records');
     } catch (Exception $e) {
         $this->fail('Save Author records');
     }
     // Add book records
     // ----------------
     try {
         $phoenix = new Book();
         $phoenix->setTitle("Harry Potter and the Order of the Phoenix");
         $phoenix->setISBN("043935806X");
         $phoenix->setAuthor($rowling);
         $phoenix->setPublisher($scholastic);
         $phoenix->save();
         $phoenix_id = $phoenix->getId();
         $this->assertFalse($rowling->isNew(), 'saving book also saves related author');
         $this->assertFalse($scholastic->isNew(), 'saving book also saves related publisher');
         $qs = new Book();
         $qs->setISBN("0380977427");
         $qs->setTitle("Quicksilver");
         $qs->setAuthor($stephenson);
         $qs->setPublisher($morrow);
         $qs->save();
         $qs_id = $qs->getId();
         $dj = new Book();
         $dj->setISBN("0140422161");
         $dj->setTitle("Don Juan");
         $dj->setAuthor($byron);
         $dj->setPublisher($penguin);
         $dj->save();
         $dj_id = $qs->getId();
         $td = new Book();
         $td->setISBN("067972575X");
         $td->setTitle("The Tin Drum");
         $td->setAuthor($grass);
         $td->setPublisher($vintage);
         $td->save();
         $td_id = $td->getId();
         $this->assertTrue(true, 'Save Book records');
     } catch (Exception $e) {
         $this->fail('Save Author records');
     }
     // Add review records
     // ------------------
     try {
         $r1 = new Review();
         $r1->setBook($phoenix);
         $r1->setReviewedBy("Washington Post");
         $r1->setRecommended(true);
         $r1->setReviewDate(time());
         $r1->save();
         $r1_id = $r1->getId();
         $r2 = new Review();
         $r2->setBook($phoenix);
         $r2->setReviewedBy("New York Times");
         $r2->setRecommended(false);
         $r2->setReviewDate(time());
         $r2->save();
         $r2_id = $r2->getId();
         $this->assertTrue(true, 'Save Review records');
     } catch (Exception $e) {
         $this->fail('Save Review records');
     }
     // Perform a "complex" search
     // --------------------------
     $results = BookQuery::create()->filterByTitle('Harry%')->find();
     $this->assertEquals(1, count($results));
     $results = BookQuery::create()->where('Book.ISBN IN ?', array("0380977427", "0140422161"))->find();
     $this->assertEquals(2, count($results));
     // Perform a "limit" search
     // ------------------------
     $results = BookQuery::create()->limit(2)->offset(1)->orderByTitle()->find();
     $this->assertEquals(2, count($results));
     // we ordered on book title, so we expect to get
     $this->assertEquals("Harry Potter and the Order of the Phoenix", $results[0]->getTitle());
     $this->assertEquals("Quicksilver", $results[1]->getTitle());
     // Perform a lookup & update!
     // --------------------------
     // Updating just-created book title
     // First finding book by PK (=$qs_id) ....
     $qs_lookup = BookQuery::create()->findPk($qs_id);
     $this->assertNotNull($qs_lookup, 'just-created book can be found by pk');
     $new_title = "Quicksilver (" . crc32(uniqid(rand())) . ")";
     // Attempting to update found object
     $qs_lookup->setTitle($new_title);
     $qs_lookup->save();
     // Making sure object was correctly updated: ";
     $qs_lookup2 = BookQuery::create()->findPk($qs_id);
     $this->assertEquals($new_title, $qs_lookup2->getTitle());
     // Test some basic DATE / TIME stuff
     // ---------------------------------
     // that's the control timestamp.
     $control = strtotime('2004-02-29 00:00:00');
     // should be two in the db
     $r = ReviewQuery::create()->findOne();
     $r_id = $r->getId();
     $r->setReviewDate($control);
     $r->save();
     $r2 = ReviewQuery::create()->findPk($r_id);
     $this->assertEquals(new Datetime('2004-02-29 00:00:00'), $r2->getReviewDate(null), 'ability to fetch DateTime');
     $this->assertEquals($control, $r2->getReviewDate('U'), 'ability to fetch native unix timestamp');
     $this->assertEquals('2-29-2004', $r2->getReviewDate('n-j-Y'), 'ability to use date() formatter');
     // Handle BLOB/CLOB Columns
     // ------------------------
     $blob_path = dirname(__FILE__) . '/../../etc/lob/tin_drum.gif';
     $blob2_path = dirname(__FILE__) . '/../../etc/lob/propel.gif';
     $clob_path = dirname(__FILE__) . '/../../etc/lob/tin_drum.txt';
     $m1 = new Media();
     $m1->setBook($phoenix);
     $m1->setCoverImage(file_get_contents($blob_path));
     $m1->setExcerpt(file_get_contents($clob_path));
     $m1->save();
     $m1_id = $m1->getId();
     $m1_lookup = MediaQuery::create()->findPk($m1_id);
     $this->assertNotNull($m1_lookup, 'Can find just-created media item');
     $this->assertEquals(md5(file_get_contents($blob_path)), md5(stream_get_contents($m1_lookup->getCoverImage())), 'BLOB was correctly updated');
     $this->assertEquals(file_get_contents($clob_path), (string) $m1_lookup->getExcerpt(), 'CLOB was correctly updated');
     // now update the BLOB column and save it & check the results
     $m1_lookup->setCoverImage(file_get_contents($blob2_path));
     $m1_lookup->save();
     $m2_lookup = MediaQuery::create()->findPk($m1_id);
     $this->assertNotNull($m2_lookup, 'Can find just-created media item');
     $this->assertEquals(md5(file_get_contents($blob2_path)), md5(stream_get_contents($m2_lookup->getCoverImage())), 'BLOB was correctly overwritten');
     // Test Validators
     // ---------------
     require_once 'tools/helpers/bookstore/validator/ISBNValidator.php';
     $bk1 = new Book();
     $bk1->setTitle("12345");
     // min length is 10
     $ret = $bk1->validate();
     $this->assertFalse($ret, 'validation failed');
     $failures = $bk1->getValidationFailures();
     $this->assertEquals(1, count($failures), '1 validation message was returned');
     $el = array_shift($failures);
     $this->assertContains("must be more than", $el->getMessage(), 'Expected validation message was returned');
     $bk2 = new Book();
     $bk2->setTitle("Don Juan");
     $ret = $bk2->validate();
     $this->assertFalse($ret, 'validation failed');
     $failures = $bk2->getValidationFailures();
     $this->assertEquals(1, count($failures), '1 validation message was returned');
     $el = array_shift($failures);
     $this->assertContains("Book title already in database.", $el->getMessage(), 'Expected validation message was returned');
     //Now trying some more complex validation.
     $auth1 = new Author();
     $auth1->setFirstName("Hans");
     // last name required; will fail
     $bk1->setAuthor($auth1);
     $rev1 = new Review();
     $rev1->setReviewDate("08/09/2001");
     // will fail: reviewed_by column required
     $bk1->addReview($rev1);
     $ret2 = $bk1->validate();
     $this->assertFalse($ret2, 'validation failed');
     $failures2 = $bk1->getValidationFailures();
     $this->assertEquals(3, count($failures2), '3 validation messages were returned');
     $expectedKeys = array(AuthorPeer::LAST_NAME, BookPeer::TITLE, ReviewPeer::REVIEWED_BY);
     $this->assertEquals($expectedKeys, array_keys($failures2), 'correct columns failed');
     $bk2 = new Book();
     $bk2->setTitle("12345678901");
     // passes
     $auth2 = new Author();
     $auth2->setLastName("Blah");
     //passes
     $auth2->setEmail("*****@*****.**");
     //passes
     $auth2->setAge(50);
     //passes
     $bk2->setAuthor($auth2);
     $rev2 = new Review();
     $rev2->setReviewedBy("Me!");
     // passes
     $rev2->setStatus("new");
     // passes
     $bk2->addReview($rev2);
     $ret3 = $bk2->validate();
     $this->assertTrue($ret3, 'complex validation can pass');
     // Testing doCount() functionality
     // -------------------------------
     // old way
     $c = new Criteria();
     $records = BookPeer::doSelect($c);
     $count = BookPeer::doCount($c);
     $this->assertEquals($count, count($records), 'correct number of results');
     // new way
     $count = BookQuery::create()->count();
     $this->assertEquals($count, count($records), 'correct number of results');
     // Test many-to-many relationships
     // ---------------
     // init book club list 1 with 2 books
     $blc1 = new BookClubList();
     $blc1->setGroupLeader("Crazyleggs");
     $blc1->setTheme("Happiness");
     $brel1 = new BookListRel();
     $brel1->setBook($phoenix);
     $brel2 = new BookListRel();
     $brel2->setBook($dj);
     $blc1->addBookListRel($brel1);
     $blc1->addBookListRel($brel2);
     $blc1->save();
     $this->assertNotNull($blc1->getId(), 'BookClubList 1 was saved');
     // init book club list 2 with 1 book
     $blc2 = new BookClubList();
     $blc2->setGroupLeader("John Foo");
     $blc2->setTheme("Default");
     $brel3 = new BookListRel();
     $brel3->setBook($phoenix);
     $blc2->addBookListRel($brel3);
     $blc2->save();
     $this->assertNotNull($blc2->getId(), 'BookClubList 2 was saved');
     // re-fetch books and lists from db to be sure that nothing is cached
     $crit = new Criteria();
     $crit->add(BookPeer::ID, $phoenix->getId());
     $phoenix = BookPeer::doSelectOne($crit);
     $this->assertNotNull($phoenix, "book 'phoenix' has been re-fetched from db");
     $crit = new Criteria();
     $crit->add(BookClubListPeer::ID, $blc1->getId());
     $blc1 = BookClubListPeer::doSelectOne($crit);
     $this->assertNotNull($blc1, 'BookClubList 1 has been re-fetched from db');
     $crit = new Criteria();
     $crit->add(BookClubListPeer::ID, $blc2->getId());
     $blc2 = BookClubListPeer::doSelectOne($crit);
     $this->assertNotNull($blc2, 'BookClubList 2 has been re-fetched from db');
     $relCount = $phoenix->countBookListRels();
     $this->assertEquals(2, $relCount, "book 'phoenix' has 2 BookListRels");
     $relCount = $blc1->countBookListRels();
     $this->assertEquals(2, $relCount, 'BookClubList 1 has 2 BookListRels');
     $relCount = $blc2->countBookListRels();
     $this->assertEquals(1, $relCount, 'BookClubList 2 has 1 BookListRel');
     // Cleanup (tests DELETE)
     // ----------------------
     // Removing books that were just created
     // First finding book by PK (=$phoenix_id) ....
     $hp = BookQuery::create()->findPk($phoenix_id);
     $this->assertNotNull($hp, 'Could find just-created book');
     // Attempting to delete [multi-table] by found pk
     $c = new Criteria();
     $c->add(BookPeer::ID, $hp->getId());
     // The only way for cascading to work currently
     // is to specify the author_id and publisher_id (i.e. the fkeys
     // have to be in the criteria).
     $c->add(AuthorPeer::ID, $hp->getAuthor()->getId());
     $c->add(PublisherPeer::ID, $hp->getPublisher()->getId());
     $c->setSingleRecord(true);
     BookPeer::doDelete($c);
     // Checking to make sure correct records were removed.
     $this->assertEquals(3, AuthorPeer::doCount(new Criteria()), 'Correct records were removed from author table');
     $this->assertEquals(3, PublisherPeer::doCount(new Criteria()), 'Correct records were removed from publisher table');
     $this->assertEquals(3, BookPeer::doCount(new Criteria()), 'Correct records were removed from book table');
     // Attempting to delete books by complex criteria
     BookQuery::create()->filterByISBN("043935806X")->orWhere('Book.ISBN = ?', "0380977427")->orWhere('Book.ISBN = ?', "0140422161")->delete();
     // Attempting to delete book [id = $td_id]
     $td->delete();
     // Attempting to delete authors
     AuthorQuery::create()->filterById($stephenson_id)->delete();
     AuthorQuery::create()->filterById($byron_id)->delete();
     $grass->delete();
     // Attempting to delete publishers
     PublisherQuery::create()->filterById($morrow_id)->delete();
     PublisherQuery::create()->filterById($penguin_id)->delete();
     $vintage->delete();
     // These have to be deleted manually also since we have onDelete
     // set to SETNULL in the foreign keys in book. Is this correct?
     $rowling->delete();
     $scholastic->delete();
     $blc1->delete();
     $blc2->delete();
     $this->assertEquals(array(), AuthorPeer::doSelect(new Criteria()), 'no records in [author] table');
     $this->assertEquals(array(), PublisherPeer::doSelect(new Criteria()), 'no records in [publisher] table');
     $this->assertEquals(array(), BookPeer::doSelect(new Criteria()), 'no records in [book] table');
     $this->assertEquals(array(), ReviewPeer::doSelect(new Criteria()), 'no records in [review] table');
     $this->assertEquals(array(), MediaPeer::doSelect(new Criteria()), 'no records in [media] table');
     $this->assertEquals(array(), BookClubListPeer::doSelect(new Criteria()), 'no records in [book_club_list] table');
     $this->assertEquals(array(), BookListRelPeer::doSelect(new Criteria()), 'no records in [book_x_list] table');
 }
Example #30
0
    public function testAddToStringDefault()
    {
        $this->assertTrue(method_exists('Author', '__toString'), 'addPrimaryString() adds a __toString() method even if no column has the primaryString attribute');
        $author = new Author();
        $author->setFirstName('Leo');
        $author->setLastName('Tolstoi');
        $expected = <<<EOF
Id: null
FirstName: Leo
LastName: Tolstoi
Email: null
Age: null

EOF;
        $this->assertEquals($expected, (string) $author, 'addPrimaryString() adds a __toString() method returning the YAML representation of the object where no column is defined as primaryString');
    }