Custom ELGG (1.8) Plugin Upload A Picture to Entity - php

This could be a very simple thing to do, but it is proving quite hard for me to achieve.
I am in the process of creating a custom plugin for elgg to build a library of things. I want to be able to upload an image when creating a new item.
Currently in my views/default/form/cust_plugin/save.php i have
elgg_view('input/file',array('name'=>'image','value'=>$image);
And in the actions/cust_plugin/save.php i have
$cust_plugin->image = $image;
but this doesn't work.
What am I missing, what am I doing wrong?
Thanks

To upload an image I use "file" plugin so I can manage it very simple.
In my function I call
//Load file library
elgg_load_library('elgg:file');
//Set multipart/form-data attribute on my form
$vars = array('enctype' => 'multipart/form-data');
$body_vars = file_prepare_form_vars();
//Create Array values to return
$return = array(
'title' => elgg_echo('gallery:title:add'),
'content' => elgg_view_form('elgg-gallery/uppa', $vars,$body_vars) //My form
);
My form is:
<div>
<label for="image_upload">Image upload</label>
<?php echo elgg_view('input/file', array('name' => 'img_upload')); ?>
</div>
And my action:
if (empty($_FILES['img_upload']['name']))
{
$error = elgg_echo('file:nofile');
register_error($error);
forward(REFERER);
}
//Make a file
$file = new FilePluginFile();
$file->subtype = "file";
// if no title, grab filename
if (empty($titolo))
$titolo = htmlspecialchars($_FILES['img_upload']['name'], ENT_QUOTES, 'UTF-8');
$file->title = $titolo;
$file->description = "description file";
$file->access_id = ACCESS_PUBLIC;
$file->owner_guid = elgg_get_logged_in_user_guid();
// we have a file upload, so process it
if (isset($_FILES['img_upload']['name']) && !empty($_FILES['img_upload']['name']))
{
//Generate filename
$prefix = "file/";
$filestorename = elgg_strtolower(time().$_FILES['img_upload']['name']);
$file->setFilename($prefix . $filestorename);
//Set Mimetype
$mime_type = ElggFile::detectMimeType($_FILES['img_upload']['tmp_name'], $_FILES['img_upload']['type']);
$file->setMimeType($mime_type);
//Set attributes
$file->originalfilename = $_FILES['img_upload']['name'];
$file->simpletype = file_get_simple_type($mime_type);
// Open the file to guarantee the directory exists
$file->open("write");
$file->close();
//Move file
move_uploaded_file($_FILES['img_upload']['tmp_name'], $file->getFilenameOnFilestore());
//Save file
$guid = $file->save();
//Make thumbnails
if ($guid && $file->simpletype == "image")
{
$file->icontime = time();
$thumbnail = get_resized_image_from_existing_file($file->getFilenameOnFilestore(), 60, 60, true);
if ($thumbnail)
{
$thumb = new ElggFile();
$thumb->setMimeType($_FILES['img_upload']['type']);
$thumb->setFilename($prefix."thumb".$filestorename);
$thumb->open("write");
$thumb->write($thumbnail);
$thumb->close();
$file->thumbnail = $prefix."thumb".$filestorename;
unset($thumbnail);
}
$thumbsmall = get_resized_image_from_existing_file($file->getFilenameOnFilestore(), 153, 153, true);
if ($thumbsmall)
{
$thumb->setFilename($prefix."smallthumb".$filestorename);
$thumb->open("write");
$thumb->write($thumbsmall);
$thumb->close();
$file->smallthumb = $prefix."smallthumb".$filestorename;
unset($thumbsmall);
}
$thumblarge = get_resized_image_from_existing_file($file->getFilenameOnFilestore(), 600, 600, false);
if ($thumblarge)
{
$thumb->setFilename($prefix."largethumb".$filestorename);
$thumb->open("write");
$thumb->write($thumblarge);
$thumb->close();
$file->largethumb = $prefix."largethumb".$filestorename;
unset($thumblarge);
}
}
if ($guid)
{
$message = elgg_echo("gallery:status:upsuccess");
system_message($message);
forward($guid->getURL());
}

Related

Can someone help me to Insert multiple pictures on laravel 7 [duplicate]

This question already has answers here:
Laravel 5.3 multiple file uploads
(8 answers)
Closed 1 year ago.
I am new to laravel so tried to insert informations to table on mysql used migrate for Images table but when i insert Multiple pictures it's returns with this error :
Invalid argument supplied for foreach()
If you guys have experience to this feel free to advise thanks.
Here is Input code of multiple pictures:
<input type="file" id="file" name="file[]" multiple>
Here is Controller code
use DB;
use Illuminate\Http\Testing\MimeType;
use Illuminate\Http\Request;
use App\Images;
public function insert (Request $Request){
$name = $Request->input('name');
$price = $Request->input('price');
$qty = $Request->input('qty');
$description = $Request->input('description');
$email = $Request->input('email');
$utas = $Request->input('utas');
$uruu = $Request->input('uruu');
$garage = $Request->input('garage');
$duureg = $Request->input('duureg');
$tagt = $Request->input('tagt');
$bairshil = $Request->input('bairshil');
$talbai = $Request->input('talbai');
$haalga = $Request->input('haalga');
$tsonh = $Request->input('tsonh');
$shal = $Request->input('shal');
$ttsonh = $Request->input('ttsonh');
$bdawhar = $Request->input('bdawhar');
$ashigon = $Request->input('ashig');
$lizing = $Request->input('lizing');
$bairlal = $Request->input('bairlal');
$hereg = $Request->input('hereg');
$zahi = $Request->input('zahi');
$file='';
$file_tmp='';
$location="uploads/";
$data='';
foreach($_FILES['images']['name'] as $key=>$val)
{
$file=$_FILES['images']['name'][$key];
$file_tmp=$_FILES['images']['tmp_name'][$key];
move_uploaded_file($file_tmp,$location.$file);
$data .=$file." ";
}
DB::table('laravel_products')
->insert( array(
'name' => $name,
'price' => $price,
'qty' => $qty,
'description' => $description,
'uruu' => $uruu,
'garage' => $garage,
'duureg' => $duureg,
'tagt' => $tagt,
'talbai' => $talbai,
'haalga' => $haalga,
'tsonh' => $tsonh,
'shal' => $shal,
'tsonhtoo' => $ttsonh,
'hdawhar' => $bdawhar,
'lizing' => $lizing,
'utas' => $utas,
'email' => $email,
'hereg' => $hereg,
'bairshil' => $bairshil,
'bairlal' => $bairlal,
'ashig' => $ashigon,
'zahi' => $zahi,
'image' => $data
)
);
$lastInsertedID = DB::getPdo()->lastInsertId();
$images = $Request->input('file');
foreach ($images as $image){
$image_new_name = time() . $image->getClientOriginalName();
$image->move('uploads',$image_new_name);
$post = new Images;
$post->product_id = $lastInsertedID;
$post->image = 'uploads/' . $image_new_name;
$post->save();
}
return view('createproduct');
}
}
I do like this. Hope this could be helpful for you.
$image1 = $request->image1; // keep image in variable
$image2 = $request->image2; // keep image in variable
$data = array(); // declare a array type variable
if(!empty($image1)) //check image1 is empty or not
{
$image1_name=uniqid().date('dmYhis'); // set image name
$image1_upload_path='backend/product_images/'; // set upload path
$ext6=strtolower($image1->getClientOriginalExtension()); //get extension
$image1_full_name=$image1_name.'.'.$ext6; // set image name with extension
$image1_url=$image1_upload_path.$image1_full_name; // keep image upload url to a variable
$success=$image1->move($image1_upload_path,$image1_full_name); // move to upload folder
$data['image1']=$image1_url; // finaly store image link to database
}
if(!empty($image2)) //check image2 is empty or not
{
$image2_name=uniqid().date('dmYhis'); // set image name
$image2_upload_path='backend/product_images/'; // set upload path
$ext6=strtolower($image1->getClientOriginalExtension()); //get extension
$image2_full_name=$image2_name.'.'.$ext6; // set image name with extension
$image2_url=$image2_upload_path.$image2_full_name; // keep image upload url to a variable
$success=$image2->move($image2_upload_path,$image2_full_name); // move to upload folder
$data['image2']=$image2_url; // finaly store image link to database
}
$store = Product::create($data); // store data to database with Product model

Moodle Filemanager draft image visible only to me

I have been making a plugin which allows admins to upload image, i can see the image(so can other people which is expected), delete and re-upload, but the problem is when another admin try to edit the plugin, they cant see the draft image, they only see the image they upload and i see the image i upload as draft. What i want is if i upload an image everyone that tries to edit, they should see the image i have upload as draft.
I will add my code below, if someone can help i will really appreciate it.
view.php:
$i = 1;
$out = array();
$fs = get_file_storage();
$files = $fs->get_area_files($this->context->id, 'block_cls_user_profile', 'cls_img', $i, false, false);
foreach ($files as $file) {
$filename = $file->get_filename();
$url = moodle_url::make_pluginfile_url(
$file->get_contextid(),
$file->get_component(),
$file->get_filearea(),
$file->get_itemid(),
$file->get_filepath(),
$filename);
// $out[] = html_writer::link($url, $filename);
}
// $br = html_writer::empty_tag('br');
lib.php
// Check the contextlevel is as expected - if your plugin is a block, this becomes CONTEXT_BLOCK, etc.
if ($context->contextlevel != CONTEXT_BLOCK) {
return false;
}
// Make sure the filearea is one of those used by the plugin.
if ($filearea !== 'cls_img') {
return false;
}
// $fs = get_file_storage();
// $file = $fs->get_file($context->id, 'local_myplugin', $filearea, $args[0], '/', $args[1]);
// send_stored_file($file);
// Make sure the user is logged in and has access to the module (plugins that are not course modules should leave out the 'cm' part).
require_login($course, true);
// No check for capability, because everybody needs to see it
// Check the relevant capabilities - these may vary depending on the filearea being accessed.
/*
if (!has_capability('mod/bookcase:addinstance', $context)) {
return false;
}
*/
// Leave this line out if you set the itemid to null in make_pluginfile_url (set $itemid to 0 instead).
$itemid = array_shift($args); // The first item in the $args array.
// Use the itemid to retrieve any relevant data records and perform any security checks to see if the
// user really does have access to the file in question.
// Extract the filename / filepath from the $args array.
$filename = array_pop($args); // The last item in the $args array.
if (!$args) {
$filepath = '/'; // $args is empty => the path is '/'
} else {
$filepath = '/'.implode('/', $args).'/'; // $args contains elements of the filepath
}
// Retrieve the file from the Files API.
$fs = get_file_storage();
$file = $fs->get_file($context->id, 'block_cls_user_profile', $filearea, $itemid, $filepath, $filename);
if (!$file) {
return false; // The file does not exist.
}
// We can now send the file back to the browser - in this case with a cache lifetime of 1 day and no filtering.
// From Moodle 2.3, use send_stored_file instead.
send_stored_file($file, 86400, 0, $forcedownload, $options);
edit_form.php
$mform->addElement('filemanager', 'config_profile_image', get_string('file'), null,
array('maxbytes' => $CFG->maxbytes, 'areamaxbytes' => 10485760, 'maxfiles' => 1,
'accepted_types' => '*', 'return_types'=> FILE_INTERNAL | FILE_EXTERNAL));
$i = 1;
if ($draftitemid = file_get_submitted_draft_itemid('config_profile_image')) {
file_save_draft_area_files($draftitemid, $this->block->context->id, 'block_cls_user_profile', 'cls_img', $i,array('subdirs' => false, 'maxfiles' => 1));
}
I have edited the edit_form.php and now it looks like this:
global $CFG, $mform;
$i = 0;
$draftitemid = file_get_submitted_draft_itemid('config_profile_image');
file_prepare_draft_area($draftitemid, $this->block->context->id, 'block_cls_user_profile', 'cls_img', $i,
array('subdirs' => 0, 'maxbytes' => $CFG->maxbytes, 'maxfiles' => 1));
$entry->config_profile_image = $draftitemid;
$mform->set_data($entry);
file_save_draft_area_files($draftitemid, $this->block->context->id, 'block_cls_user_profile', 'cls_img', $i,array('subdirs' => false, 'maxfiles' => 1));
parent::set_data($defaults);}}
But the error i get now is 'Call to a member function set_data() on null'.
Thank you.

