Using PHP to write to .swf files - php

I was wondering how to basically edit a .swf file using php, to change a single variable or to change more. How would I go about doing this? Is there a way to edit it without knowing machine code?
If there is an example of how to do this, where can I find it?
Thanks!
Or, if there is an easier way to go about doing this, please let me know!

take a look at libming
php documentation at http://docs.php.net/manual/en/book.ming.php

With Actionscript, it's very simple to load external data: XML and JSON are two standardized ways to do it, and both are easily generated by PHP. What exactly are you trying to do?

The question is old, but since it happens to coincide with what I've been working on, I figured I would put something together in case others find it useful. The solution works for AS3 only. It let you to change the values of instance variables and constants.
Suppose you have the following class:
package pl.krakow.rynek {
import flash.display.Sprite;
public class Advertisement extends Sprite {
private var title:String = 'Euro 2012 LIVE!';
/* ... */
}
}
You want the var title to be something else. The code for doing so is as follow:
<?php
require_once 'flaczki/classes.php';
// parse the SWF file, decoding only those tags needed by the injector
$input = fopen("input.swf", "rb");
$parser = new SWFParser;
$injector = new AS3ConstantInjector;
$swfFile = $parser->parse($input, $injector->getRequiredTags());
$classConstants = array(
'pl.krakow.rynek.Advertisement' => array(
'title' => 'Free Beer!'
)
);
// inject the values and reassemble the file
$injector->inject($swfFile, $classConstants);
$output = fopen($outPath, "wb");
$assembler = new SWFAssembler;
$assembler->assemble("output.swf", $swfFile);
?>
The code should be self-explanatory. The SWF file is first parsed, modifications are made, and the in-memory structure is saved to file. AS3ConstantInjector.inject() expects as the second argument an array of arrays keyed by the qualified names of the classes you wish to modify. The arrays themselves hold the new values for each class, with the key as the variable/constant name.
To see The variables in a SWF file, use AS3ConstantExtractor:
<?php
require_once 'flaczki/classes.php';
$input = fopen("button.swf", "rb");
$parser = new SWFParser;
$extractor = new AS3ConstantExtractor;
$swfFile = $parser->parse($input, $extractor->getRequiredTags());
$classConstants = $extractor->extract($swfFile);
print_r($classConstants);
?>
The Flaczki classes can be downloaded at http://code.google.com/p/flaczki/downloads/list
You can find out more about the Flaczki framework at the project development blog at http://flaczkojad.blogspot.com/

check out the SWF-library in php

Instead of thinking how to generate swf files, do the opposite and let the internal behavior depend on external logic in a php script. This way you never need to (re)compile your swf.

Related

Use ob_start to avoid creating zip files and get their content

I have this code that creates a ".zip" file and inside it a ".xml" file obtained from a string.
As seen in the example later I get your information and convert it to base64 and hash.
The code is functional.
What I want now is to use "ob_start()" so as not to have to create the ".zip" file, I don't know if someone could help me with a basic example, greetings...
<?php
$content = '<?xml version="1.0"?><Catalog><Book id="bk101"><Author>Garghentini, Davide</Author><Title>XML Developers Guide</Title><Genre>Computer</Genre><Price>44.95</Price><PublishDate>2000-10-01</PublishDate><Description>An in-depth look at creating applicationswith XML.</Description></Book><Book id="bk102"><Author>Garcia, Debra</Author><Title>Midnight Rain</Title><Genre>Fantasy</Genre><Price>5.95</Price><PublishDate>2000-12-16</PublishDate><Description>A former architect battles corporate zombies,an evil sorceress, and her own childhood to become queenof the world.</Description></Book></Catalog>';
$route = './temp/';
$name = 'facturaElectronicaCompraVenta.xml.zip';
$file = "{$route}{$name}";
// CREATE ZIP
$zp = gzopen($file,'w9');
gzwrite($zp,$content);
gzclose($zp);
// READ ZIP
$fp = fopen($file,'rb');
$binary = fread($fp,filesize($file));
$res = [
'archivo' => base64_encode($binary),
'hashArchivo' => hash('sha256',$binary),
];
print_r($res);
First of all, the output buffer (ob...) functions don't accomplish anything related to files, they only capture the script output (e.g., echo 'Hello, World!).
If you want to keep using gzopen(), perhaps you can just provide a stream wrapper pointing to anything that isn't a physical file (I haven't investigated that option) but it looks easier to just switch to gzencode().

Parse XML file within laravel

