/**
  * Updates the given LexEntry in $projectId
  * @param string $projectId
  * @param array $params
  * @param string $userId
  * @return LexEntryModel
  */
 public static function updateEntry($projectId, $params, $userId)
 {
     CodeGuard::checkTypeAndThrow($params, 'array');
     $project = new LexiconProjectModel($projectId);
     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 = new \DateTime();
         $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 ______"
     }
     // set authorInfo
     $entry->authorInfo->modifiedDate = new \DateTime();
     $entry->authorInfo->modifiedByUserRef->id = $userId;
     $params = self::recursiveRemoveEmptyFieldValues($params);
     //$params = self::recursiveAlignCustomFieldsWithModel($params);
     JsonDecoder::decode($entry, $params);
     $entry->write();
     ActivityCommands::writeEntry($project, $userId, $entry, $action);
     return JsonEncoder::encode($entry);
 }
 public function offsetSet($index, $newval)
 {
     if ($index != NULL) {
         CodeGuard::checkTypeAndThrow($index, 'integer');
     }
     parent::offsetSet($index, $newval);
 }
 /**
  *
  * @param UserProfileModel $user
  * @param ProjectSettingsModel $project
  * @param string $subject
  * @param string $smsTemplate
  * @param string $emailTemplate
  * @param string $htmlEmailTemplate
  * @param DeliveryInterface $delivery
  */
 public static function communicateToUser($user, $project, $subject, $smsTemplate, $emailTemplate, $htmlEmailTemplate = '', DeliveryInterface $delivery = null)
 {
     // Prepare the email message if required
     if ($user->communicate_via == UserModel::COMMUNICATE_VIA_EMAIL || $user->communicate_via == UserModel::COMMUNICATE_VIA_BOTH) {
         CodeGuard::checkNotFalseAndThrow($project->emailSettings->fromAddress, 'email from address');
         CodeGuard::checkNotFalseAndThrow($user->email, 'email to address');
         $from = array($project->emailSettings->fromAddress => $project->emailSettings->fromName);
         $to = array($user->email => $user->name);
         $vars = array('user' => $user, 'project' => $project);
         $template = CommunicateHelper::templateFromString($emailTemplate);
         $content = $template->render($vars);
         $htmlContent = '';
         if ($htmlEmailTemplate) {
             $template = CommunicateHelper::templateFromString($emailTemplate);
             $htmlContent = $template->render($vars);
         }
         CommunicateHelper::deliverEmail($from, $to, $subject, $content, $htmlContent, $delivery);
     }
     // Prepare the sms message if required
     if ($project->smsSettings->hasValidCredentials()) {
         if ($user->communicate_via == UserModel::COMMUNICATE_VIA_SMS || $user->communicate_via == UserModel::COMMUNICATE_VIA_BOTH) {
             $databaseName = $project->databaseName();
             $sms = new SmsModel($databaseName);
             $sms->providerInfo = $project->smsSettings->accountId . '|' . $project->smsSettings->authToken;
             $sms->to = $user->mobile_phone;
             $sms->from = $project->smsSettings->fromNumber;
             $vars = array('user' => $user, 'project' => $project);
             $template = CommunicateHelper::templateFromString($smsTemplate);
             $sms->message = $template->render($vars);
             CommunicateHelper::deliverSMS($sms, $delivery);
         }
     }
 }
 /**
  * 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);
 }
 public static function updateReply($projectId, $userId, $website, $commentId, $params)
 {
     CodeGuard::checkTypeAndThrow($params, 'array');
     CodeGuard::checkEmptyAndThrow($commentId, 'commentId in updateReply()');
     $project = new LexiconProjectModel($projectId);
     $comment = new LexCommentModel($project, $commentId);
     $rightsHelper = new RightsHelper($userId, $project, $website);
     $replyId = $params['id'];
     if (array_key_exists('id', $params) && $replyId != '') {
         $reply = $comment->getReply($replyId);
         if ($reply->authorInfo->createdByUserRef->asString() != $userId && !$rightsHelper->userHasProjectRight(Domain::COMMENTS + Operation::EDIT)) {
             throw new \Exception("No permission to update other people's lex comment replies!");
         }
         if ($reply->content != $params['content']) {
             $reply->authorInfo->modifiedDate = new \DateTime();
         }
         $reply->content = $params['content'];
         $comment->setReply($replyId, $reply);
     } else {
         $reply = new LexCommentReply();
         $reply->content = $params['content'];
         $reply->authorInfo->createdByUserRef->id = $userId;
         $reply->authorInfo->modifiedByUserRef->id = $userId;
         $reply->authorInfo->createdDate = new \DateTime();
         $comment->replies->append($reply);
         $replyId = $reply->id;
     }
     $comment->write();
     return $replyId;
 }
 /**
  * @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\\Mapper\\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 $key
  * @param object $model
  * @param MongoDate $data
  */
 public function decodeDateTime($key, $model, $data)
 {
     CodeGuard::checkTypeAndThrow($data, 'MongoDate', CodeGuard::CHECK_NULL_OK);
     if ($data !== null) {
         $model->setTimeStamp($data->sec);
     }
 }
