Example #1
0
 public function executeImage(sfWebRequest $request)
 {
     $member = $this->getRoute()->getMember();
     if (!$member) {
         return sfView::NONE;
     }
     $community = Doctrine::getTable('Community')->find($request->getParameter('id'));
     if (!$community) {
         return sfView::ERROR;
     }
     $isAdmin = Doctrine::getTable('CommunityMember')->isAdmin($member->getId(), $community->getId());
     if (!$isAdmin || $community->getImageFileName()) {
         return sfView::ERROR;
     }
     $message = $request->getMailMessage();
     if ($images = $message->getImages()) {
         $image = array_shift($images);
         $validator = new opValidatorImageFile();
         $validFile = $validator->clean($image);
         $file = new File();
         $file->setFromValidatedFile($validFile);
         $file->setName('c_' . $community->getId() . '_' . $file->getName());
         $community->setFile($file);
         $community->save();
     }
     return sfView::NONE;
 }
Example #2
0
 public function executeImage(sfWebRequest $request)
 {
     $member = $this->getRoute()->getMember();
     if (!$member) {
         return sfView::NONE;
     }
     $message = $request->getMailMessage();
     $images = $message->getImages();
     foreach ($images as $image) {
         $count = $member->getMemberImage()->count();
         if ($count >= 3) {
             return sfView::ERROR;
         }
         $validator = new opValidatorImageFile();
         $validFile = $validator->clean($image);
         $file = new File();
         $file->setFromValidatedFile($validFile);
         $file->setName('m_' . $member->getId() . '_' . $file->getName());
         $memberImage = new MemberImage();
         $memberImage->setMember($member);
         $memberImage->setFile($file);
         if (!$count) {
             $memberImage->setIsPrimary(true);
         }
         $memberImage->save();
     }
     return sfView::NONE;
 }
Example #3
0
 public function save()
 {
     $file = new File();
     $file->setFromValidatedFile($this->getValue('file'));
     $file->setName(sprintf('admin_%s_%d', $this->getValue('imageName'), time()));
     return $file->save();
 }
Example #4
0
 /**
  * Create a file instance from a file info array ($_FILES)
  * 
  * @param array $fileInfo
  *
  * @return File The created file
  */
 public static function createFromArray(array $fileInfo)
 {
     $file = new File();
     $file->setName(isset($fileInfo['name']) ? $fileInfo['name'] : null);
     $file->setSize(isset($fileInfo['size']) ? $fileInfo['size'] : 0);
     $file->setType(isset($fileInfo['type']) ? $fileInfo['type'] : null);
     $file->setTmpName(isset($fileInfo['tmp_name']) ? $fileInfo['tmp_name'] : null);
     $file->setError(isset($fileInfo['error']) ? $fileInfo['error'] : 0);
     return $file;
 }
