programatically insert content with image field in Drupal - php

I'm trying to write PHP to insert lots of content into my website's drupal 6 database.
The content type has got 3 custom fields:
field_theme_preview_demo_link - text field
field_theme_preview_content_styl - text selector
field_theme_preview_thumb - image field with an 'alt'
I just copied the images over to the correct directory manually.
I created the content type (and manually inserted some content to confirm it was all ok).
I then found some code sample for programatically inserting content...
Creating Drupal CCK content programatically/ via API
and
http://drupal.org/node/458778#comment-1653696
(for this one I couldnt understand the mod that is suggested for D6).
I tried to modify it but couldnt get it to work - it does create the new content but the image field is blank. (To run this code I just paste into the 'Execute PHP Code' block.)
global $user;
$newnode = new stdClass();
$newnode->title = 'New node title';
$newnode->body = "the body";
$newnode->uid = $user->uid;
$newnode->type = 'theme_preview';
$newnode->status = 1;
$newnode->promote = 0;
$newnode->active = 1;
$newnode->field_theme_preview_demo_link[0]['value'] = 'the link';
$newnode->field_theme_preview_content_styl[0]['value'] = 'Books';
$newnode->field_theme_preview_thumb = array(
array(
'fid' => 'upload',
'alt' => 'the alt',
'filename' => 'sites/default/files/theme_preview_thumbs/41531.jpg',
'filepath' => 'sites/default/files/theme_preview_thumbs',
'filesize' => filesize('sites/default/files/theme_preview_thumbs/41531.jpg'),
),
);
node_save($newnode);

Setting the fid field to 'upload' is something that is done by a node's form when there actually is a file being uploaded. If you are programatically generating content, you will need to fetch the fid from somewhere else.
You will probably need to manually use the file api to enter a file from somewhere on the filesystem into the file database, and then draw your fid from the resulting object.

Use http://drupal.org/project/node_export this module to import or export content to particular content type, it really works for me and also image will be uploaded automatically.
One thing you have to consider for using this module, after importing nodes, make sure that images are matched with its content.
Using this module i have uploaded 100s of news article to my website from my local server site.

#Seth Battin, # Ayesh K, thanks for the tips,
working code...
global $user;
$newnode = new stdClass();
$newnode->title = 'New node title';
$newnode->body = "this is a new node, created by import function";
$newnode->uid = $user->uid;
$newnode->type = 'theme_preview';
$newnode->status = 1;
$newnode->promote = 0;
$newnode->active = 1;
$newnode->field_theme_preview_demo_link[0]['value'] = 'test 1';
$newnode->field_theme_preview_content_styl[0]['value'] = 'Books';
$field = field_file_save_file(
'sites/default/files/srcImage1.jpg',
array(),
'sites/default/files/theme_preview_thumbs');
if( !isset($field['data']) ) $field['data'] = array();
$field['data']['title'] = "the image title";
$field['data']['alt'] = "the image alt";
$newnode->field_theme_preview_thumb = array(0 => $field);
$newnode = node_submit($newnode);
node_save($newnode);

Related

PHPWORD - Insert image in front of text on every page of a docx file

Using PhpWord library, please tell me if it is possible to insert an image in front of text and on every page, in the same position, when creating a new docx file.
You could use a development version which implements this:
Have a look at this issue: https://github.com/PHPOffice/PHPWord/issues/939
This pull request implements this: https://github.com/PHPOffice/PHPWord/pull/1084
here is a simple example to illustrate what I meant with using global header to place an image in the top of every page (with single section containing a long table):
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$header = $section->addHeader();
$header->addImage('resources/PhpWord.png', array('width' => 80, 'height' => 80, 'alignment' => \PhpOffice\PhpWord\SimpleType\Jc::START));
// generate long table just for demo that spans over multiple pages
$table = $section->addTable();
for ($i = 0; $i < 200; $i++) {
$table->addRow();
$table->addCell(4500)->addText('dummy');
$table->addCell(4500)->addText("contents $i");
}

How to get multiple images from a single Drupal node using PHP

