Transliterate text from PHP to JavaScript - javascript

INTRODUCTION
I am working on personal project and using Symfony3.
In order to upload files i am using OneUpUploaderBundle.
And I am not accepting file name that consists of characters with accents, Cyrillic characters, etc.
In order to do so - I am using function from CODE section
TARGET
I would like to use PHP function in CODE section in JavaScript!
CODE
// transliterate text
public function transliterateText($input_text)
{
$input_russian = transliterator_transliterate('Russian-Latin/BGN', $input_text);
$input_german_french = transliterator_transliterate('Any-Latin; Latin-ASCII', $input_russian);
$input_baltic = iconv('UTF-8', 'ASCII//TRANSLIT', $input_german_french);
$transliterated_text = preg_replace('/[^a-zA-Z_0-9\(\)\n]/', '_', $input_baltic );
$transliterated_text = strtolower($transliterated_text);
return $transliterated_text;
}
EXAMPLE
input: "12345 Rūķīši Проверка äöüß àâæçéèêëïîôœùûüÿ.txt"
output: "12345_rukisi_proverka_aouss_aaaeceeeeiiooeuuuy.txt"
QUESTION
I did not found many information about this problem on the Internet.
May be it is not a good idea to use JavaScript for this task...
Or maybe I should create service in Symfony3, that is accessible through AJAX and returns transliterated text instead?
CONCLUSION
Please advise.
Thank You for your time and knowledge.
UPDATE
I would like to use this function in JavaScript in order to show user what the filename would look like when on the server. (File names are going to be transliterated on server anyway). At the moment I am sending (in the UploadListener) following information for each file [{'error':'none'}{'orig':'my file name.txt'}{'t13n':'my_file_name.txt'}]. I would like to send as little as possible informātion from server to browser. So if there was "translation" of the CODE I would need only to send error for each file...

Related

how to fix yandex api code leak in twitter bot?

I'm a beginner in programming and I'm developing a bot on node-red in the ibm cloud, and I've had problems with the return of the yandex translation API. It returns part of the api code in the tweets, which is not pleasant at all.
The api of yandex allows the api to return in json or xml, I tried both and I could not solve the problem. The bot in question has other api's in use and I was able to configure them normally, something that does not occur with the result of that, which would be the final result for the tweet to be released.
to send the translation to be made use the following request in a function of node red:
var translate = msg.method ='GET';
msg.url = "https://translate.yandex.net/api/v1.5/tr/translate?key= *API KEY* &text=" + recipe + "&lang=pt"
return [msg,null];]
in the next block, and the last one before sending the message, I'm using something like:
var yandex= msg.payload;
yandex = 'a' + msg.payload.text;
return msg;
and this makes me return something like this in the public tweet
"<?xml version="1.0" encoding="utf-8"?>
< Translation code="200" lang="en-pt"><text>é uma receita com Estilo grego Desfrutar de sua comida!</text>< / T"
hope to remove all this code that is being sent to output and only send the translation to the tweet, which is what is inside .
Forgive me code redundancies, but I do not know javascript fully and my college is teaching languages a bit old, like pascal.
You can perform the translation without writing a single line of code. This is the power of Node-RED. All you need is to send a properly formatted payload to an http request node. In the configuration dialog of this node tick the option Append msg.payload as query string parameters. You will get the translation by extracting msg.payload.text.
The payload to send to the http request has to be structured as follows:
{
"key": "you key",
"lang": "en-pt",
"format": "plain",
"text": "Life is like a game"
}
The code you posted has syntax errors and will not produce the output you want.
I recommend you to study a little bit more Node-RED and ask questions their forum in case you did not understand what is explained above.

Python: Retrieve post parameter from javascript button

I am programming in python a script to obtain statistical data of the public schools of the city in which I live. With the following code I get the source code of a page that shows, by pages, the first 100 results of a total of 247 schools:
import requests
url = "http://www.madrid.org/wpad_pub/run/j/BusquedaAvanzada.icm"
post_call = {'Public title': 'S', 'cdMuni': '079', 'cdNivelEdu': '6545'}
r = requests.post(url, data = post_call)
The page can be viewed here.
On that page there is a button that activates a javascript function to download a csv file with all 247 results. I was thinking of using Selenium to download this file, but I have seen, using Tamper Data, that when the button is pressed a POST call occurs, in which the parameter codCentrosExp is sent with the codes of the 247 colleges. The parameter looks like this:
CodCentrosExp = 28077877%3B28077865%3B28063751%3B28018392%3B28018393%...(thus up to the 247 codes)
This makes my work easier, since I do not have to download the csv file, open it, select the code column, etc. And I could do it with Tamper Data, but my question is: how can I get that parameter with my Python script, without having to use Tamper Data?
I finally found the parameter in the page's source code, and extracted them as follows:
schools = BeautifulSoup(r.content, "lxml")
school_codes = schools.findAll(Attrs = {"name": "codCentrosExp", "value": re.compile("^.+$")})[0]["value"]
school_codes = school_codes.split(";")
Anyway, if anyone knows how to respond to the original question, I would be grateful to know how it could be done.

