[development] Info needed to add content to Drupal via shell/curl script

Richard Morse remorse at partners.org
Wed Jan 7 16:33:55 UTC 2009


On Jan 7, 2009, at 11:18 AM, Tomáš Fülöpp wrote:

> Hi, Ricky,
>
> Seems very useful. Are you planning to package and provide it as a  
> module at
> d.o.? Then people could comment and supply patches to develop it  
> further.
>
> If there are no such plans, I'll appreciate getting the existing code.


Hi! Here is the code. First is the php code, then the perl code. I've  
obfuscated some specific values (ip addresses, user names, etc), but  
it should be fairly clear...



<?php

/**
  * Implementation of hook_xmlrpc.
  *
  * This function returns a list of the available XML-RPC calls provided
  * by this module.
  *
  * This module provides one call, which allows XXXX to submit reports
  * without having to do it manually.
  */
function reports_upload_xmlrpc() {
   return array(
     array('reports.submit', 'reports_upload_receive', array('string',  
'struct'), t('Receive a report')),
   );
}

/**
  * This function is the actual processor of the XML-RPC call
  */
function reports_upload_receive($params) {
   // first, make sure that the remote computer is XXXX, otherwise fail
   if($_SERVER['REMOTE_ADDR'] != 'XXX.XXX.XXX.XXX') {
     return xmlrpc_error(1, t('Not allowed'));
   }

/*
we receive:

   [title] => title,
   [report_date] => date,
   [body] => body,
   [input_format] => format (if empty, default format is used)
   [oi_restrict] => oi_restriction,
   [terms] => [ taxonomy_identifier, * ]
   [attachments] => ** this one is optional
     0 =>
       [name]
       [mime]
       [data]

*/

   // validate the structure of the submission
   if (empty($params['title'])) {
     return xmlrpc_error(10, t('Missing title'));
   }
   if (empty($params['report_date'])) {
     return xmlrpc_error(11, t('Missing report date'));
   }
   if (empty($params['body'])) {
     return xmlrpc_error(12, t('Missing title'));
   }
   if (empty($params['input_format'])) {
     $params['input_format'] = variable_get('filter_default_format', 1);
   }
   else if (is_numeric($params['input_format'])) {
     // do nothing
   }
   else {
     // this is broken right now, I don't know why...
     $input_filter_name = $params['input_format'];
     if (false !== strpos($input_filter_name, '"')) {
       return xmlrpc_error(12, t('Invalid filter format specified:  
quotes not allowed'));
     }
     $matching_formats = array_filter(filter_formats(),
         create_function('$f', 'return $f->name == "' .  
$input_filter_name . '";'));

     if (count($matching_formats) == 1) {
       $params['input_format'] = array_shift($matching_formats)->format;
     }
     else {
       return xmlrpc_error(12, t('Invalid filter format specified. No  
matching formats to !format', array('!format' => $input_filter_name)));
     }
   }
   if (empty($params['oi_restrict'])) {
     return xmlrpc_error(13, t('Missing restriction'));
   }

   if (!is_array($params['terms'])) {
     return xmlrpc_error(14, t('Bad terms parameter'));
   }
   if (!empty($params['attachments'])) {
     foreach ( $params['attachments'] as $attachment_num =>  
$attachment_info ) {
       if (!is_numeric($attachment_num)) {
         return xmlrpc_error(15, t('Bad attachment index: !index',  
array('!index' => $attachment_num)));
       }
       if (empty($attachment_info['name'])) {
         return xmlrpc_error(16, t('Missing attachment name for index ! 
index', array('!index' => $attachment_num)));
       }
       if (empty($attachment_info['mime'])) {
         return xmlrpc_error(16, t('Missing attachment mime-type for  
index !index', array('!index' => $attachment_num)));
       }
       if (empty($attachment_info['data'])) {
         return xmlrpc_error(16, t('Missing attachment data for index ! 
index', array('!index' => $attachment_num)));
       }
     }
   }

   // set the proper user
   global $user;
   $orig_user = $user;
   $new_user  = user_load(array('name' => 'XXXX'));

   $user      = $new_user;

   // create a new node as an array
   $node = array(
     // our particular information
     'type'                => 'report',
     'title'               => $params['title'],
     'field_report_date'   => array(array('value' =>  
$params['report_date'])),
     'body'                => $params['body'],
     'format'              => $params['input_format'],

     'oi_nodeapi_restrict_eid' =>  
oi_get_entity_eid($params['oi_restrict']),

     // some variable, but for our purposes static, information
     'uid'     => $user->uid,

     // misc stuff that is needed to make things function
     'status'  => 1,
     'promote' => 0,
     'sticky'  => 0,
   );

   // add in the taxonomy for the report type
   $node['taxonomy'] = array();
   foreach($params['terms'] as $term) {
     $tids = taxonomy_get_term_by_name($term);
     if (count($tids) != 1) {
       xmlrpc_error(14, t('Invalid report type -- returned !count  
terms for !term', array('!term' => $term, '!count' => count($tids))));
     }
     $tid_obj = $tids[0];
     $node['taxonomy'][$tid_obj->vid][$tid_obj->tid] = $tid_obj->tid;
   }
   if (!count($node['taxonomy'])) {
     delete ( $node['taxonomy'] );
   }

   // add in any attachments
   if (!empty($params['attachments'])) {
     $node['files'] = array();
     foreach ($params['attachments'] as $a_index => $a_info) {
       $file_temp = file_save_data($a_info['data'],  
file_directory_path() . '/' . $a_info['name'], FILE_EXISTS_RENAME);
       $node['files']['upload_' . $a_index] = array(
         'fid'         => 'upload_' . $a_index,
         'title'       => basename($file_temp),
         'description' => $a_info['name'],
         'filename'    => basename($file_temp),
         'filepath'    => $file_temp,
         'filesize'    => filesize($file_temp),
         'filemime'    => $a_info['mime'],
         'remove'      => 0,
         'list'        => 1,
       );
     }
   }

   // convert to an object
   $node_obj = (object) $node;

   // save it
   node_save($node_obj);

   // fix the user to the original user
   $user = $orig_user;

   // return the node id created
   return "created : " . $node_obj->nid;
}

?>

#------------------------ Perl ---------

#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;                   # handle command line parameters
use Date::Format;                   # provides date formatting
use File::Slurp qw( slurp );        # makes it easier to read a file
use XMLRPC::Lite;                   # communicate with the website
use Data::Dumper;                   # dispaly any error messages

# the directory to take files from
my $in_dir = '';
my $in_file = '';
GetOptions('indir=s' => \$in_dir, 'file=s' => \$in_file);
if ($in_dir eq '') {
     die("You must supply the '-indir' parameter\n");
}
if ($in_file eq '') {
     die("You must supply the '-file' parameter\n");
}

# two date formats we'll need
my $todays_date = strftime('%Y-%m-%dT00:00:00', @{[localtime()]});
my $rep_month = strftime('%Y-%m', @{[localtime()]});

# read in the 'processed.html' file
my $body = slurp($in_dir .'/' . $in_file);

# find all of the referenced images
my @imgs = ($body =~ m/\[inline:([-A-Za-z0-9_]+\.(?:png|gif|jpg))\]/g);

# start creating the submission object
my $submission = {
     'title'        => "Report - $rep_month",
     'report_date'  => $todays_date,
     'body'         => $body,
     'input_format' => 6, # should be: 'Markdown (full html)', but  
this doesn't work right now
     'oi_restrict'  => 'XXXX',
     'terms'        => [ 'XXXX', 'YYYY', 'ZZZZ', 'Report' ],
};

my $count = 0;
foreach my $file (@imgs) {
     my $fdata = slurp($in_dir .'/' . $file, 'binmode' => ':raw');
     $submission->{'attachments'}{"$count"} = {
         'name' => $file,
         'mime' => 'image/' . get_mime_type($file),
         'data' => $fdata,
     };
     $count++;
}

print "Submitting .. ";

my $xmlobj = XMLRPC::Lite
     ->proxy('http://www.example.com/xmlrpc.php')
     ->call('reports.submit', $submission);

if ($xmlobj->fault()) {
     print "error:\n", Dumper($xmlobj->fault()), "\n";
}
else {
     print $xmlobj->result(), "\n";
}

print "done\n";

##########

sub get_mime_type {
     my ($fname) = @_;
     my ($ext) = ($fname =~ m/\.(png|gif|jpg)$/);
     return {
         'png' => 'png',
         'gif' => 'gif',
         'jpg' => 'jpeg',
     }->{$ext};
}

__END__


The information in this e-mail is intended only for the person to whom it is
addressed. If you believe this e-mail was sent to you in error and the e-mail
contains patient information, please contact the Partners Compliance HelpLine at
http://www.partners.org/complianceline . If the e-mail was sent to you in error
but does not contain patient information, please contact the sender and properly
dispose of the e-mail.



More information about the development mailing list