Example #5
0
 public function executePost(sfWebRequest $request)
 {
     $this->forward400If('' === (string) $request['title'], 'title parameter is not specified.');
     $this->forward400If('' === (string) $request['body'], 'body parameter is not specified.');
     $this->forward400If(!isset($request['public_flag']) || '' === (string) $request['public_flag'], 'public flag is not specified');
     if (isset($request['id']) && '' !== $request['id']) {
         $diary = Doctrine::getTable('Diary')->findOneById($request['id']);
         $this->forward400If(false === $diary, 'the specified diary does not exit.');
         $this->forward400If(false === $diary->isAuthor($this->member->getId()), 'this diary is not yours.');
     } else {
         $diary = new Diary();
         $diary->setMemberId($this->member->getId());
     }
     $diary->setTitle($request['title']);
     $diary->setBody($request['body']);
     $diary->setPublicFlag($request['public_flag']);
     $diary->save();
     $this->diary = $diary;
     for ($i = 1; $i <= 3; $i++) {
         $diaryImage = Doctrine::getTable('DiaryImage')->retrieveByDiaryIdAndNumber($diary->getId(), $i);
         $filename = basename($_FILES['diary_photo_' . $i]['name']);
         if (!is_null($filename) && '' !== $filename) {
             try {
                 $validator = new opValidatorImageFile(array('required' => false));
                 $validFile = $validator->clean($_FILES['diary_photo_' . $i]);
             } catch (Exception $e) {
                 $this->forward400($e->getMessage());
             }
             $f = new File();
             $f->setFromValidatedFile($validFile);
             $f->setName(hash('md5', uniqid((string) $i) . $filename));
             if ($stream = fopen($_FILES['diary_photo_' . $i]['tmp_name'], 'r')) {
                 if (!is_null($diaryImage)) {
                     $diaryImage->delete();
                 }
                 $bin = new FileBin();
                 $bin->setBin(stream_get_contents($stream));
                 $f->setFileBin($bin);
                 $f->save();
                 $di = new DiaryImage();
                 $di->setDiaryId($diary->getId());
                 $di->setFileId($f->getId());
                 $di->setNumber($i);
                 $di->save();
                 $diary->updateHasImages();
             } else {
                 $this->forward400(__('Failed to write file to disk.'));
             }
         }
         $deleteCheck = $request['diary_photo_' . $i . '_photo_delete'];
         if ('on' === $deleteCheck && !is_null($diaryImage)) {
             $diaryImage->delete();
         }
     }
 }
 public function getFile($isCreate = false)
 {
     if ($this->hasFile()) {
         return $this->file;
     }
     if ($isCreate) {
         $file = new File();
         $file->setName(self::FILE_NAME);
         $file->setFileBin(new FileBin());
         return $file;
     }
     return false;
 }
 public function save()
 {
     $file = new File();
     $file->setFromValidatedFile($this->getValue('file'));
     $file->setName('b_' . $file->getName());
     if ($this->isNew()) {
         $bannerImage = new BannerImage();
     } else {
         $bannerImage = $this->getObject();
     }
     $bannerImage->setFile($file);
     $bannerImage->setUrl($this->getValue('url'));
     $bannerImage->setName($this->getValue('name'));
     return $bannerImage->save();
 }
 function testGetFile()
 {
     if (!$this->bucket) {
         $this->fail('Cannot continue without valid bucket');
     }
     $file = new File();
     $file->setName('S3ConnectionTest.txt');
     try {
         $size = $this->bucket->getFileSize($file);
     } catch (Exception $e) {
         $error = true;
         echo $e->getMessage();
     }
     $this->assertFalse(isset($error));
 }
 public function save()
 {
     $count = $this->member->getMemberImage()->count();
     if ($count >= 3) {
         throw new opRuntimeException('Cannot add an image any more.');
     }
     $file = new File();
     $file->setFromValidatedFile($this->getValue('file'));
     $file->setName('m_' . $this->member->getId() . '_' . $file->getName());
     $memberImage = new MemberImage();
     $memberImage->setMember($this->member);
     $memberImage->setFile($file);
     if (!$count) {
         $memberImage->setIsPrimary(true);
     }
     return $memberImage->save();
 }
 public function control()
 {
     $this->redirectToSternIndiaEndPoint();
     $config = Config::getInstance();
     if (isset($_POST['upload']) && $_POST['upload'] == 'Upload') {
         $target_dir = new FileSystem('upload/');
         $file = new File('foo', $target_dir);
         $name = date('D_d_m_Y_H_m_s_');
         $name = $name . $file->getName();
         $file->setName($name);
         $config = Config::getInstance();
         $file->addValidations(array(new Mimetype($config->getMimeTypes()), new Size('5M')));
         $data = array('name' => $file->getNameWithExtension(), 'extension' => $file->getExtension(), 'mime' => $file->getMimetype(), 'size' => $file->getSize(), 'md5' => $file->getMd5());
         try {
             // /Profiler::debugPoint(true,__METHOD__, __FILE__, __LINE__,$data);
             $file->upload();
             //Profiler::debugPoint(true,__METHOD__, __FILE__, __LINE__,$data);
         } catch (Exception $e) {
             $errors = $file->getErrors();
         }
         $csvReader = new CSVReader();
         $destinationFile = $target_dir->directory . $file->getNameWithExtension();
         $data = $csvReader->parse_file($destinationFile);
         //$country= DAOFactory::getDAO('LocationDAO');
         foreach ($data as $loc_arr) {
             Utils::processLocation($loc_arr);
         }
         //Profiler::debugPoint(true,__METHOD__, __FILE__, __LINE__);
         $target_dir = "uploads/";
         $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
         $uploadOk = 1;
         $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
         // Check if image file is a actual image or fake image
         if (isset($_POST["submit"])) {
             $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
             if ($check !== false) {
                 echo "File is an image - " . $check["mime"] . ".";
                 $uploadOk = 1;
             } else {
                 echo "File is not an image.";
                 $uploadOk = 0;
             }
         }
     }
     return $this->generateView();
 }