I have a custom content type in Drupal that allows multiple image uploads through a single field. I want to programmatically access the image URI's, apply my theme, and then get the output one by one. I can do this with a single image like so,
<?php
$image_style_name = 'my_theme';
$image_uri = $entity->field_image['und'][0]['uri'];
$image = theme('image_style', array('style_name' => $image_style_name, 'path' => $image_uri));
$image = image_style_url($image_style_name, $image_uri); ?>
but I am unsure how to access the entire array of images.
For anyone who needs it... the full solution:
<?php
$image_style_name = 'my_theme';
foreach($entity->field_image['und'] as $key => $value){
$image_uri = $entity->field_image['und'][$key]['uri'];
$image = theme('image_style', array('style_name' => $image_style_name, 'path' => $image_uri));
$output = image_style_url($image_style_name, $image_uri);
echo $output;
}
?>
They should be in the $entity->field_image['und'] array so you should be able to loop over the array and theme each one with something like
foreach($entity->field_image['und'] as $image_field){
..etc
}

Creating a new Page of Posts in Wordpress

I am currently trying to make a e-zine using wordpress, and have most of it done. The homepage displays a list of the "pieces" which are included in that edition of the e-zine. I would like to make it so that, when an edition expires (currently using Post Expirator plugin), a new page is created automatically resembling the front page in showing the index of that particular (now expired) edition.
I'm not very experienced using PHP, and still a newbie at wordpress. How could I accomplish this?
The idea is this, you just have to get the expiration date and make a condition with it. You just need to have a basic php skills in order for you to do it. Heres the logic
if($curdate > $expiration_date){ //you can change the condition into ">=" if you want to create a post on and after expiration date
//sample wordpress wp_insert_post
$my_post = array(
'post_title' => 'My post',
'post_content' => 'This is my post.',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array(8,39)
);
// Insert the post into the database
wp_insert_post( $my_post );
}
for more info visit http://codex.wordpress.org/Function_Reference/wp_insert_post
Here is what I ended up doing, using the suggestions of Felipe as a starting point. There might be a less convulted way of doing this, but, as I said, I'm just a beginner, so this is what I came up with:
First, I created a volnum variable, which keeps track of the current volume number. Then, I cache the front page so that later I can save it as an independent html document:
This is at the beginning of the index.php, before the get_header().
<?php $volnum; ?>
<?php ob_start(); ?>
In the front page, I have an editorial and, next to it, I have the content index. I am saving the editorial tag's (which is always "voln" where 'n' is the volume number) volume number (maybe the foreach is not necessary since the editorial only has one tag) :
<?php $tags = get_the_tags();
foreach ($tags as $tag){
$volnum = $tag->name;
}
?>
Finally, at the end of the document, after the last html, I have added the following code:
<?php
$handle = opendir("past_vol/");
$numOfFiles = count($handle);
$volExists = false;
for($i=0;$i<=$numOfFiles;$i++){
$name = readdir($handle);
if($volnum.".html" == ($name)){
$volExists = true;
continue;
}
}
if($volExists == false){
$cachefile = "past_vol/".$volnum.".html";
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
}
closedir($handle);
ob_end_flush();
?>
"past_vol" is the directory where I am saving the past volume html files. So the directory is opened, the amount of files is counted, and a loop that goes through each file's name is started. If a file with the same name as $volnum, then $volExists is true. If at the end of the loop $volExists is false, then it saves the cached page.
Again, it could probably be optimized a whole lot, but for now this works!

Errors while exporting to .xls using PHP

