Translating Kohana-modules in a convenient way? - php

I have been looking for a convenient way of making and maintaining translations of my Kohana-modules. I have played around with POEdit and have extracted all __()'s from my modules. Really like the way POedit works, and it's just to run a quick update to gather all new strings and save a new catalog later on. I could afterwards convert the po-files to PHP-arrays sort of...it seems a bit complicated with all steps.
I have seen this approach but I would rather not install tables and new modules for translations, I think this gets to complicated and "drupalish" ;-).
How do you managing localizations and translations on different languages in your Kohana-projects? Any hints would be much appreciated!

This is how I did it. First of all POEdit for Mac is very buggy and strange, unfortunately.
In POEdit, created a new catalog with correct path and __ as a keyword.
Run POEdit to extract all the strings.
After this I ran this simple PHP-script over the generated PO-file. The output from the script I pasted into the files in i18n-folder of the project.
$file = 'sv_SE.po';
$translations = array();
$po = file($file);
$current = null;
foreach ($po as $line) {
if (substr($line,0,5) == 'msgid') {
$current = trim(substr(trim(substr($line,5)),1,-1));
}
if (substr($line,0,6) == 'msgstr') {
$translations[$current] = trim(substr(trim(substr($line,6)),1,-1));
}
}
echo "<?php\n\n";
foreach ($translations as $msgid => $msgstr) {
echo '\'' . $msgid . '\' => \'' . $msgstr . "',\n";
}
echo "\n?>";
By using POEdit it's easy to maintain the project-localizations since it's syncing all the strings but just clicking "Update". I'll get a report of new and obsolete strings and can update the localizations in a few moments. Hope it helps someone.

Try this I18n_Plural module. I like how it handles plural forms, very simple and easy. There is a lot of examples in readme file (showing on a main module page).

Related

Iterate over SimpleXMLElement array and print items to separate text files

So I'm having a rough time with possibly a simple problem. I have a SimpleXMLElement array of objects (PDF data bytes). I'm trying to iterate over my array and have the code write out each chunk of PDF
data bytes to individual text files so I can write them to individual PDF files. My code is as follows:
$docfiles = $xml->EnvelopeStatus->EnvelopeID . "/" . $xml->EnvelopeStatus->DocumentStatuses->DocumentStatus->Name . '.txt';
$doctxt = fopen($docfiles,"w");
$docarr = array();
foreach($xml->DocumentPDFs->DocumentPDF as $post){
foreach ($post->PDFBytes as $docusigntxt) {
$docarr[] = $docusigntxt;
foreach ($docarr as $value) {
fwrite($doctxt,$value);
}
}
}
fclose($doctxt);
What am I doing wrong? Any suggestions would be greatly appreciated.
If you haven't already done so, it might be worth checking out the DocuSign SOAP API sample code that's available on GitHub: https://github.com/docusign/DocuSign-eSignature-SDK. What you're trying to accomplish is pretty straight-forward -- I imagine the PHP folder in the GitHub repository would contain a code snippet that shows you how to achieve your goal.
This was just a case of getting to know how to properly drill down into the SimpleXML syntax. This is what solved my problem. I skipped over creating the text files and created PDFs, which is what I wanted:
foreach($xml->DocumentPDFs->DocumentPDF as $value) {
$binary = base64_decode($value->PDFBytes);
file_put_contents($xml->EnvelopeStatus->EnvelopeID . "/" . $value->Name, $binary);
}
That's it.

Search for files dynamically in php