Example #8
0
 /**
  * Returns the array of rights for this $role in the given $realm
  * @param string $role
  * @return array
  */
 protected static function _getRightsArray($rightsArray, $role)
 {
     CodeGuard::checkNotFalseAndThrow($role, 'role');
     if (!array_key_exists($role, $rightsArray)) {
         throw new \Exception("Role '{$role}' does not exist.");
     }
     return $rightsArray[$role];
 }
 /**
  * @see addRef - this should only be called by the addRef method of other ReferenceLists
  * @param string $id
  */
 public function _addRef($id)
 {
     CodeGuard::checkTypeAndThrow($id, 'string');
     // CARRY ON HERE CP :-)
     $idModel = new Id($id);
     if (!in_array($idModel, $this->refs)) {
         $this->refs[] = $idModel;
     }
     // TODO log if ref already exists?
 }
 /**
  * Writes the model to the mongo collection
  * @return string The unique id of the object written
  * @see MongoMapper::write()
  */
 public function write()
 {
     CodeGuard::checkTypeAndThrow($this->id, 'Api\\Model\\Shared\\Mapper\\Id');
     $now = UniversalTimestamp::now();
     $this->dateModified = $now;
     if (Id::isEmpty($this->id)) {
         $this->dateCreated = $now;
     }
     $this->id->id = $this->_mapper->write($this, $this->id->id);
     return $this->id->id;
 }
function _createCustomField($data)
{
    CodeGuard::checkTypeAndThrow($data, 'array');
    if (array_key_exists('value', $data)) {
        return new LexiconField();
    } elseif (array_key_exists('values', $data)) {
        return new LexiconMultiValueField();
    } else {
        return new MultiText();
    }
}
 /**
  * Update the optionlist with params
  * @param $projectId
  * @param LexOptionListModel $params
  */
 public static function updateList($projectId, $params)
 {
     CodeGuard::checkTypeAndThrow($params, 'array');
     $project = new LexiconProjectModel($projectId);
     if (array_key_exists('id', $params) && $params['id'] != '') {
         $optionlist = new LexOptionListModel($project, $params['id']);
     } else {
         $optionlist = new LexOptionListModel($project);
     }
     JsonDecoder::decode($optionlist, $params);
     $optionlist->write();
 }
 /**
  * @param array $questionTemplateIds
  * @return int Total number of questionTemplate questions removed.
  */
 public static function deleteQuestionTemplates($projectId, $questionTemplateIds)
 {
     CodeGuard::checkTypeAndThrow($questionTemplateIds, 'array');
     $count = 0;
     $projectModel = new ProjectModel($projectId);
     foreach ($questionTemplateIds as $questionTemplateId) {
         CodeGuard::checkTypeAndThrow($questionTemplateId, 'string');
         $questionTemplate = new QuestionTemplateModel($projectModel, $questionTemplateId);
         $questionTemplate->remove();
         $count++;
     }
     return $count;
 }
