/** * Delete file from S3 when deleted from local disk * * Wordpress sometimes sends a partial path and sometimes sends an unescaped path * (depending on the OS), so this function normalizes it and removes the object * from the S3 bucket and returns a true absolute path to the file for `unlink()` * to do it's job. * * @param string $file Some sort of path * @return string Absolute path to file */ function deleteS3File($file) { $s3Key = get_option('s3_access_key'); $s3KeySecret = get_option('s3_access_secret'); $bucket = get_option('s3_bucket'); $S3 = new S3($s3Key, $s3KeySecret); $path = getS3Path($file); // delete from bucket $S3->deleteObject($bucket, $path); // save this image path for later cloudfront invalidation $pathsToInvalidate[] = "/{$path}"; return $file; }
public function delete() { $appHouseAds = AppHouseAdUtil::getAppHouseAdsByCid($this->id); foreach ($appHouseAds as $appHouseAd) { $appHouseAd->delete(); } if (!empty($this->imageLink)) { if (extension_loaded('curl') && !@dl(PHP_SHLIB_SUFFIX == 'so' ? 'curl.so' : 'php_curl.dll')) { $s3 = new S3(HouseAd::$HOUSEAD_AWS_KEY, HouseAd::$HOUSEAD_AWS_SECRET); $s3->deleteObject(HouseAd::$HOUSEAD_BUCKET, basename($this->imageLink)); } } parent::delete(); CacheUtil::invalidateCustom($this->id); }
/** * Delete a file from Amazon S3 or locally. * * @access public * @param string $path * @return boolean */ public function delete($path) { if ($this->s3 !== null) { return $this->s3->deleteObject($this->s3->bucket, $this->s3->path . basename($path)); } return $this->uploader->delete($path); }
/** * Delete a file from Amazon S3 or locally. * * @access public * @param string $path * @return boolean */ public function delete($path) { if ($this->s3 !== null && strpos($path, self::AS3_DOMAIN) !== false) { return $this->s3->deleteObject($this->s3->bucket, $this->s3->path . basename($path)); } return $this->uploader->delete($path); }
public function delete() { if ($this->isHydrated()) { $s3 = new S3(AMAZON_AWS_KEY, AMAZON_AWS_SECRET); $s3->deleteObject($this->get('bucket'), $this->get('path')); } parent::delete(); }
function deleteFile($filename) { $s3svc = new S3(); // Removing the first slash is important - otherwise the URL is different. $aws_filename = eregi_replace('^/', '', $filename); $s3svc->deleteObject($aws_filename, MIRROR_S3_BUCKET); unset($s3svc); }
/** * @inheritDoc BaseAssetSourceType::deleteSourceFolder() * * @param AssetFolderModel $parentFolder * @param $folderName * * @return bool */ protected function deleteSourceFolder(AssetFolderModel $parentFolder, $folderName) { $this->_prepareForRequests(); $bucket = $this->getSettings()->bucket; $objectsToDelete = $this->_s3->getBucket($bucket, $this->_getPathPrefix() . $parentFolder->path . $folderName); foreach ($objectsToDelete as $uri) { @$this->_s3->deleteObject($bucket, $uri['name']); } return true; }
/** * Delete directory * * @param string $path Short path * * @return boolean */ public function deleteDirectory($path) { $result = false; try { foreach ($this->readDirectory($path) as $k => $v) { $this->client->deleteObject(\XLite\Core\Config::getInstance()->CDev->AmazonS3Images->bucket, $k); } $result = $this->delete($path); } catch (\S3Exception $e) { $result = false; \XLite\Logger::getInstance()->registerException($e); } return $result; }
/** * Tests S3 * * @param string $error * @return boolean */ function test(&$error) { if (!parent::test($error)) { return false; } $string = 'test_s3_' . md5(time()); if (!$this->_init($error)) { return false; } $this->_set_error_handler(); $buckets = @$this->_s3->listBuckets(); if ($buckets === false) { $error = sprintf('Unable to list buckets (%s).', $this->_get_last_error()); $this->_restore_error_handler(); return false; } if (!in_array($this->_config['bucket'], (array) $buckets)) { $error = sprintf('Bucket doesn\'t exist: %s.', $this->_config['bucket']); $this->_restore_error_handler(); return false; } if (!@$this->_s3->putObjectString($string, $this->_config['bucket'], $string, S3::ACL_PUBLIC_READ)) { $error = sprintf('Unable to put object (%s).', $this->_get_last_error()); $this->_restore_error_handler(); return false; } if (!($object = @$this->_s3->getObject($this->_config['bucket'], $string))) { $error = sprintf('Unable to get object (%s).', $this->_get_last_error()); $this->_restore_error_handler(); return false; } if ($object->body != $string) { $error = 'Objects are not equal.'; @$this->_s3->deleteObject($this->_config['bucket'], $string); $this->_restore_error_handler(); return false; } if (!@$this->_s3->deleteObject($this->_config['bucket'], $string)) { $error = sprintf('Unable to delete object (%s).', $this->_get_last_error()); $this->_restore_error_handler(); return false; } $this->_restore_error_handler(); return true; }
/** * Tests S3 * * @param string $error * @return boolean */ function test(&$error) { $string = 'test_s3_' . md5(time()); if (!$this->_init($error)) { return false; } $domain = $this->get_domain(); if (!$domain) { $error = 'Empty domain.'; return false; } if (gethostbyname($domain) == $domain) { $error = sprintf('Unable to resolve domain: %s.', $domain); return false; } $buckets = @$this->_s3->listBuckets(); if (!$buckets) { $error = 'Unable to list buckets (check your credentials).'; return false; } if (!in_array($this->_config['bucket'], (array) $buckets)) { $error = sprintf('Bucket doesn\'t exist: %s', $this->_config['bucket']); return false; } if (!@$this->_s3->putObjectString($string, $this->_config['bucket'], $string, S3::ACL_PUBLIC_READ)) { $error = 'Unable to put object.'; return false; } if (!($object = @$this->_s3->getObject($this->_config['bucket'], $string))) { $error = 'Unable to get object.'; return false; } if ($object->body != $string) { @$this->_s3->deleteObject($this->_config['bucket'], $string); $error = 'Objects are not equal.'; return false; } if (!@$this->_s3->deleteObject($this->_config['bucket'], $string)) { $error = 'Unable to delete object.'; return false; } return true; }
public function lblDelete_Click($strFormId, $strControlId, $strParameter) { $objAttachment = Attachment::Load($strParameter); if (AWS_S3) { require __DOCROOT__ . __PHP_ASSETS__ . '/s3.class.php'; $objS3 = new S3(); $objS3->deleteObject('attachments/' . $objAttachment->TmpFilename, AWS_BUCKET); } else { if (file_exists($objAttachment->Path)) { unlink($objAttachment->Path); } } $objAttachment->Delete(); if ($this->objParentControl) { $this->objParentControl->pnlAttachments_Create(); } else { $this->objForm->pnlAttachments_Create(); } }
public function lblDelete_Click($strFormId, $strControlId, $strParameter) { $objAttachment = Attachment::Load($strParameter); if (AWS_S3) { require __DOCROOT__ . __PHP_ASSETS__ . '/S3.php'; $objS3 = new S3(AWS_ACCESS_KEY, AWS_SECRET_KEY); $strS3Path = AWS_PATH != '' ? ltrim(AWS_PATH, '/') . '/' : ''; $objS3->deleteObject(AWS_BUCKET, $strS3Path . 'attachments/' . $objAttachment->TmpFilename); } else { if (file_exists($objAttachment->Path)) { unlink($objAttachment->Path); } } $objAttachment->Delete(); if ($this->objParentControl) { $this->objParentControl->pnlAttachments_Create(); } else { $this->objForm->pnlAttachments_Create(); } }
/** * rename location icon * @param string $new_name * @return boolean */ public function rename_icon($new_name) { if (!$this->_loaded) { throw new Kohana_Exception('Cannot delete :model model because it is not loaded.', array(':model' => $this->_object_name)); } @rename('images/locations/' . $this->seoname . '.png', 'images/locations/' . $new_name . '.png'); if (core::config('image.aws_s3_active')) { require_once Kohana::find_file('vendor', 'amazon-s3-php-class/S3', 'php'); $s3 = new S3(core::config('image.aws_access_key'), core::config('image.aws_secret_key')); $s3->copyObject(core::config('image.aws_s3_bucket'), 'images/locations/' . $this->seoname . '.png', core::config('image.aws_s3_bucket'), 'images/locations/' . $new_name . '.png', S3::ACL_PUBLIC_READ); $s3->deleteObject(core::config('image.aws_s3_bucket'), 'images/locations/' . $this->seoname . '.png'); } }
public static function purgeUnusedFiles() { throw new Exception("Now sharded"); self::requireLibrary(); // Get all used files and files that were last deleted more than a month ago $sql = "SELECT MD5(CONCAT(hash, filename, zip)) AS file FROM storageFiles\n\t\t\t\t\tJOIN storageFileItems USING (storageFileID)\n\t\t\t\tUNION\n\t\t\t\tSELECT MD5(CONCAT(hash, filename, zip)) AS file FROM storageFiles\n\t\t\t\t\tWHERE lastDeleted > NOW() - INTERVAL 1 MONTH"; $files = Zotero_DB::columnQuery($sql); S3::setAuth(Z_CONFIG::$S3_ACCESS_KEY, Z_CONFIG::$S3_SECRET_KEY); $s3Files = S3::getBucket(Z_CONFIG::$S3_BUCKET); $toPurge = array(); foreach ($s3Files as $s3File) { preg_match('/^([0-9a-g]{32})\\/(c\\/)?(.+)$/', $s3File['name'], $matches); if (!$matches) { throw new Exception("Invalid filename '" . $s3File['name'] . "'"); } $zip = $matches[2] ? '1' : '0'; // Compressed file $hash = md5($matches[1] . $matches[3] . $zip); if (!in_array($hash, $files)) { $toPurge[] = array('hash' => $matches[1], 'filename' => $matches[3], 'zip' => $zip); } } Zotero_DB::beginTransaction(); foreach ($toPurge as $info) { S3::deleteObject(Z_CONFIG::$S3_BUCKET, self::getPathPrefix($info['hash'], $info['zip']) . $info['filename']); $sql = "DELETE FROM storageFiles WHERE hash=? AND filename=? AND zip=?"; Zotero_DB::query($sql, array($info['hash'], $info['filename'], $info['zip'])); // TODO: maybe check to make sure associated files haven't just been created? } Zotero_DB::commit(); return sizeOf($toPurge); }
} if (isset($_POST) && isset($_POST['extension'])) { $file_extension = $_POST['extension']; } $bucket_name = $aws['bucket']; $s3 = new S3($aws['key'], $aws['secret']); $results = array('success' => false, 'url' => 'http://blockstrap.com', 'msg' => 'Unable to copy or delete file'); $year = date('y'); $month = date('m'); $day = date('d'); $original_location = 'temp/' . $year . '/' . $month . '/' . $hash . '.' . $file_extension; $new_location = 'paid/' . $year . '/' . $month . '/' . $day . '/' . $txid . '.' . $file_extension; $vars = '?txid=' . $txid . '&extension=' . $file_extension . '&type=' . $type . '&chain=' . $chain; if ($save === true || $save === 'true') { if ($s3->copyObject($bucket_name, $original_location, $bucket_name, $new_location)) { if ($s3->deleteObject($bucket_name, $original_location)) { $results['success'] = true; $results['url'] = $urls['image'] . $vars; $results['msg'] = 'Copied and deleted file'; } else { $results['msg'] = 'Unable to delete original file'; } } } else { if ($s3->deleteObject($bucket_name, $original_location)) { $results['success'] = true; $results['url'] = false; $results['msg'] = 'Deleted file'; } else { $results['msg'] = 'Unable to delete file'; }
public function action_update() { //template header $this->template->title = __('Edit Product'); Breadcrumbs::add(Breadcrumb::factory()->set_title(__('Edit Product'))); $this->template->styles = array('css/sortable.css' => 'screen', '//cdn.jsdelivr.net/bootstrap.datepicker/0.1/css/datepicker.css' => 'screen', '//cdn.jsdelivr.net/jquery.fileupload/9.5.2/css/jquery.fileupload.css' => 'screen', 'css/jasny-bootstrap.min.css' => 'screen'); $this->template->scripts['footer'] = array('//cdn.jsdelivr.net/bootstrap.datepicker/0.1/js/bootstrap-datepicker.js', 'js/jasny-bootstrap.min.js', 'js/oc-panel/products.js', 'js/jquery-sortable-min.js', '//cdn.jsdelivr.net/jquery.fileupload/9.5.2/js/vendor/jquery.ui.widget.js', '//cdn.jsdelivr.net/jquery.fileupload/9.5.2/js/jquery.iframe-transport.js', '//cdn.jsdelivr.net/jquery.fileupload/9.5.2/js/jquery.fileupload.js'); $cats = Model_Category::get_as_array(); $order = Model_Category::get_multidimensional(); $obj_product = new Model_Product($this->request->param('id')); if ($obj_product->loaded()) { // get currencies from product, returns array $currency = $obj_product::get_currency(); $this->template->content = View::factory('oc-panel/pages/products/update', array('product' => $obj_product, 'categories' => $cats, 'order_categories' => $order, 'currency' => $currency)); if ($product = $this->request->post()) { // save product file if (isset($_FILES['file_name'])) { if ($file = $_FILES['file_name']) { $file = $obj_product->save_product($file); if ($file != FALSE) { $obj_product->file_name = $file; } else { Alert::set(Alert::INFO, __('Product is not uploaded.')); } } } // deleting single image by path $deleted_image = core::post('img_delete'); if (is_numeric($deleted_image)) { $img_path = $obj_product->gen_img_path($obj_product->id_product, $obj_product->created); $img_seoname = $obj_product->seotitle; // delete image from Amazon S3 if (core::config('image.aws_s3_active')) { require_once Kohana::find_file('vendor', 'amazon-s3-php-class/S3', 'php'); $s3 = new S3(core::config('image.aws_access_key'), core::config('image.aws_secret_key')); //delete original image $s3->deleteObject(core::config('image.aws_s3_bucket'), $img_path . $img_seoname . '_' . $deleted_image . '.jpg'); //delete formated image $s3->deleteObject(core::config('image.aws_s3_bucket'), $img_path . 'thumb_' . $img_seoname . '_' . $deleted_image . '.jpg'); //re-ordering image file names for ($i = $deleted_image; $i < $obj_product->has_images; $i++) { //rename original image $s3->copyObject(core::config('image.aws_s3_bucket'), $img_path . $img_seoname . '_' . ($i + 1) . '.jpg', core::config('image.aws_s3_bucket'), $img_path . $img_seoname . '_' . $i . '.jpg', S3::ACL_PUBLIC_READ); $s3->deleteObject(core::config('image.aws_s3_bucket'), $img_path . $img_seoname . '_' . ($i + 1) . '.jpg'); //rename formated image $s3->copyObject(core::config('image.aws_s3_bucket'), $img_path . 'thumb_' . $img_seoname . '_' . ($i + 1) . '.jpg', core::config('image.aws_s3_bucket'), $img_path . 'thumb_' . $img_seoname . '_' . $i . '.jpg', S3::ACL_PUBLIC_READ); $s3->deleteObject(core::config('image.aws_s3_bucket'), $img_path . 'thumb_' . $img_seoname . '_' . ($i + 1) . '.jpg'); } } if (!is_dir($img_path)) { return FALSE; } else { //delete original image @unlink($img_path . $img_seoname . '_' . $deleted_image . '.jpg'); //delete formated image @unlink($img_path . 'thumb_' . $img_seoname . '_' . $deleted_image . '.jpg'); //re-ordering image file names for ($i = $deleted_image; $i < $obj_product->has_images; $i++) { rename($img_path . $img_seoname . '_' . ($i + 1) . '.jpg', $img_path . $img_seoname . '_' . $i . '.jpg'); rename($img_path . 'thumb_' . $img_seoname . '_' . ($i + 1) . '.jpg', $img_path . 'thumb_' . $img_seoname . '_' . $i . '.jpg'); } } $obj_product->has_images = $obj_product->has_images > 0 ? $obj_product->has_images - 1 : 0; $obj_product->updated = Date::unix2mysql(); try { $obj_product->save(); } catch (Exception $e) { throw HTTP_Exception::factory(500, $e->getMessage()); } $this->redirect(Route::url('oc-panel', array('controller' => 'product', 'action' => 'update', 'id' => $obj_product->id_product))); } // end of img delete //delete product file $product_delete = core::post('product_delete'); if ($product_delete) { $p_path = $obj_product->get_file($obj_product->file_name); if (!is_file($p_path)) { return FALSE; } else { @chmod($p_path, 0755); //delete product unlink($p_path); $obj_product->file_name = ''; $obj_product->save(); $this->redirect(Route::url('oc-panel', array('controller' => 'product', 'action' => 'update', 'id' => $obj_product->id_product))); } } $product['status'] = (!isset($_POST['status']) or core::post('status') === NULL) ? Model_Product::STATUS_NOACTIVE : Model_Product::STATUS_ACTIVE; $product['updated'] = Date::unix2mysql(); //we do this so we assure use the entire day , nasty $product['offer_valid'] .= ' 23:59:59'; $product['featured'] .= ' 23:59:59'; // each field in edit product foreach ($product as $field => $value) { // do not include submit if ($field != 'submit' and $field != 'notify') { // check if its different, and set it is if ($value != $obj_product->{$field}) { $obj_product->{$field} = $value; // if title is changed, make new seotitle if ($field == 'title') { $seotitle = $obj_product->gen_seotitle($product['title']); $obj_product->seotitle = $seotitle; } } } } // save product or trow exeption try { $obj_product->save(); Alert::set(Alert::SUCCESS, __('Product saved.')); Sitemap::generate(); //notify users of new update if ($this->request->post('notify')) { //get users with that product $query = DB::select('email')->select('name')->from(array('users', 'u'))->join(array('orders', 'o'), 'INNER')->on('u.id_user', '=', 'o.id_user')->where('u.status', '=', Model_User::STATUS_ACTIVE)->where('o.status', '=', Model_Order::STATUS_PAID)->where('o.id_product', '=', $obj_product->id_product)->execute(); $users = $query->as_array(); if (count($users) > 0) { //download link $download = ''; if ($obj_product->has_file() == TRUE) { $download = '\\n\\n==== ' . __('Download') . ' ====\\n' . Route::url('oc-panel', array('controller' => 'profile', 'action' => 'orders')); } //theres an expire? 0 = unlimited $expire = ''; $expire_hours = Core::config('product.download_hours'); $expire_times = Core::config('product.download_times'); if (($expire_hours > 0 or $expire_times > 0) and $obj_product->has_file() == TRUE) { if ($expire_hours > 0 and $expire_times > 0) { $expire = sprintf(__('Your download expires in %u hours and can be downloaded %u times.'), $expire_hours, $expire_times); } elseif ($expire_hours > 0) { $expire = sprintf(__('Your download expires in %u hours.'), $expire_hours); } elseif ($expire_times > 0) { $expire = sprintf(__('Can be downloaded %u times.'), $expire_times); } $expire = '\\n' . $expire; } if (!Email::content($users, '', NULL, NULL, 'product-update', array('[TITLE]' => $obj_product->title, '[URL.PRODUCT]' => Route::url('product', array('seotitle' => $obj_product->seotitle, 'category' => $obj_product->category->seoname)), '[DOWNLOAD]' => $download, '[EXPIRE]' => $expire, '[VERSION]' => $obj_product->version))) { Alert::set(Alert::ERROR, __('Error on mail delivery, not sent')); } else { Alert::set(Alert::SUCCESS, __('Email sent to all the users')); } } else { Alert::set(Alert::ERROR, __('Mail not sent')); } } } catch (Exception $e) { throw HTTP_Exception::factory(500, $e->getMessage()); } // save images if (isset($_FILES)) { foreach ($_FILES as $file_name => $file) { if ($file_name != 'file_name') { $file = $obj_product->save_image($file); } if ($file) { $obj_product->has_images++; } } //since theres images save the ad again... try { $obj_product->save(); } catch (Exception $e) { throw HTTP_Exception::factory(500, $e->getMessage()); } } } } }
protected function _cleanOldFile() { if ($this->error) { return $this->getDebug() ? call_user_func_array('error', $this->error) : false; } switch ($this->getDriver()) { case 'local': if ($paths = $this->getAllPaths()) { foreach ($paths as $path) { if (file_exists($path = FCPATH . implode(DIRECTORY_SEPARATOR, $path)) && is_file($path)) { if (!@unlink($path)) { return $this->getDebug() ? error('OrmUploader 錯誤!', '清除檔案發生錯誤!', '請程式設計者確認狀況!') : false; } } } } return true; break; case 's3': if ($paths = $this->getAllPaths()) { foreach ($paths as $path) { if (!S3::deleteObject($this->getS3Bucket(), implode(DIRECTORY_SEPARATOR, $path))) { return $this->getDebug() ? error('OrmUploader 錯誤!', '清除檔案發生錯誤!', '請程式設計者確認狀況!') : false; } } } return true; break; } return $this->getDebug() ? error('OrmUploader 錯誤!', '未知的 driver,系統尚未支援 ' . $this->getDriver() . ' 的空間!', '請檢查 config/system/orm_uploader.php 設定檔!') : false; }
function profile($img = null) { $photo = urldecode($img); if (defined('USE_S3') && USE_S3) { $s3 = new S3(awsAccessKey, awsSecretKey); $info = $s3->getObjectInfo(BUCKET_NAME, DIR_USER_PHOTOS_S3_FOLDER . $photo); } else { if ($photo && file_exists(DIR_USER_PHOTOS . $photo)) { $info = 1; } } if ($photo && $info) { $checkPhoto = $this->User->find('count', array('conditions' => array('User.photo' => $photo, 'id' => SES_ID))); if ($checkPhoto) { if (defined('USE_S3') && USE_S3) { $s3->deleteObject(BUCKET_NAME, DIR_USER_PHOTOS_S3_FOLDER . $photo); } else { unlink(DIR_USER_PHOTOS . $photo); } $User['id'] = SES_ID; $User['photo'] = $photo_name; $this->User->save($User); $this->Session->write("SUCCESS", "Profile photo removed successfully"); $this->redirect(HTTP_ROOT . "users/profile"); } } $userdata = $this->User->findById(SES_ID); $this->set('userdata', $userdata); $this->loadModel('TimezoneName'); $timezones = $this->TimezoneName->find('all'); $this->set('timezones', $timezones); $email_update = 0; if (isset($this->request->data['User'])) { if (trim($this->request->data['User']['email']) == "") { $this->Session->write("ERROR", "Email cannot be left blank"); $this->redirect(HTTP_ROOT . "users/profile"); } else { if (trim($this->request->data['User']['email']) != $userdata['User']['email']) { $is_exist = $this->User->find('first', array('conditions' => array('User.email' => trim($this->request->data['User']['email'])))); $this->loadmodel('CompanyUser'); $is_cmpinfo = $this->CompanyUser->find('count', array('conditions' => array('CompanyUser.user_id' => $is_exist['User']['id']))); if (!$is_cmpinfo) { $this->User->id = $userdata['User']['id']; $userdata['User']['update_email'] = trim($this->request->data['User']['email']); $userdata['User']['update_random'] = $this->Format->generateUniqNumber(); $this->User->save($userdata); $email_update = trim($this->request->data['User']['email']); $this->send_update_email_noti($userdata, trim($this->request->data['User']['email'])); $this->request->data['User']['email'] = $userdata['User']['email']; } else { $this->Session->write("ERROR", "Opps! Email address already exists."); $this->redirect(HTTP_ROOT . "users/profile"); } } } $photo_name = ''; if (isset($this->request->data['User']['photo'])) { if (!empty($this->request->data['User']['photo']) && !empty($this->request->data['User']['exst_photo'])) { $checkProfPhoto = $this->User->find('count', array('conditions' => array('User.photo' => $this->request->data['User']['exst_photo'], 'id' => SES_ID))); if ($checkProfPhoto) { if (defined('USE_S3') && USE_S3) { $s3->deleteObject(BUCKET_NAME, DIR_USER_PHOTOS_S3_FOLDER . $this->request->data['User']['exst_photo']); } else { unlink(DIR_USER_PHOTOS . $this->request->data['User']['exst_photo']); } } } //$photo_name = $this->Format->uploadPhoto($this->request->data['User']['photo']['tmp_name'],$this->request->data['User']['photo']['name'],$this->request->data['User']['photo']['size'],DIR_USER_PHOTOS,SES_ID); //$photo_name = $this->Format->uploadPhoto($this->request->data['User']['photo']['tmp_name'],$this->request->data['User']['photo']['name'],$this->request->data['User']['photo']['size'],DIR_USER_PHOTOS,SES_ID,"profile_img"); $photo_name = $this->Format->uploadProfilePhoto($this->request->data['User']['photo'], DIR_USER_PHOTOS); if ($photo_name == "ext") { $this->Session->write("ERROR", "Opps! Invalid file format! The formats supported are gif, jpg, jpeg & png."); $this->redirect(HTTP_ROOT . "users/profile"); } elseif ($photo_name == "size") { $this->Session->write("ERROR", "Profile photo size cannot excceed 1mb"); $this->redirect(HTTP_ROOT . "users/profile"); } } if (trim($this->request->data['User']['name']) == "") { $this->Session->write("ERROR", "Name cannot be left blank"); $this->redirect(HTTP_ROOT . "users/profile"); } else { $this->request->data['User']['id'] = SES_ID; if (empty($this->request->data['User']['photo']) && !empty($this->request->data['User']['exst_photo'])) { $this->request->data['User']['photo'] = $this->request->data['User']['exst_photo']; } else { $this->request->data['User']['photo'] = $photo_name; } $this->User->save($this->request->data); if ($this->request->data['User']['timezone_id'] != $_COOKIE['USERTZ']) { $this->loadModel('Timezone'); $timezn = $this->Timezone->find('first', array('conditions' => array('Timezone.id' => $this->request->data['User']['timezone_id']), 'fields' => array('Timezone.gmt_offset', 'Timezone.dst_offset', 'Timezone.code'))); setcookie("USERTZ", '', time() - 3600, '/', DOMAIN_COOKIE, false, false); setcookie("USERTZ", $this->request->data['User']['timezone_id'], COOKIE_TIME, '/', DOMAIN_COOKIE, false, false); $auth_user = $this->Auth->user(); $auth_user['timezone_id'] = $this->request->data['User']['timezone_id']; $this->Session->write('Auth.User', $auth_user); } if ($email_update) { $this->Session->write("SUCCESS", "Profile updated successfully.<br />A confirmation link has been sent to '{$email_update}'."); } else { $this->Session->write("SUCCESS", "Profile updated successfully"); } $this->redirect(HTTP_ROOT . "users/profile"); } } $Company = ClassRegistry::init('Company'); $Company->recursive = -1; $getCompany = $Company->find('first', array('conditions' => array('Company.id' => SES_COMP))); $this->set('getCompany', $getCompany); }
public static function storeHouseAdImage($type) { if ($type == HouseAd::HOUSEAD_TYPE_ICON) { $scaledWidth = 38; $scaledHeight = 38; } elseif ($type == HouseAd::HOUSEAD_TYPE_BANNER) { $scaledWidth = 320; $scaledHeight = 50; } else { return ''; } $uploadedFile = isset($_FILES['image']['tmp_name']) ? $_FILES['image']['tmp_name'] : null; // TODO - Check file size if (isset($uploadedFile)) { if ($_FILES["image"]["type"] == "image/jpg" || $_FILES["image"]["type"] == "image/jpeg") { $src = imagecreatefromjpeg($uploadedFile); $imgType = 'jpg'; } elseif ($_FILES["image"]["type"] == "image/gif") { $src = imagecreatefromgif($uploadedFile); $imgType = 'gif'; } elseif ($_FILES["image"]["type"] == "image/png") { $src = imagecreatefrompng($uploadedFile); $imgType = 'png'; } else { return ''; } list($width, $height) = getimagesize($uploadedFile); $tmp = imagecreatetruecolor($scaledWidth, $scaledHeight); imagecopyresampled($tmp, $src, 0, 0, 0, 0, $scaledWidth, $scaledHeight, $width, $height); $randToken = md5(uniqid()); $filename = "../www.adwhirl.com/imagesTemp/" . $randToken . '.jpg'; imagejpeg($tmp, $filename, 100); imagedestroy($src); imagedestroy($tmp); $uploadFile = dirname(__FILE__) . '/../' . $filename; $bucketName = HouseAd::$HOUSEAD_BUCKET; if (!file_exists($uploadFile) || !is_file($uploadFile)) { return ''; } if (!extension_loaded('curl') && !@dl(PHP_SHLIB_SUFFIX == 'so' ? 'curl.so' : 'php_curl.dll')) { return ''; } $s3 = new S3(HouseAd::$HOUSEAD_AWS_KEY, HouseAd::$HOUSEAD_AWS_SECRET); if ($s3->putObjectFile($uploadFile, $bucketName, baseName($uploadFile), S3::ACL_PUBLIC_READ)) { if (isset($oldImageLink)) { $s3->deleteObject($bucketName, basename($oldImageLink)); } $imageLink = HouseAd::$HOUSEAD_BUCKET_PREFIX . $bucketName . '/' . basename($uploadFile); } else { return ''; } } else { return ''; } return $imageLink; }
/** * Method called automatically by model's delete * * @param object $model Object of model * @return boolean Return's true if delete should continue, false otherwise */ function beforeDelete(&$model) { App::import('Vendor', 'S3', array('file' => 'S3.php')); foreach ($this->settings[$model->name] as $field => $options) { $accessKey = $this->__accessKey; $secretKey = $this->__secretKey; // If we have S3 credentials for this field/file if (!empty($options['s3_access_key']) && !empty($options['s3_secret_key'])) { $accessKey = $options['s3_access_key']; $secretKey = $options['s3_secret_key']; } // Instantiate the class $aws = new S3($accessKey, $secretKey); // Get model's data for filename of photo $filename = $model->field($model->name . '.' . $field); // If filename is found then delete original photo if (!empty($filename)) { $aws->deleteObject($options['s3_bucket'], $filename); } } // Return true by default return true; }
/** * delete an object from a location in the current S3 bucket * @param string $locationOnS3 - path to the object relative to the bucket * @return boolean - TRUE on successful delete, FALSE on failure. */ public function deleteObject($locationOnS3) { try { S3::deleteObject($this->bucket, $locationOnS3); return true; } catch (Exception $e) { return false; } }
/** * Set primary image by swapping ids * @param integer $primary_image * @return void */ public function set_primary_image($primary_image) { // if ad doesn't have at least two images do nothing if ($this->has_images < 2) { return; } $img_path = $this->image_path(); // delete image from Amazon S3 if (core::config('image.aws_s3_active')) { require_once Kohana::find_file('vendor', 'amazon-s3-php-class/S3', 'php'); $s3 = new S3(core::config('image.aws_access_key'), core::config('image.aws_secret_key')); //re-ordering image file names $s3->copyObject(core::config('image.aws_s3_bucket'), $this->image_name('1'), core::config('image.aws_s3_bucket'), $this->image_name('1_old'), S3::ACL_PUBLIC_READ); $s3->deleteObject(core::config('image.aws_s3_bucket'), $this->image_name('1')); $s3->copyObject(core::config('image.aws_s3_bucket'), $this->image_name('1', 'thumb'), core::config('image.aws_s3_bucket'), $this->image_name('1_old', 'thumb'), S3::ACL_PUBLIC_READ); $s3->deleteObject(core::config('image.aws_s3_bucket'), $this->image_name('1', 'thumb')); $s3->copyObject(core::config('image.aws_s3_bucket'), $this->image_name($primary_image), core::config('image.aws_s3_bucket'), $this->image_name('1'), S3::ACL_PUBLIC_READ); $s3->deleteObject(core::config('image.aws_s3_bucket'), $this->image_name($primary_image)); $s3->copyObject(core::config('image.aws_s3_bucket'), $this->image_name($primary_image, 'thumb'), core::config('image.aws_s3_bucket'), $this->image_name('1', 'thumb'), S3::ACL_PUBLIC_READ); $s3->deleteObject(core::config('image.aws_s3_bucket'), $this->image_name($primary_image, 'thumb')); $s3->copyObject(core::config('image.aws_s3_bucket'), $this->image_name('1_old'), core::config('image.aws_s3_bucket'), $this->image_name($primary_image), S3::ACL_PUBLIC_READ); $s3->deleteObject(core::config('image.aws_s3_bucket'), $this->image_name('1_old')); $s3->copyObject(core::config('image.aws_s3_bucket'), $this->image_name('1_old', 'thumb'), core::config('image.aws_s3_bucket'), $this->image_name($primary_image, 'thumb'), S3::ACL_PUBLIC_READ); $s3->deleteObject(core::config('image.aws_s3_bucket'), $this->image_name('1_old', 'thumb')); } //re-ordering image file names @rename($this->image_name('1'), $this->image_name('1_old')); @rename($this->image_name('1', 'thumb'), $this->image_name('1_old', 'thumb')); @rename($this->image_name($primary_image), $this->image_name('1')); @rename($this->image_name($primary_image, 'thumb'), $this->image_name('1', 'thumb')); @rename($this->image_name('1_old'), $this->image_name($primary_image)); @rename($this->image_name('1_old', 'thumb'), $this->image_name($primary_image, 'thumb')); $this->last_modified = Date::unix2mysql(); try { $this->save(); return TRUE; } catch (Exception $e) { throw HTTP_Exception::factory(500, $e->getMessage()); } return FALSE; }
function test_s3($accesskey, $secretkey, $bucket, $directory = '', $ssl) { if (empty($accesskey) || empty($secretkey) || empty($bucket)) { return 'Missing one or more required fields.'; } require_once dirname(__FILE__) . '/lib/s3/s3.php'; $s3 = new S3($accesskey, $secretkey); if ($ssl != '1') { S3::$useSSL = false; } if ($s3->getBucketLocation($bucket) === false) { // Easy way to see if bucket already exists. $s3->putBucket($bucket, S3::ACL_PUBLIC_READ); } if (!empty($directory)) { $directory = $directory . '/'; } if ($s3->putObject('Upload test for BackupBuddy for Amazon S3', $bucket, $directory . 'backupbuddy.txt', S3::ACL_PRIVATE)) { // Success... just delete temp test file later... } else { return 'Unable to upload. Verify your keys, bucket name, and account permissions.'; } if (!S3::deleteObject($bucket, $directory . '/backupbuddy.txt')) { return 'Partial success. Could not delete temp file.'; } return true; // Success! }
$aws_bucket = $destination['bucket']; $aws_directory = $destination['directory']; if (!empty($aws_directory)) { $aws_directory = $aws_directory . '/'; } require_once $this->_pluginPath . '/lib/s3/s3.php'; $s3 = new S3($aws_accesskey, $aws_secretkey); // Delete S3 backups if (!empty($_POST['delete_file'])) { $delete_count = 0; if (!empty($_POST['files']) && is_array($_POST['files'])) { // loop through and delete s3 files foreach ($_POST['files'] as $s3file) { $delete_count++; // Delete S3 file $s3->deleteObject($aws_bucket, $s3file); } } if ($delete_count > 0) { $this->alert('Deleted ' . $delete_count . ' file(s).'); } } // Copy S3 backups to the local backup files if (!empty($_GET['copy_file'])) { $this->alert('The remote file is now being copied to your <a href="' . $this->_selfLink . '-backup">local backups</a>.'); $this->log('Scheduling Cron for creating s3 copy.'); wp_schedule_single_event(time(), $this->_parent->_var . '-cron_s3_copy', array($_GET['copy_file'], $aws_accesskey, $aws_secretkey, $aws_bucket, $aws_directory)); spawn_cron(time() + 150); // Adds > 60 seconds to get around once per minute cron running limit. update_option('_transient_doing_cron', 0); // Prevent cron-blocking for next item.
// echo "S3::getAccessControlPolicy(): {$bucketName}: ".print_r($acp, 1); // Update an access control policy ($acp should be the same as the data returned by S3::getAccessControlPolicy()) // $s3->setAccessControlPolicy($bucketName, '', $acp); // $acp = $s3->getAccessControlPolicy($bucketName); // echo "S3::getAccessControlPolicy(): {$bucketName}: ".print_r($acp, 1); // Enable logging for a bucket: // $s3->setBucketLogging($bucketName, 'logbucket', 'prefix'); // if (($logging = $s3->getBucketLogging($bucketName)) !== false) { // echo "S3::getBucketLogging(): Logging for {$bucketName}: ".print_r($contents, 1); // } else { // echo "S3::getBucketLogging(): Logging for {$bucketName} not enabled\n"; // } // Disable bucket logging: // var_dump($s3->disableBucketLogging($bucketName)); // Delete our file if ($s3->deleteObject($bucketName, baseName($uploadFile))) { echo "S3::deleteObject(): Deleted file\n"; // Delete the bucket we created (a bucket has to be empty to be deleted) if ($s3->deleteBucket($bucketName)) { echo "S3::deleteBucket(): Deleted bucket {$bucketName}\n"; } else { echo "S3::deleteBucket(): Failed to delete bucket (it probably isn't empty)\n"; } } else { echo "S3::deleteObject(): Failed to delete file\n"; } } else { echo "S3::putObjectFile(): Failed to copy file\n"; } } else { echo "S3::putBucket(): Unable to create bucket (it may already exist and/or be owned by someone else)\n";
/** * [delete_image description] * @param integer $deleted_image * @return void */ public function delete_image($deleted_image) { $img_path = $this->image_path(); $img_seoname = $this->seotitle; // delete image from Amazon S3 if (core::config('image.aws_s3_active')) { require_once Kohana::find_file('vendor', 'amazon-s3-php-class/S3', 'php'); $s3 = new S3(core::config('image.aws_access_key'), core::config('image.aws_secret_key')); //delete original image $s3->deleteObject(core::config('image.aws_s3_bucket'), $img_path . $img_seoname . '_' . $deleted_image . '.jpg'); //delete formated image $s3->deleteObject(core::config('image.aws_s3_bucket'), $img_path . 'thumb_' . $img_seoname . '_' . $deleted_image . '.jpg'); //re-ordering image file names for ($i = $deleted_image; $i < $this->has_images; $i++) { //rename original image $s3->copyObject(core::config('image.aws_s3_bucket'), $img_path . $img_seoname . '_' . ($i + 1) . '.jpg', core::config('image.aws_s3_bucket'), $img_path . $img_seoname . '_' . $i . '.jpg', S3::ACL_PUBLIC_READ); $s3->deleteObject(core::config('image.aws_s3_bucket'), $img_path . $img_seoname . '_' . ($i + 1) . '.jpg'); //rename formated image $s3->copyObject(core::config('image.aws_s3_bucket'), $img_path . 'thumb_' . $img_seoname . '_' . ($i + 1) . '.jpg', core::config('image.aws_s3_bucket'), $img_path . 'thumb_' . $img_seoname . '_' . $i . '.jpg', S3::ACL_PUBLIC_READ); $s3->deleteObject(core::config('image.aws_s3_bucket'), $img_path . 'thumb_' . $img_seoname . '_' . ($i + 1) . '.jpg'); } } //delte image from local filesystem if (!is_dir($img_path)) { return FALSE; } else { //delete original image @unlink($img_path . $img_seoname . '_' . $deleted_image . '.jpg'); //delete formated image @unlink($img_path . 'thumb_' . $img_seoname . '_' . $deleted_image . '.jpg'); //re-ordering image file names for ($i = $deleted_image; $i < $this->has_images; $i++) { @rename($img_path . $img_seoname . '_' . ($i + 1) . '.jpg', $img_path . $img_seoname . '_' . $i . '.jpg'); @rename($img_path . 'thumb_' . $img_seoname . '_' . ($i + 1) . '.jpg', $img_path . 'thumb_' . $img_seoname . '_' . $i . '.jpg'); } } $this->has_images = $this->has_images > 0 ? $this->has_images - 1 : 0; $this->last_modified = Date::unix2mysql(); try { $this->save(); return TRUE; } catch (Exception $e) { throw HTTP_Exception::factory(500, $e->getMessage()); } return FALSE; }
public function onImageDeletion(ImageDeletionEvent $event) { global $config; $access = $config->get_string("amazon_s3_access"); $secret = $config->get_string("amazon_s3_secret"); $bucket = $config->get_string("amazon_s3_bucket"); if (!empty($bucket)) { log_debug("amazon_s3", "Deleting Image #" . $event->image->id . " from S3"); $s3 = new S3($access, $secret); $s3->deleteObject($bucket, "images/" + $event->image->hash); $s3->deleteObject($bucket, "thumbs/" + $event->image->hash); } }
public static function tearDownAfterClass() { parent::tearDownAfterClass(); foreach (self::$toDelete as $file) { $deleted = S3::deleteObject(self::$config['s3Bucket'], $file); if (!$deleted) { echo "\n{$file} not found on S3 to delete\n"; } } }
public static function rm($pattern) { global $globals; S3::setAuth($globals['Amazon_access_key'], $globals['Amazon_secret_key']); if (preg_match('/\\*$/', $pattern)) { $pattern = preg_replace('/\\*$/', '', $pattern); $files = self::ls($pattern); foreach ($files as $file => $values) { S3::deleteObject($globals['Amazon_S3_media_bucket'], $file); } } S3::deleteObject($globals['Amazon_S3_media_bucket'], $pattern); }
/** * CRUD controller: DELETE */ public function action_delete() { if (!Core::get('name')) { return FALSE; } if (core::config('image.aws_s3_active')) { require_once Kohana::find_file('vendor', 'amazon-s3-php-class/S3', 'php'); $s3 = new S3(core::config('image.aws_access_key'), core::config('image.aws_secret_key')); } $image_name = Core::get('name'); $root = DOCROOT . 'images/cms/'; //root folder if (!is_dir($root)) { return FALSE; } else { //delete image @unlink($root . $image_name); // delete image from Amazon S3 if (core::config('image.aws_s3_active')) { $s3->deleteObject(core::config('image.aws_s3_bucket'), 'images/cms/' . $image_name); } } return TRUE; }