/** * Uploads files to FTP * * @param array $files * @param array $results * @param boolean $force_rewrite * @return boolean */ function upload($files, &$results, $force_rewrite = false) { $count = 0; $error = null; if (!$this->_init($error)) { $results = $this->get_results($files, W3_CDN_RESULT_HALT, $error); return false; } foreach ($files as $local_path => $remote_path) { if (!file_exists($local_path)) { $results[] = $this->get_result($local_path, $remote_path, W3_CDN_RESULT_ERROR, 'Source file not found'); continue; } if (!$force_rewrite) { $info = @$this->_s3->getObjectInfo($this->_config['bucket'], $remote_path); if ($info) { $hash = @md5_file($local_path); $s3_hash = isset($info['hash']) ? $info['hash'] : ''; if ($hash === $s3_hash) { $results[] = $this->get_result($local_path, $remote_path, W3_CDN_RESULT_ERROR, 'Object already exists'); continue; } } } $result = @$this->_s3->putObjectFile($local_path, $this->_config['bucket'], $remote_path, S3::ACL_PUBLIC_READ); $results[] = $this->get_result($local_path, $remote_path, $result ? W3_CDN_RESULT_OK : W3_CDN_RESULT_ERROR, $result ? 'OK' : 'Unable to put object'); if ($result) { $count++; } } return $count; }
private function _lookupFileInfo() { //look up our real info. $s3 = new S3(AMAZON_AWS_KEY, AMAZON_AWS_SECRET); $info = $s3->getObjectInfo($this->args('bucket'), $this->args('key'), true); if ($info['size'] == 0) { //capture for debug ob_start(); var_dump($args); var_dump($info); //try it again. sleep(1); $info = $s3->getObjectInfo($this->args('bucket'), $this->args('key'), true); var_dump($info); //still bad? if ($info['size'] == 0) { $text = ob_get_contents(); $html = "<pre>{$text}</pre>"; //email the admin $admin = User::byUsername('hoeken'); Email::queue($admin, "upload fail", $text, $html); //show us. if (User::isAdmin()) { @ob_end_clean(); echo "'failed' file upload:<br/><br/>{$html}"; exit; } //$this->set('megaerror', "You cannot upload a blank/empty file."); } @ob_end_clean(); } //send it back. return $info; }
public function uploadFile($file, $path, $acl = S3::ACL_PUBLIC_READ, $save = true) { //is it a real file? if (file_exists($file)) { //do the actual upload. $s3 = new S3(AMAZON_AWS_KEY, AMAZON_AWS_SECRET); $result = $s3->putObjectFile($file, AMAZON_S3_BUCKET_NAME, $path, S3::ACL_PUBLIC_READ); //echo "Uploading {$file} to " . AMAZON_S3_BUCKET_NAME . ":{$path}\n"; //get our info for saving $info = $s3->getObjectInfo(AMAZON_S3_BUCKET_NAME, $path, true); //save our info. $this->set('hash', $info['hash']); $this->set('size', $info['size']); $this->set('type', $info['type']); $this->set('bucket', AMAZON_S3_BUCKET_NAME); $this->set('path', $path); $this->set('add_date', date("Y-m-d H:i:s")); //for non db accessible scripts. if ($save) { $this->save(); } //yay! if ($result !== false) { return true; } } else { echo "No file at {$path} or {$file}\n"; } //fail! return false; }
/** * Uploads gzip version of file * * @param string $local_path * @param string $remote_path * @param boolean $force_rewrite * @return array */ function _upload_gzip($local_path, $remote_path, $force_rewrite = false) { if (!function_exists('gzencode')) { return $this->_get_result($local_path, $remote_path, W3TC_CDN_RESULT_ERROR, "GZIP library doesn't exist."); } if (!file_exists($local_path)) { return $this->_get_result($local_path, $remote_path, W3TC_CDN_RESULT_ERROR, 'Source file not found.'); } $contents = @file_get_contents($local_path); if ($contents === false) { return $this->_get_result($local_path, $remote_path, W3TC_CDN_RESULT_ERROR, 'Unable to read file.'); } $data = gzencode($contents); if (!$force_rewrite) { $this->_set_error_handler(); $info = @$this->_s3->getObjectInfo($this->_config['bucket'], $remote_path); $this->_restore_error_handler(); if ($info) { $hash = md5($data); $s3_hash = isset($info['hash']) ? $info['hash'] : ''; if ($hash === $s3_hash) { return $this->_get_result($local_path, $remote_path, W3TC_CDN_RESULT_OK, 'Object up-to-date.'); } } } $headers = $this->_get_headers($local_path); $headers = array_merge($headers, array('Vary' => 'Accept-Encoding', 'Content-Encoding' => 'gzip')); $this->_set_error_handler(); $result = @$this->_s3->putObjectString($data, $this->_config['bucket'], $remote_path, S3::ACL_PUBLIC_READ, array(), $headers); $this->_restore_error_handler(); if ($result) { return $this->_get_result($local_path, $remote_path, W3TC_CDN_RESULT_OK, 'OK'); } return $this->_get_result($local_path, $remote_path, W3TC_CDN_RESULT_ERROR, sprintf('Unable to put object (%s).', $this->_get_last_error())); }
/** * Check - file is exists or not * * @param string $path Short path * * @return boolean */ public function isExists($path) { try { $result = $this->client->getObjectInfo(\XLite\Core\Config::getInstance()->CDev->AmazonS3Images->bucket, $path, false); } catch (\S3Exception $e) { $result = false; \XLite\Logger::getInstance()->registerException($e); } return $result; }
/** * @inheritDoc BaseAssetSourceType::moveSourceFile() * * @param AssetFileModel $file * @param AssetFolderModel $targetFolder * @param string $fileName * @param bool $overwrite * * @return mixed */ protected function moveSourceFile(AssetFileModel $file, AssetFolderModel $targetFolder, $fileName = '', $overwrite = false) { if (empty($fileName)) { $fileName = $file->filename; } $newServerPath = $this->_getPathPrefix() . $targetFolder->path . $fileName; $conflictingRecord = craft()->assets->findFile(array('folderId' => $targetFolder->id, 'filename' => $fileName)); $this->_prepareForRequests(); $settings = $this->getSettings(); $fileInfo = $this->_s3->getObjectInfo($settings->bucket, $newServerPath); $conflict = !$overwrite && ($fileInfo || !craft()->assets->isMergeInProgress() && is_object($conflictingRecord)); if ($conflict) { $response = new AssetOperationResponseModel(); return $response->setPrompt($this->getUserPromptOptions($fileName))->setDataItem('fileName', $fileName); } $bucket = $this->getSettings()->bucket; // Just in case we're moving from another bucket with the same access credentials. $originatingSourceType = craft()->assetSources->getSourceTypeById($file->sourceId); $originatingSettings = $originatingSourceType->getSettings(); $sourceBucket = $originatingSettings->bucket; $this->_prepareForRequests($originatingSettings); if (!$this->_s3->copyObject($sourceBucket, $this->_getPathPrefix($originatingSettings) . $file->getFolder()->path . $file->filename, $bucket, $newServerPath, \S3::ACL_PUBLIC_READ)) { $response = new AssetOperationResponseModel(); return $response->setError(Craft::t("Could not save the file")); } @$this->_s3->deleteObject($sourceBucket, $this->_getS3Path($file, $originatingSettings)); if ($file->kind == 'image') { if ($targetFolder->sourceId == $file->sourceId) { $transforms = craft()->assetTransforms->getAllCreatedTransformsForFile($file); $destination = clone $file; $destination->filename = $fileName; // Move transforms foreach ($transforms as $index) { // For each file, we have to have both the source and destination // for both files and transforms, so we can reliably move them $destinationIndex = clone $index; if (!empty($index->filename)) { $destinationIndex->filename = $fileName; craft()->assetTransforms->storeTransformIndexData($destinationIndex); } $from = $file->getFolder()->path . craft()->assetTransforms->getTransformSubpath($file, $index); $to = $targetFolder->path . craft()->assetTransforms->getTransformSubpath($destination, $destinationIndex); $this->copySourceFile($from, $to); $this->deleteSourceFile($from); } } else { craft()->assetTransforms->deleteAllTransformData($file); } } $response = new AssetOperationResponseModel(); return $response->setSuccess()->setDataItem('newId', $file->id)->setDataItem('newFileName', $fileName); }
public static function getRemoteFileInfo(Zotero_StorageFileInfo $info) { self::requireLibrary(); S3::setAuth(Z_CONFIG::$S3_ACCESS_KEY, Z_CONFIG::$S3_SECRET_KEY); $url = self::getPathPrefix($info->hash, $info->zip) . $info->filename; $remoteInfo = S3::getObjectInfo(Z_CONFIG::$S3_BUCKET, $url, true); if (!$remoteInfo) { return false; } return $remoteInfo; }
if ($i == MAX_TRIES) { echo 'Failed to download ', $image, "\n"; if (file_exists($image)) { unlink($image); } //Go to next image continue 2; } } } else { echo 'File ', $image, ' was already downloaded', "\n"; } $dispersionPath = substr($image, $imgPrefixLen); foreach ($dimensions as $thumbPrefix => $dimension) { $thumb = $thumbPrefix . $dispersionPath; $thumbInfo = $s3->getObjectInfo($bucket, $thumb, $compareThumbsBySize); //Check if thumb exists in the bucket if ($thumbInfo && !$_reuploadThumbs) { echo 'Thumb ', $thumb, ' exists', "\n"; continue; } if (!file_exists($thumb) || $recalculateThumbs) { //Create directories for the thumb createDirectory(substr($thumb, 0, strlen($thumbPrefix) + 4)); $adapter = new Varien_Image_Adapter_Gd2(); //Default settings from Mage $adapter->keepAspectRatio(true); $adapter->keepFrame(false); $adapter->keepTransparency(true); $adapter->constrainOnly(true); $adapter->backgroundColor(array(255, 255, 255));
function pub_file_exists($folder, $fileName) { //echo $fileName;exit; $s3 = new S3(awsAccessKey, awsSecretKey); $info = $s3->getObjectInfo(BUCKET_NAME, $folder . $fileName); if ($info) { //File exists return true; } else { //File doesn't exists return false; } }
/** * get information about an object in the current S3 bucket * @param string $locationOnS3 - path the file should have on S3 relative to the current bucket * @return array */ public function getObjectInfo($locationOnS3) { return S3::getObjectInfo($this->bucket, $locationOnS3); }
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); }
function downloadFile($filename) { set_time_limit(0); ob_clean(); if (!isset($filename) || empty($filename)) { $var = "<table align='center' width='100%'><tr><td style='font:bold 14px verdana;color:#FF0000;' align='center'>Please specify a file name for download.</td></tr></table>"; die($var); } if (USE_S3 == 0) { if (strpos($filename, "") !== FALSE) { die(''); } $fname = basename($filename); if (file_exists(DIR_CASE_FILES . $fname)) { $file_path = DIR_CASE_FILES . $fname; } else { $var = "<table align='center' width='100%'><tr><td style='font:bold 12px verdana;color:#FF0000;' align='center'>Oops! File not found.<br/> File may be deleted or make sure you specified correct file name.</td></tr></table>"; die($var); } } else { $s3 = new S3(awsAccessKey, awsSecretKey); $info = $s3->getObjectInfo(BUCKET_NAME, DIR_CASE_FILES_S3_FOLDER . $filename); if ($info) { $fileurl = $this->generateTemporaryURL(DIR_CASE_FILES_S3 . $filename); //$file_path = DIR_CASE_FILES_S3.$filename; $file_path = $fileurl; } else { $var = "<table align='center' width='100%'><tr><td style='font:bold 12px verdana;color:#FF0000;' align='center'>Oops! File not found.<br/> File may be deleted or make sure you specified correct file name.</td></tr></table>"; die($var); } } /* Figure out the MIME type | Check in array */ $known_mime_types = array("pdf" => "application/pdf", "txt" => "text/plain", "html" => "text/html", "htm" => "text/html", "exe" => "application/octet-stream", "zip" => "application/zip", "doc" => "application/msword", "xls" => "application/vnd.ms-excel", "ppt" => "application/vnd.ms-powerpoint", "gif" => "image/gif", "png" => "image/png", "jpeg" => "image/jpg", "jpg" => "image/jpg", "php" => "text/plain"); $file_extension = strtolower(substr(strrchr($filename, "."), 1)); if (array_key_exists($file_extension, $known_mime_types)) { $mime_type = $known_mime_types[$file_extension]; } else { $mime_type = "application/force-download"; } // Send file headers header("Content-type: {$mime_type}"); header("Content-Disposition: attachment;filename={$filename}"); header('Pragma: no-cache'); header('Expires: 0'); //$file_path = DIR_CASE_FILES_S3.$filename; // Send the file contents. readfile($file_path); }
die('Please enter your Amazon S3 credentials on the <a href="' . admin_url('options-general.php?page=' . $this->plugin_slug) . '">options page</a>'); } else { require dirname(dirname(dirname(dirname(__FILE__)))) . '/includes/S3.php'; $s3Files = array(); // Store bucket names and bucket files in array $AwsS3Client = new S3($awsAccessKey, $awsSecretKey); // Get all buckets $buckets = @$AwsS3Client->listBuckets(); if (is_array($buckets)) { foreach ($buckets as $bucket) { // Get all objects in bucket $bucketFiles = $AwsS3Client->getBucket($bucket); if (is_array($bucketFiles)) { foreach ($bucketFiles as $filename => $fileinfo) { // Get detailed info about object $info = $AwsS3Client->getObjectInfo($bucket, $filename); if (is_array($info)) { //If object is not a folder and have a size>0 then add it to $s3Files array if ($info['size'] > 0 && $info['type'] != 'binary/octet-stream') { $s3Files[$bucket][] = $filename; } } } } } } } if (empty($s3Files)) { die('It seems that your Amazon S3 doesn\'t have any files or check your Amazon S3 credentials on the <a href="' . admin_url('options-general.php?page=' . $this->plugin_slug) . '">options page</a>'); } ?>
echo 'Creating Marker for Folder ' . $awsObjectInfo["name"] . " on CloudFiles\n"; $objMossoObject = $objMossoContainer->create_object($awsObjectInfo["name"]); $objMossoObject->content_type = $directoryType; // 'application/directory'; // Get a Zero-byte file pointer $fp = @fopen("php://temp", "wb+"); $objMossoObject->write($fp, 0); @fclose($fp); continue; } // Get object into a TMP file $tmpFileName = tempnam(sys_get_temp_dir(), 'S3toMosso'); echo 'Downloading ' . $awsObjectInfo["name"] . " from Amazon S3 to {$tmpFileName}\n"; $objS3->getObject($awsBucketName, $awsObjectInfo["name"], $tmpFileName); // Send Object to Mosso echo 'Creating object ' . $awsObjectInfo["name"] . " in container {$mossoContainerName}\n"; $objMossoObject = $objMossoContainer->create_object($awsObjectInfo["name"]); try { $objMossoObject->_guess_content_type($tmpFileName); } catch (BadContentTypeException $e) { // Get the content type from Amazon $info = $objS3->getObjectInfo($awsBucketName, $awsObjectInfo["name"], true); $objMossoObject->content_type = $info['type']; } echo 'Uploading ' . $awsObjectInfo["name"] . ' to Cloud Files Server' . "\n"; $objMossoObject->load_from_filename($tmpFileName); // Remove the TEMP file unlink($tmpFileName); } } ////////////////////////////// THE END ///////////////////////////
function file_processValue($Value, $Type, $Field, $Config, $EID) { if (!empty($Value)) { //dump($Value); //dump($Type); //dump($Field); //dump($Config); //die; switch ($Type) { case 'image': $Value = strtok($Value, '?'); $imageWidth = $Config['_ImageSizeX'][$Field] == 'auto' ? '100' : $Config['_ImageSizeX'][$Field]; $imageHeight = $Config['_ImageSizeY'][$Field] == 'auto' ? '100' : $Config['_ImageSizeY'][$Field]; $iconWidth = $Config['_IconSizeX'][$Field] == 'auto' ? '100' : $Config['_IconSizeX'][$Field]; $iconHeight = $Config['_IconSizeY'][$Field] == 'auto' ? '100' : $Config['_IconSizeY'][$Field]; $uploadVars = wp_upload_dir(); $SourceFile = str_replace($uploadVars['baseurl'], $uploadVars['basedir'], $Value); if (!file_exists($SourceFile)) { return 'Image does not exists.'; } $dim = getimagesize($SourceFile); $newDim = image_resize_dimensions($dim[0], $dim[1], $iconWidth, $iconHeight, true); if (!empty($newDim)) { $Sourcepath = pathinfo($SourceFile); $URLpath = pathinfo($Value); $iconURL = $URLpath['dirname'] . '/' . $URLpath['filename'] . '-' . $newDim[4] . 'x' . $newDim[5] . '.' . $URLpath['extension']; if (!file_exists($Sourcepath['dirname'] . '/' . $Sourcepath['filename'] . '-' . $newDim[4] . 'x' . $newDim[5] . '.' . $Sourcepath['extension'])) { $image = image_resize($SourceFile, $imageWidth, $imageHeight, true); $icon = image_resize($SourceFile, $iconWidth, $iconHeight, true); } } else { $iconURL = $Value; $iconWidth = $dim[0]; $iconHeight = $dim[1]; } $ClassName = ''; if (!empty($Config['_ImageClassName'][$Field])) { $ClassName = 'class="' . $Config['_ImageClassName'][$Field] . '" '; } if (!empty($Config['_IconURLOnly'][$Field])) { return $iconURL; } return '<img src="' . $iconURL . '" ' . $ClassName . image_hwstring($iconWidth, $iconHeight) . '>'; break; case 'mp3': $File = explode('?', $Value); $UniID = uniqid($EID . '_'); //$ReturnData = '<span id="'.$UniID.'">'.$File[1].'</span>'; $ReturnData = '<audio id="' . $UniID . '" src="' . $File[0] . '">unavailable</audio>'; $_SESSION['dataform']['OutScripts'] .= "\n\t\t\t\t\tAudioPlayer.embed(\"" . $UniID . "\", {\n\t\t\t\t\t"; if (!empty($Config['_PlayerCFG']['Autoplay'][$Field])) { $_SESSION['dataform']['OutScripts'] .= " autostart: 'yes', "; } if (!empty($Config['_PlayerCFG']['Animation'][$Field])) { $_SESSION['dataform']['OutScripts'] .= " animation: 'yes', "; } $_SESSION['dataform']['OutScripts'] .= "\n transparentpagebg: 'yes',\n\t\t\t\t\t\tsoundFile: \"" . $File[0] . "\",\n\t\t\t\t\t\ttitles: \"" . $File[1] . "\"\n\t\t\t\t\t});\n\n\t\t\t\t"; $_SESSION['dataform']['OutScripts'] .= "\n jQuery(document).ready(function(\$) {\n AudioPlayer.setup(\"" . WP_PLUGIN_URL . "/db-toolkit/data_form/fieldtypes/file/player.swf\", {\n width: '100%',\n initialvolume: 100,\n transparentpagebg: \"yes\",\n left: \"000000\",\n lefticon: \"FFFFFF\"\n });\n });"; return $ReturnData; break; case 'file': case 'multi': if (empty($Config['_fileReturnValue'][$Field])) { $Config['_fileReturnValue'][$Field] = 'iconlink'; } $pathInfo = pathinfo($Value); $s3Enabled = false; $prime = $Field; if (!empty($Config['_CloneField'][$Field]['Master'])) { $prime = $Config['_CloneField'][$Field]['Master']; } if (!empty($Config['_enableS3'][$prime]) && !empty($Config['_AWSAccessKey'][$prime]) && !empty($Config['_AWSSecretKey'][$prime])) { include_once DB_TOOLKIT . 'data_form/fieldtypes/file/s3.php'; $s3 = new S3($Config['_AWSAccessKey'][$prime], $Config['_AWSSecretKey'][$prime]); $s3Enabled = true; } switch ($Config['_fileReturnValue'][$Field]) { case 'iconlink': if (empty($Value)) { return 'no file uploaded'; } if (!empty($Config['_enableS3'][$prime]) && !empty($Config['_AWSAccessKey'][$prime]) && !empty($Config['_AWSSecretKey'][$prime])) { $File = 'http://' . $Config['_AWSBucket'][$prime] . '.s3.amazonaws.com/' . $Value; } else { $File = $Value; } $Dets = pathinfo($File); $ext = strtolower($Dets['extension']); if (file_exists(WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/file/icons/' . $ext . '.gif')) { $Icon = '<img src="' . WP_PLUGIN_URL . '/db-toolkit/data_form/fieldtypes/file/icons/' . $ext . '.gif" align="absmiddle" /> '; } else { $Icon = '<img src="' . WP_PLUGIN_URL . '/db-toolkit/data_form/fieldtypes/file/icons/file.gif" align="absmiddle" /> '; } return '<a href="' . $File . '">' . $Icon . ' ' . basename($File) . '</a>'; break; case 'filesize': if (!empty($s3Enabled)) { $object = $s3->getObjectInfo($Config['_AWSBucket'][$prime], $Value); return file_return_bytes($object['size']); } else { $uploadDir = wp_upload_dir(); $file = str_replace($uploadDir['baseurl'], $uploadDir['basedir'], $Value); return file_return_bytes(filesize($file)); } break; case 'filesizeraw': if (!empty($s3Enabled)) { $object = $s3->getObjectInfo($Config['_AWSBucket'][$prime], $Value); return $object['size']; } else { $uploadDir = wp_upload_dir(); $file = str_replace($uploadDir['baseurl'], $uploadDir['basedir'], $Value); return filesize($file); } break; case 'filename': if (!empty($s3Enabled)) { return basename($Value); } else { return $pathInfo['basename']; } break; case 'filepath': return $Value; break; case 'ext': return $pathInfo['extension']; break; case 'mimetype': $uploadDir = wp_upload_dir(); $file = str_replace($uploadDir['baseurl'], $uploadDir['basedir'], $Value); $type = wp_check_filetype($file); return $type['type']; break; } break; } return; } }
/** * {@inheritdoc} */ protected function _exists($path) { return $this->_s3->getObjectInfo($this->_params->bucket, $path, false); }
} // Instantiate the class $s3 = new S3(awsAccessKey, awsSecretKey); // List your buckets: echo "S3::listBuckets(): " . print_r($s3->listBuckets(), 1) . "\n"; // Create a bucket with public read access if ($s3->putBucket($bucketName, S3::ACL_PUBLIC_READ)) { echo "Created bucket {$bucketName}" . PHP_EOL; // Put our file (also with public read access) if ($s3->putObjectFile($uploadFile, $bucketName, baseName($uploadFile), S3::ACL_PUBLIC_READ)) { echo "S3::putObjectFile(): File copied to {$bucketName}/" . baseName($uploadFile) . PHP_EOL; // Get the contents of our bucket $contents = $s3->getBucket($bucketName); echo "S3::getBucket(): Files in bucket {$bucketName}: " . print_r($contents, 1); // Get object info $info = $s3->getObjectInfo($bucketName, baseName($uploadFile)); echo "S3::getObjectInfo(): Info for {$bucketName}/" . baseName($uploadFile) . ': ' . print_r($info, 1); // You can also fetch the object into memory // var_dump("S3::getObject() to memory", $s3->getObject($bucketName, baseName($uploadFile))); // Or save it into a file (write stream) // var_dump("S3::getObject() to savefile.txt", $s3->getObject($bucketName, baseName($uploadFile), 'savefile.txt')); // Or write it to a resource (write stream) // var_dump("S3::getObject() to resource", $s3->getObject($bucketName, baseName($uploadFile), fopen('savefile.txt', 'wb'))); // Get the access control policy for a bucket: // $acp = $s3->getAccessControlPolicy($bucketName); // 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:
function doesfileexist($type, $key) { if ($type == 'cfile') { if ($GLOBALS['filehandertypecfiles'] == 's3') { $s3 = new S3($GLOBALS['AWSkey'], $GLOBALS['AWSsecret']); return $s3->getObjectInfo($GLOBALS['AWSbucket'], 'cfiles/' . $key, false); } else { $base = rtrim(dirname(dirname(__FILE__)), '/\\') . '/course/files/'; return file_exists($base . $key); } } else { if ($GLOBALS['filehandertype'] == 's3') { $s3 = new S3($GLOBALS['AWSkey'], $GLOBALS['AWSsecret']); return $s3->getObjectInfo($GLOBALS['AWSbucket'], $key, false); } else { $base = rtrim(dirname(dirname(__FILE__)), '/\\') . '/filestore/'; return file_exists($base . $key); } } }
/** * @method public removeTempFilesFromS3() It will check the temp file and delete those file which are created b4 24 hours. * @return bool */ function removeTempFilesFromS3() { try { $s3 = new S3(awsAccessKey, awsSecretKey); // Get the contents of our bucket $contents = $s3->getBucket(BUCKET_NAME, DIR_CASE_FILES_S3_FOLDER_TEMP); $date_before_24hr = date('F_dS_Y', strtotime('-24 hours', time())); if (isset($contents) && $contents != '') { foreach ($contents as $file) { $fname = $file['name']; $content1s = $s3->getObjectInfo(BUCKET_NAME, $fname); if ($content1s) { $file_created_date = date('F_dS_Y', $content1s['time']); if ($date_before_24hr == $file_created_date) { $s3->deleteObject(BUCKET_NAME, $fname); } } } die; } } catch (Exception $e) { //print $e->getMessage();exit; } }
public function getObjectInfo($bucket = '', $uri = '', $returnInfo = true) { return S3::getObjectInfo($bucket, $uri, $returnInfo); }
function upload_static_file($bucket, $remote_name, $local_name, $args) { global $AMZ_KEY, $AMZ_SECRET; // Prepare any additional headers... $headers = array(); if ($args->flag('x')) { $headers['Expires'] = date('D, j M Y H:i:s', time() + 86400 * 365 * 10) . ' GMT'; // 10 years } // Version the file? if ($args->flag('version')) { $info = pathinfo($remote_name); $dir = $info['dirname'] . '/'; if ($dir == './') { $dir = ''; } $remote_name = $dir . $info['filename'] . $args->flag('version') . '.' . $info['extension']; } elseif ($args->flag('t')) { $info = pathinfo($remote_name); $dir = $info['dirname'] . '/'; if ($dir == './') { $dir = ''; } $remote_name = $dir . $info['filename'] . '.' . date('YmdHis') . '.' . $info['extension']; } // Begin the upload proccess $s3 = new S3($AMZ_KEY, $AMZ_SECRET); // Should we check to see if the file has already been uploaded? $ok_to_upload = true; if ($args->flag('c')) { $info = $s3->getObjectInfo($bucket, $remote_name); if (substr($info['ETag'], 1, -2) == md5_file($local_name)) { $ok_to_upload = false; echo "Skipping (MD5 match): http://{$bucket}.s3.amazonaws.com/{$remote_name}\n"; } } // Actually upload the file... if ($ok_to_upload) { if ($s3->uploadFile($bucket, $remote_name, $local_name, true, $headers)) { echo "http://{$bucket}.s3.amazonaws.com/{$remote_name}\n"; } else { trigger_error("Unable to upload '{$local_name}' to '{$remote_name}'\n", E_USER_ERROR); } } // Upload the gzipped version... if ($args->flag('z')) { $info = pathinfo($remote_name); $dir = $info['dirname'] . '/'; if ($dir == './') { $dir = ''; } $remote_name = $dir . $info['filename'] . '.gz.' . $info['extension']; $gzname = tempnam('/tmp', 's3up') . '.' . $info['extension']; shell_exec(sprintf('gzip -c %s > %s', escapeshellarg($local_name), $gzname)); $headers['Content-Encoding'] = 'gzip'; // Should we check to see if the file has already been uploaded? $ok_to_upload = true; if ($args->flag('c')) { $info = $s3->getObjectInfo($bucket, $remote_name); if (substr($info['ETag'], 1, -2) == md5_file($local_name)) { $ok_to_upload = false; echo "Skipping (MD5 match): http://{$bucket}.s3.amazonaws.com/{$remote_name}\n"; } } // Actually upload the file... if ($ok_to_upload) { if ($s3->uploadFile($bucket, $remote_name, $gzname, true, $headers)) { echo "http://{$bucket}.s3.amazonaws.com/{$remote_name}\n"; } else { trigger_error("Unable to upload '{$local_name}' to '{$remote_name}' (gzip version)\n", E_USER_ERROR); } } } }
function GenerateThumbFile($from_name1, $to_name, $max_x, $max_y, $filename) { // if src is URL then download file first if (defined('USE_S3') && USE_S3 && $filename != 'user.png') { $from_name = $this->generateTemporaryURL($from_name1); //print_r($from_name);exit; } else { $from_name = $from_name1; } $temp = false; if (substr($from_name, 0, 7) == 'https://') { $tmpfname = tempnam("tmp/", "TmP-"); $temp = @fopen($tmpfname, "w"); if ($temp) { @fwrite($temp, @file_get_contents($from_name)) or die("Cannot download image"); @fclose($temp); $from_name = $tmpfname; } else { die("Cannot create temp file"); } } // check if file exists if (defined('USE_S3') && USE_S3 && $filename != 'user.png') { $s3 = new S3(awsAccessKey, awsSecretKey); $info = $s3->getObjectInfo(BUCKET_NAME, DIR_USER_PHOTOS_S3_FOLDER . $filename); //print_r($info); $file_mime = $info['type']; } else { if (file_exists($from_name)) { $info = 1; } else { if (file_exists(DIR_USER_PHOTOS . 'user.png')) { $from_name = DIR_USER_PHOTOS . 'user.png'; $info = 1; } } } if ($info) { // get source image size (width/height/type) // orig_img_type 1 = GIF, 2 = JPG, 3 = PNG $getimagesize = @getimagesize($from_name); //list($orig_x, $orig_y, $orig_img_type, $img_sizes) = @getimagesize($from_name); $orig_x = $getimagesize[0]; $orig_y = $getimagesize[1]; $orig_img_type = $getimagesize['2']; if (!$file_mime) { $file_mime = $getimagesize['mime']; } // cut image if specified by user if ($this->cut_x > 0) { $orig_x = min($this->cut_x, $orig_x); } if ($this->cut_y > 0) { $orig_y = min($this->cut_y, $orig_y); } // should we override thumb image type? $this->image_type = $this->image_type != -1 ? $this->image_type : $orig_img_type; // check for allowed image types if ($orig_img_type < 1 or $orig_img_type > 3) { die("Image type not supported"); } if ($orig_x > $max_x or $orig_y > $max_y) { if (!$file_mime) { $file_mime = @finfo_file(finfo_open(FILEINFO_MIME_TYPE), $from_name); } if ($file_mime) { header("Content-Type:{$file_mime}"); } // resize $per_x = $orig_x / $max_x; $per_y = $orig_y / $max_y; if ($per_y > $per_x) { $max_x = $orig_x / $per_y; } else { $max_y = $orig_y / $per_x; } } else { if ($orig_x < $max_x or $orig_y < $max_y) { $max_x = $orig_x; $max_y = $orig_y; if (!$file_mime) { $file_mime = @finfo_file(finfo_open(FILEINFO_MIME_TYPE), $from_name); } if ($file_mime) { header("Content-Type:{$file_mime}"); } } else { // keep original sizes, i.e. just copy if ($this->save_to_file) { @copy($from_name, $to_name); } else { switch ($this->image_type) { case 1: header("Content-type: image/gif"); readfile($from_name); break; case 2: header("Content-type: image/jpeg"); readfile($from_name); break; case 3: header("Content-type: image/png"); readfile($from_name); break; } } return; } } if ($this->image_type == 1) { // should use this function for gifs (gifs are palette images) $ni = imagecreate($max_x, $max_y); } else { // Create a new true color image $ni = ImageCreateTrueColor($max_x, $max_y); } // Fill image with white background (255,255,255) $white = imagecolorallocate($ni, 255, 255, 255); /* if($this->image_type == 3) { $white = imagecolorallocate($ni, 0, 0, 0); imagecolortransparent($ni, $white); } */ imagefilledrectangle($ni, 0, 0, $max_x, $max_y, $white); // Create a new image from source file $im = $this->ImageCreateFromType($orig_img_type, $from_name); // Copy the palette from one image to another imagepalettecopy($ni, $im); // Copy and resize part of an image with resampling imagecopyresampled($ni, $im, 0, 0, 0, 0, $max_x, $max_y, $orig_x, $orig_y); // srcW, srcH // save thumb file $this->SaveImage($ni, $to_name); if ($temp) { unlink($tmpfname); // this removes the file } } else { //File doesn't exists echo "Source image does not exist!"; exit; } }
/** * Return true if a transform exists at the location for a file. * * @param AssetFileModel $file * @param $location * @return mixed */ public function transformExists(AssetFileModel $file, $location) { $this->_prepareForRequests(); return (bool) @$this->_s3->getObjectInfo($this->getSettings()->bucket, $this->_getPathPrefix() . $file->getFolder()->fullPath . $location . '/' . $file->filename); }
function casePosting($formdata) { $pagename = $formdata['pagename']; $postParam['Easycase']['isactive'] = 1; $postParam['Easycase']['project_id'] = $formdata['CS_project_id']; $postParam['Easycase']['istype'] = $formdata['CS_istype']; $postParam['Easycase']['title'] = $formdata['CS_title']; $postParam['Easycase']['type_id'] = $formdata['CS_type_id']; $postParam['Easycase']['priority'] = $formdata['CS_priority']; $postParam['Easycase']['assign_to'] = $formdata['CS_assign_to']; $postParam['Easycase']['legend'] = $formdata['CS_legend']; $postParam['Easycase']['hours'] = $formdata['hours']; $postParam['Easycase']['estimated_hours'] = $formdata['estimated_hours']; $postParam['Easycase']['completed_task'] = $formdata['completed'] ? $formdata['completed'] : 0; $postParam['Easycase']['is_chrome_extension'] = isset($formdata['is_chrome_extension']) ? $formdata['is_chrome_extension'] : 0; $prelegend = $formdata['prelegend']; if (isset($formdata['datatype']) && $formdata['datatype'] == 1) { $postParam['Easycase']['message'] = $formdata['CS_message']; } else { $postParam['Easycase']['message'] = $formdata['CS_message']; } $postParam['Easycase']['due_date'] = $formdata['CS_due_date']; $postParam['Easycase']['postdata'] = $formdata['postdata']; if ($postParam['Easycase']['due_date'] == "No Due Date") { $postParam['Easycase']['due_date'] = NULL; } if (isset($formdata['CS_milestone']) && $formdata['CS_milestone']) { $milestone_id = $formdata['CS_milestone']; } if (isset($formdata['CS_id']) && $formdata['CS_id']) { $caseid = $formdata['CS_id']; } if (isset($formdata['CS_case_no']) && $formdata['CS_case_no']) { $postParam['Easycase']['case_no'] = $formdata['CS_case_no']; } $emailUser = $formdata['emailUser']; $allUser = $formdata['allUser']; $fileArray = $formdata['allFiles']; $domain = isset($formdata['auth_domain']) ? $formdata['auth_domain'] : HTTP_ROOT; $cloud_storages = $formdata['cloud_storages']; //By Orangescrum $success = "fail"; $emailTitle = ""; $Easycase = ClassRegistry::init('Easycase'); $Easycase->recursive = -1; $update = 0; ######## Check File Exists and Size $chk = 0; if (is_array($fileArray) && count($fileArray)) { $usedspace = $GLOBALS['usedspace']; foreach ($fileArray as $filename) { if ($filename && strstr($filename, "|")) { $fl = explode("|", $filename); if (isset($fl['0'])) { $file = $fl['0']; $filesize = number_format($fl[1] / 1024, 2, '.', ''); if (strtolower($GLOBALS['Userlimitation']['storage']) == 'unlimited' || $usedspace <= $GLOBALS['Userlimitation']['storage']) { $usedspace += $filesize; if (USE_S3 == 0) { if (file_exists(DIR_CASE_FILES . $file)) { $chk++; } } else { $s3 = new S3(awsAccessKey, awsSecretKey); $info = $s3->getObjectInfo(BUCKET_NAME, DIR_CASE_FILES_S3_FOLDER_TEMP . $file); if ($info) { $chk++; } } } } } } } ###### Get Ptoject Id if ($formdata['CS_project_id'] != "all") { $Project = ClassRegistry::init('Project'); $Project->recursive = -1; $prjArr = $Project->find('first', array('conditions' => array('Project.uniq_id' => $formdata['CS_project_id']), 'fields' => array('Project.id', 'Project.name'))); $projId = $prjArr['Project']['id']; //$projName = urlencode($prjArr['Project']['name']); $projName = $prjArr['Project']['name']; } else { $projId = $formdata['pid']; $projName = 'All'; } ####### Case Format if (isset($cloud_storages) && !empty($cloud_storages)) { //By Orangescrum $postParam['Easycase']['format'] = 1; $format = 1; } else { if (!$formdata['task_uid']) { if ($chk == 0) { $postParam['Easycase']['format'] = 2; $format = 2; } else { $postParam['Easycase']['format'] = 1; $format = 1; } } elseif ($chk != 0) { $postParam['Easycase']['format'] = 1; $format = 1; } } $emailTitle = $this->Format->convert_ascii($postParam['Easycase']['title']); $caseIstype = $postParam['Easycase']['istype']; if ($caseIstype == 1) { ####### Case Type (if not selected it is "2", if type is update priority is NULL) if ($postParam['Easycase']['type_id'] == 10) { $postParam['Easycase']['priority'] = NULL; } $casePriority = $postParam['Easycase']['priority']; $caseTypeId = $postParam['Easycase']['type_id']; ####### Case Message (can be NULL) if ($postParam['Easycase']['message'] == "Enter Description...") { $postParam['Easycase']['message'] = ""; } ####### Due Date (can be NULL, change Date format) if ($postParam['Easycase']['due_date']) { $postParam['Easycase']['due_date'] = date("Y-m-d", strtotime($postParam['Easycase']['due_date'])); } else { $postParam['Easycase']['due_date'] = NULL; } $postParam['Easycase']['status'] = 1; $postParam['Easycase']['legend'] = 1; ###### Get Case# if ($formdata['task_uid'] && $formdata['taskid']) { $emailbody = "Updated a task: "; $userCaseView = 1; $csType = "New"; $caseNoArr = $Easycase->findByUniqId($formdata['task_uid']); $easy_id = $caseNoArr['Easycase']['id']; $caseNo = $caseNoArr['Easycase']['case_no']; $postParam['Easycase']['case_count'] = $caseNoArr['Easycase']['case_count'] + 1; unset($caseNoArr['Easycase']['id']); $caseNoArr['Easycase']['legend'] = 6; //$caseNoArr['Easycase']['updated_by']=SES_ID; $caseNoArr['Easycase']['hours'] = 0; $caseNoArr['Easycase']['estimated_hours'] = 0; $caseNoArr['Easycase']['istype'] = 2; $caseNoArr['Easycase']['dt_created'] = GMT_DATETIME; $caseNoArr['Easycase']['actual_dt_created'] = GMT_DATETIME; $Easycase->save($caseNoArr); //Update updated_by in parent task $Easycase->id = $easy_id; $Easycase->saveField('updated_by', SES_ID); $Easycase->id = ''; } else { if ($update == 0) { $caseNoArr = $Easycase->find('first', array('conditions' => array('Easycase.project_id' => $projId), 'fields' => array('MAX(Easycase.case_no) as caseno'))); $caseNo = $caseNoArr[0]['caseno'] + 1; $postParam['Easycase']['case_no'] = $caseNo; } else { $caseNo = $postParam['Easycase']['case_no']; } ##### Status & Email Settings $postParam['Easycase']['status'] = 1; $postParam['Easycase']['legend'] = 1; $msg = "<font color='#737373'><b>Status: </b></font><font color='#763532'>NEW</font>"; if ($update == 0) { $userCaseView = 1; $csType = "New"; $emailbody = "posted a new Task"; } if ($postParam['Easycase']['type_id'] == 10) { $msg = ""; } } } else { $postParam['Easycase']['title'] = ""; $caseTypeId = $postParam['Easycase']['type_id']; $casePriority = $postParam['Easycase']['priority']; $caseNo = $postParam['Easycase']['case_no']; ##### Status if ($postParam['Easycase']['legend'] == "") { } else { if ($postParam['Easycase']['legend'] == 3) { $postParam['Easycase']['status'] = 2; $status = 2; } else { $postParam['Easycase']['status'] = 1; $status = 1; } $postParam['Easycase']['legend'] = $postParam['Easycase']['legend']; $legend = $postParam['Easycase']['legend']; $userCaseView = $postParam['Easycase']['legend']; ##### Email Settings if ($postParam['Easycase']['legend'] == 3) { $msg = "<font color='#737373' style='font-weight:bold'>Status:</font> <font color='green'>CLOSED</font>"; $csType = "Close"; $emailbody = "<font color='green'>CLOSED</font> the Task"; } if ($postParam['Easycase']['legend'] == 1) { $userCaseView = 2; $csType = "Replied"; $msg = "<font color='#737373' style='font-weight:bold'>Status:</font> <font color='#EF6807' >REPLIED</font>"; $emailbody = "responded on the Task"; } if ($postParam['Easycase']['legend'] == 2) { $csType = "WIP"; $msg = "<font color='#737373' style='font-weight:bold'>Status:</font> <font color='#EF6807'>In Progress</font>"; $emailbody = "responded on the Task"; } if ($postParam['Easycase']['legend'] == 5) { $csType = "Resolved"; $msg = "<font color='#737373' style='font-weight:bold'>Status:</font> <font color='#EF6807'>RESOLVED</font>"; $emailbody = "<font color='#EF6807'>RESOLVED</font> the Task"; } if ($postParam['Easycase']['legend'] == 4) { $csType = "Started"; $msg = "<font color='#737373' style='font-weight:bold'>Status:</font> <font color='#55A0C7'>STARTED</font>"; $emailbody = "<font color='#55A0C7'>STARTED</font> the Task"; } } #### Update the status and legend of original case $dtcreated = GMT_DATETIME; $updquery = ""; if ($postParam['Easycase']['assign_to']) { $updquery = ",assign_to='" . $postParam['Easycase']['assign_to'] . "'"; } $updquery .= ",priority='" . $postParam['Easycase']['priority'] . "'"; $qryFrmt = ""; if ($format == 1) { $qryFrmt = "format='" . $format . "',"; } /* $total = $Easycase->find('count', array('conditions'=>array('Easycase.case_no' => $postParam['Easycase']['case_no'],'Easycase.project_id' => $postParam['Easycase']['project_id'],'Easycase.isactive'=>1,'Easycase.id !='=>$cases['Easycase']['id']),'fields'=>'DISTINCT Easycase.id')); $case_count = $total+1; */ $Easycase->query("UPDATE easycases SET status='" . $status . "',updated_by='" . SES_ID . "',case_count=case_count+1,legend='" . $legend . "', " . $qryFrmt . " dt_created='" . $dtcreated . "' " . $updquery . " WHERE id='" . $caseid . "'"); $getTitle = $Easycase->query("SELECT title FROM easycases WHERE id='" . $caseid . "'"); $emailTitle = $this->Format->convert_ascii($getTitle[0]['easycases']['title']); } $emailMsg = $postParam['Easycase']['message']; if ($update == 0 && !$formdata['task_uid']) { $caseUniqId = md5(uniqid()); $postParam['Easycase']['uniq_id'] = $caseUniqId; $postParam['Easycase']['actual_dt_created'] = GMT_DATETIME; $postParam['Easycase']['isactive'] = 1; if (isset($formdata['CS_user_id']) && $formdata['CS_user_id']) { $postParam['Easycase']['user_id'] = $formdata['CS_user_id']; //it is used when reading from mail } else { $postParam['Easycase']['user_id'] = SES_ID; } $postParam['Easycase']['user_short_name'] = ""; $postParam['Easycase']['assign_short_name'] = ""; } elseif ($formdata['task_uid']) { $caseUniqId = $postParam['Easycase']['uniq_id']; $postParam['Easycase']['id'] = $formdata['taskid']; $postParam['Easycase']['uniq_id'] = $formdata['task_uid']; } else { $caseUniqId = $postParam['Easycase']['uniq_id']; } $postParam['Easycase']['dt_created'] = GMT_DATETIME; $postParam['Easycase']['project_id'] = $projId; $postParam['Easycase']['title'] = $this->Format->convert_ascii(trim($postParam['Easycase']['title'])); $postParam['Easycase']['message'] = $this->Format->convert_ascii(trim($postParam['Easycase']['message'])); if ($formdata['user_auth_key']) { $postParam['Easycase']['user_id'] = $formdata['CS_user_id']; $postParam['Easycase']['estimated_hours'] = 0; } //return pr($postParam); if ($Easycase->save($postParam)) { $Project = ClassRegistry::init('Project'); $ProjectUser = ClassRegistry::init('ProjectUser'); $ProjectUser->recursive = -1; $getUser = $ProjectUser->query("SELECT user_id FROM project_users WHERE project_id='" . $projId . "'"); $prjuniq = $Project->query("SELECT uniq_id, short_name FROM projects WHERE id='" . $projId . "'"); $prjuniqid = $prjuniq[0]['projects']['uniq_id']; //print_r($prjuniq); $projShName = strtoupper($prjuniq[0]['projects']['short_name']); if (isset($postParam['Easycase']['assign_to']) && !empty($postParam['Easycase']['assign_to'])) { //$Project->query("UPDATE projects SET default_assign='".$postParam['Easycase']['assign_to']."' WHERE id='".$projId."'"); } if ($caseIstype == 2) { //if($postParam['Easycase']['message'] != '' && $caseIstype == 2) //socket.io implement start $channel_name = $prjuniqid; $pname = $this->Format->getProjectName($projId); $msgpub = "'Case Replay Available in '" . $postParam['Easycase']['title'] . "''"; $this->iotoserver(array('channel' => $channel_name, 'message' => 'Updated.~~' . SES_ID . '~~' . $postParam['Easycase']['case_no'] . '~~' . 'UPD' . '~~' . $emailTitle . '~~' . $projShName)); //socket.io implement end } else { //socket.io implement start $channel_name = $prjuniqid; $pname = $this->Format->getProjectName($projId); $msgpub = "'New Case Available in " . $pname . "'"; $this->iotoserver(array('channel' => $channel_name, 'message' => 'Updated.~~' . SES_ID . '~~' . $postParam['Easycase']['case_no'] . '~~' . 'NEW' . '~~' . $postParam['Easycase']['title'] . '~~' . $projShName)); //socket.io implement end } //return pr($Easycase->getLastInsertID()); if (isset($milestone_id) && $milestone_id) { $EasycaseMilestone = ClassRegistry::init('EasycaseMilestone'); $EasycaseMilestone->recursive = -1; if ($formdata['task_uid']) { $milestone_dtls = $EasycaseMilestone->find('first', array('conditions' => array('easycase_id' => $formdata['taskid'], 'project_id' => $projId))); if ($milestone_dtls) { $EasycaseMiles['id'] = $milestone_dtls['EasycaseMilestone']['id']; } $EasycaseMiles['easycase_id'] = $formdata['taskid']; } else { $EasycaseMiles['easycase_id'] = $Easycase->getLastInsertID(); } $EasycaseMiles['milestone_id'] = $milestone_id; $EasycaseMiles['project_id'] = $projId; $EasycaseMiles['user_id'] = SES_ID; $EasycaseMiles['dt_created'] = GMT_DATETIME; $EasycaseMilestone->saveAll($EasycaseMiles); } if ($update == 0) { if ($formdata['task_uid']) { $caseid = $formdata['taskid']; } else { $caseid = $Easycase->getLastInsertID(); } } if ($caseIstype == 1) { $ProjectUser = ClassRegistry::init('ProjectUser'); $ProjectUser->recursive = -1; $ProjectUser->query("UPDATE project_users SET dt_visited='" . GMT_DATETIME . "' WHERE project_id=" . $projId . " AND user_id=" . SES_ID); } //By Orangescrum if (isset($cloud_storages) && !empty($cloud_storages)) { $this->fileInfo($cloud_storages, $projId, $caseid); } $isUserModule = 0; if ($update == 1 || $formdata['task_uid']) { $CaseUserEmail = ClassRegistry::init('CaseUserEmail'); $CaseUserEmail->query("DELETE FROM case_user_emails WHERE easycase_id=" . $caseid); } $caUid = ""; $assignTo = ""; if ($postParam['Easycase']['assign_to']) { $caUid = $postParam['Easycase']['assign_to']; } $due_date = ""; $padd = ""; if ($postParam['Easycase']['due_date']) { $due_date = $postParam['Easycase']['due_date']; } if ($caUid && $caUid != SES_ID) { if ($isUserModule == 0) { $User = ClassRegistry::init('User'); $User->recursive = -1; } $usrDtls2 = $User->find('first', array('conditions' => array('User.id' => $caUid, 'User.isactive' => 1), 'fields' => array('User.name'))); if (count($usrDtls2) && $usrDtls2['User']['name']) { $assignTo = "<tr><td align='left' style='color:#235889;line-height:20px;padding-top:10px'>This task is assigned to <i>" . $usrDtls2['User']['name'] . "</i></td></tr>"; } } if ($due_date != "NULL" && $due_date != "0000-00-00" && $due_date != "") { if (!$assignTo) { $padd = "padding-top:10px;"; } $assignTo .= "<tr><td align='left' style='" . $padd . "'>Due date: <font color='#235889'>" . date("m/d/Y", strtotime($due_date)) . "</font></td></tr>"; } $allfiles = ""; if (is_array($fileArray) && count($fileArray)) { $editRemovedFile = $formdata['editRemovedFile']; if ($editRemovedFile && $formdata['taskid']) { $this->removeFiles($editRemovedFile, $formdata['taskid']); } $allfiles = $this->uploadAndInsertFile($fileArray, $caseid, 0, $projId, $domain, $editRemovedFile); } $this->write('STATUS', "", '-365 days'); $this->write('PRIORITY', "", '-365 days'); $this->write('CS_TYPES', "", '-365 days'); $this->write('MEMBERS', "", '-365 days'); $this->write('IS_SORT', "", '-365 days'); $this->write('ORD_DATE', "", '-365 days'); $this->write('ORD_TITLE', "", '-365 days'); $this->write('SEARCH', "", '-365 days'); $success = "success"; } //} $ret_res = array('success' => $success, 'pagename' => $pagename, 'formdata' => $formdata['CS_project_id'], 'postParam' => $postParam['Easycase']['postdata'], 'caseUniqId' => $caseUniqId, 'format' => $format, 'allfiles' => $allfiles['allfiles'], 'caseNo' => $caseNo, 'emailTitle' => $emailTitle, 'emailMsg' => $emailMsg, 'casePriority' => $casePriority, 'caseTypeId' => $caseTypeId, 'msg' => $msg, 'emailbody' => $emailbody, 'assignTo' => $assignTo, 'name_email' => $name_email, 'csType' => $csType, 'projId' => $projId, 'caseid' => $caseid, 'caUid' => $caUid, 'caseIstype' => $caseIstype, 'projName' => $projName, "storage_used" => $allfiles['storage'], 'file_upload_error' => $allfiles['file_error']); //return $success."|".$pagename."|".$formdata['CS_project_id']."|".$postParam['Easycase']['postdata']."|".$caseUniqId."|".$format; //pr($ret_res);exit; return json_encode($ret_res); }
public function load_gearman($path, $table, $chunk_size = null, $segment_count = null, $columns_str = null, $set_str = null, $ignore = "", $replace = "") { $SQ = $this->SQ; if (!isset($chunk_size)) { $chunk_size = $this->chunk_size; } if (!isset($segment_count)) { $chunker = new ChunkIt($this->line_terminator); if (strstr($path, "s3://")) { if (!isset($this->SQ->state->aws_access_key) || !isset($this->SQ->state->aws_secret_key)) { $this->errors[] = "Missing AWS secret key or AWS access key. Please set them in the schemata_config table"; return false; } $pathinfo = $this->extract_s3_path($path); $bucket = $pathinfo[1]; $file = $pathinfo[2]; $path = $pathinfo; $s3 = new S3($this->SQ->state->aws_access_key, $this->SQ->state->aws_secret_key); $info = @$s3->getObjectInfo($bucket, $file); if (!$info) { $this->errors[] = "Could not get S3 information for {$path}"; return false; } $segment_count = floor($info['size'] / $chunk_size); echo "Getting file offsets (may take awhile)\n"; $info = $chunker->s3_find_offsets($s3, $bucket, $file, $info['size'], $chunk_size, $segment_count); } elseif (strstr($path, "http://") || strstr($path, "https://")) { $fs = $this->curl_get_file_size($path); if (!$fs) { $this->errors[] = "Could not get size of {$path}"; return false; } $segment_count = floor($fs / $chunk_size); $info = $chunker->http_find_offsets($path, $fs, $chunk_size, $segment_count); } else { /* NON-S3 load here */ $fs = @filesize($path); if (!$fs) { $this->errors[] = "Could not get size of {$path}"; return false; } $segment_count = floor($fs / $chunk_size); $info = $chunker->find_offsets($path, $segment_count); } } if ($segment_count === 0.0) { $segment_count = 1; } $jobs = array(); $loadspec = array('line_terminator' => $this->line_terminator, 'enclosure' => $this->enclosure, 'delimiter' => $this->delimiter, 'columns_str' => $columns_str, 'set_str' => $set_str, 'ignore' => $ignore, 'replace' => $replace); $job_id = $SQ->state->mapper->register_job(null, 0, 0, $table, "[LOAD DATA LOCAL] FILE:{$path}", "load", count($info)); echo "Scheduling jobs for file chunks:\n"; foreach ($info as $segment) { echo " Table: {$table}\n File: " . print_r($path, true) . "\nOffsets: from_pos: {$segment['start']}, to_pos: {$segment['end']}\n"; $jobs[] = array('job_id' => $job_id, 'path' => $path, 'table' => $table, 'start' => $segment['start'], 'end' => $segment['end'], 'loadspec' => $loadspec); } $set = $this->create_gearman_set($jobs); echo "Running background jobs for loading\n"; $this->run_set($SQ->state, $set); return true; }