Example #14
0
 /**
  * @param SmsModel $smsModel
  */
 public static function queue($smsModel)
 {
     CodeGuard::checkTypeAndThrow($smsModel, 'Api\\Library\\Shared\\Communicate\\Sms\\SmsModel');
     // Check if the smsModel is valid
     if (!$smsModel->to || !$smsModel->from || $smsModel->userRef == null || !$smsModel->userRef->asString()) {
         error_log("Error: Attempting to queue invalid sms");
         error_log(" Dump: " . var_export($smsModel, true));
         return;
     }
     $id = $smsModel->write();
     $databaseName = $smsModel->databaseName();
     error_log("wrote sms: {$id} to {$databaseName}");
 }
 /**
  * This function handle a request binding it to a given object
  *
  * @param Request $request
  * @param object $object
  * @return array|null
  * @throws \Exception
  */
 public static function handle(Request $request, $object)
 {
     // user-defined error handler to catch annoying php errors and throw them as exceptions
     set_error_handler(function ($errno, $errstr, $errfile, $errline) {
         throw new ErrorHandler($errstr, 0, $errno, $errfile, $errline);
     }, E_ALL);
     // checks if a JSON-RPC request has been received
     if ($_SERVER['REQUEST_METHOD'] != 'POST' || empty($_SERVER['CONTENT_TYPE']) || strrpos($_SERVER['CONTENT_TYPE'], "application/json") === false && strrpos($_SERVER['CONTENT_TYPE'], "application/xml") === false) {
         throw new \Exception("Not a JSON-RPC request: ct: '" . @$_SERVER['CONTENT_TYPE'] . "'");
     }
     // executes the task on local object
     try {
         // TODO: refactor to use an error dto
         $object->checkPermissions($request->request->get('method'), $request->request->get('params'));
         if (method_exists($object, $request->request->get('method'))) {
             $result = call_user_func_array(array($object, $request->request->get('method')), $request->request->get('params'));
             $response = array('jsonrpc' => '2.0', 'id' => $request->request->get('id'), 'result' => $result, 'error' => NULL);
         } else {
             $response = array('jsonrpc' => '2.0', 'id' => $request->request->get('id'), 'result' => NULL, 'error' => array('type' => 'UnknownMethod', 'message' => sprintf("unknown method '%s' on class '%s'", $request->request->get('method'), get_class($object))));
         }
     } catch (\Exception $e) {
         $response = array('id' => $request->request->get('id'), 'result' => NULL, 'error' => array('type' => get_class($e), 'message' => $e->getMessage() . " line " . $e->getLine() . " " . $e->getFile() . " " . CodeGuard::getStackTrace($e->getTrace())));
         if ($e instanceof ResourceNotAvailableException) {
             $response['error']['type'] = 'ResourceNotAvailableException';
             $response['error']['message'] = $e->getMessage();
         } elseif ($e instanceof UserNotAuthenticatedException) {
             $response['error']['type'] = 'UserNotAuthenticatedException';
             $response['error']['message'] = $e->getMessage();
         } elseif ($e instanceof UserUnauthorizedException) {
             $response['error']['type'] = 'UserUnauthorizedException';
             $response['error']['message'] = $e->getMessage();
         }
         $message = '';
         $message .= $e->getMessage() . "\n";
         $message .= $e->getTraceAsString() . "\n";
         error_log($message);
     }
     if (!$request->request->get('id')) {
         // notifications don't want response
         return null;
     }
     return $response;
 }