I've asked a similar question previously but Ive been told my question is just me being lazy so let me rephrase.
Ive been using a PHP class script to enable me to export my SQL data to a .xls file but the resultant excel file doesnt display any values and no error is being displayed on the webpage itself.
The class file Im using is documented in the link below:
http://web.burza.hr/blog/php-class-for-exporting-data-in-multiple-worksheets-excel-xml/
And Ive incorporated it in my site as follows
$dbase->loadextraClass('excel.xml');
$excel = new excel_xml();
$header_style = array(
'bold' => 1,
'size' => '14',
'color' => '#000000',
'bgcolor' => '#ffffff'
);
$excel->add_style('header',$header_style);
if(isset($_POST['fec_save']))
{
if($_POST['reporttype']=='films')
{
$films = $dbase->runquery("SELECT datetime,title,country_of_origin,language,runningtime,(SELECT name FROM fec_client WHERE filmid = fec_film.filmid) AS client, (SELECT rating_decision FROM fec_rating_report WHERE filmid = fec_film.filmid) AS rating FROM fec_film WHERE datetime >= '".strtotime($_POST['fromdate'])."' AND datetime <= '".strtotime($_POST['todate'])."'",'multiple');
$filmcount = $dbase->getcount($films);
//continue with excel buildup
$columns = array('Date','Title','Origin','Language','Minutes','Client','Rating');
$excel->add_row($columns,'header');
for($i=1; $i<=$filmcount; $i++)
{
$film = $dbase->fetcharray($films);
$excel->add_row($film['datetime'],$film['title'],$film['country_of_origin'],$film['language'],$film['runningtime'],$film['client'],$film['rating']);
}
$excel->create_worksheet('From_'.str_replace(' ','',$_POST['fromdate']).'_to'.str_replace(' ','',$_POST['todate']));
$xml = $excel->generate();
$excel->download('FilmsClassified_from_'.str_replace(' ','',$_POST['fromdate']).'_to'.str_replace(' ','',$_POST['todate']));
}
}
I would like some assistance as to what I maybe doing wrong.
Thanks
Too long to post as a comment:
$xml = $excel->generate();
creates all the xml file content as a string and stores it in $xml
while
$excel->create_worksheet('From_'.str_replace(' ','',$_POST['fromdate']).'_to'.str_replace(' ','',$_POST['todate']));
creates the xml and directs it to output, with appropriate headers for downloading.
So you're not using the class correctly, as that's unnecessary duplication of work.

How can I remove the copyright tag from ID3 of mp3s in python or php?

I have a bunch of mp3 files that are pretty old and don't have any copy rights. Yet, the place I got them from has filled the copy right tags with its own website url.
I was wondering if there's an easy way to remove these tags programmatically? There's a winamp add on that allows me to do this for each song, but that's not very feasible.
Edit: Is copyright part of the ID3 tags?
Thanks,
-Roozbeh
For Python, there's the mutagen library and tool, which is very easy to use.
However if you're not looking to actually do this programmatically, on Windows there's the freeware app MP3Tag, which I can heartily recommend. It'll do batch transformations and lots more.
You can use getID3 library.
Here is the example:
<?php
$TaggingFormat = 'UTF-8';
require_once('../getid3/getid3.php');
// Initialize getID3 engine
$getID3 = new getID3;
$getID3->setOption(array('encoding'=>$TaggingFormat));
require_once('../getid3/write.php');
// Initialize getID3 tag-writing module
$tagwriter = new getid3_writetags;
//$tagwriter->filename = '/path/to/file.mp3';
$tagwriter->filename = 'd:/file.mp3';
$tagwriter->filename = 'P:/webroot/_dev/getID3/testfiles/_writing/2011-02-02/test.mp3';
//$tagwriter->tagformats = array('id3v1', 'id3v2.3');
$tagwriter->tagformats = array('id3v2.3');
// set various options (optional)
$tagwriter->overwrite_tags = true;
$tagwriter->overwrite_tags = false;
$tagwriter->tag_encoding = $TaggingFormat;
$tagwriter->remove_other_tags = true;
// populate data array
$TagData = array(
'title' => array('My Song'),
'artist' => array('The Artist'),
'album' => array('Greatest Hits'),
'year' => array('2004'),
'genre' => array('Rock'),
'comment' => array('excellent!'),
'track' => array('04/16'),
);
$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);
}
?>
You can just use VLC player. Click on Tools->Media Information
My solution, change path you want:
import os
import shutil
from mutagen.mp3 import MP3
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith('.mp3'):
f = os.path.join(root, file)
try:
mp3 = MP3(f)
mp3.delete()
mp3.save()
print('ok')
except:
print('no ID3 tag')
print('Done')
There are open source tools like Amarok which will let you make batch changes to ID3 tags.
Take a look at: http://amarok.kde.org/
Yes Yes This works!
Just download the latest version of VLC media player. Open the mp3 file in it.
Right click on file > choose 'information' > edit publisher & copyright information there > click 'Save Metadata' below.
And u r done. :)
No Need Of any PHP code
Just Reproduce the mp3 file i.e.either burn & rip or cut the size &time making a new file where you can specify your own multitudes of options

Categories