I have a MediaWiki installation and I'm writing a custom script that reads some database entries and produces a custom output for client.
However, the text are in wiki format, and I need to convert them to HTML. Is there some PHP API I could call -- well there must be, but what and how exactly?
What files to include and what to call?
You use the global object $wgParser to do this:
<?php
require(dirname(__FILE__) . '/includes/WebStart.php');
$output = $wgParser->parse(
"some ''wikitext''",
Title::newFromText('Some page title'),
new ParserOptions());
echo $output->getText();
?>
Although I have no idea whether doing it this way is a good practice, or whether there is some better way.
All I found is dumpHTML.php that will dump all your mediawiki ; or may be better API:Parser wiki text which tells :
If you are interested in simply getting the rendered content of a
page, you can bypass the api and simply add action=render to your url,
like so: /w/index.php?title=API:Parsing_wikitext&action=render
Once you add action=render it seems you can get the html page ; dont you think ?
hope this could help.
regards.
Related
I am using wordpress for a web site. I am using snippets (my own custom php code) to fetch data from a database and echo that data onto my web site.
if($_GET['commentID'] && is_numeric($_GET['commentID'])){
$comment_id=$_GET['commentID'];
$sql="SELECT comments FROM database WHERE commentID=$comment_id";
$result=$database->get_results($sql);
echo "<dl><dt>Comments:</dt>";
foreach($result as $item):
echo "<dd>".$item->comment."</dd>";
endforeach;
echo "</dl>";
}
This specific page reads an ID from the URL and shows all comments related to that ID. In most cases, these comments are texts. But some comments should be able to point to other pages on my web site.
For example, I would like to be able to input into the comment-field in the database:
This is a magnificent comment. You should also check out this other section for more information
where getURLtoSectionPage() is a function I have declared in my functions.php to provide the static URLs to each section of my home page in order to prevent broken links if I change my URL pattern in the future.
I do not want to do this by using eval(), and I have not been able to accomplish this by using output buffers either. I would be grateful for any hints as to how I can get this working as safely and cleanly as possible. I do not wish to execute any custom php code, only make function calls to my already existing functions which validates input parameters.
Update:
Thanks for your replies. I have been thinking of this problem a lot, and spent the evening experimenting, and I have come up with the following solution.
My SQL "shortcode":
This is a magnificent comment. You should also check out this other section for more information
My php snippet in wordpress:
ob_start();
// All my code that echo content to my page comes here
// Retrieve ID from url
// Echo all page contents
// Finished generating page contents
$entire_page=ob_get_clean();
replaceInternalLinks($entire_page);
PHP function in my functions.php in wordpress
if(!function_exists("replaceInternalLinks")){
function replaceInternalLinks($reference){
mb_ereg_search_init($reference,"\[custom_func:([^\]]*):([^\]]*)\]");
if(mb_ereg_search()){
$matches = mb_ereg_search_getregs(); //get first result
do{
if($matches[1]=="getURLtoSectionPage" && is_numeric($matches[2])){
$reference=str_replace($matches[0],getURLtoSectionPage($matches[2]),$reference);
}else{
echo "Help! An unvalid function has been inserted into my tables. Have I been hacked?";
}
$matches = mb_ereg_search_regs();//get next result
}while($matches);
}
echo $reference;
}
}
This way I can decide which functions it is possible to call via the shortcode format and can validate that only integer references can be used.
I am safe now?
Don't store the code in the database, store the ID, then process it when you need to. BTW, I'm assuming you really need it to be dynamic, and you can't just store the final URL.
So, I'd change your example comment-field text to something like:
This is a magnificent comment. You should also check out this other section for more information
Then, when you need to display that text, do something like a regular expression search-replace on 'href="#comment-([0-9]+)"', calling your getURLtoSectionPage() function at that point.
Does that make sense?
I do not want to do this by using eval(), and I have not been able to accomplish this by using output buffers either. I would be grateful for any hints as to how I can get this working as safely and cleanly as possible. I do not wish to execute any custom php code, only make function calls to my already existing functions which validates input parameters.
Eval is a terrible approach, as is allowing people to submit raw PHP at all. It's highly error-prone and the results of an error could be catastrophic (and that's without even considering the possibly that code designed by a malicious attacker gets submitted).
You need to use something custom. Possibly something inspired by BBCode.
I have built a custom CMS. Recently, I added the ability to create pages dynamically. I used CKEditor for the content of these pages.
I would also like to run some php functions that may be included in the content of the page stored in mysql.
I DO NOT want to store actual PHP code in the database, but rather function names perhaps. For example, in a page stored in the database I may have.
<?php //begin output
hello world!
check out this latest news article.
news($type, $id);
//end output
?>
What is the best way to find and execute this existing function without using EVAL if its found in the output? I was thinking along the lines of wordpress style short codes. Maybe [[news(latest, 71]] ? Then have a function to find and execute these functions if they exist in my functions.php file. Not really sure the best way to go about this.
I'm not searching for any code answers, but more of a best practice for this type of scenario, especially one that is safest against possible injections.
I found a solution from digging around and finding this thread
How to create a Wordpress shortcode-style function in PHP
I am able to pass short codes like this in CKEditor
[[utube 1 video_id]]
Then, in my page that renders the code:
print shortcodify($page_content);
using this function:
function shortcodify($string){
return preg_replace_callback('#\[\[(.*?)\]\]#', function ($matches) {
$whitespace_explode = explode(" ", $matches[1]);
$fnName = array_shift($whitespace_explode);
return function_exists($fnName) ? call_user_func_array($fnName,$whitespace_explode) : $matches[0];
}, $string);
}
If the function name exist (utube) it will fire the function.
Only problem Im having at the moment is not matter where I place the [[shortcode]] in my editor, it always executes first.
For example, in CKEditor I put:
Hello world! Check out my latest video
[[utube 1 video_id]]
It will always put the text under the video instead of where it is in the document. I need to figure a way to have the short code execute in the order it is placed.
I have continued my voyage into creating a extremely simple template engine.
Because I wanted to add logic to my template I eventually got back to the point that I allowed PHP tags into my code which I enabled by evalling the code.
Maybe not the best solution but when looking at the WordPress templates I noticed that the idea itself may not be that bad.
But now there still is one small problem left.
And that is that I want to translate the generated code.
But it has been evalled already. Hence parsed.
I thought of solving this problem by using ob_get_contents().
But this brought one more question and in case of errors it shows a white screen. (memory usage etc.)
Plus it still did not take away the problem of eval that it parsed the contents when evalled.
In short the class logic is:
Loading template files
Adding the contents
Compiling the template
Eval the code (but unfortunately also displaying the code)
Translate the code so I can translate the code parsed by a PHP script
I would love something like:
$code = eval('?>'.$tpl.'<?php');
$code = translate($code);
WriteCache($code);
SetDocumentHeader();
echo $code;
Would anyone know how to achieve this?
Thanks in advance!
$code = eval($tpl);
Check this out.
I wish to write the response of hitting a given url into the href attribute of an anchor tag using PHP. How can I do this?
Here's an example of what I excpect to happen
mylink.com/getdoc?name=documentA
returns a string as a response:
mylink.com/document2012-03-15.pdf
I need to write this response (using PHP into the href attribute as shown below:
Open Document A
(so the above will be the final source of my page.
I think there are a few ways to do what you want. Not all of them will work exactly as you ask for, but the end result should be the same.
Solution one
My first possible solution was already posted by #shanethehat. You could use file_get_contents to call your PHP script via HTTP and get the response.
Solution two
Another possible solution was suggested in the comments of the post by #YourCommonSense. You could simply include the getdoc script in the PHP script that is generating your HTML file, like this:
$_GET["name"] = "documentA";
echo " Open Document A ";
Solution three
Or you could change the way the getdoc script works. You could use a script more like this:
header("Content-type:application/pdf");
header("Content-Disposition:attachment; filename=\"{$_GET["name"]}\"");
readfile($_GET["name"]);
And you keep your link like this: Open Document A . When getdoc.php is called, it will get the specified file and start a file download.
NOTE: you should probably do some input sanitization with this method (removing slashes, making sure the file ends in .pdf, etc) to make sure someone doesn't try to get a file they're not allowed to get.
That's all I'm coming up with at the moment. There might be a more clever way to do it, but hopefully one of these solutions will do it for you. I would try solution 2 or 3 first, and if they don't work out for you, then go with solution 1.
<?php
//get output from URL
$myfile = file_get_contents('http://mylink.com/getdoc?name=documentA');
?>
Open Document A
How to write response to file using php
Noway.
PHP do not process HTTP requests.
You have to set up your web server to do the rewrite.
There are 100500 questions under mod_rewrite tag, you will find the solution easily.
Note that you may wish to rewrite your url to /getdoc.php?name=document2012-03-15.pdf, not one you mentioned in your question
On a Drupal site, PHP code is enabled for Page body content. How can I get the argument and its value in PHP code? For example, I'd like to get ref and 33002 from:
http://example.com/node/1?ref=33002
In the following code:
<?php
print arg(0);
print arg(1);
print arg(2);
print arg(3);
?>
I can get node and 1, but nothing about ref or 33002.
Thanks!
You can use drupal_get_query_parameters() as follows:
$params = drupal_get_query_parameters();
if (isset($params['ref']) && is_numeric($params['ref'])) {
var_dump(check_plain($params['ref']));
}
Use this:
<?php
$a=$_REQUEST['ref'];
echo "The value of the ref parameter is ".$a;
?>
The solution by crowicked works, but "the Drupal way" is to pass the ref value as a url argument, ie:
http://example.com/node/1/33002
Now you can access the ref value using the arg() function:
$ref = arg(2);
Of course an approach like this can only work if the ref value is always the third argument.
Even though the code above works, it is not recommended to place php scripts in the node body. It makes your site harder to maintain and debug. The day will come when an editor deletes your php node by accident, thus breaking your site.
If you have a php script that you want to run, the best way is to add a simple custom module to your site which implements hook_menu. Have a look at the Menu Example module or this hello world module to learn more about hook_menu.
Lastly, regardless of the method you choose (php nodes or a custom module), always make sure to sanitize url input, for instance with check_plain().