function generateCustomField($data)
{
    CodeGuard::checkTypeAndThrow($data, 'array');
    if (array_key_exists('type', $data)) {
        switch ($data['type']) {
            case LexConfig::MULTIPARAGRAPH:
                return new LexMultiParagraph();
            default:
                $type = $data['type'];
                throw new \Exception("Cannot generate unknown custom field type: {$type}");
        }
    } elseif (array_key_exists('value', $data)) {
        return new LexValue();
    } elseif (array_key_exists('values', $data)) {
        return new LexMultiValue();
    } elseif (array_key_exists('paragraphs', $data)) {
        return new LexMultiParagraph();
    } else {
        return new LexMultiText();
    }
}
 /**
  * Activate a user on the specified site and validate email if it was empty, otherwise login
  * @param string $username
  * @param string $password
  * @param string $email
  * @param Website $website
  * @param Application $app
  * @param DeliveryInterface $delivery
  * @return string|boolean $userId|false otherwise
  */
 public static function activate($username, $password, $email, $website, $app, DeliveryInterface $delivery = null)
 {
     CodeGuard::checkEmptyAndThrow($username, 'username');
     CodeGuard::checkEmptyAndThrow($password, 'password');
     CodeGuard::checkEmptyAndThrow($email, 'email');
     CodeGuard::checkNullAndThrow($website, 'website');
     $identityCheck = self::checkIdentity($username, $email, $website);
     if ($website->allowSignupFromOtherSites && $identityCheck->usernameExists && !$identityCheck->usernameExistsOnThisSite && ($identityCheck->emailIsEmpty || $identityCheck->emailMatchesAccount)) {
         $user = new PasswordModel();
         if ($user->readByProperty('username', $username)) {
             if ($user->verifyPassword($password)) {
                 $user = new UserModel($user->id->asString());
                 $user->siteRole[$website->domain] = $website->userDefaultSiteRole;
                 if ($identityCheck->emailIsEmpty) {
                     $user->emailPending = $email;
                 }
                 $user->write();
                 // if website has a default project then add them to that project
                 $project = ProjectModel::getDefaultProject($website);
                 $url = '/app';
                 if ($project) {
                     $project->addUser($user->id->asString(), ProjectRoles::CONTRIBUTOR);
                     $user->addProject($project->id->asString());
                     $project->write();
                     $user->write();
                     $url = '/app/' . $project->appName . '/' . $project->id->asString();
                 }
                 if ($identityCheck->emailIsEmpty) {
                     Communicate::sendSignup($user, $website, $delivery);
                 }
                 if ($identityCheck->emailMatchesAccount) {
                     Auth::login($app, $username, $password);
                     return Auth::result(Auth::LOGIN_SUCCESS, $url, 'location');
                 }
                 return Auth::result(Auth::LOGIN_FAIL_USER_UNAUTHORIZED, '', 'location');
             }
         }
     }
     return false;
 }
 /**
  * Update the user project role in the project
  * @param string $projectId
  * @param string $userId
  * @param string $projectRole
  * @throws \Exception
  * @return string $userId
  */
 public static function updateUserRole($projectId, $userId, $projectRole = ProjectRoles::CONTRIBUTOR)
 {
     CodeGuard::checkNotFalseAndThrow($projectId, '$projectId');
     CodeGuard::checkNotFalseAndThrow($userId, 'userId');
     //CodeGuard::assertInArrayOrThrow($role, array(ProjectRoles::CONTRIBUTOR, ProjectRoles::MANAGER));
     // Add the user to the project
     $user = new UserModel($userId);
     $project = ProjectModel::getById($projectId);
     if ($project->userIsMember($userId) && $projectRole == $project->users[$userId]->role) {
         return $userId;
     }
     if ($userId == $project->ownerRef->asString()) {
         throw new \Exception("Cannot update role for project owner");
     }
     ProjectCommands::usersDto($projectId);
     if (!$project->userIsMember($userId)) {
         ActivityCommands::addUserToProject($project, $userId);
     }
     $project->addUser($userId, $projectRole);
     $user->addProject($projectId);
     $project->write();
     $user->write();
     return $userId;
 }
 /**
  * Decodes the mongo array into the ReferenceList $model
  * @param ReferenceList $model
  * @param array $data
  * @throws \Exception
  */
 public function decodeReferenceList($model, $data)
 {
     $model->refs = array();
     if (array_key_exists('refs', $data)) {
         // This likely came from an API client, who shouldn't be sending this.
         return;
     }
     $refsArray = $data;
     foreach ($refsArray as $objectId) {
         CodeGuard::checkTypeAndThrow($objectId, 'string');
         array_push($model->refs, new Id((string) $objectId));
     }
 }
 /**
  * Returns the rights array for the $userId role.
  * @param string $userId
  * @return array
  */
 public function getRightsArray($userId)
 {
     if (!method_exists($this->rolesClass, 'getRightsArray')) {
         throw new \Exception('getRightsArray method cannot be called directly from ProjectModel');
     }
     CodeGuard::checkTypeAndThrow($userId, 'string');
     if (!key_exists($userId, $this->users)) {
         $result = array();
     } else {
         $role = $this->users[$userId]->role;
         $rolesClass = $this->rolesClass;
         $result = $rolesClass::getRightsArray($role);
     }
     return $result;
 }