Example #11
0
 public function toFile($filename = "file", $folder = "PDF")
 {
     $filename = $this->addFileExt($filename);
     $filedir = ASSETS_DIR . "/{$folder}/{$filename}";
     $filepath = ASSETS_PATH . DIRECTORY_SEPARATOR . $folder . DIRECTORY_SEPARATOR . $filename;
     $folder = Folder::find_or_make($folder);
     $output = $this->output();
     if ($fh = fopen($filepath, 'w')) {
         fwrite($fh, $output);
         fclose($fh);
     }
     $file = new File();
     $file->setName($filename);
     $file->Filename = $filedir;
     $file->ParentID = $folder->ID;
     $file->write();
     return $file;
 }
 public function save()
 {
     if ($this->getValue('file')) {
         if ($this->community->getFile()) {
             $this->community->getFile()->delete();
         }
         $file = new File();
         $file->setFromValidatedFile($this->getValue('file'));
         $file->setName('c_' . $this->community->getId() . '_' . $file->getName());
         $this->community->setFile($file);
     } elseif ($this->getValue('file_delete')) {
         $this->community->getFile()->delete();
         $this->community->setFile(null);
     } else {
         return;
     }
     $this->community->save();
 }
 public function updateObject($values = null)
 {
     if (is_null($values)) {
         $values = $this->getValues();
     }
     $image = null;
     if (array_key_exists('image', $values)) {
         $image = $values['image'];
         unset($values['image']);
     }
     $obj = parent::updateObject($values);
     if ($image instanceof sfValidatedFile) {
         unset($obj->Image);
         $file = new File();
         $file->setFromValidatedFile($image);
         $file->setName('oauth_' . $obj->getId() . '_' . $file->getName());
         $obj->setImage($file);
     }
 }
 public function savePchFileFromRawData(&$pchData, Doctrine_Connection $conn = null)
 {
     if ($this->getPchFileId()) {
         $pchFile = $this->getPchFile();
     } else {
         $pchFile = new File();
     }
     $pchFile->setType('image/pch');
     $pchFile->setName('cccc_' . time() . '_pch');
     $pchFile->save($conn);
     $fileBin = $pchFile->getFileBin();
     if (!$fileBin) {
         $fileBin = new FileBin();
         $fileBin->setFileId($pchFile->getId);
     }
     $fileBin->setBin($pchData);
     $fileBin->save($conn);
     $this->setPchFileId($pchFile->getId());
 }
 public function setImage($data)
 {
     $form = new MemberImageForm(array(), array('member' => $this->member));
     $imageUri = '';
     $pathList = array('media/image/default', 'media/image/aspect11', 'media/image/aspect43', 'media/image/aspect34');
     foreach ($pathList as $v) {
         $img = $this->getValue($data, $v);
         if ($img) {
             $imageUri = $img;
             break;
         }
     }
     if ($imageUri) {
         $client = new Zend_Http_Client(array_shift($imageUri));
         $response = $client->request();
         if (!$response->isError()) {
             $type = $response->getHeader('Content-type');
             if (is_array($type)) {
                 $type = array_shift($type);
             }
             $tmppath = tempnam(sys_get_temp_dir(), 'IMG');
             $fh = fopen($tmppath, 'w');
             fwrite($fh, $response->getBody());
             fclose($fh);
             $image = array('tmp_name' => $tmppath, 'type' => $type);
             $validator = new opValidatorImageFile();
             $validFile = $validator->clean($image);
             $file = new File();
             $file->setFromValidatedFile($validFile);
             $file->setName('m_' . $this->member->getId() . '_' . $file->getName());
             $memberImage = new MemberImage();
             $memberImage->setMember($this->member);
             $memberImage->setFile($file);
             $memberImage->setIsPrimary(true);
             $memberImage->save();
         }
     }
 }
 function action()
 {
     $FileManager =& $this->_Parent->ExtensionManager->create('filemanager');
     $file = new File(DOCROOT . $FileManager->getStartLocation() . $_GET['file']);
     if (isset($_POST['action']['save'])) {
         $fields = $_POST['fields'];
         $file->setName($fields['name']);
         if (isset($fields['contents'])) {
             $file->setContents($fields['contents']);
         }
         $file->setPermissions($fields['permissions']);
         $relpath = str_replace(DOCROOT . $FileManager->getStartLocation(), NULL, dirname($_GET['file']));
         if ($file->isWritable()) {
             redirect($FileManager->baseURL() . 'properties/?file=' . rtrim(dirname($_GET['file']), '/') . '/' . $file->name() . '&result=saved');
         } else {
             redirect($FileManager->baseURL() . 'browse/' . $relpath);
         }
     } elseif (isset($_POST['action']['delete'])) {
         General::deleteFile($file->path() . '/' . $file->name());
         $relpath = str_replace(DOCROOT . $FileManager->getStartLocation(), NULL, dirname($_GET['file']));
         redirect($FileManager->baseURL() . 'browse/' . $relpath);
     }
 }
