Skip to content

Optional upload directory on S3 upload field #24

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: integration
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions extension.driver.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public function install() {
`unique_filename` tinyint(1) DEFAULT '1',
`ssl_option` tinyint(1) DEFAULT '0',
`validator` varchar(255),
`directory` varchar(255),
PRIMARY KEY (`id`),
KEY `field_id` (`field_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"
Expand All @@ -37,6 +38,11 @@ public function update($previousVersion) {
"ALTER TABLE `tbl_fields_s3upload` ADD `ssl_option` tinyint(1) DEFAULT '0'"
);
}
if(version_compare($previousVersion, '0.10.0', '<')) {
Symphony::Database()->query(
"ALTER TABLE `tbl_fields_s3upload` ADD `directory` varchar(255)"
);
}
}

public function getSubscribedDelegates(){
Expand Down
3 changes: 3 additions & 0 deletions extension.meta.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
</author>
</authors>
<releases>
<release version="0.10.0" date="2015-04-04" min="2.3.1" max="2.6.x">
* Support for uploading files to a directory within a bucket
</release>
<release version="0.9.0" date="2015-03-25" min="2.3.1" max="2.x.x">
* Fixed issues with SSL; added facade; replaced S3 logic
* Updated to AWS SDK Phar Version 2.7.23
Expand Down
45 changes: 36 additions & 9 deletions fields/field.s3upload.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ public function createTable()
`id` int(11) unsigned NOT NULL auto_increment,
`entry_id` int(11) unsigned NOT NULL,
`file` varchar(255) default NULL,
`directory` varchar(255) default NULL,
`size` int(11) unsigned NULL,
`mimetype` varchar(255) default NULL,
`meta` varchar(255) default NULL,
Expand Down Expand Up @@ -69,12 +70,13 @@ public function entryDataCleanup($entry_id, $data)
private function getUrl($file)
{
$protocol = ($this->get('ssl_option') == true ? 'https://' : 'http://');
$file_path = $this->getFullPath($file, $this->get('directory'));

if ($this->get('cname') == '') {
$url = $protocol . "s3.amazonaws.com/" . $this->get('bucket') . "/" . $file;
$url = $protocol . "s3.amazonaws.com/" . $this->get('bucket') . "/" . $file_path;
}
else {
$url = $protocol . $this->get('cname') . "/" . $file;
$url = $protocol . $this->get('cname') . "/" . $file_path;
}
return $url;
}
Expand All @@ -86,6 +88,12 @@ private function getUniqueFilename(&$file)
$file = preg_replace("/(.*)(\.[^\.]+)/e", "substr('$1', 0, $crop).'-'.uniqid().'$2'", $file);
}

private function getFullPath($file, $directory)
{
if (is_null($directory) || $directory == '') return $file;
return $directory . "/" . $file;
}

/*-------------------------------------------------------------------------
Settings:
-------------------------------------------------------------------------*/
Expand All @@ -95,7 +103,7 @@ public function displaySettingsPanel(XMLElement &$wrapper, $errors = null)
Field::displaySettingsPanel($wrapper, $errors);
$options = array();

$div = new XMLElement('div', NULL, array('class' => 'two columns'));
$div = new XMLElement('div', NULL, array('class' => 'three columns'));

try {
$buckets = $this->s3->listBuckets();
Expand Down Expand Up @@ -133,6 +141,17 @@ public function displaySettingsPanel(XMLElement &$wrapper, $errors = null)
$div->appendChild($label);
}

$label = Widget::Label(__('Directory'));
$label->setAttribute('class', 'column');
$label->appendChild(new XMLElement('i', __('Optional')));
$label->appendChild(Widget::Input('fields['.$this->get('sortorder').'][directory]', htmlspecialchars($this->get('directory'))));

if (isset($errors['directory'])) {
$div->appendChild(Widget::Error($label, $errors['directory']));
} else {
$div->appendChild($label);
}

$wrapper->appendChild($div);

$this->buildValidationSelect($wrapper, $this->get('validator'), 'fields['.$this->get('sortorder').'][validator]', 'upload');
Expand Down Expand Up @@ -166,6 +185,10 @@ public function checkFields(&$errors, $checkForDuplicates=true)
$errors['cname'] = __('This is an invalid CNAME. Don\'t include the protocol (http/s).');
}

if($this->get('directory') != '' && !preg_match('/^[a-zA-Z0-9\-_]+(\/[a-zA-Z0-9\-_]+)*$/', $this->get('directory'))) {
$errors['directory'] = __('Invalid directory name. Should be alphanumerics, underscores, hyphens with no leading or trailing slash.');
}

// Check if a related section has been selected
if($this->get('bucket') == '') {
$errors['bucket'] = __('You have not setup your S3 Access keys yet. Please do so <a href="'.SYMPHONY_URL.'/system/preferences/">here</a>.');
Expand All @@ -191,6 +214,7 @@ public function commit()
$fields['unique_filename'] = ($this->get('unique_filename') == '' ? '0' : '1');
$fields['ssl_option'] = ($this->get('ssl_option') == '' ? '0' : '1');
$fields['validator'] = ($fields['validator'] == 'custom' ? NULL : $this->get('validator'));
$fields['directory'] = $this->get('directory');

return FieldManager::saveSettings($id, $fields);
}
Expand Down Expand Up @@ -291,14 +315,15 @@ public function checkPostFieldData($data, &$message, $entry_id=NULL)

## check if the file exists since we can't check directly through the s3 library, the file field is unique
$row = Symphony::Database()->fetchRow(0, sprintf("
SELECT * FROM `tbl_entries_data_%d` WHERE `file` = '%s'
SELECT * FROM `tbl_entries_data_%d` WHERE `file` = '%s' AND `directory` = '%s'
",
$this->get('id'),
$data['name']
$data['name'],
$data['directory']
));

if (isset($row['file'])) {
$message = __('A file with the name %1$s already exists at that bucket. Please rename the file first, or choose another.', array($data['name']));
$message = __('A file with the name %2$s/%1$s already exists at that bucket. Please rename the file first, or choose another.', array($data['name']), array($data['directory']));
return self::__INVALID_FIELDS__;
}

Expand Down Expand Up @@ -362,7 +387,8 @@ public function processRawFieldData($data, &$status, &$message=null, $simulate=f
(!is_null($existing_file) && strtolower($existing_file) != strtolower($data['file']))
|| ($data['error'] == UPLOAD_ERR_NO_FILE && !is_null($existing_file))
) {
$this->s3->deleteObject($this->get('bucket'), basename($existing_file));
$file_path = $this->getFullPath(basename($existing_file), $this->get('directory'));
$this->s3->deleteObject($this->get('bucket'), $file_path);
}
}

Expand All @@ -372,6 +398,7 @@ public function processRawFieldData($data, &$status, &$message=null, $simulate=f

// Sanitize the filename
$data['name'] = Lang::createFilename($data['name']);
$upload_key = $this->getFullPath($data['name'], $this->get('directory'));

## Upload the new file
$options = array(
Expand All @@ -386,7 +413,7 @@ public function processRawFieldData($data, &$status, &$message=null, $simulate=f
try {
$this->s3->putObject(
$this->get('bucket'),
$data['name'],
$upload_key,
$data['tmp_name'],
$options
);
Expand All @@ -396,7 +423,7 @@ public function processRawFieldData($data, &$status, &$message=null, $simulate=f
$message = __(
__('There was an error while trying to upload the file %s to the bucket %s.'),
array(
'<code>' . $data['name'] . '</code>',
'<code>' . $upload_key . '</code>',
'<code>'. $this->get('bucket') . '</code>'
)
);
Expand Down