Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Tuesday, 20 March 2012

Creating a Flash app with a PHP script to upload webcam images to Wordpress

This month's challenge is to build a flash application that is able to take a photo, upload it, and insert it into a wordpress post so that posts can be easily edited later. (AND ALL WITHIN ONE OR TWO WEEKS!) I am building this for a museum exhibition that has just opened and it is going to be a kiosk with a large touchscreen that will be moved around from venue to venue, collecting photos of people's pockets and stuff, and then digitally archiving them, while allowing one to also tag it collaboratively after that.

I am not a PHP developer although I understand PHP sufficiently well in order to make it do what I need to do, so if anyone more technically inclined can tell me if this is an efficient way to proceed with this, I would be glad to hear if there are other ways to do this!

1. Uploading Image to server


I used php's mktime to generate a unique number for each photo's filename. Each photo was encoded using JPGEncoder in flash, and then using urlLoader I sent it to my php file, which saved it onto my server with a filename derived from the mktime number.

After that, the posts were pushed to wordpress with the help of Incutio XML-RPC Library for PHP. You can post to wordpress with a php script with the help of xml-rpc. The following examples are my own mashup of bits and pieces found online, the most instructive guide being this entry: WordPress XMLRPC – Posting Content From Outside WordPress Admin Panel

<?php
if(isset($GLOBALS["HTTP_RAW_POST_DATA"])){
 
 $jpg = $GLOBALS["HTTP_RAW_POST_DATA"];
 $img = $_GET["img"];
 $filename = "images/booth_" . mktime(). ".jpg";
 file_put_contents($filename, $jpg);
 
require_once("IXR_Library.php.inc");
 
$client->debug = true; //Set it to false in Production Environment 
$title='Pocket No. '.mktime(); // $title variable will insert your blog title 
$body='<img src="http://yourdomain.org/'.$filename.'">'; // $body will insert your blog content (article content)
$category="pocket"; // Comma seperated pre existing categories. Ensure that these categories exists in your blog.
$keywords="keyword1, keyword2, keyword3"; // Comma Seperated keywords
$customfields=array('key'=>'Author-bio', 'value'=>'Author Bio Here'); // Insert your custom values like this in Key, Value format
 
    $title = htmlentities($title,ENT_NOQUOTES,$encoding);
    $keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding);
 
    $content = array(
        'title'=>$title,
        'description'=>$body,
        'mt_allow_comments'=>0,  // 1 to allow comments
        'mt_allow_pings'=>0,  // 1 to allow trackbacks
        'post_type'=>'post',
        'mt_keywords'=>$keywords,
        'categories'=>array($category),
  'custom_fields' =>  array($customfields)
    );
 
// Create the client object
$client = new IXR_Client('http://yourdomain.org/xmlrpc.php');
$username = "admin"; 
$password = "password"; 
$params = array(0,$username,$password,$content,true); // Last parameter 'true' means post immediately, to save as draft set it as 'false'
 
// Run a query for PHP
if (!$client->query('metaWeblog.newPost', $params)) {
    die('Something went wrong - '.$client->getErrorCode().' : '.$client->getErrorMessage());
}
else
    echo "Article Posted Successfully";
    
} else{
 echo "Encoded JPEG information not received.";
}
?>

2. Retrieving images to put into gallery


This php script will retrieve the last 10 entries in your wordpress and help format them into an xml sheet that you can use in flash to display wordpress entries and images in a flash gallery.

<?php
set_time_limit(0);
require_once("IXR_Library.php.inc"); 
// Echo the header (XML)
header("Content-Type: application/xml;charset=ISO-8859-1");
echo '<?xml version="1.0" encoding="ISO-8859-1"?>' . "\r\n";
echo "<GALLERY>\r\n"; 

// Prepare the XML file
$client->debug = true; // Set it to false in Production Environment
 
// Create the client object
$client = new IXR_Client('http://artsciencepocketbooth.org/xmlrpc.php');
$username = "admin"; 
$password = "password"; 
$params = array(0,$username,$password,10); // Last Parameter tells how many posts to fetch
 
// Run a query To Read Posts From Wordpress
if (!$client->query('metaWeblog.getRecentPosts', $params)) {
    die('Something went wrong - '.$client->getErrorCode().' : '.$client->getErrorMessage());
} 
$myresponse = $client->getResponse();
$i=0; ?>