Example #21
0
 /**
  * Writes the model to the mongo collection
  * @return string The unique id of the object written
  * @see MongoMapper::write()
  */
 public function write()
 {
     CodeGuard::checkTypeAndThrow($this->id, 'Api\\Model\\Mapper\\Id');
     $this->dateModified = new \DateTime();
     if (Id::isEmpty($this->id)) {
         $this->dateCreated = new \DateTime();
     }
     $this->id->id = $this->_mapper->write($this, $this->id->id);
     return $this->id->id;
 }
 /**
  * Updates an answer's tags.
  * @param string $projectId
  * @param string $questionId
  * @param string $answerId
  * @param array $tagsArray
  * @return array Returns an encoded QuestionDTO fragment for the Answer
  */
 public static function updateAnswerTags($projectId, $questionId, $answerId, $tagsArray)
 {
     CodeGuard::checkNotFalseAndThrow($answerId, 'answerId');
     $project = new ProjectModel($projectId);
     ProjectCommands::checkIfArchivedAndThrow($project);
     $question = new QuestionModel($project, $questionId);
     $answer = $question->readAnswer($answerId);
     $answer->tags = new ArrayOf();
     foreach ($tagsArray as $tag) {
         $answer->tags[] = $tag;
     }
     $question->writeAnswer($answer);
     return self::encodeAnswer($answer);
 }
 /**
  * Update the user project role in the project
  * @param string $projectId
  * @param string $userId
  * @param string $projectRole
  * @return string - userId
  */
 public static function updateUserRole($projectId, $userId, $projectRole = ProjectRoles::CONTRIBUTOR)
 {
     CodeGuard::checkNotFalseAndThrow($projectId, '$projectId');
     CodeGuard::checkNotFalseAndThrow($userId, 'userId');
     //CodeGuard::assertInArrayOrThrow($role, array(ProjectRoles::CONTRIBUTOR, ProjectRoles::MANAGER));
     // Add the user to the project
     $user = new UserModel($userId);
     $project = ProjectModel::getById($projectId);
     if ($userId == $project->ownerRef->asString()) {
         throw new \Exception("Cannot update role for project owner");
     }
     // TODO: Only trigger activity if this is the first time they have been added to project
     $usersDto = ProjectCommands::usersDto($projectId);
     if (!$project->users->offsetExists($userId)) {
         ActivityCommands::addUserToProject($project, $userId);
     }
     $project->addUser($userId, $projectRole);
     $user->addProject($projectId);
     $project->write();
     $user->write();
     return $userId;
 }