Example #17
0
 /**
  *  Редактирование язика
  */
 public function anyEdit()
 {
     $id = (int) $this->getRequestParam('id') ?: null;
     if (Arr::get($this->getPostData(), 'submit') !== null) {
         //Редактирование данных в базе
         $data = Arr::extract($this->getPostData(), ['name', 'iso', 'status']);
         try {
             // Загрузка картинки
             $file = new UploadFile('image', new FileSystem('uploads/images'));
             // Optionally you can rename the file on upload
             $file->setName(uniqid());
             // Validate file upload
             $file->addValidations(array(new UploadMimeType(['image/png', 'image/jpg', 'image/gif']), new UploadSize('50M')));
             // Try to upload file
             try {
                 // Success!
                 $file->upload();
                 $data['flag'] = $file->getNameWithExtension();
             } catch (Exception $e) {
                 // Fail!
                 Message::instance()->warning($file->getErrors());
             }
             // здесь надо использовать QueryBuilder потому-что стадартни update исползует метод Baum-а
             Capsule::table('langs')->whereId($id)->update($data);
             Event::fire('Admin.languageUpdate');
         } catch (QueryException $e) {
             Message::instance()->warning('Language was not editing');
         }
     }
     $item = LangModel::find($id);
     if (empty($item)) {
         throw new HttpException(404, json_encode(['errorMessage' => 'Incorrect Language']));
     }
     // отправка в шаблон
     $this->layout->content = View::make('back/languages/edit')->with('item', $item);
 }
Example #18
0
	function setName($name) {
		$this->setField('Title',$name);
		parent::setName($name);
	}
Example #19
0
 /**
  * Override setting the Title of Folders to that Name and Title are always in sync.
  * Note that this is not appropriate for files, because someone might want to create a human-readable name
  * of a file that is different from its name on disk. But folders should always match their name on disk.
  *
  * @param string $name
  * @return $this
  */
 public function setName($name)
 {
     parent::setName($name);
     $this->setField('Title', $this->Name);
     return $this;
 }
Example #20
0
 /**
  * setName() should throw InvalidArgumentException if $name is not readable
  */
 public function testSetName_throwsInvalidArgumentException_ifNameIsNotReadable()
 {
     $this->setExpectedException('InvalidArgumentException');
     $chunker = new File();
     $chunker->setName('foo');
     return;
 }
Example #21
0
 public function executePost(sfWebRequest $request)
 {
     $body = (string) $request['body'];
     $this->forward400If('' === $body, 'body parameter not specified.');
     $this->forward400If(mb_strlen($body) > 140, 'The body text is too long.');
     $memberId = $this->getUser()->getMemberId();
     $options = array();
     if (isset($request['public_flag'])) {
         $options['public_flag'] = $request['public_flag'];
     }
     if (isset($request['in_reply_to_activity_id'])) {
         $options['in_reply_to_activity_id'] = $request['in_reply_to_activity_id'];
     }
     if (isset($request['uri'])) {
         $options['uri'] = $request['uri'];
     } elseif (isset($request['url'])) {
         $options['uri'] = $request['url'];
     }
     if (isset($request['target']) && 'community' === $request['target']) {
         if (!isset($request['target_id'])) {
             $this->forward400('target_id parameter not specified.');
         }
         $options['foreign_table'] = 'community';
         $options['foreign_id'] = $request['target_id'];
     }
     $options['source'] = 'API';
     $imageFiles = $request->getFiles('images');
     if (!empty($imageFiles)) {
         foreach ((array) $imageFiles as $imageFile) {
             $validator = new opValidatorImageFile(array('required' => false));
             try {
                 $obj = $validator->clean($imageFile);
             } catch (sfValidatorError $e) {
                 $this->forward400('This image file is invalid.');
             }
             if (is_null($obj)) {
                 continue;
                 // empty value
             }
             $file = new File();
             $file->setFromValidatedFile($obj);
             $file->setName('ac_' . $this->getUser()->getMemberId() . '_' . $file->getName());
             $file->save();
             $options['images'][]['file_id'] = $file->getId();
         }
     }
     $this->activity = Doctrine::getTable('ActivityData')->updateActivity($memberId, $body, $options);
     if ('1' === $request['forceHtml']) {
         // workaround for some browsers (see #3201)
         $this->getRequest()->setRequestFormat('html');
         $this->getResponse()->setContentType('text/html');
     }
     $this->setTemplate('object');
 }