I basically want to search for a file on my computer. I know how to search but is there a fast way of searching a name and an extension without flooding my script with more than 2 for loops? the names (eg.. file,virus,node,misc) and the extensions will be added dynamically, Not through the source code.. the names will be in the thousands so i dont want to add them one by one, hence why i am doing it dynamically.
i was thinking:
foreach($names as $i){
if (file_exists($i.".exe" | $i.".py" | $i.".js" | $i.".html" | )){
//echo true or false}}
Like i said. I will be adding in extensions dynamically also. Would it be worth it having the code long with file_exists(20 thousand extensions) or just add them with a form?
Would it be a for loop inside another for loop?
If your code is on a linux server and you have the program 'locate', I would consider using that instead. It will save you a lot of load on your server and will return results a lot faster.
There is a way using the Spl Iterators.
The following example is taken from the documentation of RecursiveDirectoryIterator. It searches for a file called 'Yourfile.py':
$filename = 'Yourfile.py';
$directory = new RecursiveDirectoryIterator('path/to/search_root/');
$iterator = new RecursiveIteratorIterator($directory);
$regexiterator = new RegexIterator(
$iterator,
'/^' . preg_quote($filename) . '$/',
RecursiveRegexIterator::GET_MATCH
);
foreach($regexiterator as $fileinfo) {
var_dump($fileinfo);
}

php & recursive Iterator : finding a specific file and its path

I'm a newbie in SPL and recursiveIterator... So could you help me?
What I want to achieve :
I would like to find a file in a folders tree and i would like to obtain its path.
My folder tree could seems to be like this :
./ressources
./ressources/Images
./ressources/Images/Image01
./ressources/Images/Image02
./resources/Images/ImagesSub/Image03
./ressources/Docs
./ressources/Docs/Doc01
and so on...
I obtain the name of my File with sql query (warning : they never have an extension).
Now, i want to find the file's location by doing a recursive Iterator on './ressources' folder.
Then, when i've found the file, i would like to return the whole link './ressources/Folder/File'.
I've read Gordon's solution but it doesn't work, I tried only to echo something, but doesn't display anything.
Here is my code :
$doc_id = $bean->id;
$query = "SELECT a.document_revision_id FROM documents as a, document_revisions as b ";
$query .= "WHERE a.document_revision_id = b.id AND a.id = '" . $doc_id . "' LIMIT 1";
$results = $bean->db->query($query, true);
$row = $bean->db->fetchByAssoc($results);
$file_id = $row['document_revision_id'];
$ressources = './ressources/';
$iter = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($ressources, RecursiveDirectoryIterator::KEY_AS_FILENAME), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iter as $entry) {
if ($entry->getFilename() === $file_id){
echo '<script> alert('.$entry->getFilepath().');</script>';
}
}
(i know doing an alert into a echo is bullsh*t, but whith sugar it is quite difficult to display something
Specifications
I'm trying to do this in a SugarCrm CE 6.5.2 logic_hook and it's running on archlinux. And my PHP version is 5.4.6
It is really urgent, so I would be reaaaally happy if you could help me!!
Thanks by advance!
EDIT FROM 12/10/09 2pm:
What is my sugar project and why i can't get the pathname from my database
I created a custom field in Documents module called folder_name_c. You fill it with the name of the folder (under ressources) where you want to upload your document.
I want to allow the user to move the file uploaded from its ancient folder to new one when i edit the document.
When editing a document, I did a after_retrieve hook to permit the logic_hook to work when editing (before, it was just done for edit view)
So, if i get the $bean->folder_name_c, it pick up the field's content. If i try sql, it will pick the folder_name_c only after i click "save".
So, i don't have any clue to get my old folder_name to create an
$old_link = '.ressources/'.$old_folder.'/'.$file_id;
I can only create the
$new_link = '.ressources/'.$bean->folder_name_c.'/'.$file_id;
So, after a long time, i figured out that i could browse my ressources folder and my sub folders to find my file named $file_id and then create the $old_link
FYI, by creating a new custom field under studio in sugar, i gained a lot of time.
I don't want to pass my life on adding a custom_code calling database or else. this is URGENT and recursive iterator seems to be simple and quick.
There is no method such as getFilepath for the (Recursive)DirectoryIterator, just use $entry itself, when used in a string context it's casted to such one (à la __toString):
$file_id = 'test';
$ressources = './ressources/';
// [...]
echo '<script>alert('.$entry.');</script>'; // is casted to a string which contains the full path
// results in alerting ./resources/SubFolder/test
I tested it with the same structure and without extension.
So, I've found out how to use recursive iterators for my problem!
Here is my code :
$ressources = './ressources/';
$directoryIter = new RecursiveDirectoryIterator($ressources);
$iter = new RecursiveIteratorIterator($directoryIter, RecursiveIteratorIterator::SELF_FIRST);
$old_path = '';
$new_path = $ressources.$bean->folder_name_c.'/'.$file_id;
chmod($new_path,0777);
foreach ($iter as $entry) {
if (!$directoryIter->isDot()) {
if ($entry->getFileName() == $file_id) {
$old_path = $entry->getPathName();
chmod($old_path, 0777);
copy($old_path,$new_path);
}
}
}
So i succeed to get my file's origin path! :)
But as always, there is a problem:
I want to cut and paste my file from $old_path to $new_path (as you can see in my code). The copy here works well, but i don't know where i have to unlink() the old_path.. if anyone knows ...
(and if i wrote the copy in the wrong line, just tell me please! :D )

Find and replace in multiple files

OK, whats the best solution in php to search through a bunch of files contents for a certain string and replace it with something else.
Exactly like how notepad++ does it but obviously i dont need the interface to that.
foreach (glob("path/to/files/*.txt") as $filename)
{
$file = file_get_contents($filename);
file_put_contents($filename, preg_replace("/regexhere/","replacement",$file));
}
So I recently ran into an issue in which our web host converted from PHP 5.2 to 5.3 and in the process it broke our installation of Magento. I did some individual tweaks that were suggested, but found that there were still some broken areas. I realized that most of the problems were related to an issue with the "toString" function present in Magento and the now deprecated PHP split function. Seeing this, I decided that I would try to create some code that would find and replace all the various instances of the broken functions. I managed to succeed in creating the function, but unfortunately the shot-gun approach didn't work. I still had errors afterwards. That said, I feel like the code has a lot of potential and I wanted to post what I came up with.
Please use this with caution, though. I'd recommended zipping a copy of your files so that you can restore from a backup if you have any issues.
Also, you don't necessarily want to use this as is. I'm providing the code as an example. You'll probably want to change what is replaced.
The way the code works is that it can find and replace whatever is in the folder it is put in and in the sub folders. I have it tweaked so that it will only look for files with the extension PHP, but you could change that as needed. As it searches, it will list what files it changes. To use this code save it as "ChangePHPText.php" and upload that file to wherever you need the changes to happen. You can then run it by loading the page associated with that name. For example, mywebsite.com\ChangePHPText.php.
<?php
## Function toString to invoke and split to explode
function FixPHPText( $dir = "./" ){
$d = new RecursiveDirectoryIterator( $dir );
foreach( new RecursiveIteratorIterator( $d, 1 ) as $path ){
if( is_file( $path ) && substr($path, -3)=='php' && substr($path, -17) != 'ChangePHPText.php'){
$orig_file = file_get_contents($path);
$new_file = str_replace("toString(", "invoke(",$orig_file);
$new_file = str_replace(" split(", " preg_split(",$new_file);
$new_file = str_replace("(split(", "(preg_split(",$new_file);
if($orig_file != $new_file){
file_put_contents($path, $new_file);
echo "$path updated<br/>";
}
}
}
}
echo "----------------------- PHP Text Fix START -------------------------<br/>";
$start = (float) array_sum(explode(' ',microtime()));
echo "<br/>*************** Updating PHP Files ***************<br/>";
echo "Changing all PHP containing toString to invoke and split to explode<br/>";
FixPHPText( "." );
$end = (float) array_sum(explode(' ',microtime()));
echo "<br/>------------------- PHP Text Fix COMPLETED in:". sprintf("%.4f", ($end-$start))." seconds ------------------<br/>";
?>

Using PHP to write to .swf files

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.

Categories