How do I write an image, along with other data, to my database using php and mysql

Hello: I have a web form that submits data to my db. I am able to create a signature image and save it within my directory. I want to save/store that signature image in my mysql db along with the record so I can call it later.
Written in CodeIgniter 2.0
here are my model and controller.
public function sig_to_img()
{
if($_POST){
require_once APPPATH.'signature-to-image.php';
$json = $_POST['output'];
$img = sigJsonToImage($json);
imagepng($img, 'signature.png');
imagedestroy($img);
$form = $this->input->post();
var_dump($form);
$this->coapp_mdl->insert_signature($form);
}
}
public function insert_signature($data)
{
$sig_hash = sha1($data['output']);
$created = time();
$ip = $_SERVER['REMOTE_ADDR'];
$data = array(
'first_name' => $data['fname'],
'last_name' => $data['lname'],
'signator' => $data['name'],
'signature' => $data['output'],
'sig_hash' => $sig_hash,
'ip' => $ip,
'created' => $created
);
return $this->db->insert('signatures', $data);
}
I found the function below on php.net but apparently I am doing something wrong or various things wrong. Does anyone know how to accomplish this functionality?
$imagefile = "changethistogourimage.gif";
$image = imagecreatefromgif($imagefile);
ob_start();
imagepng($image);
$imagevariable = ob_get_contents();
ob_end_clean();
Got it - For those curious here are the changes to my controller:
public function sig_to_img()
{
if($_POST){
require_once APPPATH.'signature-to-image.php';
$json = $_POST['output'];
$img = sigJsonToImage($json);
// Save to file
$file_name = trim(str_replace(" ","_",$_POST['name']));//name to used for filename
imagepng($img, APPPATH."../images/signatures/".$file_name.'.png');
$sig_name = $file_name.'.png'; //pass to model
// Destroy the image in memory when complete
imagedestroy($img);
$form = $this->input->post();
var_dump($form);
$this->coapp_mdl->insert_signature($form, $sig_name);
}
}

