How can I programatically add images to a drupal node? - php

I'm using Drupal 6.x and I'm writing a php class that will grab an RSS feed and insert it as nodes.
The problem I'm having is that the RSS feed comes with images, and I cannot figure out how to insert them properly.
This page has some information but it doesn't work.
I create and save the image to the server, and then I add it to the node object, but when the node object is saved it has no image object.
This creates the image object:
$image = array();
if($first['image'] != '' || $first['image'] != null){
$imgName = urlencode('a' . crypt($first['image'])) . ".jpg";
$fullName = dirname(__FILE__) . '/../../sites/default/files/rssImg/a' . $imgName;
$uri = 'sites/default/files/rssImg/' . $imgName;
save_image($first['image'], $fullName);
$imageNode = array(
"fid" => 'upload',
"uid" => 1,
"filename" => $imgName,
"filepath" => $uri,
"filemime" => "image/jpeg",
"status" => 1,
'filesize' => filesize($fullName),
'timestamp' => time(),
'view' => '<img class="imagefield imagefield-field_images" alt="' . $first['title'] . '" src="/' . $uri . '" /> ',
);
$image = $imageNode;
}
and this adds the image to the node:
$node->field_images[] = $image;
I save the node using
module_load_include('inc', 'node', 'node.pages');
// Finally, save the node
node_save(&$node);
but when I dump the node object, it no longer as the image. I've checked the database, and an image does show up in the table, but it has no fid. How can I do this?

Why not get the Feedapi, along with feedapi mapper, and map the image from the RSS field into an image CCK field you create for whatever kind of node you're using?
It's very easy, and you can even do it with a user interface.
Just enable feedapi, feedapi node (not sure on the exact name of that module), feedapi mapper, and create a feed.
Once you've created the feed, go to map (which you can do for the feed content type in general as well) on the feed node, and select which feed items will go to which node fields.
You'll want to delete your feed items at this point if they've already been created, and then refresh the feed. That should be all you need to do.
Do you need to create a separate module, or would an existing one work for you?
Are you using hook_nodeapi to add the image object to the node object when $op = 'prepare'?