<?php 
//foreach ($myresponse as $key => $value)
foreach ($myresponse as $res)
{ 
 
  if($res['post_status']!="draft"){
   //$times = new IXR_Date(); ?>
     <image id ='<?php echo $i+1; ?>' postid='<?php echo $res['postid']; ?>' title='<?php echo $res['title']; ?>' keywords='<?php echo $res['mt_keywords']; ?>'/>
<?php $i++; } } ?>
<?php echo "</GALLERY>"; ?>


The resulting XML file will look like this:
Screen shot 2012-03-21 at PM 08

3. Tagging images in gallery




PHP: Creating automatic XML Sheet from ALL images within a folder

If you need to create an XML sheet from all the photos within one folder, this is a script you can use to create one! It will include any image with a image-related file extension. This is my script which I have customised for my own needs based on notes and tutorials found online.

<?php
// Set which extensions should be approved in the XML file
$extensions = array
(
  'jpg', 'JPG',
  'png', 'PNG',
  'gif', 'GIF',
  'bmp', 'BMP'
);
 
// Echo the header (XML)
header("Content-Type: application/xml;charset=ISO-8859-1");
 
// Prepare the XML file
echo '<?xml version="1.0" encoding="ISO-8859-1"?>' . "\r\n";
echo "<GALLERY>\r\n";
 
// Get the files from the current directory
if (file_exists ("./"))
{
  if (is_dir ("./"))
  {
    $dh = opendir ("./") or die (" Directory Open failed !");
    
    // Prepare the images array
    $imgs = array();
    while ($file = readdir ($dh))
    {
      // Only get the files ending with the correct extension
      if ( in_array( substr($file, -3), $extensions ) )
      {
        array_push($imgs, $file);
      }
    }
  Closedir ($dh);
  }
  
  // Sort the array
  sort($imgs);
  
  foreach ($imgs as $img)
  {
    // Return all images in XML format
    echo ('   <image FULL="/images/' . $img . '" THUMB="/images/' . $img . '" />');
    echo "\r\n";
  }
}
echo "</GALLERY>";
?>



OOP & PHP?


there is an interesting article here that argues for OOP in PHP. i admit even in flash sometimes when doing something quick dirty for example i would use global code instead instead of encapsulation. but i guess i find the analogies arguing in favour of OOP rather interesting.

Monday, 9 January 2012

Mediawiki Lockdown - How to make your wiki private


For some years now I have been using a couple of private wikis for storing and sorting short notes on topics and interests.

Wikicliki - general wiki
Design Patterns - design and scripting wiki (for my students)
Disukowiki - language wiki

Lately there have been some issues with spam bots which seem to be getting smarter but even more bizarre, creating generic account names of the same type, and generating or writing over my pages with what looks a lot like actual paragraphs of useful information about random irrelevant topics (examples being: homopathy, ugg boots, weather, self-confidence mastery, etc) sometimes with no outbound links. Why do the spambots do this, it is still a complete mystery to me. It serves no purpose (not even SEO-wise for them) except to be a real pain in the ass to the wikisysop.

What makes me sad is the abuse of the system that actually has the potential of providing open space for some really interesting things, so I almost find it a pity to close it up. Some years back, once there was someone who posted on my wiki saying they were doing an experiment in which they stored chunks of (gibberish/encoded) data over a number of open wikis.

They set up anonymous accounts on people's open wikis (like mine), and posted these encrypted chunks of data in text form. In posting these fragments of the file online, their experiment/goal was to create a system in which people could transmit a really large and encrypted file to someone else. The recipient would have to locate and visit all these wikis to find the numerous segments of encrypted data, and then recompile it together with their prearranged encryption key to get the original huge file. A brilliant idea, although perhaps it would be a bit tedious in practice.

On that bittersweet note:
If you haven't edited your wiki's settings yet, do this now. Add this to LocalSettings.php:

# Disable anonymous editing
$wgGroupPermissions['*']['edit'] = false;

# Disable editing by ALL users
$wgGroupPermissions['user']['edit'] = false;

# Enable editing by ONLY sysops
$wgGroupPermissions['sysop']['edit'] = true;

# Prevent new user registrations except by sysops
$wgGroupPermissions['*']['createaccount'] = false;

After doing this, make sure you open up your FTP browser and chmod LocalSettings.php to 600. Duplicate a copy of LocalSettings.php and rename it to LocalSettings_date.php so that in case something unexpected happens you still have a backup of LocalSettings.php from when it was still alright...

Picture 23


You can look at the Mediawiki guide to Preventing Access to see more options on how you can tailor the privacy settings (for example, you could set it so that only users with accounts of a certain age, like say a few weeks, can create new pages).