Example #22
0
 /**
  * @param array $params
  * @return string
  */
 public function createFile($params)
 {
     if (isset($params['folder-id'])) {
         $folder = $this->fs->loadFolder($params['folder-id']['value']);
         if ($folder) {
             $file = new File();
             $file->setCreatedTime(new \DateTime());
             if (isset($params['file-name'])) {
                 $file->setName($params['file-name']['value']);
             }
             if (isset($params['file-size'])) {
                 $file->setSize($params['file-size']['value']);
             }
             try {
                 $file = $this->fs->createFile($file, $folder);
                 return 'New file with id: ' . $file->getId() . ' created successfully in folder with id ' . $folder->getId();
             } catch (\Exception $ex) {
                 return $ex->getMessage();
             }
         } else {
             return 'Specified Folder ID doesn\'t exist in database';
         }
     } else {
         return 'Folder ID was not specified';
     }
 }
 /**
  * @param \SimpleXMLElement $fileXml
  *
  * @return File
  */
 private function hydrateFile(\SimpleXMLElement $fileXml)
 {
     $file = new File();
     $file->setName($this->findAttributeByName($fileXml, 'name'));
     $methodNumber = 0;
     foreach ($fileXml->class as $classXml) {
         $class = new ClassDto();
         $class->setName($this->findAttributeByName($classXml, 'name'));
         $class->setMethodCount($this->findAttributeByName($classXml->metrics, 'methods'));
         $class->setLineCount($this->findAttributeByName($classXml->metrics, 'statements'));
         $class->setMethodCoveredCount($this->findAttributeByName($classXml->metrics, 'coveredmethods'));
         $class = $this->hydrateMethod($fileXml, $class, $methodNumber);
         $file->addClass($class);
     }
     foreach ($fileXml->line as $lineXml) {
         $file->addLine($this->findAttributeByName($lineXml, 'num'), $this->findAttributeByName($lineXml, 'type'), (bool) $this->findAttributeByName($lineXml, 'count'));
     }
     return $file;
 }
 public function save_file_data($file_name, $file_type, $file_size, $file_path)
 {
     $file_entity = new File();
     $base = new Base();
     $file_entity->setName($file_name);
     $file_entity->setSize($file_size);
     $file_entity->setType($file_type);
     $file_entity->setPath($file_path);
     $base->audit_fields($file_entity, 'create');
     $file_entity->save();
 }