Converting PHP object to JSON object using only Javascript

I am making a mobile app with Phonegap and using Wordpress as a backend. I am using Advanced Custom Fields with a Google Maps post field which returns a PHP object to the app using JSON API. My Wordpress backend sends a normal JSON object to the app, but inside that object is where a stringified PHP object is returned.
I need to convert the PHP object to a JSON object somehow on the client side(the app which is not in Wordpress). I have looked at other answers that say to use json_encode for this but my problem is that the app is just HTML/Javascript and no PHP. Is there a way to use PHP code in the middle of a Javascript function to do this? Or would it be better to change the backend so that it returns a JSON object instead of a PHP object in the first place? If so, how do I do that?
My experience in PHP is still somewhat limited so any help is appreciated.
edit: To clarify a bit more, I am using Wordpress on a separate domain from my Phonegap app and only using the JSON API plugin on the Wordpress end. I am then using jQuery Ajax calls to retrieve data from the Wordpress backend.
Also the returned PHP object looks like this: a:3:{s:7:\"address\";s:48:\"8915 W 159th St, Orland Hills, IL, United States\";s:3:\"lat\";s:17:\"41.60111599999999\";s:3:\"lng\";s:11:\"-87.8364575\";}
Another way I just thought of as well, would it be possible to just leave it as a PHP object and still read out the values from it somehow? I don't NEED it to be a JSON array, I just need a way to read the individual elements in the array in one way or another.
Here is also a tiny snippet of the JSON returned to clarify what I'm talking about.
"custom_fields": {
"location": [
"a:3:{s:7:\"address\";s:48:\"8915 W 159th St, Orland Hills, IL, United States\";s:3:\"lat\";s:17:\"41.60111599999999\";s:3:\"lng\";s:11:\"-87.8364575\";}"
]
}
That of course isn't the entire JSON object but it gives you an idea of what I'm dealing with.
I know you have a solution that works on the front end, but I still think it'd be better to fix this on the server.
Based on our conversation in the comments, I've had a closer look the code in the WordPress forum. The problem seems to be that the location field is an array of strings, not just a string. maybe_unserialize (and is_serialized, which it uses) don't handle arrays. Here's the updated code, which you should be able to drop into your theme's functions.php. I did a quick test, and it works for me.
class unserialize_php_arrays_before_sending_json {
function __construct() {
add_action( 'json_api_import_wp_post',
array( $this, 'json_api_import_wp_post' ),
10,
2 );
}
function json_api_import_wp_post( $JSON_API_Post, $wp_post ) {
foreach ( $JSON_API_Post->custom_fields as $key => $custom_field ) {
if (is_array($custom_field)) {
$unserialized_array = array();
foreach($custom_field as $field_key => $field_value) {
$unserialized_array[$field_key] = maybe_unserialize( $field_value );
}
$JSON_API_Post->custom_fields->$key = $unserialized_array;
}
else {
$JSON_API_Post->custom_fields->$key = maybe_unserialize( $custom_field );
}
}
}
}
new unserialize_php_arrays_before_sending_json();
If you're using a JSON API to retrieve the data, then why don't you deliver the data in JSON format to your app? Otherwise you seem to remove much of the point of using an API in the first place... You could of course parse that string in JavaScript if you really want to but that's a very ugly and error prone solution.
The JSON API plugin does seem to use JSON:
https://wordpress.org/plugins/json-api/screenshots/
I need to convert the PHP object to a JSON object somehow on the client side(the app which is not in Wordpress).
This bit here leaves me confused. You do not have PHP objects on the client-side, PHP is a back-end technology. What is returned to the client is a string which can be HTML, XML, JSON, plaintext on any other form of encoding.
That said, saying you have an object $obj in PHP, you could pass it to your front-end application creating an end-point retrieve_object.php and in there:
echo json_encode($obj);
So long as that is the only thing your are outputting, you lient-side app can make a request (Eg: AJAX) to retrieve_object.php and get the json object.
BUT , and this is important (!) in doing so you serialize object properties. You will lose any PHP object method. If any object property is an object itself (EG: A DB Connection) then this will be lost too.
Hope this helps!

How to validate Stock Market data

Honestly, I am not an expert & right now very much confused about how to even state my problem...so please forgive my lack of knowledge and this long confusing question.
I was assigned a project today where the clients are displaying stock market's info on their page (image attached below). And when you click on any one of the buttons (for example, NASDAQ) more info is displayed in a pop-up box.
They are using onClick() to send the whole string to this third party to collect the data. Here is the HTML code for NASDAQ link:
<li>
<a href="#" onClick="open('https://app.quotemedia.com/quotetools/clientForward?symbol=^NASD&targetURL=http://app.quotemedia.com/quotetools/popups/quote.jsp?webmasterId=99944&locale=en_US','miniwin','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,width=550,height=270,top=20,left=0'); return false;">
NASDAQ
<span id="imageNASDAQ"></span>
<span id="valueNASDAQ" class="share_value"></span>
<span id="textNASDAQ"></span>
</a>
<script type="text/javascript" src="/getStockInfo.php?Stocks[NASD]=NASDAQ"></script>
</li>
And then in getStockInfo.php file they are collecting the data as a JSON string and then parsing it. Here's how they are collecting the data:
<?php
if (array_key_exists("Stocks", $_GET)) {
foreach($_GET['Stocks'] as $symbol=>$stock) {
print file_get_contents("https://app.quotemedia.com/quotetools/jsVarsQuotes.go?webmasterId=99944&symbol=$symbol");
?>
So far pretty simple. But now the client wants to do some
"user input validation"
"Only accept 4 symbols: SP500, SPX, DOW & NASDAQ"
This is where I am getting confused. From their code (HTML part) looks like everything is hard coded (open('...symbol=^NASD...'); or open('...symbol=^SPX...'); or open('...symbol=^DJI...');) and each button/link is sending specific Stock symbol's info to the getStockInfo.php file (src="/getStockInfo.php?Stocks[NASD]=NASDAQ" or src="...Stocks[SPX]=SP500" or src="...Stocks[DJI]=DOW") where the stock quotes are being fetched. There is absolutely NO way my client's users can provide any other stock symbols through the site to change the display, the only way to manipulate the symbols are by changing the code itself.
BUT, my client wants to implement these above 2 conditions in the code anyhow. And I am not sure how to do this.
Not sure if I was able to explain my problem properly :( But I really need some help. Also I'm sorry for not being able to provide any link to the actual page here. Thank you so much for reading my confusing post and investing your time!! :)
Here's a proof of concept:
if (array_key_exists("Stocks", $_GET)) {
$stocks = array_filter($_GET['Stocks'], 'filterStocks');
foreach ($stocks as $symbol => $stock) {
print file_get_contents(…);
}
}
function filterStocks($symbol) {
return in_array(
$symbol,
array('SP500', 'SPX', 'DOW', 'NASDAQ')
)
}
Now getStockInfo.php will only return data for the four symbols. If you need that configurable on an individual user basis, a simple solution would be to do change the filterStocks function and callback to
function filterStocksForLoggedInUser($symbol) {
return in_array($symbol, getAllowedSymbolsForUser());
}
function getAllowedSymbolsForUser()
{
$permissions = include '/path/to/permissions/file.php';
return isset($permissions[$_SESSION['username']])
? $permissions[$_SESSION['username']]
: array();
}
}
and then in the permissions file put
return array(
'Walahh' => array('SP500', 'SPX', 'DOW', 'NASDAQ'),
'JohnDoe' => array('SP500', 'GOOG')
);
Note 1: the above assumes you have some sort of way to identify users, here $_SESSION['username']. Change that with whatever you are using and adjust the permission file accordingly.
Note 2: the permissions file will be read each time from disk. Disk I/O is usually slow, so you might want to consider moving the permissions to someplace faster.
Note 3: this is just a proof of concept. It's very pragmatic. You can certainly improve the design and structure, but I guess it's good enough to illustrate how to approach the problem.

Dumbed down Powershell web client function to let me post form data easily

Ive been using an Internet Explorer automation script found here:
http://www.pvle.be/2009/06/web-ui-automationtest-using-powershell/
That lets me easily post form data using commands (functions) like this:
NavigateTo "http://www.websiteURI/"
SetElementValueByName "q" "powershell variable scope"
SetElementValueByName "num" "30"
SetElementValueByName "lr" "lang_en"
ClickElementById "sb_form_go"
The above would let me post values to elements and click to submit the form.
I would like to do the equivalent with Powershell's web client using helper functions. I haven't found such a script. The closest I could find was The Scripting Guys, Send-WebRequest:
http://gallery.technet.microsoft.com/scriptcenter/7e7b6bf2-d067-48c3-96b3-b38f26a1d143
which I'm not even sure it does what I expect (since there's no working examples showing how to do what I want).
Anyway, I'd really appreciate some help to get me started to do the equivalent of what I showed up there with working examples (as simple as possible). A bonus would be to also be able to get a list of element names for a URI in order to know what form elements I want to submit.
PS: I also need to be able to specify user-agent and credentials; so, examples with these included would be ideal.
Have you taken a look at the Invoke-WebRequest commmand? (requires powershell 3.0 or above) I believe the following would work for submitting the data
#POSTing data
Invoke-WebRequest http://www.websiteURI/ `
-UserAgent 'My User Agent' `
-Credential $cred `
-Method Post `
-Body #{
q = 'powershell variable scope'
num = 30
lr = 'lang_en'
}
For your bonus, the result of Invoke-WebRequest contains a collection of the InputFields on the page, which you can use to get a list of form elements to set.
#List input elements
Invoke-WebRequest http://www.websiteURI/ | select -ExpandProperty InputFields

Categories

Resources