protected function populateFiles()
{
if (is_array($_REQUEST['fID'])) {
foreach ($_REQUEST['fID'] as $fID) {
$f = File::getByID($fID);
if (is_object($f)) {
$this->files[] = $f;
}
}
}
if (count($this->files) > 0) {
$this->canEdit = true;
foreach ($this->files as $f) {
$fp = new \Permissions($f);
if (!$fp->canViewFileInFileManager()) {
$this->canEdit = false;
}
}
} else {
$this->canEdit = false;
}
return $this->canEdit;
}
public function getTreeNodeName()
{
$f = \Concrete\Core\File\File::getByID($this->fID);
if (is_object($f)) {
return $f->getFileName();
}
}
/**
* @param $queryRow
* @return \Concrete\Core\File\File
*/
public function getResult($queryRow)
{
$f = File::getByID($queryRow['fID']);
if (is_object($f) && $this->checkPermissions($f)) {
return $f;
}
}
public function getContentObject()
{
$db = \Database::connection();
$fID = $db->GetOne('select fID from FileVersions where fvFilename = ?', array($this->getReference()));
if ($fID) {
$f = File::getByID($fID);
return $f;
}
}
public function setPermissionObject(File $f)
{
$this->permissionObject = $f;
if ($f->overrideFileSetPermissions()) {
$this->permissionObjectToCheck = $f;
} else {
$sets = $f->getFileSets();
$permsets = array();
foreach ($sets as $fs) {
if ($fs->overrideGlobalPermissions()) {
$permsets[] = $fs;
}
}
if (count($permsets) > 0) {
$this->permissionObjectToCheck = $permsets;
} else {
$fs = FileSet::getGlobal();
$this->permissionObjectToCheck = $fs;
}
}
}
public function __construct(File $file)
{
$this->loadPictureSettingsFromTheme();
if ($this->isResponsive) {
$sources = array();
foreach ($this->theme->getThemeResponsiveImageMap() as $thumbnail => $width) {
$type = \Concrete\Core\File\Image\Thumbnail\Type\Type::getByHandle($thumbnail);
if ($type !== null) {
$src = $file->getThumbnailURL($type->getBaseVersion());
if ($width) {
$sources[] = $src . ' ' . str_replace('px', '', $width) . 'w';
}
}
}
$this->srcset(implode(', ', $sources));
$this->layout('responsive');
}
$path = $file->getRelativePath();
if (!$path) {
$path = $file->getURL();
}
$this->src($path);
$this->width($file->getAttribute('width'));
$this->height($file->getAttribute('height'));
}
public static function createAndGetFile($f_id, $fs_id)
{
$db = Loader::db();
$fsfID = $db->GetOne('SELECT fsfID FROM FileSetFiles WHERE fID = ? AND fsID = ?', array($f_id, $fs_id));
if ($fsfID > 0) {
return static::getByID($fsfID);
} else {
$fs = FileSet::getByID($fs_id);
$f = \Concrete\Core\File\File::getByID($f_id);
$fsf = static::add($f, $fs);
return $fsf;
}
}
public function approve()
{
foreach ($this->file->getFileVersions() as $fv) {
$fv->fvIsApproved = false;
$fv->save(false);
}
$this->fvIsApproved = true;
$this->save();
$fe = new \Concrete\Core\File\Event\FileVersion($this);
Events::dispatch('on_file_version_approve', $fe);
$fo = $this->getFile();
$fo->reindex();
}
public function approve()
{
foreach ($this->file->getFileVersions() as $fv) {
$fv->fvIsApproved = false;
$fv->save(false);
}
$this->fvIsApproved = true;
$this->save();
$fe = new \Concrete\Core\File\Event\FileVersion($this);
Events::dispatch('on_file_version_approve', $fe);
$fo = $this->getFile();
$fo->reindex();
\Core::make('cache/request')->delete('file/version/approved/' . $this->getFileID());
}
public function on_start()
{
if (!isset($this->file)) {
$request = $this->request;
$fID = Loader::helper('security')->sanitizeInt($request->query->get('fID'));
if ($fID) {
$file = ConcreteFile::getByID($fID);
if (is_object($file) && !$file->isError()) {
$this->setFileObject($file);
} else {
throw new Exception(t('Invalid file.'));
}
}
}
}
public function view($object, $mode = 'select')
{
$this->set('object', $object);
$migrate = new Migration();
// process import file selection
if ($mode == 'select' && $this->post()) {
$data = $this->post();
$file_id = $data['file'];
if ($file_id) {
$file = File::getByID($file_id);
$file_version = $file->getRecentVersion();
if ($object == 'file') {
$filePath = $file_version->getRelativePath();
$fi = new FileImport();
$test = $fi->importTest();
$mode = 'test';
$this->set('test', $test);
} else {
$file_contents = $file_version->getFileContents();
$this->xml = simplexml_load_string($file_contents);
$mode = 'test';
$migrate->importTest($object, $this->xml);
$this->set('test', $migrate->test);
}
$this->set('file_id', $file_id);
}
}
// do migration
if ($mode == 'execute' && $this->post()) {
$data = $this->post();
$file_id = $data['file'];
$file = File::getByID($file_id);
$file_version = $file->getRecentVersion();
if ($object == 'file') {
$fi = new FileImport();
$result = $fi->import($file_version);
$this->set('result', $result);
} else {
$file_contents = $file_version->getFileContents();
$this->xml = simplexml_load_string($file_contents);
$migrate->import($object, $this->xml);
$this->set('result', $migrate->result);
}
}
// set mode
$this->set('mode', $mode);
}
public function submit()
{
if ($this->validateAction()) {
$post = $this->request->request->all();
$fsl = FileStorageLocation::getByID($post['fslID']);
if (is_object($fsl)) {
$fIDs = $post['fID'];
if (is_array($fIDs)) {
foreach ($fIDs as $fID) {
$f = File::getByID($fID);
if (is_object($f)) {
$fp = new Permissions($f);
if ($fp->canEditFilePermissions()) {
try {
$f->setFileStorageLocation($fsl);
} catch (\Exception $e) {
$json = new \Concrete\Core\Application\EditResponse();
$err = \Core::make('error');
$err->add($e->getMessage());
$json->setError($err);
$json->outputJSON();
}
}
}
}
}
} else {
$json = new \Concrete\Core\Application\EditResponse();
$err = \Core::make('error');
$err->add(t('Please select valid file storage location.'));
$json->setError($err);
$json->outputJSON();
}
$response = new EditResponse();
$response->setFiles($this->files);
$response->setMessage(t('File storage locations updated successfully.'));
$response->outputJSON();
}
}
protected function download(\Concrete\Core\File\File $file, $rcID = null)
{
$filename = $file->getFilename();
$file->trackDownload($rcID);
$fsl = $file->getFileStorageLocationObject();
$configuration = $fsl->getConfigurationObject();
$fv = $file->getVersion();
if ($configuration->hasPublicURL()) {
return \Redirect::url($fv->getURL())->send();
} else {
return $fv->forceDownload();
}
}
/**
* @return \Concrete\Core\Entity\File\File|null
*/
public function getFileObject()
{
return File::getByID($this->getFileID());
}
public function rescanMultiple()
{
$files = $this->getRequestFiles('canEditFileContents');
$q = Queue::get('rescan_files');
if ($_POST['process']) {
$obj = new stdClass();
$messages = $q->receive(5);
foreach ($messages as $key => $msg) {
// delete the page here
$file = unserialize($msg->body);
$f = \Concrete\Core\File\File::getByID($file['fID']);
if (is_object($f)) {
$this->doRescan($f);
}
$q->deleteMessage($msg);
}
$obj->totalItems = $q->count();
if ($q->count() == 0) {
$q->deleteQueue(5);
}
print json_encode($obj);
exit;
} else {
if ($q->count() == 0) {
foreach ($files as $f) {
$q->send(serialize(array('fID' => $f->getFileID())));
}
}
}
$totalItems = $q->count();
Loader::element('progress_bar', array('totalItems' => $totalItems, 'totalItemsSummary' => t2("%d file", "%d files", $totalItems)));
return;
}
/**
* @deprecated
*/
public function isError()
{
return parent::isError();
}
/**
* Add attachment to send with an email.
*
* Sample Code:
* $attachment = $mailHelper->addAttachment($fileObject);
* $attachment->filename = "CustomFilename";
* $mailHelper->send();
*
* @param File $fob File to attach
* @return StdClass Pointer to the attachment
*/
public function addAttachment(\Concrete\Core\File\File $fob)
{
// @TODO make this work with the File Storage Locations
$fv = $fob->getVersion();
$path = $fob->getPath();
$name = $fv->getFileName();
$type = false;
if (!function_exists('mime_content_type')) {
function mime_content_type($path)
{
return false;
}
}
$type = @mime_content_type($path);
// This is deprecated. Should be stable until php5.6
if (!$type) {
$mt = Loader::helper('mime');
$ext = preg_replace('/^.+\\.([^\\.]+)$/', '\\1', $path);
$type = $mt->mimeFromExtension($ext);
}
$contents = @file_get_contents($path);
if (!$contents) {
throw new Exception(t('Unable to get the file contents for attachment.'));
}
$file = new StdClass();
$file->object = $fob;
$file->type = $type;
$file->path = $path;
$file->filename = $name;
$file->contents = $contents;
unset($contents);
$this->attachments[] = $file;
return $file;
// Returns a pointer
}
public function action_delete_case_document($bID = false, $DocumentID)
{
if ($this->bID != $bID) {
return false;
}
$this->view();
$user = new User();
$file = \Concrete\Core\File\File::getByID($DocumentID);
if ($file->getUserID() != $user->getUserID()) {
return;
}
$file->delete();
$db = Loader::db();
$ql = "DELETE FROM `CaseDocuments` WHERE DocumentID=? AND DocumentOwnerID=?";
$val = array(intval($DocumentID), intval($user->getUserID()));
$db->query($ql, $val);
}
public function csv()
{
$dateHelper = Loader::helper('date');
/* @var $dateHelper \Concrete\Core\Localization\Service\Date */
$this->pageSize = 0;
$this->loadSurveyResponses();
$textHelper = Loader::helper('text');
$questionSet = $this->get('questionSet');
$answerSets = $this->get('answerSets');
$questions = $this->get('questions');
$surveys = $this->get('surveys');
$escapeCharacter = "'";
$charactersToEscape = array('-', '+', '=');
$fileName = $textHelper->filterNonAlphaNum($surveys[$questionSet]['surveyName']);
header("Content-Type: text/csv");
header("Cache-control: private");
header("Pragma: public");
$date = date('Ymd');
header("Content-Disposition: attachment; filename=" . $fileName . "_form_data_{$date}.csv");
$fp = fopen('php://output', 'w');
// write the columns
$row = array(t('Submitted Date'), t('User'));
foreach ($questions as $questionId => $question) {
if ($question['inputType'] == 'checkboxlist') {
$options = explode('%%', $question['options']);
foreach ($options as $opt) {
$row[] = $questions[$questionId]['question'] . ': ' . $opt;
}
} else {
$row[] = $questions[$questionId]['question'];
}
}
fputcsv($fp, $row);
// write the data
foreach ($answerSets as $answerSet) {
$row = array();
$row[] = $dateHelper->formatCustom($dateHelper::DB_FORMAT, $answerSet['created']);
if ($answerSet['uID'] > 0) {
$ui = UserInfo::getByID($answerSet['uID']);
if (is_object($ui)) {
$row[] = $ui->getUserName();
}
} else {
$row[] = '';
}
foreach ($questions as $questionId => $question) {
if ($question['inputType'] == 'checkboxlist') {
$options = explode('%%', $question['options']);
$subanswers = explode(',', $answerSet['answers'][$questionId]['answer']);
for ($i = 1; $i <= count($options); $i++) {
if (in_array(trim($options[$i - 1]), $subanswers)) {
$row[] = 'x';
} else {
$row[] = '';
}
}
} else {
if ($question['inputType'] == 'fileupload') {
$fID = intval($answerSet['answers'][$questionId]['answer']);
$file = File::getByID($fID);
if ($fID && $file) {
$fileVersion = $file->getApprovedVersion();
$row[] = $fileVersion->getDownloadURL();
} else {
$row[] = t('File not found');
}
} else {
$answer = $answerSet['answers'][$questionId]['answer'] . $answerSet['answers'][$questionId]['answerLong'];
if (in_array(substr($answer, 0, 1), $charactersToEscape)) {
$row[] = $escapeCharacter . $answer;
} else {
$row[] = $answer;
}
}
}
}
fputcsv($fp, $row);
}
fclose($fp);
die;
}
/**
* Called when we're saving the attribute from the frontend.
* @param $data
*/
public function saveForm($data)
{
$sessionKey = $data['value'];
$files = $_SESSION['multi_file'][$sessionKey];
$db = Database::connection();
// create or get file set
$fileSetName = sprintf('Multi File %s', date('Y-m-d'));
$fileSet = FileSet::getByID($data['fsID']);
if ($fileSet == null) {
$fileSet = FileSet::add($fileSetName);
}
$db->Replace('atMultiFile', array('avID' => $this->getAttributeValueID(), 'fsID' => $fileSet->getFileSetID()), 'avID', true);
// Update sort order of files
if (isset($data['sortOrder']) && !empty($data['sortOrder'])) {
$sortOrder = $data['sortOrder'];
parse_str($sortOrder, $sortOrderArray);
$fileSet->updateFileSetDisplayOrder($sortOrderArray['file']);
}
// Remove files
if (isset($data['removeFiles']) && !empty($data['removeFiles'])) {
$removeFiles = preg_split('[,]', $data['removeFiles'], -1, PREG_SPLIT_NO_EMPTY);
foreach ($removeFiles as $fID) {
$file = File::getByID($fID);
if (!is_null($file)) {
$file->delete();
}
}
}
// Import files
if (is_array($files)) {
foreach ($files as $file) {
$fi = new FileImporter();
$fileVersion = $fi->import($file['fileName'], $file['name']);
unlink($file['fileName']);
if ($fileVersion instanceof Version) {
$fileSet->addFileToSet($fileVersion);
} else {
// @TODO now what?
switch ($fileVersion) {
case FileImporter::E_FILE_INVALID_EXTENSION:
break;
case FileImporter::E_FILE_INVALID:
break;
}
}
}
}
// Clear session
unset($_SESSION['multi_file'][$sessionKey]);
}
/**
* Add attachment to send with an email.
*
* Sample Code:
* $attachment = $mailHelper->addAttachment($fileObject);
* $attachment->filename = "CustomFilename";
* $mailHelper->send();
*
* @param \Concrete\Core\File\File $fob File to attach
*
* @return \StdClass Pointer to the attachment
*
* @throws \Exception
*/
public function addAttachment(\Concrete\Core\File\File $fob)
{
// Get file version.
$fv = $fob->getVersion();
// Get file data.
$mimetype = $fv->getMimeType();
$filename = $fv->getFilename();
$resource = $fob->getFileResource();
$content = $resource->read();
// Create attachment.
$mp = new MimePart($content);
$mp->type = $mimetype;
$mp->disposition = Mime::DISPOSITION_ATTACHMENT;
$mp->encoding = Mime::ENCODING_BASE64;
$mp->filename = $filename;
// Add mimepart to attachments.
$this->attachments[] = $mp;
}
/**
* @return
*/
public function getVersion()
{
return File::getByID($this->fID, $this->fvID);
}
public function csv()
{
$dateHelper = Core::make('helper/date');
/* @var $dateHelper \Concrete\Core\Localization\Service\Date */
$this->pageSize = 0;
$this->loadSurveyResponses();
$textHelper = Core::make('helper/text');
$questionSet = $this->get('questionSet');
$answerSets = $this->get('answerSets');
$questions = $this->get('questions');
$surveys = $this->get('surveys');
$fileName = $textHelper->filterNonAlphaNum($surveys[$questionSet]['surveyName']);
if (!empty($_REQUEST['encoding'])) {
$encoding = $textHelper->filterNonAlphaNum($_REQUEST['encoding']);
}
header("Content-Type: text/csv");
header("Cache-control: private");
header("Pragma: public");
$date = date('Ymd');
header("Content-Disposition: attachment; filename=" . $fileName . "_form_data_{$date}.csv");
// write the columns
if ($encoding && function_exists(mb_convert_encoding)) {
$fp = fopen('php://temp', 'w');
$row = array(mb_convert_encoding(t('Submitted Date'), $encoding), mb_convert_encoding(t('User'), $encoding));
foreach ($questions as $questionId => $question) {
if ($question['inputType'] == 'checkboxlist') {
$options = explode('%%', $question['options']);
foreach ($options as $opt) {
$row[] = mb_convert_encoding($questions[$questionId]['question'], $encoding) . ': ' . mb_convert_encoding($opt, $encoding);
}
} else {
$row[] = mb_convert_encoding($questions[$questionId]['question'], $encoding);
}
}
fputcsv($fp, $row);
// write the data
foreach ($answerSets as $answerSet) {
$row = array();
$row[] = $dateHelper->formatCustom($dateHelper::DB_FORMAT, $answerSet['created']);
if ($answerSet['uID'] > 0) {
$ui = UserInfo::getByID($answerSet['uID']);
if (is_object($ui)) {
$row[] = $ui->getUserName();
}
} else {
$row[] = '';
}
foreach ($questions as $questionId => $question) {
if ($question['inputType'] == 'checkboxlist') {
$options = explode('%%', mb_convert_encoding($question['options'], $encoding));
$subanswers = explode(',', mb_convert_encoding($answerSet['answers'][$questionId]['answer'], $encoding));
for ($i = 1; $i <= count($options); $i++) {
if (in_array(trim($options[$i - 1]), $subanswers)) {
$row[] = 'x';
} else {
$row[] = '';
}
}
} else {
if ($question['inputType'] == 'fileupload') {
$fID = intval($answerSet['answers'][$questionId]['answer']);
$file = File::getByID($fID);
if ($fID && $file) {
$fileVersion = $file->getApprovedVersion();
$row[] = $fileVersion->getDownloadURL();
} else {
$row[] = t('File not found');
}
} else {
$row[] = mb_convert_encoding($answerSet['answers'][$questionId]['answer'], $encoding) . mb_convert_encoding($answerSet['answers'][$questionId]['answerLong'], $encoding);
}
}
}
}
fputcsv($fp, $row);
rewind($fp);
if ($encoding == "SJIS") {
$csvContents = str_replace("\n", "\r\n", stream_get_contents($fp));
} else {
$csvContents = $fp;
}
fclose($fp);
$fpmain = fopen('php://output', 'w');
fwrite($fpmain, $csvContents);
fclose($fpmain);
die;
} else {
$fp = fopen('php://output', 'w');
$row = array(t('Submitted Date'), t('User'));
foreach ($questions as $questionId => $question) {
if ($question['inputType'] == 'checkboxlist') {
$options = explode('%%', $question['options']);
foreach ($options as $opt) {
$row[] = $questions[$questionId]['question'] . ': ' . $opt;
}
} else {
$row[] = $questions[$questionId]['question'];
}
}
fputcsv($fp, $row);
// write the data
foreach ($answerSets as $answerSet) {
$row = array();
$row[] = $dateHelper->formatCustom($dateHelper::DB_FORMAT, $answerSet['created']);
if ($answerSet['uID'] > 0) {
$ui = UserInfo::getByID($answerSet['uID']);
if (is_object($ui)) {
$row[] = $ui->getUserName();
}
} else {
$row[] = '';
}
foreach ($questions as $questionId => $question) {
if ($question['inputType'] == 'checkboxlist') {
$options = explode('%%', $question['options']);
$subanswers = explode(',', $answerSet['answers'][$questionId]['answer']);
for ($i = 1; $i <= count($options); $i++) {
if (in_array(trim($options[$i - 1]), $subanswers)) {
$row[] = 'x';
} else {
$row[] = '';
}
}
} else {
if ($question['inputType'] == 'fileupload') {
$fID = intval($answerSet['answers'][$questionId]['answer']);
$file = File::getByID($fID);
if ($fID && $file) {
$fileVersion = $file->getApprovedVersion();
$row[] = $fileVersion->getDownloadURL();
} else {
$row[] = t('File not found');
}
} else {
$row[] = $answerSet['answers'][$questionId]['answer'] . $answerSet['answers'][$questionId]['answerLong'];
}
}
}
}
fputcsv($fp, $row);
fclose($fp);
die;
}
}
/**
* {@inheritDoc}
*/
public function isError()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'isError', array());
return parent::isError();
}
/**
* Imports a file in the default file storage location's incoming directory.
*
* @param string $filename
* @param ConcreteFile|bool $fr
*
* @return number Error Code | \Concrete\Core\File\Version
*/
public function importIncomingFile($filename, $fr = false)
{
$fh = Loader::helper('validation/file');
$fi = Loader::helper('file');
$cf = Core::make('helper/concrete/file');
$sanitizedFilename = $fi->sanitize($filename);
$default = StorageLocation::getDefault();
$storage = $default->getFileSystemObject();
if (!$storage->has(REL_DIR_FILES_INCOMING . '/' . $filename)) {
return Importer::E_FILE_INVALID;
}
if (!$fh->extension($filename)) {
return Importer::E_FILE_INVALID_EXTENSION;
}
// first we import the file into the storage location that is the same.
$prefix = $this->generatePrefix();
try {
$copied = $storage->copy(REL_DIR_FILES_INCOMING . '/' . $filename, $cf->prefix($prefix, $sanitizedFilename));
} catch (\Exception $e) {
$copied = false;
}
if (!$copied) {
$storage->write($cf->prefix($prefix, $sanitizedFilename), $storage->read(REL_DIR_FILES_INCOMING . '/' . $filename));
}
if (!$fr instanceof File) {
// we have to create a new file object for this file version
$fv = ConcreteFile::add($sanitizedFilename, $prefix, array('fvTitle' => $filename), $default);
$fv->refreshAttributes($this->rescanThumbnailsOnImport);
$fr = $fv->getFile();
} else {
// We get a new version to modify
$fv = $fr->getVersionToModify(true);
$fv->updateFile($sanitizedFilename, $prefix);
$fv->refreshAttributes($this->rescanThumbnailsOnImport);
}
return $fv;
}
/**
* Forces the download of a file and shuts down.
* Returns null if approved version wasn't found.
*
* @param File $file
* @param null|int $rcID
*/
protected function force_download($file, $rcID = null)
{
$file->trackDownload($rcID);
// Magic call to approved FileVersion
return $file->forceDownload();
}