Example #25
0
 /**
  * Get File Revisions
  *
  * @param fileId - required -
  *		The id of the file.
  *
  * @return 	A File object is return with all the revisions
  * or the error code and message returned by the server.
  */
 public function getFileRevisions($fileId)
 {
     $urld = 'dpi/v1/folder/file/' . $fileId . '/revisions';
     $parameters = array();
     $this->response = $this->restTransportInstance->sendRequest($urld, $parameters, self::HTTP_GET, $this->authToken);
     $responseBody = simplexml_load_string($this->response);
     $returnObject = new File();
     if ($responseBody === false) {
         $errorCode = 'N/A';
         $errorMessage = 'The server has encountered an error, please try again.';
         $errorObject = new ErrorStatus($errorCode, $errorMessage);
         $returnObject->setErrorStatus($errorObject);
     } else {
         $errorStatus = $responseBody->errorStatus;
         if (empty($errorStatus)) {
             $returnObject->setRevision((string) $responseBody->attributes()->revision);
             $returnObject->setId((string) $responseBody->attributes()->id);
             $returnObject->setStatus((string) $responseBody->status);
             $returnObject->setCreatedOn((string) $responseBody->createdOn);
             $returnObject->setName((string) $responseBody->name);
             $returnObject->setOwnedByStorage((string) $responseBody->ownedByStorage);
             $returnObject->setParentId((string) $responseBody->parentid);
             $returnObject->setRevisionCount((string) $responseBody->revisionCount);
             $returnObject->setSize((string) $responseBody->size);
             $revisions = array();
             $revisionsTag = (string) $responseBody->revisions->count();
             if ($revisionsTag > 0) {
                 foreach ($responseBody->revisions->children() as $currentRevision) {
                     if ($currentRevision->count() > 0) {
                         $revision = new Revision();
                         $revision->setId((string) $currentRevision->attributes()->id);
                         $revision->setCurrent((string) $currentRevision->current);
                         $revision->setDownloadUrl((string) $currentRevision->downloadUrl);
                         $revision->setSize((string) $currentRevision->size);
                         array_push($revisions, $revision);
                     }
                 }
                 $returnObject->setRevisions($revisions);
             }
         } else {
             $errorCode = (string) $responseBody->errorStatus->code;
             $errorMessage = (string) $responseBody->errorStatus->message;
             $errorObject = new ErrorStatus($errorCode, $errorMessage);
             $returnObject->setErrorStatus($errorObject);
         }
     }
     return $returnObject;
 }
 /**
  * Upload single file
  *
  * @param void
  * @return null
  */
 function upload_single()
 {
     if ($this->request->isSubmitted()) {
         if (!File::canAdd($this->logged_user, $this->active_project)) {
             if ($this->request->isApiCall()) {
                 $this->httpError(HTTP_ERR_FORBIDDEN, null, true, true);
             } else {
                 die('error - upload not permitted');
             }
             // if
         }
         // if
         $file_data = $this->request->post('file');
         if (!is_array($file_data)) {
             $file_data = array('milestone_id' => $this->request->get('milestone_id'), 'visibility' => $this->active_project->getDefaultVisibility());
             if (instance_of($this->active_category, 'Category')) {
                 $file_data['parent_id'] = $this->active_category->getId();
             }
             // if
         }
         // if
         $this->smarty->assign('file_data', $file_data);
         if ($this->request->isSubmitted()) {
             db_begin_work();
             $this->active_file = new File();
             $attached = attach_from_files($this->active_file, $this->logged_user);
             // Do we have an upload error?
             if (is_error($attached) || $attached != 1) {
                 if ($this->request->isApiCall()) {
                     $this->serveData(is_error($attached) ? $attached : new Error('0 files uploaded'));
                 } else {
                     die('error - nothing uploaded');
                 }
                 // if
             }
             // if
             $this->active_file->setAttributes($file_data);
             if ($this->active_file->getName() == '') {
                 $this->active_file->setName($this->active_file->pending_files[0]['name']);
             }
             // if
             $this->active_file->setRevision(1);
             $this->active_file->setProjectId($this->active_project->getId());
             if (trim($this->active_file->getCreatedByName()) == '' || trim($this->active_file->getCreatedByEmail()) == '') {
                 $this->active_file->setCreatedBy($this->logged_user);
             }
             // if
             $this->active_file->setState(STATE_VISIBLE);
             $save = $this->active_file->save();
             if ($save && !is_error($save)) {
                 if ($this->active_file->countRevisions() > 0) {
                     $subscribers = array($this->logged_user->getId());
                     if (is_foreachable($this->request->post('notify_users'))) {
                         $subscribers = array_merge($subscribers, $this->request->post('notify_users'));
                     } else {
                         $subscribers[] = $this->active_project->getLeaderId();
                     }
                     // if
                     if (!in_array($this->active_project->getLeaderId(), $subscribers)) {
                         $subscribers[] = $this->active_project->getLeaderId();
                     }
                     // if
                     Subscriptions::subscribeUsers($subscribers, $this->active_file);
                     db_commit();
                     $this->active_file->ready();
                     if ($this->request->isApiCall()) {
                         $this->serveData($this->active_file, 'file');
                     } else {
                         die('success');
                         // async
                     }
                     // if
                 } else {
                     if ($this->request->isApiCall()) {
                         $this->httpError(HTTP_ERR_OPERATION_FAILED, null, true, true);
                     } else {
                         die('error - unable to attach file');
                     }
                     // if
                 }
                 // if
             } else {
                 if ($this->request->isApiCall()) {
                     $this->serveData($save);
                 } else {
                     die('error - could not save file object');
                     // async
                 }
                 // if
             }
             // if
         }
         // if
     } else {
         if ($this->request->isApiCall()) {
             $this->httpError(HTTP_ERR_BAD_REQUEST, null, true, true);
         } else {
             die('error - request is not POST request');
             // async
         }
         // if
     }
     // if
 }