I want to select a XML file from my computer to be parsed. The form works and I can use the Input::file('file'); function. However I want to parse this document by favour with uploading it only as temporary file. When I want to parse it I get errors like: "unable to parse from string". It seems that parser can't find the file. I tried two parsers: SimpleXML and XMLParser(from orchestral).
public function uploadFile(Request $ file){
$data =Input::file('file');
$informationdata = array('file' => $data);
$rules = array(
'file' => 'required|mimes:xml|Max:10000000',
);
$validator= Validator::make($informationdata, $rules);
if($validator->fails()){
echo 'the file has not the correct extension';
} else{
XmlParser::load($data->getRealPath());
}
I also tried to parse it after storing the file.
private function store($data){
$destinationPath = public_path('uploads\\');
$fileName = $data->getClientOriginalName();
$data->move($destinationPath,$fileName);
$xml = simplexml_load_file($destinationPath.$fileName);
}
Thanks in advance for helping.
When you say "parse" what do you mean? Find nodes? Delete nodes? Add nodes? Or only read nodes?
Because you can find and read with the SimpleXMLElement class but if you want to add or delete I suggest you to use DomDocument instead.
Using SimpleXMLElement, the construct would be:
$xml = new SimpleXMLElement($destinationPath.$fileName, null, true);
While the DomDocument would be:
$xml = new DomDocument('1.0', 'utf-8'); // Or the right version and encoding of your xml file
$xml->load($destinationPath.$fileName);
After you create the object, you cand handle all the document.
It is unknown, whether you want to validate some exiting xml-file on your computer or want to implement the ability for users to upload any xml file and write some logic to cope this task. However, this is not the point.
I would recommend you to use the built-in to PHP core simplexml_load_file() function which has helped me with the project. Because you will never get Laravel to parse xml into some decent understendable array or object to work with through Request $file injections etc. This is good to work with html-forms or json, not with xml or other formats.
That's why you should work with object which will be the result of (for example) such code:
$xml_object = simplexml_load_file($request->file('action')->getRealPath());
And then you'll need to verify every xml node and field by yourself, writing some logic as you lose the possibility of using built-in to Laravel Illuminate\Http\Request validate() method.

Phalcon - Create an new file instance

In phalcon you can get uploaded file with this piece of code
//Check if the user has uploaded files
if ($this->request->hasFiles() == true) {
//Print the real file names and their sizes
foreach ($this->request->getUploadedFiles() as $file){
echo $file->getName(), " ", $file->getSize(), "\n";
}
}
each $file is an Phalcon\Http\Request\File instance.
But what if I want to create an file instance from an existing file on the server, how can I do that?
What I tried is this:
new Phalcon\Http\Request\File(array($fileDir));
But it returns an instance with empty properties.
any help would be appreciated :D
As per the documentation of that class I think the constructor does not expect an array. So just leave out the array( ) that you are passing to the constructor and you should be fine. Disclaimer: I did not check out the code and rely on the documentation being proper here.
Code example:
new Phalcon\Http\Request\File($fileDir);
But what if I want to create an file instance from an existing file on the server, how can I do that?
This class is designed to work with $_FILES superglobal, so as for me you are using wrong tool. I would create your own wrapper for using files that are already on server, or go for SplFileObject.
Anyway, how should parameter array look like you may be able to anderstand from here starting at line 74+ and it pretty reflects $_FILES structure.

Replace HTML elements content of a PHP/HTML file with PHP

Problem
I'm trying to edit HTML/PHP files server side with PHP. With AJAX Post I send three different values to the server:
the url of the page that needs to be edited
the id of the element that needs to be edited
the new content for the element
The PHP file I have now looks like this:
<?php
$data = json_decode(stripslashes($_POST['data']));
$count = 0;
foreach ($data as $i => $array) {
if (!is_array($array) && $count == 0){
$count = 1;
// $array = file url
}
elseif (is_array($array)) {
foreach($array as $i => $content){
// $array[0] = id's
// $array[1] = contents
}
}
}
?>
As you can see I wrapped the variables in an array so it's possible to edit multiple elements at a time.
I've been looking for a solution for hours but can't make up my mind and tell what's the best/possible solution.
Solution
I tried creating a new DOMElement and load in the html, but when dealing with a PHP file, this solution isn't possible since it can't save php files:
$html = new DOMDocument();
$html->loadHTMLFile('file.php');
$html->getElementById('myId')->nodeValue = 'New value';
$html->saveHTMLFile("foo.html");
(From this answer)
Opening a file, writing in it and saving it comes is another way to do this. But I guess I must be using str_replace or preg_replace this way.
$fname = "demo.txt";
$fhandle = fopen($fname,"r");
$content = fread($fhandle,filesize($fname));
$content = str_replace("oldword", "newword", $content);
$fhandle = fopen($fname,"w");
fwrite($fhandle,$content);
fclose($fhandle);
(From this page)
I read everywhere that str_replace and preg_replace are risky 'caus I'm trying to edit all kinds of DOM elements, and not a specific string/element. I guess the code below comes close to what I'm trying to achieve but I can't really trust it..
$replace_with = 'id="myID">' . $replacement_content . '</';
if ($updated = preg_replace('#id="myID">.*?</#Umsi', $replace_with, $file)) {
// write the contents of $file back to index.php, and then refresh the page.
file_put_contents('file.php', $updated);
}
(From this answer)
Question
In short: what is the best solution, or is it even possible to edit HTML elements content in different file types with only an id provided?
Wished steps:
get file from url
find element with id
replace it's content
First of all, you are right in not wanting to use a regex function for HTML parsing. See the answer here.
I'm going to answer this question under the presumption you are committed to the idea of retrieving PHP files server-side before they are interpreted. There is an issue with your approach right now, since you seem to be under the impression that you can retrieve the source PHP file by the URL parameter - but that's the location of the result (interpreted PHP). So be careful your structure does what you want.
I am under the assumption that the PHP files are structured like this:
<?php include_some_header(); ?>
<tag>...</tag>
<!-- some HTML -->
<?php //some code ?>
<tag>...</tag>
<!-- some more HTML -->
<?php //some code ?>
Your problem now is that you cannot use an HTML reader (and writer), since your file is not HTML. My answer is that you should restructure your code, separating templating language from business logic. Get started with some templating language. Afterwards, you'll be able to open the template, without the code, and write back the template using a DOM parser and writer.
Your only alternative in your current setup is to use the replace function as you have found in this answer. It's ugly. It might break. But it's definitely not impossible. Make backups before writing over your own code with your own code.

Drupal 6 Programmatically adding an image to a FileField

How do I programmatically add an image to a file field? I have an url/filepath of an image that I wish to upload. I have tried the following:
$newNode->field_profile_image[0]['value'] = 'http://www.mysite.com/default.gif';
But it does not seem to work.
I have also tried:
$newNode->field_profile_image[0]['value'] = 'sites/default/files/default.gif';
The file does not need to be external to the webiste. I am happy to have it anywhere on the site in question.
You're probably going to have to use hook_nodeapi to set this correctly. You're going to want to modify it under the "Insert" operation. Make sure that you resave the node after you've added the required fields.
Drupal wants to map the image to an entry in the file table, so simply setting the URL will not work. First off, if it's a remote file, you can use the function listed in the Brightcove module on line 176, brightcove_remote_image, to grab the image and move it into your local directory.
Once the remote image is moved into place, you need to save it into the files table and then properly configure the node's property. I've done it in this method:
////// in NodeAPI /////
case "insert":
$node->field_image[0] = _mymod_create_filearray($image_url);
node_save($node);
This writes the files record, and then returns a properly formatted image array.
///// mymod_create_filearray /////
function _mymod_create_filearray($remote_url){
if ($file_temp = brightcove_remote_image($remote_url)) {
$file = new stdClass();
$file->filename = basename($file_temp);
$file->filepath = $file_temp;
$file->filemime = file_get_mimetype($file_temp);
$file->filesize = filesize($file_temp);
$file->uid = $uid;
$file->status = FILE_STATUS_PERMANENT;
$file->timestamp = time();
drupal_write_record('files', $file);
$file = array(
'fid' => $file->fid,
'title' => basename($file->filename),
'filename' => $file->filename,
'filepath' => $file->filepath,
'filesize' => $file->filesize,
'mimetype' => $mime,
'description' => basename($file->filename),
'list' => 1,
);
return $file;
}
else {
return array();
}
}
And that should do it. Let me know if you have any questions.
Check out my Answer to a similar question from a while ago, where I describe how we did pretty much exactly what you need (if I understood the problem correctly).
The main point is to use the field_file_save_file() function from the filefield module for attaching a file (during hook_nodeapi, on operation presave), which will do most of the work for you (more or less what jacobangel's '_mymod_create_filearray()' tries to do, but more tuned to filefields needs, including validation).
This assumes that the file already exists on the servers filesystem somewhere (usually in /tmp), and will correctly 'import' it into Drupal, with corresponding entries in the files table, etc. If you want to import files from remote URLs, you'll need to add the additional step of fetching them as a separate task/functionality first.
As mentioned in the answer linked above, I ended up using the code from the Remote File module as an example for a custom implementation, as we needed some project specific additions - maybe you can use it more directly for your purposes.
using nodeapi you should be able to set the value like you are trying to in the code example, but only or local images. You will most likely need to have the images in the "files" folder in your drupal install, but if that is set up everything else should work without a hitch. When using the nodeapi all the things that would normally happen when you save a node using a form would happen, such as updating the files table etc.
If you wanted to pull the image from the remote site using a module like feeds make it possible to pull the remote images, and create nodes. Depending on your use case you could either use it, or take a look at how it pulls the images and maps them to local files.
What you try will not work. Drupal offers no way to handle remote files, without the use for a module. AFAIK there is no module that offers an API to upload remote files trough.
Here is a quick example taken from one of my projects.
$node = new stdClass;
$node->title = 'Example Callout';
$node->type = 'wn_hp_callout';
// Search examples directory to attach some images.
$callouts_dir = drupal_get_path('module', 'wn_hp_callout').'/imgs/examples/';
$callout_imgs = glob($callouts_dir.'*.{jpg,jpeg,png,gif}',GLOB_BRACE);
// Now add the images and provide imagefield extended additional text.
foreach($callout_imgs as $img) {
$img_info = pathinfo($img);
$field = field_file_save_file($img, array(), file_directory_path() .'/example_callouts/');
if( !isset($field['data']) ) {
$field['data'] = array();
}
$field['data']['title'] = ucwords(str_replace('_',' ',$img_info['filename']));
$field['data']['alt'] = 'This is alt text.';
$node->field_wn_hp_callout_image[] = $field;
}
$node = node_submit($node);
node_save($node);

Categories