Can user's custom JavaScript on MediaWiki call a Lua module? - javascript

On MediaWiki wikis each user has a user JavaScript page they can put code in, much like GreaseMonkey but without extensions. Such as at User:YourUsername/vector.js
MediaWiki has also had an embedded Lua, called Scribunto, for a little while now.
I know Lua modules can be called from MediaWiki templates, and I suppose that's their main use. But Googling and hunting around the MediWiki docs I can't find whether there's a way to call a Lua module from your user JavaScript.
(I need to map names of languages to language codes in my JS and there's a Lua module to do just that without me duplicating the code (mainly data) in a second language.)

You can't do this directly, because JS runs on the client and Lua on the server. What you can do is to use the MediaWiki API from JS to invoke the module. Specifically using the expandtemplates API module.
For example, if you wanted to call the function h2d from Module:Hex with the parameter FF ({{#invoke:hex|h2d|FF}} in wikitext) and alert the result, then the JS would look like this:
var api = new mw.Api();
api.get( {
action: 'expandtemplates',
text: '{{#invoke:hex|h2d|FF}}'
} ).done ( function ( data ) {
alert(data.expandtemplates['*']);
} );
And for the OP's specific case, running on the English Wiktionary:
var langName = 'Esperanto';
(new mw.Api()).get({
action: 'expandtemplates',
format: 'json',
prop: 'wikitext',
text: '{{#invoke:languages/templates|getByCanonicalName|' + langName + '|getCode}}'
}).done(function(data) {
alert('Language name: ' + langName + '\nLanguage code: ' + data.expandtemplates.wikitext);
});
(prop: 'wikitext' avoids a warning from the API and lets you access the result as data.expandtemplates.wikitext rather than the slightly mystifying data.expandtemplates['*']. Otherwise there's no difference.)

Related

How to use Python function with JavaScript

I have a JavaScript file that is used for a google chrome extension, Also I have a Python file which has functions in it, only for the example let's imagine that in the python file we have a function like so
external.py
def name(x)
return "your" + x
So I want to call this function through JavaScript and get the return value inside of JavaScript, so if the Python file named external.py and the JS file named index.js for example, so the code will JS be something like that
index.js
data = "external.py".name("John") //(It doesn't have to be like that, just for the example)
I've tried using ajax but it does not work (I've tried to import jquery way too many times, but it doesn't seem to work) maybe because it's a google chrome extension.
Also, I've tried to use fetch but I have no idea how to write it exactly and if it's impossible with fetch.
I am new to JS though, so go easy with me.
Use this code.
Do ajax call in your js code.
It may help you.
$.ajax({
type: "POST",
url: "~/pythoncode.py",
data: { param: text}
}).done(function( o ) {
// do something
});
Or you can ref to this link for js with python work https://pyscript.net/

JSON get Javascript from API, but I want to get from my own work

So currently I have a code that get's random quotes from https://forismatic.com/en/api/ , using this code in my main.js file:
$.ajaxSetup({
cache: false,
"error": function() {
init()
}
});
function init () {
$.getJSON('https://cors-anywhere.herokuapp.com/https://api.forismatic.com/api/1.0/?method=getQuote&key=0&format=json&lang=en').then(function (data) {
$('blockquote').html(data.quoteText)
});
}
How can I change this so I can create my own sheet with quotes and display it on the same way?
You can't just add a flat file (or you can, but not with this method) with quotes on it, you need to create an API, which will require a server. You can use node.js for this if you are comfortable with javascript, but you can use any language really.
There are many simple guides online on how to do this, for Node.js they will generally use Express for the server, and some may suggest using a database such as MongoDB (I would suggest avoiding that for such a simple task at this point).

How to access the same JSON file from both javascript and python?

NOTE: This is not for web programming. We use javascript to interface with low level hardware, hence let's not go with jQuery APIs etc.
I have a javascript file that performs a sequence of actions on a device, and I have a python file that will be invoked later to validate these actions. There is a set of hardware information hard-coded in both javascript file and python file. I want to avoid this duplication of information by putting these info into a JSON file so both can access it.
// Javascript
var hardware_info = JSON.parse(load('hardware.json'));
// load() is probably not standard javascript API, but it basically copies that code into the existing script.
Already failed by this step because 'hardware.json' is not using javascript syntax...
I already validated the json using jshint/jslint, hardware.json looks like this:
{
"hardware1": {
"ID": "xxx"
},
"hardware2": {
"ID": "yyy"
}
}
The following Python works well for accessing the json, there is not much to it:
with open('hardware.json', 'r') as f:
data = json.load(f)
It looks like load() executes the specified file, not read it and return the contents. If this is your only option to read another file, then I suggest you use JSONP instead of JSON.
JSONP works by adding a callback around the data. Instead of:
{"key": "value"}
the file contains a function call with the data being passed in:
callback({"key": "value"});
This is meant to be executed by a JavaScript engine, causing it to execute the callback. load() would execute your file, and the callback function would be called as a result, passing in the data.
When used on the web, you'd call a JSONP service and pass in the name of the callback the service should add, but when just sharing a configuration file between a JS engine and Python, you'd hardcode that callback name.
In Python, you'd have to strip off the callback text before loading it as JSON data. That could be as easy as just removing the first N and last M characters:
with open('hardware.json', 'r') as f:
jsonp_data = f.read()
# remove first 9 and last 3 characters to remove JSONP callback
data = json.loads(jsonp_data[9:-3])
A little more sophisticated technique could use newlines:
callback(
{"key": "value"}
);
to make it easier to remove the first and last line in Python. Or you could use jsonp_data.partition('(')[-1].jsonp.rpartition(')')[0] to take everything between the first ( and the last ) character in the string. Etc.

how to query the sharepoint List from outside website by Javascript

I'm totally new on JavaScript and SharePoint.
What I am trying to do is to build a website that be able to connect SharePoint 2010 and query data from it using JavaScript. The website I am building is outside the SharePoint.
I searched a lot of questions and examples about this topic. But all of these confused me, a very very new programer. So please forgive me if you think I am asking silly questions, but those things really confuse new programer like me. I wish my question could also help others who is as fresh as I am.
Here comes my questions:
1) what method should I use
I found a lot of samples teaching how to query the List of SharePoint, e.g. using Client Object Model. Does it is applied to my case? I think that is for the SharePoint website programming, am I right? Because based on the sample I see, there is no any URL that link to the SharePoint Server I want to query.
Or using xmlhttp.open("POST", "http://[my SharePoint Sever]/_vti_bin/search.asmx", true) ...
2) what is right URL of the SharePoint Server and its List
According to my understanding, in my codes, I should first link to the right SharePoint ( or the specific List). so there should be a URL of the SP. I don't think opening the SharePoint List and do copy paste the Address is the right. how to get the right URL and how to alter it (like adding _vti_bin/search.asmx at the end of URL)
3) what is the right query format
when I try to right my own query. too many different format of query examples confused me a lot.
soapEnvelope = "<?xml version=\"1.0\"?> \
<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" \
...
and some looks like this,
var soapEnv =
'<?xml version="1.0" encoding="utf-8"?>' +
'<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' +
...
4) any reference should I quote to make my codes work
should I use Qjuery, XML, or Ajax? What's the connection and how to use them? (sorry about this unclear question, not sure what to ask specifically )
I'm sorta embraced about my un-mature questions. I really need to figure it out somehow....
I will appreciate it a lot if you could give me a full example including and . So I could have a better idea of where is the right place to put my coding.
Thank you so so so much!!!!
There is an open source library created for Sharepoint 2010, code name Camelot. You can find more information here:
http://camelotjson.codeplex.com/
This is a code sample from the link above:
Javscript:
// Build the command
var command = {
Type: "SELECT",
List: "Tasks"
}
var result;
// Send the command using JQUERY
$.ajax({
type: "GET",
contentType: "application/json",
data: { command: JSON.stringify(command)},
url: "/_vti_bin/Camelot.JSONAPI/jsonapi.svc/Items",
success: function (data) {
// Decode and store the result in a variable
result = $.parseJSON(data.d);
console.log("Successfully executed the command, please check the 'result' variable.");
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
You probably want to look at SPService or at the library I created: SharepointPlus.
I think SharepointPlus is really easy to use. For example if you want to query a list to get the data you'll do something like:
$SP().list("Name of your list").get({fields:"First_x0020_Field,OtherField", where:"OtherField = 'something'"}, function(data) {
for (var i=data.length; i--;) console.log(data[i].getAttribute("First_x0020_Field"))
})
Check the SharepointPlus website, it's full of examples. I think it's what you're looking for :-)

Javascript - Sanitize Malicious code from file (string)

I have a data javascript file, which is being dynamically added to website via some custom code.
This file comes from a third party vendor, who could potentially add malicious code in the file
Before this file is added to the website, I would like to parse through it, and look for malicious code, such as redirects or alerts, that inherently get executed upon a files inclusion in the project/website.
For example, my js file could look like this :
alert ('i am malicious');
var IAmGoodData =
[
{ Name :'test', Type:'Test2 },
{ Name :'test1', Type:'Test21' },
{ Name :'test2', Type:'Test22' }
]
I load this file into a object via a XMLHttpRequest call, and when this call returns, I can use the variable (which is my file text) and search it for words:
var client = new XMLHttpRequest();
client.open('GET', 'folder/fileName.js');
client.onreadystatechange = function()
{
ScanText(client.responseText);
}
client.send();
function ScanText(text)
{
alert(text);
var index = text.search('alert'); //Here i can search for keywords
}
The last line would return index of 0, as the word alert is found at index 0 in the file.
Questions:
Is there a more efficient way to search for keywords in the file?
What specific keywords should i be searching for to prevent malicious code being run? ie redirects, popups, sounds etc.....
Instead of having them include var IAmGoodData =, make them simply provide JSON (which is basically what the rest of the file is, or seems to be). Then you parse it as JSON, using JSON.parse(). If it fails, they either didn't follow the JSON format well, or have external code, and in either case you would ignore the response.
For example, you'd expect data from the external file like:
[
{ Name :'test', Type:'Test2' },
{ Name :'test1', Type:'Test21' },
{ Name :'test2', Type:'Test22' }
]
which needs to be properly serialized as JSON (double quotes instead of single quotes, and double quotes around the keys). In your code, you'd use:
var json;
try {
json = JSON.parse(client.responseText);
catch (ex) {
// Invalid JSON
}
if (json) {
// Do something with the response
}
Then you could loop over json and access the Name and Type properties of each.
Random Note:
In your client.onreadystatechange callback, make sure you check client.readyState === 4 && client.status === 200, to know that the request was successful and is done.
This is extremely difficult to do. There are no intrinsically malicious keywords or functions in JavaScript, there are malicious applications. You could be getting false positives for "malicious" activity and prevent a legitimate code with a real purpose from being executed. And at the same time, anyone with a little bit of imagination could bypass any "preventive" method you may implement.
I'd suggest you look for a different approach. This is one of those problems (like CAPTCHA) in which it's trivial for a human to solve while for a machine is practically impossible to do so. You could try having a moderator or some human evaluator to interpret the code and accept it.
You should have them provide valid JSON rather than arbitrary Javascript.
You can then call JSON.parse() to read their data without any risk of code execution.
In short, data is not code, and should not be able to contain code.
You shouldn't. The user should be allowed to type whatever they want, and it's your job to display it.
It all depends on where it is being put, of course:
Database: mysql_real_escape_string or equivalent for whatever engine you're using.
HTML: htmlspecialchars in PHP, createTextNode or .replace(/</g,"<") in JavaScript
JavaScript: json_encode in PHP, JSON.stringify in JavaScript.
At the end of the day, just don't be Yahoo

Categories

Resources