Example #24
0
 /**
  * Reads a MultiText from the XmlNode $sxeNode given by the element 'gloss'
  *
  * @param SimpleXMLElement $sxeNode
  * @param MultiText $multiText
  * @param ArrayOf $inputSystems
  * @return MultiText
  */
 public function readMultiTextGloss($sxeNode, $multiText, $inputSystems = null)
 {
     CodeGuard::checkTypeAndThrow($multiText, 'Api\\Model\\Languageforge\\Lexicon\\MultiText');
     if ($sxeNode->getName() != 'gloss') {
         throw new \Exception("'" . $sxeNode->getName() . "' is not a gloss");
     }
     $inputSystemTag = (string) $sxeNode['lang'];
     $multiText->form($inputSystemTag, (string) $sxeNode->text);
     $this->projectModel->addInputSystem($inputSystemTag);
     // TODO InputSystems should extend ArrayOf (or Map) and become more useful. CP 2014-10
     if (isset($inputSystems)) {
         // i.e. $inputSystems->ensureFieldHasInputSystem($inputSystemTag);
         $inputSystems->value($inputSystemTag);
     }
 }
 /**
  * @param string $type - this is one of
  * @param string $content
  */
 public function addContent($type, $content)
 {
     CodeGuard::checkTypeAndThrow($content, 'string');
     $this->actionContent[$type] = $content;
 }
 public function receive(Application $app, $appType, $mediaType)
 {
     // e.g. 'lf', 'entry-audio'
     // user-defined error handler to catch annoying php errors and throw them as exceptions
     ini_set('xdebug.show_exception_trace', 0);
     set_error_handler(function ($errno, $errstr, $errfile, $errline) {
         throw new ErrorHandler($errstr, 0, $errno, $errfile, $errline);
     }, E_ALL);
     $response = array();
     $status = 201;
     try {
         // check for mocked E2E upload
         if (array_key_exists('file', $_POST)) {
             $filePath = sys_get_temp_dir() . '/' . $_POST['file']['name'];
             if (file_exists($filePath) && !is_dir($filePath)) {
                 $file = $_POST['file'];
                 $file['error'] = UPLOAD_ERR_OK;
                 $tmpFilePath = $filePath;
                 $_FILES['file'] = $file;
             } else {
                 $file = $_FILES['file'];
             }
         } else {
             $file = $_FILES['file'];
         }
         if ($file['error'] == UPLOAD_ERR_OK) {
             if (!isset($tmpFilePath)) {
                 $tmpFilePath = $this->moveUploadedFile();
             }
             if ($appType == 'sf-checks') {
                 $api = new Sf($app);
                 $api->checkPermissions('sfChecks_uploadFile', array($mediaType, $tmpFilePath));
                 $response = $api->sfChecks_uploadFile($mediaType, $tmpFilePath);
             } elseif ($appType == 'lf-lexicon') {
                 $api = new Sf($app);
                 switch ($mediaType) {
                     case 'audio':
                         $api->checkPermissions('lex_uploadAudioFile', array($mediaType, $tmpFilePath));
                         $response = $api->lex_uploadAudioFile($mediaType, $tmpFilePath);
                         break;
                     case 'sense-image':
                         $api->checkPermissions('lex_uploadImageFile', array($mediaType, $tmpFilePath));
                         $response = $api->lex_uploadImageFile($mediaType, $tmpFilePath);
                         break;
                     case 'import-zip':
                         $api->checkPermissions('lex_upload_importProjectZip', array($mediaType, $tmpFilePath));
                         $response = $api->lex_upload_importProjectZip($mediaType, $tmpFilePath);
                         break;
                     case 'import-lift':
                         $api->checkPermissions('lex_upload_importLift', array($mediaType, $tmpFilePath));
                         $response = $api->lex_upload_importLift($mediaType, $tmpFilePath);
                         break;
                     default:
                         throw new \Exception("Unsupported upload type: {$mediaType}");
                 }
             } else {
                 throw new \Exception("Unsupported upload app: {$appType}");
             }
             // cleanup uploaded file if it hasn't been moved
             if ($tmpFilePath && file_exists($tmpFilePath)) {
                 @unlink($tmpFilePath);
             }
         }
     } catch (\Exception $e) {
         $response = array('result' => false, 'data' => array('errorType' => get_class($e), 'errorMessage' => $e->getMessage() . " line " . $e->getLine() . " " . $e->getFile() . " " . CodeGuard::getStackTrace($e->getTrace())));
         $status = 400;
         if ($e instanceof ResourceNotAvailableException) {
             $response['data']['errorType'] = 'ResourceNotAvailableException';
             $response['data']['errorMessage'] = $e->getMessage();
             $status = 404;
         } elseif ($e instanceof UserNotAuthenticatedException) {
             $response['data']['errorType'] = 'UserNotAuthenticatedException';
             $response['data']['errorMessage'] = $e->getMessage();
             $status = 401;
         } elseif ($e instanceof UserUnauthorizedException) {
             $response['data']['errorType'] = 'UserUnauthorizedException';
             $response['data']['errorMessage'] = $e->getMessage();
             $status = 403;
         }
         $message = '';
         $message .= $e->getMessage() . "\n";
         $message .= $e->getTraceAsString() . "\n";
         error_log($message);
     }
     return $app->json($response, $status);
 }
 /**
  * @param string $key
  * @param ReferenceList $model
  * @return array
  */
 public function encodeReferenceList($key, $model)
 {
     // Note: $key may be used in derived methods
     $result = array_map(function ($id) {
         CodeGuard::checkTypeAndThrow($id, 'Api\\Model\\Shared\\Mapper\\Id');
         return $id->id;
     }, $model->refs);
     return $result;
 }
 public function offsetSet($index, $newval)
 {
     CodeGuard::checkTypeAndThrow($index, 'string');
     parent::offsetSet($index, $newval);
 }
 /**
  * Reads a MultiText from the XmlNode $sxeNode given by the element 'gloss'
  *
  * @param \SimpleXMLElement $sxeNode
  * @param LexMultiText $multiText
  * @param ArrayOf $inputSystems
  * @throws \Exception
  */
 public function readMultiTextGloss($sxeNode, $multiText, $inputSystems = null)
 {
     CodeGuard::checkTypeAndThrow($multiText, 'Api\\Model\\Languageforge\\Lexicon\\LexMultiText');
     if ($sxeNode->getName() != 'gloss') {
         throw new \Exception("'" . $sxeNode->getName() . "' is not a gloss");
     }
     $inputSystemTag = (string) $sxeNode['lang'];
     $multiText->form($inputSystemTag, (string) $sxeNode->{'text'});
     $this->project->addInputSystem($inputSystemTag);
     if (isset($inputSystems)) {
         $inputSystems->ensureValueExists($inputSystemTag);
     }
 }
 /**
  * @param array $data
  * @param string $id
  * @param int $keyType
  * @param string $rootId
  * @param string $property
  * @return string
  */
 protected function update($data, $id, $keyType, $rootId, $property)
 {
     CodeGuard::checkTypeAndThrow($rootId, 'string');
     CodeGuard::checkTypeAndThrow($id, 'string');
     if ($keyType == self::ID_IN_KEY) {
         if (empty($rootId)) {
             $mongoid = self::mongoID($id);
             $filter = array('_id' => $mongoid);
             $updateCommand = array('$set' => $data);
             $options = array('upsert' => true);
             $this->_collection->updateOne($filter, $updateCommand, $options);
             $id = $mongoid->__toString();
         } else {
             CodeGuard::checkNullAndThrow($id, 'id');
             CodeGuard::checkNullAndThrow($property, 'property');
             $subKey = $property . '.' . $id;
             $filter = array('_id' => self::mongoID($rootId));
             $updateCommand = array('$set' => array($subKey => $data));
             $this->_collection->updateOne($filter, $updateCommand);
         }
     } else {
         CodeGuard::checkNullAndThrow($id, 'id');
         $filter = array('_id' => self::mongoID($rootId));
         $updateCommand = array('$set' => array($property . '$' . $id => $data));
         $this->_collection->updateOne($filter, $updateCommand);
     }
     return $id;
 }