/**
  * @param string $key
  * @param ReferenceList $model
  * @return array
  */
 public function encodeReferenceList($key, $model)
 {
     if ($key != 'projects') {
         return parent::encodeReferenceList($key, $model);
     }
     $domain = $this->_website->domain;
     $result = array_map(function ($id) use($domain) {
         CodeGuard::checkTypeAndThrow($id, 'Api\\Model\\Shared\\Mapper\\Id');
         /** @var Id $id */
         $projectDto = null;
         try {
             $projectModel = new ProjectModel($id->asString());
             // Filter for active projects on the same domain.
             // Also exclude projects that don't have things to modify on User Profile
             // userProfilePropertiesEnabled is type ArrayOf, so testing for empty() didn't work
             if (!$projectModel->isArchived && $projectModel->siteName == $domain && count($projectModel->userProperties->userProfilePropertiesEnabled) > 0) {
                 $projectDto = array();
                 $projectDto['id'] = $id->asString();
                 $projectDto['name'] = $projectModel->projectName;
                 $projectDto['userProperties'] = self::encode($projectModel->userProperties);
             }
         } catch (\Exception $e) {
         }
         return $projectDto;
     }, $model->refs);
     // Filter out empty entries in the project list
     return array_values(array_filter($result));
 }
 /**
  * @param string $projectId
  * @param string $userId
  * @return array - the DTO array
  */
 public static function encode($projectId, $userId)
 {
     $data = array();
     $user = new UserProfileModel($userId);
     $project = new LexProjectModel($projectId);
     $config = JsonEncoder::encode($project->config);
     $config['inputSystems'] = JsonEncoder::encode($project->inputSystems);
     $data['config'] = $config;
     // comment out at the moment until a refactor can be done that is more efficient (language data in the database?)
     /*
     $interfaceLanguageCode = $project->interfaceLanguageCode;
     if ($user->interfaceLanguageCode) {
         $interfaceLanguageCode = $user->interfaceLanguageCode;
     }
     $options = self::getInterfaceLanguages(APPPATH . 'angular-app/languageforge/lexicon/lang');
     asort($options);    // sort by language name
     $selectInterfaceLanguages = array(
         'optionsOrder' => array_keys($options),
         'options' => $options
     );
     $data['interfaceConfig'] = array('userLanguageCode' => $interfaceLanguageCode);
     $data['interfaceConfig']['selectLanguages'] = $selectInterfaceLanguages;
     */
     // a stand in for the code above
     $data['interfaceConfig'] = array('userLanguageCode' => 'en', 'selectLanguages' => array('options' => array('en' => 'English'), 'optionsOrder' => array('en')));
     $optionlistListModel = new LexOptionListListModel($project);
     $optionlistListModel->read();
     $data['optionlists'] = $optionlistListModel->entries;
     if ($project->hasSendReceive()) {
         $data['sendReceive'] = array();
         $data['sendReceive']['status'] = SendReceiveCommands::getProjectStatus($projectId);
     }
     return $data;
 }
 /**
  * Updates the given LexEntry in $projectId
  * @param string $projectId
  * @param array $params
  * @param string $userId
  * @param string $mergeQueuePath
  * @param string $pidFilePath
  * @param string $command
  * @return bool|array<encoded LexEntryModel> if the project is syncing (or on hold) return false (no save)FixSe
  */
 public static function updateEntry($projectId, $params, $userId, $mergeQueuePath = null, $pidFilePath = null, $command = null)
 {
     CodeGuard::checkTypeAndThrow($params, 'array');
     $project = new LexProjectModel($projectId);
     ProjectCommands::checkIfArchivedAndThrow($project);
     $now = UniversalTimestamp::now();
     if (array_key_exists('id', $params) && $params['id'] != '') {
         $entry = new LexEntryModel($project, $params['id']);
         $action = 'update';
     } else {
         $entry = new LexEntryModel($project);
         $entry->authorInfo->createdByUserRef->id = $userId;
         $entry->authorInfo->createdDate = $now;
         $entry->guid = Guid::create();
         $action = 'create';
         // TODO: Consider adding more specific activity entry: which fields were modified? 2014-09-03 RM
         // E.g., "User _____ updated entry _____ by adding a new sense with definition ______"
     }
     $entry->authorInfo->modifiedDate = $now;
     $entry->authorInfo->modifiedByUserRef->id = $userId;
     if ($project->hasSendReceive()) {
         //            $entry->dirtySR++;
         $entry->dirtySR = 0;
         $status = SendReceiveCommands::getProjectStatus($projectId);
         if ($status && $status['SRState'] != 'IDLE') {
             return false;
         }
     }
     LexEntryDecoder::decode($entry, $params);
     $entry->write();
     ActivityCommands::writeEntry($project, $userId, $entry, $action);
     //        SendReceiveCommands::queueProjectForUpdate($project, $mergeQueuePath);
     //        SendReceiveCommands::startLFMergeIfRequired($projectId, 'merge', $pidFilePath, $command);
     return JsonEncoder::encode($entry);
 }
 /**
  * @param string $projectId
  * @param string $textId
  * @param string $userId
  * @returns array - the DTO array
  */
 public static function encode($projectId, $textId, $userId)
 {
     $user = new UserModel($userId);
     $project = new SfchecksProjectModel($projectId);
     $text = new TextModel($project, $textId);
     $questionList = new QuestionAnswersListModel($project, $textId);
     $questionList->read();
     $data = array();
     $data['text'] = JsonEncoder::encode($text);
     $data['archivedQuestions'] = array();
     foreach ($questionList->entries as $questionData) {
         $question = new QuestionModel($project, $questionData['id']);
         if ($question->isArchived) {
             // Just want answer count, not whole list
             $questionData['answerCount'] = count($questionData['answers']);
             $responseCount = 0;
             // "Reponses" = answers + comments
             foreach ($questionData['answers'] as $a) {
                 $commentCount = count($a['comments']);
                 $responseCount += $commentCount + 1;
                 // +1 for this answer
             }
             $questionData['responseCount'] = $responseCount;
             unset($questionData['answers']);
             $questionData['dateModified'] = $question->dateModified->asDateTimeInterface()->format(\DateTime::RFC2822);
             $data['archivedQuestions'][] = $questionData;
         }
     }
     $data['rights'] = RightsHelper::encode($user, $project);
     $data['bcs'] = BreadCrumbHelper::encode('settings', $project, $text, null);
     return $data;
 }
 public function testUpdateSRProject_ProjectAndUser_SRProjectSaved()
 {
     $project = self::$environ->createProject(SF_TESTPROJECT, SF_TESTPROJECTCODE);
     $projectId = $project->id->asString();
     $sendReceiveProject = new SendReceiveProjectModel('sr_name', '', 'manager');
     $srProject = JsonEncoder::encode($sendReceiveProject);
     $srProject['identifier'] = 'sr_id';
     $newProjectId = SendReceiveCommands::updateSRProject($projectId, $srProject);
     $newProject = new LexProjectModel($newProjectId);
     $this->assertEquals($projectId, $newProjectId);
     $this->assertEquals($sendReceiveProject, $newProject->sendReceiveProject);
     $this->assertEquals($srProject['identifier'], $newProject->sendReceiveProjectIdentifier);
 }
 public function testEncodeDecodeUniversalTimestamp_HistoricalDate_Same()
 {
     $model = new TestJsonDateModel();
     $model->universalTimestamp = UniversalTimestamp::fromStringTimestamp(self::StringTimestampWithMilliseconds);
     $encoded = JsonEncoder::encode($model);
     $this->assertInternalType('string', $encoded['universalTimestamp']);
     //        var_dump($encoded);
     $decodedModel = new TestJsonDateModel();
     JsonDecoder::decode($decodedModel, $encoded);
     $iso8601 = $decodedModel->universalTimestamp->asFormattedString(UniversalTimestamp::ISO8601_WITH_MILLISECONDS);
     $this->assertEquals($encoded['universalTimestamp'], $iso8601);
     $this->assertEquals($model->universalTimestamp, $decodedModel->universalTimestamp);
     //        var_dump($iso8601);
 }
 protected function _encode($model)
 {
     $data = parent::_encode($model);
     switch (get_class($model)) {
         case 'Api\\Model\\Languageforge\\Lexicon\\LexMultiParagraph':
             // convert multiparagraph model to HTML version
             $data = array();
             $data['type'] = LexConfig::MULTIPARAGRAPH;
             $data['inputSystem'] = $model->inputSystem;
             $data['paragraphsHtml'] = $model->toHTML();
             break;
     }
     return $data;
 }
 public function testLexEntryCrud_CreateUpdateDeleteListOk()
 {
     $project = self::$environ->createProject(SF_TESTPROJECT, SF_TESTPROJECTCODE);
     $projectId = $project->id->asString();
     // create an user and add to the project
     $userId = self::$environ->getProjectMember($projectId, 'user1');
     $entry = new LexEntryModel($project);
     $entry->lexeme->form('th', 'SomeEntry');
     $sense = new LexSense();
     $sense->definition->form('en', 'red fruit');
     $sense->partOfSpeech->value = 'noun';
     $example = new LexExample();
     $example->sentence->form('th', 'example1');
     $example->translation->form('en', 'trans1');
     $sense->examples[] = $example;
     $entry->senses[] = $sense;
     // List
     $dto = LexEntryCommands::listEntries($projectId);
     $this->assertEquals(0, $dto->count);
     // Create
     $params = JsonEncoder::encode($entry);
     $result1 = LexEntryCommands::updateEntry($projectId, $params, $userId);
     $entryId = $result1['id'];
     $this->assertNotNull($entryId);
     $this->assertEquals(24, strlen($entryId));
     // Read
     $result2 = LexEntryCommands::readEntry($projectId, $entryId);
     $this->assertNotNull($result2['id']);
     $this->assertEquals('SomeEntry', $result2['lexeme']['th']['value']);
     // Update
     $result2['lexeme']['th']['value'] = 'OtherEntry';
     $result3 = LexEntryCommands::updateEntry($projectId, $result2, $userId);
     $this->assertNotNull($result3);
     $this->assertEquals($entryId, $result3['id']);
     // Read back
     $result4 = LexEntryCommands::readEntry($projectId, $entryId);
     $this->assertNotNull($result4['id']);
     $this->assertEquals('OtherEntry', $result4['lexeme']['th']['value']);
     // List
     $dto = LexEntryCommands::listEntries($projectId);
     $this->assertEquals(1, $dto->count);
     // Delete
     $result5 = LexEntryCommands::removeEntry($projectId, $entryId, $userId);
     $this->assertTrue($result5);
     // List to confirm delete
     $dto = LexEntryCommands::listEntries($projectId);
     $this->assertEquals(0, $dto->count);
     // Clean up after ourselves
     ProjectCommands::deleteProjects(array($projectId), $project->ownerRef->asString());
 }
 /**
  * @param string $projectId
  * @param string $textId
  * @param string $userId
  * @return array - the DTO array
  * @throws ResourceNotAvailableException
  */
 public static function encode($projectId, $textId, $userId)
 {
     $project = new SfchecksProjectModel($projectId);
     $text = new TextModel($project, $textId);
     $user = new UserModel($userId);
     if (($project->isArchived || $text->isArchived) && $project->users[$userId]->role != ProjectRoles::MANAGER) {
         throw new ResourceNotAvailableException("This Text is no longer available. If this is incorrect contact your project manager.");
     }
     $questionList = new QuestionAnswersListModel($project, $textId);
     $questionList->read();
     $data = array();
     $data['rights'] = RightsHelper::encode($user, $project);
     $data['entries'] = array();
     $data['project'] = array('id' => $projectId, 'name' => $project->projectName, 'slug' => $project->databaseName(), 'allowAudioDownload' => $project->allowAudioDownload);
     $data['text'] = JsonEncoder::encode($text);
     $usxHelper = new UsxHelper($text->content);
     $data['text']['content'] = $usxHelper->toHtml();
     foreach ($questionList->entries as $questionData) {
         $question = new QuestionModel($project, $questionData['id']);
         if (!$question->isArchived) {
             // Just want answer count, not whole list
             $questionData['answerCount'] = count($questionData['answers']);
             $responseCount = 0;
             // "Reponses" = answers + comments
             foreach ($questionData['answers'] as $a) {
                 $commentCount = count($a['comments']);
                 $responseCount += $commentCount + 1;
                 // +1 for this answer
             }
             $questionData['responseCount'] = $responseCount;
             unset($questionData['answers']);
             $questionData['dateCreated'] = $question->dateCreated->asDateTimeInterface()->format(\DateTime::RFC2822);
             $data['entries'][] = $questionData;
         }
     }
     // sort Questions with newest at the top
     usort($data['entries'], function ($a, $b) {
         $sortOn = 'dateCreated';
         if (array_key_exists($sortOn, $a) && array_key_exists($sortOn, $b)) {
             return strtotime($a[$sortOn]) < strtotime($b[$sortOn]) ? 1 : -1;
         } else {
             return 0;
         }
     });
     $data['count'] = count($data['entries']);
     return $data;
 }
 public function testSemDomItemCommand_UpdateSemDomItem_AddItemUpdateItem()
 {
     $environ = new SemDomMongoTestEnvironment();
     $lang = 'en2';
     $languageName = 'English';
     $environ->cleanPreviousProject($lang);
     $environ->getEnglishProjectAndCreateIfNecessary();
     $user1Id = $environ->createUser('u', 'u', 'u');
     $targetProject = $environ->createSemDomProject($lang, $languageName, $user1Id);
     // insert dummy models
     $targetItemModel = new SemDomTransItemModel($targetProject);
     $targetItemModel->xmlGuid = 'asdf123';
     $targetItemModel->key = '1';
     $targetItemModel->name = new SemDomTransTranslatedForm('universe');
     $targetItemModel->description = new SemDomTransTranslatedForm('Universe description');
     $sq = new SemDomTransQuestion('A universe question', 'A universe question term');
     $targetItemModel->questions[] = $sq;
     $data = JsonEncoder::encode($targetItemModel);
     $itemId = SemDomTransItemCommands::update($data, $targetProject->id->asString());
     $readItem = new SemDomTransItemModel($targetProject, $itemId);
     $this->assertNotNull($readItem->key);
     $this->assertEquals('1', $readItem->key);
     $this->assertNotNull($readItem->name);
     $this->assertEquals('universe', $readItem->name->translation);
     $this->assertEquals(SemDomTransStatus::Draft, $readItem->name->status);
     $this->assertNotNull($readItem->description->translation);
     $this->assertEquals('Universe description', $readItem->description->translation);
     $this->assertEquals(SemDomTransStatus::Draft, $readItem->description->status);
     $readItem->name = new SemDomTransTranslatedForm('universe-edited');
     $data = JsonEncoder::encode($readItem);
     SemDomTransItemCommands::update($data, $targetProject->id->asString());
     $readItemAgain = new SemDomTransItemModel($targetProject, $itemId);
     $this->assertNotNull($readItemAgain->key);
     $this->assertEquals('1', $readItemAgain->key);
     $this->assertNotNull($readItemAgain->name);
     $this->assertEquals('universe-edited', $readItemAgain->name->translation);
     $this->assertEquals(SemDomTransStatus::Draft, $readItemAgain->name->status);
     $this->assertNotNull($readItemAgain->description->translation);
     $this->assertEquals('Universe description', $readItemAgain->description->translation);
     $this->assertEquals(SemDomTransStatus::Draft, $readItemAgain->description->status);
 }
 /**
  * Encodes a QuestionModel and related data for $questionId
  * @param string $projectId
  * @param string $questionId
  * @param string $userId
  * @return array - The DTO.
  * @throws ResourceNotAvailableException
  */
 public static function encode($projectId, $questionId, $userId)
 {
     $user = new UserModel($userId);
     $project = new SfchecksProjectModel($projectId);
     $question = new QuestionModel($project, $questionId);
     $textId = $question->textRef->asString();
     $text = new TextModel($project, $textId);
     if (($text->isArchived || $question->isArchived) && $project->users[$userId]->role != ProjectRoles::MANAGER) {
         throw new ResourceNotAvailableException("This Question is no longer available. If this is incorrect contact your project manager.");
     }
     $usxHelper = new UsxHelper($text->content);
     //echo $usxHelper->toHtml();
     //echo $text->content;
     $votes = new UserVoteModel($userId, $projectId, $questionId);
     $votesDto = array();
     foreach ($votes->votes as $vote) {
         $votesDto[$vote->answerRef->id] = true;
     }
     $unreadAnswerModel = new UnreadAnswerModel($userId, $project->id->asString(), $questionId);
     $unreadAnswers = $unreadAnswerModel->unreadItems();
     $unreadAnswerModel->markAllRead();
     $unreadAnswerModel->write();
     $unreadCommentModel = new UnreadCommentModel($userId, $project->id->asString(), $questionId);
     $unreadComments = $unreadCommentModel->unreadItems();
     $unreadCommentModel->markAllRead();
     $unreadCommentModel->write();
     $unreadActivityModel = new UnreadActivityModel($userId, $projectId);
     $unreadActivity = $unreadActivityModel->unreadItems();
     $dto = array();
     $dto['question'] = QuestionCommentDtoEncoder::encode($question);
     $dto['votes'] = $votesDto;
     $dto['text'] = JsonEncoder::encode($text);
     $dto['text']['content'] = $usxHelper->toHtml();
     $dto['project'] = JsonEncoder::encode($project);
     $dto['project']['slug'] = $project->databaseName();
     $dto['rights'] = RightsHelper::encode($user, $project);
     $dto['unreadAnswers'] = $unreadAnswers;
     $dto['unreadComments'] = $unreadComments;
     $dto['unreadActivityCount'] = count($unreadActivity);
     return $dto;
 }
 /**
  * @param string $username
  * @param string $password
  * @param ClientInterface|null $client
  * @return SendReceiveGetUserProjectResult
  */
 public static function getUserProjects($username, $password, ClientInterface $client = null)
 {
     $result = new SendReceiveGetUserProjectResult();
     if (!$username) {
         return JsonEncoder::encode($result);
     }
     if (is_null($client)) {
         $client = new Client();
     }
     self::mockE2ETestingData($username, $password, $client);
     $url = 'http://admin.languagedepot.org/api/user/' . $username . '/projects';
     $postData = ['json' => ['password' => $password]];
     $tryCounter = 1;
     while ($tryCounter <= 5) {
         try {
             $result->errorMessage = '';
             $response = $client->post($url, $postData);
             break;
         } catch (RequestException $e) {
             $response = $e->getResponse();
             if ($e->getCode() != 403 && $e->getCode() != 404) {
                 $tryCounter++;
                 $result->errorMessage = $e->getMessage();
                 continue;
             }
             break;
         }
     }
     /** @noinspection PhpUndefinedVariableInspection */
     if ($response->getStatusCode() == 403) {
         $result->isKnownUser = true;
     }
     if ($response->getStatusCode() == 200) {
         $result->isKnownUser = true;
         $result->hasValidCredentials = true;
         foreach ($response->json() as $index => $srProject) {
             $result->projects[] = new SendReceiveProjectModelWithIdentifier($srProject['identifier'], $srProject['name'], $srProject['repository'], $srProject['role']);
         }
     }
     $data = JsonEncoder::encode($result);
     self::addSRProjectClarification($data['projects']);
     self::sortSRProjectByName($data['projects']);
     self::checkSRProjectsAreLinked($data['projects']);
     return $data;
 }
 /**
  * @param string $projectId
  * @param string $textId
  * @return array
  */
 public static function readText($projectId, $textId)
 {
     $projectModel = new ProjectModel($projectId);
     $textModel = new TextModel($projectModel, $textId);
     return JsonEncoder::encode($textModel);
 }
 public function lex_upload_importLift($mediaType, $tmpFilePath)
 {
     $response = LexUploadCommands::importLiftFile($this->projectId, $mediaType, $tmpFilePath);
     return JsonEncoder::encode($response);
 }
 public function testDecode_ReadOnlyPropertiesInTwoMaps_PropertiesNotChanged()
 {
     $objectData = new PropertyObject();
     $objectData->name = 'can change name';
     $objectData->shouldBeReadOnly = 'cannot change this';
     $key = 'key1';
     $object1 = new PropertyObjectInMap();
     $object1->name = 'can change name';
     $object1->data[$key] = $objectData;
     $object = new PropertyObjectInMap2();
     $object->name = 'can change name';
     $object->data2[$key] = $object1;
     $params = json_decode(json_encode(JsonEncoder::encode($object)), true);
     $this->assertArrayHasKey('name', $params);
     $this->assertArrayHasKey('shouldBeReadOnly', $params['data2'][$key]['data'][$key]);
     $this->assertEquals($object->data2[$key]->data[$key]->shouldBeReadOnly, $params['data2'][$key]['data'][$key]['shouldBeReadOnly']);
     $params['name'] = 'different name2';
     $params['data2'][$key]['name'] = 'different name1';
     $params['data2'][$key]['data'][$key]['name'] = 'different name';
     $params['data2'][$key]['data'][$key]['shouldBeReadOnly'] = 'changed';
     JsonDecoder::decode($object, $params);
     $this->assertEquals('different name2', $object->name);
     $this->assertEquals('different name1', $object->data2[$key]->name);
     $this->assertEquals('different name', $object->data2[$key]->data[$key]->name);
     $this->assertEquals('cannot change this', $object->data2[$key]->data[$key]->shouldBeReadOnly);
 }
 public static function readProjectSettings($projectId)
 {
     $project = new ProjectSettingsModel($projectId);
     return array('sms' => JsonEncoder::encode($project->smsSettings), 'email' => JsonEncoder::encode($project->emailSettings));
 }
 /**
  * Sets key/values in the array from the public properties of $model
  * @param object $model
  * @return array
  */
 public static function encode($model)
 {
     $encoder = new JsonEncoder();
     return $encoder->_encode($model);
 }
 /**
  * @param string $validationKey
  * @return array
  * @throws \Exception
  */
 public static function readForRegistration($validationKey)
 {
     $user = new UserModelBase();
     if (!$user->readByProperty('validationKey', $validationKey)) {
         return array();
     }
     if (!$user->validate(false)) {
         throw new \Exception("Sorry, your registration link has expired.");
     }
     return JsonEncoder::encode($user);
 }
 public static function readQuestion($projectId, $questionId)
 {
     $projectModel = new ProjectModel($projectId);
     $questionModel = new QuestionModel($projectModel, $questionId);
     return JsonEncoder::encode($questionModel);
 }
 public function encode()
 {
     return JsonEncoder::encode($this);
 }
 public static function readTemplate($projectId, $id)
 {
     $projectModel = new ProjectModel($projectId);
     $questionTemplate = new QuestionTemplateModel($projectModel, $id);
     return JsonEncoder::encode($questionTemplate);
 }