writing APIC to mp3 file with getid3 (id3v2)

I am trying to write APIC picture to mp3 file with getid3. here is the code;
$cover = "/home/user/public_html/artwork/cover.jpg";
$TagData['attached_picture'][]=array(
'picturetypeid'=>2, // Cover. More: module.tag.id3v2.php -> function APICPictureTypeLookup
'description'=>'cover', // text field
'mime'=>'image/jpeg', // Mime type image
'data'=>$cover // Image data
);
but it doesnt work. image size is around 1.5 MB. should i resize it or sth ?
where am i wrong ?
Thanks
Looking at the demo they have on their website: http://www.getid3.org/source/demo.write.phps
snippet of code:
$fd = fopen($_FILES['userfile']['tmp_name'], 'rb')
$APICdata = fread($fd, filesize($_FILES['userfile']['tmp_name']));
fclose ($fd);
$imagetypes = array(1=>'gif', 2=>'jpeg', 3=>'png');
if (isset($imagetypes[$APIC_imageTypeID])) {
$TagData['attached_picture'][0]['data'] = $APICdata;
$TagData['attached_picture'][0]['picturetypeid'] = $_POST['APICpictureType'];
$TagData['attached_picture'][0]['description'] = $_FILES['userfile']['name'];
$TagData['attached_picture'][0]['mime'] = 'image/'.$imagetypes[$APIC_imageTypeID];
}
Seems like the data key needs to be the image content, not just the path to the image file.
So in your case, it should be something like:
$cover = "/home/user/public_html/artwork/cover.jpg";
$fd = fopen($cover, 'rb')
$APICdata = fread($fd, filesize($coverFile));
fclose ($fd);
$TagData['attached_picture'][]=array(
'picturetypeid'=>2, // Cover. More: module.tag.id3v2.php -> function APICPictureTypeLookup
'description'=>'cover', // text field
'mime'=>'image/jpeg', // Mime type image
'data'=>$APICdata // Image data
);
Note: This is just after a quick glance at the demo code, I have not used this library or tested this code.
GetID3 needs the content of the file to be send for the data, not the file path. Then only it will be able to embed them into the file. Try
$cover = "/home/user/public_html/artwork/cover.jpg";
$TagData['attached_picture'][]=array(
'picturetypeid'=>2, // Cover. More: module.tag.id3v2.php -> function APICPictureTypeLookup
'description'=>'cover', // text field
'mime'=>'image/jpeg', // Mime type image
'data'=> file_get_contents($cover) // Image data; not the file name
);
tested and working :)
I found this in the source code:
case 'APIC':
// 4.14 APIC Attached picture
// Text encoding $xx
// MIME type <text string> $00
// Picture type $xx
// Description <text string according to encoding> $00 (00)
// Picture data <binary data>
So picture data must be binary.
The solution is here: getid3 demo
This one is working for me for long time:
$TagData = array(); //your other tags
$fd = fopen($albumPath, 'rb');
$APICdata = fread($fd, filesize($albumPath));
fclose($fd);
if($APICdata) {
$TagData += array(
'attached_picture' => array(0 => array(
'data' => $APICdata,
'picturetypeid' => '0x03',
'description' => 'cover',
'mime' => image_type_to_mime_type($albumExifType)
))
);
}
//and write the tags to file
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info#getid3.org> //
// available at http://getid3.sourceforge.net //
// or http://www.getid3.org //
// also https://github.com/JamesHeinrich/getID3 //
/////////////////////////////////////////////////////////////////
// //
// /demo/demo.simple.write.php - part of getID3() //
// Sample script showing basic syntax for writing tags //
// See readme.txt for more details //
// ///
/////////////////////////////////////////////////////////////////
//die('Due to a security issue, this demo has been disabled. It can be enabled by removing line '.__LINE__.' in '.$_SERVER['PHP_SELF']);
$TextEncoding = 'UTF-8';
$albumPath = "img/img.jpg"; // path to your image
require_once('../getid3/getid3.php');
// Initialize getID3 engine
$getID3 = new getID3;
$getID3->setOption(array('encoding'=>$TextEncoding));
require_once('../getid3/write.php');
// Initialize getID3 tag-writing module
$tagwriter = new getid3_writetags;
//$tagwriter->filename = '/path/to/file.mp3';
$tagwriter->filename = 'uploads/problem.mp3';
//$tagwriter->tagformats = array('id3v1', 'id3v2.3');
$tagwriter->tagformats = array('id3v2.3');
// set various options (optional)
$tagwriter->overwrite_tags = true; // if true will erase existing tag data and write only passed data; if false will merge passed data with existing tag data (experimental)
$tagwriter->remove_other_tags = false; // if true removes other tag formats (e.g. ID3v1, ID3v2, APE, Lyrics3, etc) that may be present in the file and only write the specified tag format(s). If false leaves any unspecified tag formats as-is.
$tagwriter->tag_encoding = $TextEncoding;
$tagwriter->remove_other_tags = true;
// populate data array
$TagData = array(
'title' => array('My Song'),
'artist' => array('My Song'),
'album' => array('My Song'),
'year' => array('20015'),
'genre' => array('My Song'),
'comment' => array('My Song'),
'track' => array('01'),
);
$fd = fopen($albumPath, 'rb');
$APICdata = fread($fd, filesize($albumPath));
fclose($fd);
if($APICdata) {
$TagData += array(
'attached_picture' => array(0 => array(
'data' => $APICdata,
'picturetypeid' => '0x03',
'description' => 'cover',
'mime' => image_type_to_mime_type(#$albumExifType)
))
);
}
$tagwriter->tag_data = $TagData;
// write tags
if ($tagwriter->WriteTags()) {
echo 'Successfully wrote tags<br>';
if (!empty($tagwriter->warnings)) {
echo 'There were some warnings:<br>'.implode('<br><br>', $tagwriter->warnings);
}
} else {
echo 'Failed to write tags!<br>'.implode('<br><br>', $tagwriter->errors);
}
For anyone who just needd to update their ID3 tags including the Album Art , above code works just fine You need to have getID3 library to work .
This Answer is based on JacopKane's Answer so credit goes to him

oop concept implementation

I have this class content in which i am using s3 and sdb class how can i improve this class structure for using advanced oop concepts.
<?php
Class content{
function getcontent(){
if(!$_GET){
echo "{'success':false, 'error':'No query parameters submitted'}";
return;
}
// create connection
$sdb = new SimpleDB(awsAccessKey, awsSecretKey);
$condition = "";
$status = "";
//$params = json_decode(stripslashes($_POST['hash']));
$params = $_GET;
unset($params['command']);
foreach($params as $key => $value){
$condition .= " " . $key . " = '" . $value . "' and" ;
}
$condition = preg_replace('/and$/', "", $condition);
if($condition!='')
$condition=" and ".$condition;
$query = "select * from ".domain;
if($condition!= " _empty_ = '' "){
$query .= " where time_stamp is not null $condition order by time_stamp asc";
}
//~ echo $query;
$fileHash = '{';
if($files = $sdb->select($domain, $query)){
$status = 'true';
}else{
$status = 'false';
$files= array();
$message = "No records retrieved from SimpleDB ".json_encode($sdb->ErrorCode);
}
$array=array(
'files'=>$files,
'success'=>$status,
'message'=>$message
);
echo (json_encode($array));
}
function getthumb(){
$_url = $_REQUEST['url'];
$url='';
if ( $_url != "" ) {
echo $url = file_get_contents("$_url");
}
return $url;
}
function upload(){
//instantiate the S3 class
$s3 = new S3(awsAccessKey, awsSecretKey);
//instantiate the SimpleDB class
$sdb = new SimpleDB(awsAccessKey, awsSecretKey);
// Set temp directory where files will be written temporarily
$uploaddir = 'uploads/';
// Max file size 100 MB
$maxFileSize = 100 * 1024 * 1024;
$thumb = '';
$status = '';
$imgWidth = '';
$imgHeight = '';
// Get file size from Apache headers
$fileSize = getSize();
// Get MIME type from Apache headers
$fileType = getFileType();
if ($fileSize == 0){
return array(success=>false, error=>"File is empty.");
}
if ($fileSize > $maxFileSize){
return array(success=>false, error=>"File is too large.");
}
// Put data of pathinfo() array into $pathinfo
$pathinfo = pathinfo(getName());
// Get file name - eg: myphoto
$filename = $pathinfo['filename'];
// Get extension - eg: .jpg
$ext = $pathinfo['extension'];
$originalName = $filename.'.'.$ext;
// Generate unique id for the current object
$randName = uniqid();
// Unique file name with extension
$fileTempName = $randName . '.' . $ext;
// Complete temp file name and path
$fullTempName = $uploaddir . $fileTempName;
// Upload the file to temp directory on .net server
save($fullTempName);
// If images, call the function imgThumbs() to generate thumbnails
if(preg_match("/^image/", $fileType)){
$tbnail = $_GET['thumb_size'];
$thumb = imgThumbs($tbnail, $fullTempName, $fileType, bucket, cloudfront);
if($_REQUEST['profile_pic']=='y'){
$crop_url=$thumb;
}
list($imgWidth, $imgHeight) = getimagesize($fullTempName);
}
// If videos, call convertVideo() and return path of converted video. Then call vidThumbs() to generate thumbnails
if(preg_match("/^video/", $fileType)){
$fullTempName = convertVideo($fullTempName, $fileType); // Capture filename with complete path and flv extension
$fileTempName = preg_replace('/^uploads\//', '', $fullTempName);// Remove directory to get only the filename of flv
$fileType = "video/x-flv"; // Assign $fileType
$randName = substr($fileTempName, 0, 13); // Parse and assign the unique id to $randName
$imgWidth = 120; // Hardcoding width of video thumbnail
$imgHeight = 90; // Hardcoding height of video thumbnail
$thumb = vidThumbs($fullTempName, bucket, cloudfront); // Call the video thumbnail func
}
// If audio, call convertAudio() and return path of converted audio.
if(preg_match("/^audio/", $fileType)){
$fullTempName = convertAudio($fullTempName, $fileType); // Capture filename with complete path and mp3 extension
$fileTempName = preg_replace('/^uploads\//', '', $fullTempName);// Remove directory to get only the filename of mp3
$fileType = "audio/mpeg"; // Assign $fileType
$randName = substr($fileTempName, 0, 13); // Parse and assign the unique id to $randName
$imgWidth = $imgHeight = 100; // Hardcoding for positioning the thumbnail for audio
$thumb = 'http://dtzhqpwfdzscm.cloudfront.net/4c7247570bd4b.jpg'; // Hardcoding this url for audio thumbs
}
// Metadata for SimpleDB
$contentObjectType = "upload";
$timeStamp = time();
$url = cloudfront.$fileTempName;
$on_floor = "true";
/*
* An array of (name => (value [, replace])),
* where replace is a boolean of whether to replace the item.
* replace is optional, and defaults to false.
* If value is an array, multiple values are put.
*/
$putAttributesRequest = array(
"contentid" => array("value" => "$randName"), // unique id for EVERY object and link
"content_obj_type" => array("value" => "$contentObjectType"), // whether link or file upload
"file_name" => array("value" => "$fileTempName"), // unique generated filename
"url" => array("value" => "$url"), //file's CDN url
"original_name" => array("value" => "$originalName"), //original name of the file
"file_size" => array("value" => "$fileSize"), //size of file uploaded
"time_stamp" => array("value" => "$timeStamp"), //time
"file_type" => array("value" => "$fileType"), //mime type of uploaded file
"thumb" => array("value" => "$thumb"), //thumbnail link
"width" => array("value" => "$imgWidth"), //width of uploaded image
"height" => array("value" => "$imgHeight"), //height of uploaded image
"on_floor" => array("value" => "$on_floor") //by default all cObj on floor
);
// Get ALL the parameter hash passed
$contentObjHash = getParam();
foreach($contentObjHash as $key => $value){
$putAttributesRequest["$key"] = array("value" => "$value");
}
//check whether a form was submitted
if(isset($fileTempName)){
// Begin object hash here
$objHash = '{';
/* Move the file to S3
*
* #param mixed $fileTempName Location of temp file
* #param string bucket Bucket
* #param string $newFileName Unique generated file name
* #param constant ACL
* #param array() Dont worry about this
* #param string $fileType MIME type of file
* #return boolean
*/
if($_REQUEST['profile_pic']!='y' && !$s3->putObjectFile($fullTempName, bucket, $fileTempName, S3::ACL_PUBLIC_READ, array(), $fileType) ) {
$status = 'false';
$objHash .= "success : ".json_encode($status)."}"; // End object hash here id S3 error
echo $objHash;
return;
}
/**
* Create or update attributes
*
* #param string $domain Domain
* #param string $randName Unique generated file name
* #param array $putAttributesRequest See up for more info
* #return boolean
*/
if($sdb->putAttributes(domain, $randName, $putAttributesRequest)){
$status = 'true';
unlink($fullTempName);
}else{
$status = 'false';
$objHash .= "'SimpleDB_error' : ".json_encode($sdb->ErrorCode).",";
}
foreach($putAttributesRequest as $key => $value){
$objHash .= json_encode($key). " : " . json_encode($value["value"]) .", ";
}
$objHash .= "'success' : ".$status."}"; // End object hash after SimpleDB transaction
echo $objHash;
}
}
}
?>
Using the class by this code :
$content=new content();
switch($command){
case 'getcontent':
$content->getcontent();
break;
case 'thumb':
$content->getthumb();
break;
case 'upload':
$content->upload();
break;
case 'update':
$content->update();
break;
default:
break;
}
-- comment
your class seems to be more like a "service" class (you don't have any property). Then you need just one instance of the class : implement the singleton pattern. If the instance is used quite often or once created, you call almost all methods : create a DB attribute to avoid multiple connections (actually you could do that with a singleton on the application scope). All of that depends on your way of use the class.
-- /comment
for the singleton pattern, read this.
About the DB attribute, it will allow you to connect just once for each instance of the Content Class instead of several local variables in methods.
It could be useful in case of multiple calls of methods that need DB which is not your case for the moment.
Here is an example :
Class content{
private $db=null; // db
public function __construct(){ // CONSTRUCTOR : called with the new operator
// create connection (created once for the instance)
$this->db = new SimpleDB(awsAccessKey, awsSecretKey);
// you can pass the connection strings as parameter
}
public function getcontent(){
// You should not use directly GET here : pass it as parameter
// as the origin of the data may change some day
// in this method, it doesn't where the data come from
// -> encapsulation : the code keeps consistent when environment changes
if(!$_GET){
echo "{'success':false, 'error':'No query parameters submitted'}";
return;
}
...
// query something using the local attribute
if($files = $this->db->select($domain, $query)){

Categories