If you read the comments on the site you posted, you'll find:
To attach a file in a "File" field
(i.e. the field type supplied by
FileField module) you have to add a
"description" item to the field array,
like this:
$node->field_file = array(
array(
'fid' => 'upload',
'title' => basename($file_temp),
'filename' => basename($file_temp),
'filepath' => $file_temp,
'filesize' => filesize($file_temp),
'list' => 1, // always list
'filemime' => mimedetect_mime($file_temp),
'description' => basename($file_temp),// <-- add this
), );
maybe that works. You could also try to begin the assignment that way:
$node->field_file = array(0 => array(...

If you are just grabbing content wich has images in, why not just in the body of your nodes change the path of the images to absolute rather than local, then you won't have to worry about CCK at all.

Two other things that you may need to do
"fid" => 'upload', change this to the fid of the file when you save it. If it isn't in the files table then that is something you will need to fix. I think you will need feild_file_save_file()
2.you may need an array "data" under your imageNode array with "title", "description" and "alt" as fields.

To build file information, if you have filefield module, you can also use field_file_load() or field_file_save_file(). See file filefield/field_file.inc for details.
Example:
$node->field_name[] = field_file_load('sites/default/files/filename.gif');

Related

Randomly show image + link in html newsletter template

Let's say i have a list of 4 images and i'm trying to randomly show 2 of them each time the newsletter is loaded.
I have a file show_image.php with the following code:
$images = array(
0 => array(
'image' => 'http://example.com/img/partner1.jpg',
'link' => 'http://www.example1.com'
),
1 => array(
'image' => 'http://example.com/img/partner2.jpg',
'link' => 'http://www.example2.com'
),
2 => array(
'image' => 'http://example.com/img/partner3.jpg',
'link' => 'http://www.example3.com'
),
3 => array(
'image' => 'http://example.com/img/partner4.jpg',
'link' => 'http://www.example4.com'
)
);
$i = 0
foreach($images as $image)
{
$i++;
$zones[$i][] = $image;
if($i == 2)
$i = 0;
}
if(!empty($zones[$_GET['zone']]))
{
$zone = $zones[$_GET['zone']];
$random_index = array_rand($zone);
$partner = $zone[$random_index];
if($_GET['field'] == 'image')
{
$file = getFullPath($partner['image']);
$type = 'image/jpeg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($file));
readfile($file);
}
elseif($_GET['field'] == 'link')
{
wp_redirect( $partner['link'], 301);
exit();
}
}
In my current situation, the images in the (html) newsletter template look like this:
<a href="http://example.com/show_image.php?zone=1&field=link">
<img src="http://example.com/show_image.php?zone=1&field=image">
</a>
<a href="http://example.com/show_image.php?zone=2&field=link">
<img src="http://example.com/show_image.php?zone=2&field=image">
</a>
As you can see, the call for a random image and link are separate, causing the php script to respond with a random link that doesn't match the random image.
Can anyone point me in the right direction how to randomly show an image with the right corresponding link?
First, there is a syntax error in your code. All your child arrays are missing a comma:
0 => array(
'image' => 'http://example.com/img/partner1.jpg' // <-- Error
'link' => 'http://www.example1.com'
)
Should be:
0 => array(
'image' => 'http://example.com/img/partner1.jpg', // <-- Fixed
'link' => 'http://www.example1.com'
)
You should use rand() to get an image randomly:
$images = array(
0 => array(
'image' => 'http://example.com/img/partner1.jpg',
'link' => 'http://www.example1.com'
),
1 => array(
'image' => 'http://example.com/img/partner2.jpg',
'link' => 'http://www.example2.com'
),
2 => array(
'image' => 'http://example.com/img/partner3.jpg',
'link' => 'http://www.example3.com'
),
3 => array(
'image' => 'http://example.com/img/partner4.jpg',
'link' => 'http://www.example4.com'
)
);
$total_images = count($images) - 1; // Get total number of images. Deducted one because arrays are zero-based
$random_img = rand(0, $total_images); // Get a random number between 0 and $total_images
echo $images[$random_img]['image'] . '<br />';
echo $images[$random_img]['link'] . '<br />';
there are could be multiple solutions, all of them have positive and negative sides:
Instead of static html file with hard-coded links, you can generate page on fly with php, so in this way you will generate random number for each zone and output html with proper links/images
1.1. You can use iframe to load image and link form php server
If you have to use static html and javascript, you can perform ajax call to php with javascript, which again will fetch image and link and use them to generate html code (document.write or innerHTML)
You can try to use cookies or session mechanism, in this case in php code you will have branch like if number for zone is not generated yet - generate and store in cookie/session; return link or image for number from cookies/session
To modify your code for #3 you need to replace
$random_index = array_rand($zone);
with something like (writing without actual php, so syntax errors are possible):
$cook = 'zone' . $_GET['zone'];
$random_index = isset($_COOKIE[$cook]) ? $_COOKIE[$cook] : array_rand($zone);
setcookie($cook, $random_index);
note - it is up to you to put proper validation for any variables from GET or COOKIE
In case of e-mail clients - majority of them restrict execution of javascript code and don't store cookies (and from user's perspective is it very good that they do that), anyway you can try something like that:
during e-mail sending generate unique id for each e-mail sent (you can use UUID for that)
include this id into links in your template, like <img src="http://.../?..&id=UUID">
in image and click handler - you need to get id from url and check in database - whether you assigned value to it and if no - generate and store in db
if value in db present - you can now serve appropriate image or redirect to appropriate url
but in this scheme - users always will be presented with the same image (though different users will see different ones), to fix that you can introduce some kind of expiration, ie put timestamp in db and invalidate (regenerate) value
note - some e-mail clients can force cache of images, ignoring http headers, thus such scheme will fail
other notes:
don't forget about no-cache http headers for serving image
don't use permanent redirects, only temporary ones for your use case
some e-mail clients will not load images which are not embedded into message, for such ones you can play with <noscript> and embedded images of some single randomly picked ad

Podio API image upload on item

Hoping I can get some help here. I am able to upload image files via the API, and I receive a file_id as a response, but every time I try to update an image field in an item using the id that was returned I get:
"File with mimetype application/octet-stream is not allowed, must match one of (MimeTypeMatcher('image', ('png', 'x-png', 'jpeg', 'pjpeg', 'gif', 'bmp', 'x-ms-bmp')),)
I've even added a line of code into my PHP script to pull the jpeg from file, rewrite it as a jpeg to be certain ( imagejpeg()) before uploading. Still, when I get to the point of updating the image field on the item, I get the same error. It seems all images uploaded via the API are converted to octet-stream. How do I get around this?
I'm using the Podio PHP library.
The PHP code is as follows:
$fileName = "testUpload.jpeg";
imagejpeg(imagecreatefromstring(file_get_contents($fileName)),$fileName);
$goFile = PodioFile::upload($fileName,$itemID);
$fileID = $goFile->file_id;
PodioItem::update((int)$itemID, array(
'fields' => array(
"logo" => (int)$fileID,
)
) , array(
"hook" => 0
));
Please try and replace :
$goFile = PodioFile::upload($fileName,$itemID);
with something like:
$goFile = PodioFile::upload('/path/to/example/file/example.jpg', 'example.jpg');
$fileID = $goFile->file_id;
PodioItem::update((int)$itemID, array(
'fields' => array(
"logo" => array((int)$fileID),
)
As it is described in https://developers.podio.com/examples/files#subsection_uploading
And then use $fileID as you've used. And yes, filename should have file extension as well, so it will not work with just 123123123 but should work well with 123123123.jpg

Replace PHP script reading image alt and title values to reading image filenames

This script:
function theme_vscc_element_black_icons($vars) {
$image_vars = array(
'path' => drupal_get_path('theme', 'theme') . '/images/vscc/' . $vars['element'] . '.png',
'alt' => t($vars['element']),
'title' => t($vars['element']),
);
return theme('image', $image_vars);
}
It reads image's alt and title values that are called 'previous' and 'next', so to make it load the images, they need to be named as previous.png and next.png
What do I need to replace to make it read not the alt and title, but make it look for given file names like previous-black and next-black, so it would load the files named previous-black.png and next-black.png instead of looking for values in alt and title?
Solved by adding simple suffix for images like '-featured.png'

Display Multiple Images/Links In CDetailView Yii framework

Help
I have been surfing all day and can not find the topic, how to display multiple images in CDetailView.
My situation are as follows:
I have uploaded multiple images, the image jpg files stored in
/images/doc directory.
I have entried path to the images in a cell, means the cell contain
three filenames with comma separated: abc.jpg, xyz.jpg, abaca.jpg.
I wanna to display the link in CDetailView which clickable to open
the image in new tab browser.
I have tried with this script:
array(
'name'=>'File Link',
'type'=>'raw',
'value'=> Links of abc,
xyz,
and also this to display the images
$document= CHtml::encode($model->Document);
$file = str_getcsv($document ,",");
in CDetailView
array(
'name'=>'Image',
'type'=>'raw',
'value'=>link to $file[1]
),
array(
'name'=>'Image',
'type'=>'raw',
'value'=>link to $file[2]
),
array(
'name'=>'Image',
'type'=>'raw',
'value'=>link to $file[3]
),
but the result is not as I expected, when I click the link unrecognized opened by the browser.
I expect result like this: and it should be in Dynamic form may be using 'foreach' statement
how to use it i m not getting it
...
...
File Link : abc.jpg
xyz.jpg
abaca.jpg <== each must be clickable to the location of the image
...
...
Please Help
Regards
sandeep
If I understand your point, you need to have multiple images per row, right?
have a unanymouse function for value attribute and return the link of images:
'value' => function($data){ // here $data represents your model
$link = '';
if(!empty($data->images))
foreach($data->links as $l)
{
$link .= CHtml::link(CHtml::encode($file[$i]),Yii::app()->baseUrl . '/images/' . $file[$i]) . '<br />';
}
return $link;
}
Thanks for your help its simple and best way.......
here is my code document is an has multiple images in database and folder for one attribute
Function in Model
public function getDocument($model)
{
$link = '';
$attribute=CHtml::encode($model->documents);
$file = str_getcsv($attribute ,",");
if(!empty($model->documents))
foreach($file as $i=> $record)
{
$link .= CHtml::link(CHtml::encode($file[$i]),Yii::app()->baseURL . '/Documents/' . $file[$i]) . '<br />';
}
return $link;
}
In View widget CDetailView
array(
'name'=>"Uploaded Document ",
'value'=> $model->getDocument($model),
'type'=>'raw'
),

How to Zip mutiple files using Zend Compress Filter?

I have multiples files to be compressed into one unique file (zip), but it seems that it creates a new file everytime the loop restart, how do I do that? there is no enough documentation about this, here is my code:
$file1 = "test1.xls";
$files2 = array(
"test2.xls", "test3.xls"
);
$filter = new Zend_Filter_Compress(array(
'adapter' => 'Zip',
'options' => array(
'archive' => BASE_PATH .'/public/' . $this->configuracoes->get('media') . '/temp/zipped'.date('d-m-Y-H-i-s').'.zip'
)
));
$compress = $filter->filter($file1);
foreach($files2 as $file){
$compress = $filter->filter($file);
}
This only result a zip with test3.xls inside.
Worth looking at this link, seems to be the same answer where you open the zip, add files, then close it outside the loop.
Create zip with PHP adding files from url
An old question but I found this looking for something similar.
You can pass a directory to the filter function and it will recursively add all files within that directory.
i.e
$compress = $filter->filter('/path/to/directory/');

Categories