oop concept implementation - php

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)){

Related

Google Drive - Obtaining the FileSize of a File with Just the FileID

I need to obtain a file's meta-data from just using the Google Drive FileID only. The assumption being that I don't have knowledge of the folderID. By just using the FileID the API just returns null for the filesize but the correct values for the other meta-data.
Just to be clear, I can get all the meta data (including filesize) by processing the files within a folder, for example:
<?php
/*
* With this example I have the folderID from a Google Drive shared link
*/
$folderId = "https://drive.google.com/drive/folders/1ggWcacF9qQroZOkhfb3tTEwvBzclccwI?usp=share_link";
$Auth = new Oauth2Authentication();
$client = $Auth->GetClient();
$client = $Auth->initializeClient($client);
$drive = new DriveService($client);
$pattern = "/[-\w]{25,}(?!.*[-\w]{25,})/";
if (preg_match($pattern, $folderId, $match)); // grabs folderID from the url
/*
* Now list the folder contents
*/
$responseFiles = $drive->ListFiles($match[0]);
$files = $responseFiles['files'];
foreach ($files as $file) {
$id[] = $file->id;
$name[] = $file->name;
$mimeType[] = $file->mimeType;
$size[] = $file->size; //<- correct file size
};
$drive->DownloadFile($id, $name, $size);
The code below, which I need to work, returns most of the meta-data except that, as stated above, the $file->size is always null. My DownloadFile method needs the file size so that it can better handle large files. Is there anyone who can help me better understand the problem?
<?php
/*
* With this example I have the only the fileID from a Google Drive shared link
*/
$fileId = "https://drive.google.com/file/d/1EjNk1ijPLKJMwXfzkEIG487HFzx0v80v/view?usp=share_link";
$Auth = new Oauth2Authentication();
$client = $Auth->GetClient();
$client = $Auth->initializeClient($client);
$drive = new DriveService($client);
$pattern = "/[-\w]{25,}(?!.*[-\w]{25,})/";
if (preg_match($pattern, $fileId, $match)); // grabs fileID from the url
/*
* Now get the file meta data and download the file
*/
$fileId = $match[0];
$service = new Google_Service_Drive($client);
$file = $service->files->get($fileId);
$drive->DownloadFile($file->id, $file->name, $file->size); //$file->size is always null
Update: Thanks to #DaImTo I was pointed in the right direction. The full fileID's details can be obtained by adding
array('fields' =>'*')
to the argument list of the $service->files->get method, i.e.
$file = $service->files->get($fileId,array('fields' =>'*'));
Files.list retuns a list of files with limited response.
files": [
{
"kind": "drive#file",
"mimeType": "application/vnd.google-apps.spreadsheet",
"id": "1x8-vD-X2wltablGF22Lpwup8VtxNY",
"name": "Experts Activity Dump go/ExpertsActivities"
},
To get the file size either tweek the optimal parameter fields or just use .
Fileds=*
or
$responseFiles = $drive->ListFiles($match[0],array('fields' =>'*'))

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.

Custom ELGG (1.8) Plugin Upload A Picture to Entity

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());
}

Database Query during Dynamic Drupal node creation to get Entity ID

I have a script which grabs the latest image from our surf webcam, it saves a node of type Photos. In that content type i have an entity field which references the swell size (content type swell_data). I can add a static entity id no problem:
// Reference Swell Data ID 176821
$node->field_buoy_ref[$node->language][0]['target_id'] = 176821;
How would I dynamically find the latest node created by the swell_data content type (added hourly using a CRON job) and use that value instead? For your reference this is the current script i am using (thanks to FooNinja)
define('DRUPAL_ROOT', getcwd());
require_once 'includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$bodytext = "This was the view from the Camera at ".date('gA')." on ".date('l F jS Y');
$node = new stdClass(); // Create a new node object
$node->type = "photos"; // Or page, or whatever content type you like
node_object_prepare($node);
$node->title = "Caswell Camera ". date('D M j G:i');
$node->language = LANGUAGE_NONE;
// Author
$node->name = "Gower Live"; // UID of the author of the node; or use $node->name
// Publish Node
$node->status = 1;
//Set Body Text
$node->body[$node->language][0]['value'] = $bodytext;
$node->body[$node->language][0]['summary'] = text_summary($bodytext);
$node->body[$node->language][0]['format'] = 'filtered_html';
//Set Image Location (Caswell)
$node->field_photo_location[$node->language][0]['lat'] = 51.570195982718374;
$node->field_photo_location[$node->language][0]['lng'] = -4.030849980797484;
// Set the Photos date
$node->field_image_date[$node->language][0]['value'] = date("Y-m-d H:i:s");
// From the Webcam
$node->field_webcam_photo[$node->language][0]['value'] = "Caswell";
// Reference Wave Buoy
$node->field_buoy_ref[$node->language][0]['target_id'] = 176821; // I'd this value dynamically pulled from the DB
// Attach Latest Webcam Image
$file_path = drupal_realpath('images/webcams/caswell-webcam.jpg');
$file = (object) array(
'uid' => 1,
'uri' => $file_path,
'filemime' => file_get_mimetype($file_path),
'status' => 1,
);
// You can specify a subdirectory, e.g. public://foo/
$file = file_copy($file, 'public://');
$node->field_user_photo[$node->language][0] = (array) $file;
$path = 'node_created_on' . date('YmdHis');
$node->path = array('alias' => $path);
if($node = node_submit($node)) { // Prepare node for saving
node_save($node);
echo "Node with nid " . $node->nid . " saved!\n";
}
thanks
Lee
I added the following below the Bootstrap Line and bingo.
$result = db_query("SELECT nid, title, created FROM {node} WHERE type = :type AND title =:title", array(
':type' => 'wavebuoy_data',
':title' => "Buoy ". date('D M j gA'),
));
foreach($result as $row) {
$wave_buoy_ref_value = $row->nid;
//print_r($row);
}
Then when building the node, added the following:
// Reference Wave Buoy
$node->field_buoy_ref[$node->language][0]['target_id'] = $wave_buoy_ref_value;
Lee

Categories