Example #27
0
 /**
  * Get Item Info
  *
  * @param itemId - required -
  *         Item id
  * @return An Item object with details like itemId, expiration date, file details etc.
  * or the error code and message returned by the server.
  * 	 */
 public function getItemInfo($itemId)
 {
     $parameters = array();
     $urld = 'dpi/v1/item/' . $itemId;
     $this->response = $this->_restTransportInstance->sendRequest($urld, $parameters, 'GET', $this->_authToken);
     $responseBody = simplexml_load_string($this->response);
     $returnObject = new Item();
     if ($responseBody === false) {
         $errorCode = 'N/A';
         $errorMessage = 'The server has encountered an error, please try again.';
         $errorObject = new ErrorStatus($errorCode, $errorMessage);
         $returnObject->setErrorStatus($errorObject);
     } else {
         if (empty($responseBody->errorStatus)) {
             $create = (string) $responseBody->create;
             $returnObject->setCreate($create);
             $expiration = (string) $responseBody->expiration;
             $returnObject->setExpiration($expiration);
             $id = (string) $responseBody->id;
             $returnObject->setId($id);
             $subject = (string) $responseBody->subject;
             $returnObject->setSubject($subject);
             $message = (string) $responseBody->message;
             $returnObject->setMessage($message);
             $recipients = (string) $responseBody->recipients;
             $returnObject->setRecipients(explode(",", $recipients));
             $theFiles = array();
             $filesTag = $responseBody->file;
             if (!empty($filesTag)) {
                 foreach ($responseBody->file as $currentFile) {
                     if ($currentFile->count() > 0) {
                         $file = new File();
                         $file->setDownloadUrl((string) $currentFile->downloadUrl);
                         $file->setDownloads((string) $currentFile->downloads);
                         $file->setId((string) $currentFile->id);
                         $file->setName((string) $currentFile->name);
                         $file->setPasswordProtect((string) $currentFile->passwordProtect);
                         $file->setReturnReceipt((string) $currentFile->returnReceipt);
                         $file->setSize((string) $currentFile->size);
                         $file->setVerifyIdentity((string) $currentFile->verifyIdentity);
                         $tracking = array();
                         $trackTag = $currentFile->tracking;
                         if (!empty($trackTag)) {
                             foreach ($currentFile->tracking as $currentTrack) {
                                 if ($currentTrack->count() > 0) {
                                     $track = new Tracking();
                                     $track->setEmail((string) $currentTrack->email);
                                     $track->setWhen((string) $currentTrack->when);
                                     array_push($tracking, $track);
                                 }
                             }
                             $file->setTracking($tracking);
                         }
                         array_push($theFiles, $file);
                     }
                 }
                 $returnObject->setFiles($theFiles);
             }
         } else {
             $errorCode = (string) $responseBody->errorStatus->code;
             $errorMessage = (string) $responseBody->errorStatus->message;
             $errorObject = new ErrorStatus($errorCode, $errorMessage);
             $returnObject->setErrorStatus($errorObject);
         }
     }
     return $returnObject;
 }
 public function createActivityImageByFileInfoAndActivityId(array $fileInfo, $activityId)
 {
     $file = new File();
     $file->setOriginalFilename(basename($fileInfo['name']));
     $file->setType($fileInfo['type']);
     $fileFormat = $file->getImageFormat();
     if (is_null($fileFormat) || '' == $fileFormat) {
         $fileFormat = pathinfo($fileInfo['name'], PATHINFO_EXTENSION);
     }
     $fileBaseName = md5(time()) . '_' . $fileFormat;
     $filename = 'ac_' . $fileInfo['member_id'] . '_' . $fileBaseName;
     $file->setName($filename);
     $file->setFilesize($fileInfo['size']);
     $bin = new FileBin();
     $bin->setBin($fileInfo['binary']);
     $file->setFileBin($bin);
     $file->save();
     $activityImage = new ActivityImage();
     $activityImage->setActivityDataId($activityId);
     $activityImage->setFileId($file->getId());
     $activityImage->setUri($this->getActivityImageUriByfileInfoAndFilename($fileInfo, $filename));
     $activityImage->setMimeType($file->type);
     $activityImage->save();
     $this->createUploadImageFileByFileInfoAndSaveFileName($fileInfo, $filename);
     return $activityImage;
 }
 public function saveImportForm($data, $form)
 {
     if (isset($data['imported_files']) && is_array($data['imported_files'])) {
         $_POST['uploaded_files'] = array();
         // If the user has set a custom upload folder, cut a new copy of the file when importing
         $custom_folder = $this->getUploadFolder() != "Uploads" ? Folder::findOrMake($this->getCleanUploadFolder()) : false;
         foreach ($data['imported_files'] as $file_id) {
             $file = DataObject::get_by_id("File", $file_id);
             if ($custom_folder && $file->ParentID != $custom_folder->ID) {
                 $new_path = Director::baseFolder() . '/' . $custom_folder->Filename . $file->Name;
                 copy($file->getFullPath(), $new_path);
                 $new_file = new File();
                 $new_file->setFilename($custom_folder->Filename . $file->Name);
                 $new_file->setName($file->Name);
                 $new_file->setParentID($custom_folder->ID);
                 $new_file->write();
                 $file = $new_file;
                 $file_id = $new_file->ID;
             }
             // If something other than File has been specified as the linked file class,
             // we need to "upgrade" the imported file to the correct class.
             if ($this->fileClassName != "File" && $file->ClassName != $this->fileClassName) {
                 $file = $file->newClassInstance($this->fileClassName);
                 $file->write();
             }
             $owner_id = $data['parentIDName'];
             if ($this->hasDataObject) {
                 $do_class = $data['dataObjectClassName'];
                 $idxfield = $data['fileFieldName'] . "ID";
                 $obj = new $do_class();
                 $obj->{$idxfield} = $file_id;
                 $obj->{$owner_id} = $data['controllerID'];
                 $obj->write();
                 $_POST['uploaded_files'][] = $obj->ID;
             } else {
                 if ($file = DataObject::get_by_id($this->fileClassName, $file_id)) {
                     $id_field = $this->controllerFieldName . "ID";
                     if ($file->hasField($owner_id)) {
                         $file->{$owner_id} = $this->controllerID;
                         $file->write();
                     }
                 }
             }
         }
         $form = $this->EditUploadedForm();
         return $this->customise(array('String' => is_string($form), 'DetailForm' => $form))->renderWith($this->templatePopup);
     }
 }
 public function executeUpload(sfWebRequest $request)
 {
     // for apiKey check
     $memberId = $this->getUser()->getMember();
     if ('1' === $request->getParameter('forceHtml')) {
         // workaround for some browsers
         $this->getResponse()->setContentType('text/html');
     }
     if (!$_FILES) {
         return $this->renderJSON(array('status' => 'error', 'message' => 'null file'));
     }
     if (!$_FILES['upfile']) {
         return $this->renderJSON(array('status' => 'error', 'message' => 'null file'));
     }
     $filename = basename($_FILES['upfile']['name']);
     if (!$filename) {
         return $this->renderJSON(array('status' => 'error', 'message' => 'null file'));
     }
     $tmpFileName = $request->getParameter('changedname');
     if ($filename != $tmpFileName) {
         $separates = $separates = explode('.', $filename);
         $cnt = count($separates);
         $fname = '';
         $ext = '';
         if (1 == $cnt) {
             $fname = $value;
         } else {
             $fname = join('', array_slice($separates, 0, $cnt - 1));
             $ext = '.' . $separates[$cnt - 1];
         }
         if ('' == $fname) {
             $filename = $tmpFileName;
         }
     }
     $filename = preg_replace('/\\|\\/|\\*|:|\\?|\\&|\'|\\"|>|<|undefined|\\|/', '-', urldecode($filename));
     $communityId = (int) $request->getParameter('community_id');
     if (1 <= (int) $communityId) {
         $community = Doctrine::getTable('Community')->find($communityId);
         if (!$community->isPrivilegeBelong($this->getUser()->getMember()->getId())) {
             return $this->renderJSON(array('status' => 'error', 'message' => 'you are not this community member.'));
         }
         $dirname = '/c' . $communityId;
     } else {
         $dirname = '/m' . $this->getUser()->getMember()->getId();
     }
     //validate $filepath
     if (!preg_match('/^\\/[mc][0-9]+/', $dirname)) {
         return $this->renderJSON(array('status' => 'error', 'message' => 'file path error. ' . $dirname));
     }
     $f = new File();
     $f->setOriginalFilename($filename);
     $f->setType($_FILES['upfile']['type']);
     $f->setName($dirname . '/' . time() . $filename);
     $f->setFilesize($_FILES['upfile']['size']);
     if ($stream = fopen($_FILES['upfile']['tmp_name'], 'r')) {
         $bin = new FileBin();
         $bin->setBin(stream_get_contents($stream));
         $f->setFileBin($bin);
         $f->save();
         $response = true;
     } else {
         //file open error
         $response = false;
     }
     if (true === $response) {
         return $this->renderJSON(array('status' => 'success', 'message' => 'file up success ' . $response, 'file' => $f->toArray(false)));
     } else {
         return $this->renderJSON(array('status' => 'error', 'message' => 'file upload error'));
     }
 }