Mediawiki Extension add Javascript in Header - php

Hi my problem is that i cant load some javascript file # my special page extension.
I tried it with addscript and some other methods but the only thing what happened was that the javascript was canceled cause no-js of the mediawiki software.
In the folder of my extension is a new.js file which i want to have access only on my special page.
Here is some code (most of it of the example of the special pages).
MyExentions.php
<?php
if (!defined('MEDIAWIKI')) {
echo <<<EOT
To install my extension, put the following line in LocalSettings.php:
require_once( "$IP/extensions/MyExtension/MyExtension.php" );
EOT;
exit( 1 );
}
$wgExtensionCredits['specialpage'][] = array(
'path' => __FILE__,
'name' => '-',
'author' => 'Thomas Döring',
'descriptionmsg' => '-',
'version' => '0.0.1',
);
$dir = dirname(__FILE__) . '/';
$wgAutoloadClasses['SpecialMyExtension'] = $dir . 'SpecialMyExtension.php';
$wgExtensionMessagesFiles['MyExtension'] = $dir . 'MyExtension.i18n.php';
$wgExtensionMessagesFiles['MyExtensionAlias'] = $dir . 'MyExtension.alias.php';
$wgSpecialPages['MyExtension'] = 'SpecialMyExtension';
SpecialMyExtension.php
<?php
class SpecialMyExtension extends SpecialPage {
function __construct() {
parent::__construct( 'MyExtension' );
}
function execute( $par ) {
$request = $this->getRequest();
$output = $this->getOutput();
$this->setHeaders();
# Get request data from, e.g.
$param = $request->getText('param');
# Do stuff
# ...
if(file_exists("extensions/TimeLine/TimeLine/data.xml"))
{
$data = simplexml_load_file("extensions/TimeLine/TimeLine/data.xml");
foreach($data->event as $event)
{
$html.="<tr><td>".$event['title']."</td><td>".$event['start']."</td></tr>";
}
$html.="</table>";
$html.="klick";
$output->addHTML($html);
}
else
{
$wikitext = 'Datei nicht gefunden!';
$output->addWikiText( $wikitext );
}
}
}
?>
I hope you can help me.

addScript works in version 1.16 and before. In 1.17 and later you should use addHeadItem:
$wgHooks['ParserBeforeTidy'][] = 'wgAddJquery';
function wgAddJquery(&$parser, &$text) {
global $addJqueryScripts;
if ($addJqueryScripts === true) return true;
$parser->mOutput->addHeadItem(
'<script language="JavaScript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>'
);
$addJqueryScripts = true;
return true;
}

I added it in the skin file, in the function function setupSkinUserCss
$out->addHeadItem('maketree.js',"
<script type='text/javascript' src='/js/mktree.js'></script>");

Related

Wordpress load external scripts with local fallback

I can't figure out what I'm doing wrong! I want the function to return a freshly-created variable with a true/false value that I can use to see if we've got the file or not.
// Check to make sure external files are available
function checklink ( $link, $checkname ) {
$try_url = #fopen( $link,'r' );
if( $try_url !== false ) { return $$checkname; }
}
var_dump( checklink( 'https://code.jquery.com/jquery-3.3.1.min.js', 'jqueryOK' ) ); // NULL
I've tried setting $checkname to true or false, adding an extra line to give it a value before return ... PHP 'knows' there is a variable $jqueryOK but says it's undefined.
What am I missing?
UPDATE
Decided to share the outcome, as this is often an overlooked thing in Wordpress - and am changing the title to reflect the task.
// Check to make sure external files are available
function checklink ($link) {
return( bool )#fopen( $link, 'r' );
}
function thatwomanuk_external_scripts()
{
if ($GLOBALS['pagenow'] != 'wp-login.php' && !is_admin()) {
// jquery
$link = 'https://code.jquery.com/jquery-3.3.1.min.js';
if( checklink( $link ) ) { // true - otherwise, Wordpress will load its own
wp_deregister_script('jquery'); // remove jQuery v1
wp_register_script('jquery', $link, array(), '3.3.1', true); // add jQuery v3
wp_enqueue_script('jquery');
wp_script_add_data( 'jquery', array( 'integrity', 'crossorigin' ), array( 'sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=', 'anonymous' ) );
}
// google fonts
$link = 'https://fonts.googleapis.com/css?family=Raleway:300,400,400i,500|Ubuntu:300,400,400i,500&subset=latin-ext';
$fallback = get_template_directory_uri() . '/fonts/thatwoman-fonts-min.css';
if( checklink( $link ) ) {
wp_enqueue_style( 'custom-google-fonts', $link, false );
} else {
wp_enqueue_style( 'custom-google-fonts', $fallback, false );
}
// touch events library
$link = 'https://cdnjs.cloudflare.com/ajax/libs/jquery-touch-events/1.0.5/jquery.mobile-events.js';
$fallback = get_template_directory_uri() . '/js/lib/jquery.mobile-events.min.js';
if( checklink( $link ) ) {
wp_register_script('thatwoman-touch-events', $link, array( 'jquery' ), '1.0.5', true);
} else {
wp_register_script('thatwoman-touch-events', $fallback, array( 'jquery' ), '1.0.5', true);
}
wp_enqueue_script('thatwoman-touch-events');
}
}
add_action( 'wp_enqueue_scripts', 'thatwomanuk_external_scripts' );
Thanks to #u_mulder for making me see sense.
You should simplify your function to:
// Check to make sure external files are available
function checklink ($link) {
return (bool)#fopen( $link,'r');
}
After that in your code:
$link1Available = checklink($link1);
$link2Available = checklink($link2);
// etc
Or as an array:
$links = ['link1', 'link2', 'link3'];
$linksAvailable = [];
foreach ($links as $link) {
$linksAvailable[$link] = checklink($link);
}
If you just want to have a local fallback for a CDN loaded js file, you can use wp_scripts()->add_inline_script() which was added in 4.5, to add a js check if the library was loaded, see my detailed answer on wordpress.stackexchange here.
The short version:
You can use wp_scripts()->add_inline_script(), which will append a js script to an enqueued script, no questions asked, no code problems checked (there is a wrapper function wp_add_inline_script that does checks but does not permit </script> tags, even encoded).
This is a working example
function _enqueue_my_scripts() {
// the normal enqueue
wp_enqueue_script( 'jquery-cdn', 'https://code.jquery.com/jquery-3.3.1.min.js' );
// our custom code which will check for the existance of jQuery (in this case)
wp_scripts()->add_inline_script( 'jquery-cdn',
"window.jQuery || document.write('<script src=\"".get_template_directory_uri() ."/js/jQuery.js\">\\x3C/script>')", 'after');
}
add_action('wp_enqueue_scripts', '_enqueue_my_scripts', 100);
which will give you
<script type='text/javascript' src='https://code.jquery.com/jquery-3.3.1.min.js'></script>
<script type='text/javascript'>
window.Swiper || document.write('<script src="http://localhost/wordpress/wp-content/themes/wp-theme/js/jQuery.js">\x3C/script>')
</script>
in your HTML.
Replace 'window.jQuery' and '/js/jQuery.js' according to your needs but don't touch the rest of the line as it is meant to pass through the correct line to the HTML.
You have double $$ sign in return statement:
if( $try_url !== false ) { return $$checkname; }

How to use the content-disposition header to set a downloaded UTF-8 filename?

I am storing my files on Amazon Cloud Drive. And there are option for setting response-content-disposition to direct links from Amazon.
From the API:
response-content-disposition: (Optional) If specified, the content-disposition of the response will be set to this value
I need to set it download mp3 files. I don't need to play it on browser.
And I want to set downloaded file name: Эльбрус Джанмирзоев - Кавказская любовь.mp3
I tried many ways... Urlencode... Urlencode + http build query etc...
But now the result is: Эльбрус+Джанмирзоев+-+Кавказская+любовь.mp3 when downloading files.
And here is my php code:
<?php
function file_generate_download_link($filename = false, $force = true)
{
$json['tempLink'] = 'https://content-na.drive.amazonaws.com/cdproxy/templink/iTwUqoQ3cJXOpj6T8SCDmKwtF37TAENiSLQzy7pTSbkFfJttb';
$url = $json['tempLink'];
if($force)
{
$data['download'] = 'true';
}
if($filename)
{
$data['response-content-disposition'] = ' attachment; filename*=UTF-8\'\''.urlencode($filename).'';
}
if(isset($data)) {
$data = http_build_query($data);
$url .= '?' . $data;
}
return $url;
}
echo file_generate_download_link($filename = 'Эльбрус Джанмирзоев - Кавказская любовь.mp3');
?>
This code returns me this link:
https://content-na.drive.amazonaws.com/cdproxy/templink/iTwUqoQ3cJXOpj6T8SCDmKwtF37TAENiSLQzy7pTSbkFfJttb?download=true&response-content-disposition=+attachment%3B+filename%2A%3DUTF-8%27%27%25D0%25AD%25D0%25BB%25D1%258C%25D0%25B1%25D1%2580%25D1%2583%25D1%2581%2B%25D0%2594%25D0%25B6%25D0%25B0%25D0%25BD%25D0%25BC%25D0%25B8%25D1%2580%25D0%25B7%25D0%25BE%25D0%25B5%25D0%25B2%2B-%2B%25D0%259A%25D0%25B0%25D0%25B2%25D0%25BA%25D0%25B0%25D0%25B7%25D1%2581%25D0%25BA%25D0%25B0%25D1%258F%2B%25D0%25BB%25D1%258E%25D0%25B1%25D0%25BE%25D0%25B2%25D1%258C.mp3
If I enter this link Chrome saves this file with this name:
Эльбрус+Джанмирзоев+-+Кавказская+любовь.mp3
But I need excatly save file with this name:
Эльбрус Джанмирзоев - Кавказская любовь.mp3
Where is my mistake?
Gotcha! I need to use rawurlencode function!
So the right code is:
<?php
function file_generate_download_link($filename = false, $force = true)
{
$json['tempLink'] = 'https://content-na.drive.amazonaws.com/cdproxy/templink/iTwUqoQ3cJXOpj6T8SCDmKwtF37TAENiSLQzy7pTSbkFfJttb';
$url = $json['tempLink'];
if($force)
{
$data['download'] = 'true';
}
if($filename)
{
$data['response-content-disposition'] = ' attachment; filename*=UTF-8\'\''.rawurlencode($filename).'';
}
if(isset($data)) {
$data = http_build_query($data);
$url .= '?' . $data;
}
return $url;
}
echo file_generate_download_link($filename = 'Эльбрус Джанмирзоев - Кавказская любовь.mp3');
?>

WP not sending correct headers to download a file

I have a WP plugin that sends a link to an email to download a file in hidden location. User selects a file, then a token containing the file ID etc. is written to a database, and a link is sent. Upon clicking the link (ex. mysite.com/thank-you/?id=asd687asd68as7d6a8sdd7sd768as7d6, the "thank you" page makes a request to a php function to donload the file.
There's also a dummy "download engine" page with a shortcode [download_page] that initiates the download.
Weird thing is that while this setup works just fine at test environment, and has worked for over a year at production site, it suddenly stopped working:
call for DownloadFile() returns 0KB and correct headers at test site, and initiates the download, but
returns full HTML file and, of course, no download.
I cannot spot any changes in configuration (both sites run WP 4.2.7). Only difference seems to be the WooCommerce plugin, and Google Analytics snippet included in production site.And that test site runs PHP 5.3 while productiopn site runs 5.6.
I'd be very grateful if somebody had an insight of what's happening.. Why are headers ignored? (There's no "Headers already sent" error.) Why is full HTML of the dummy "download engine" page displayed?
BTW it's an out-of-the-box theme, but I cannot spot no faults in it. But still, maybe.. Where I'm to look for a culprit lines? What could force a page to show full HTML instead of headers sent by php?
Relevant code is such:
(download manager.php):
<?php
/*
Plugin Name: Hidden Download Manager
Description: Bla bla
*/
include_once('add_meta_boxes.php');
include_once('mfdm_frontend_functions.php');
add_action( 'init', 'program_register' );
add_shortcode( 'download_page', 'downloadFile' );
?>
(thank_you.tpl.php)
<?php
/**
Template Name: Thank You
*/
$HOST = get_option('mfdm_dbhost');
$USER = get_option('mfdm_dbuser');
$PWORD = get_option('mfdm_dbpwd');
$DB = get_option('mfdm_dbname');
$connect_db = mysqli_connect($HOST,$USER,$PWORD,$DB) or die("Some error occurred during connection " . mysqli_error($connect_db));
if(get_magic_quotes_gpc()) {
$id = stripslashes($_GET['id']);
} else {
$id = $_GET['id'];
}
$result = $connect_db->query("SELECT * FROM 3_downloadkey WHERE uniqueid = '$id'");
$row = resultToArray($result);
$redirect = '';
if (!$row) {
// redirect to 'invalid' page
$redirect = get_option('mfdm_link_invalid_page');
wp_redirect($redirect);
exit;
}
get_header();
$plugindir = plugin_dir_url(0).'mouseful_download/';
// embed the javascript file that makes the AJAX request
wp_enqueue_script( 'processLink_request', $plugindir . 'mf_downloads.js', array( 'jquery' ) );
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script('processLink_request', 'ProcessLink', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'postCommentNonce' => wp_create_nonce( 'ProcessLink-post-comment-nonce' ),
'downloadHiddenPage' => get_option('mfdm_download_hidden_page')
)
);
?>
<link rel="stylesheet" type="text/css" media="all" href="<?=$plugindir;?>mf_downloads.css">
<body onLoad="setTimeout('downloadLink()', 1000)"></body>
<div class="contents about">
<div class="row">
<div class="col banner">
<p><?php the_title(); ?></p>
</div>
</div>
<div class="row2"><div class="col">
<?php
while ( have_posts() ) : the_post();
the_content();
endwhile;
?>
</div></div></div>
<?php
get_footer();
?>
(mfdm_frontend_functions.php):
<?php
add_action( 'wp_ajax_nopriv_downloadLink-submit', 'downloadFile' );
add_action( 'wp_ajax_downloadLink-submit', 'downloadFile' );
function downloadFile() {
$HOST = get_option('mfdm_dbhost');
$USER = get_option('mfdm_dbuser');
$PWORD = get_option('mfdm_dbpwd');
$DB = get_option('mfdm_dbname');
$id = $_POST['app'];
$connect_db = mysqli_connect($HOST,$USER,$PWORD,$DB);
$result = $connect_db->query("SELECT * FROM 3_downloadkey WHERE uniqueid = '$id'");
$row = resultToArray($result);
$app_ID = $row[0]['app_ID'];
ob_start();
// get app name
$base_dir = get_option('mfdm_applications_folder');
define('BASE_DIR',$base_dir);
$fname = get_post_meta($app_ID, 'meta_source', true);
$app_download_name = get_post_meta($app_ID, 'meta_program_name', true);
$file_path = '';
$file_path = find_file1(BASE_DIR, $fname, $file_path);
if (!is_file($file_path)) {
die("File does not exist. Make sure you specified correct file name.");
}
$fsize = filesize($file_path);
$fext = strtolower(substr(strrchr($fname,"."),1));
$mime_types = array(
'msi' => 'application/x-ole-storage',
'zip' => 'application/zip',
'exe' => 'application/x-msdownload',
'sh' => 'application/x-sh',
'iso' => 'application/octet-stream',
'dmg' => 'application/octet-stream',
'pdf' => 'application/pdf',
);
$mm_type = $mime_types[$fext];
if ($fd = fopen ($file_path, "r")) {
$fsize = filesize($file_path);
$path_parts = pathinfo($file_path);
$ext = strtolower($path_parts["extension"]);
header("Content-type: $mm_type");
header("Content-Disposition: attachment; filename=\"".$app_download_name."\"");
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(ob_POST_level() > 0) {
#ob_end_clean();
}
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
}
?>
(mf_downloads.js):
function downloadLink() {
var id = window.location.search.replace("?", "").split("&")[0];
id = id.split("=")[1];
var url = ProcessLink.downloadHiddenPage;
var form = jQuery('<form action="' + url + '" method="post">' + '<input type="text" name="app" value="' + id + '" hidden="hidden"/>' + '</form>');
jQuery('body').append(form);
form.submit();
}
Your 'downloadFile' function in 'mfdm_frontend_functions.php' should end with wp_die() in order to return a proper response.
wp_die(); // this is required to terminate immediately and return a proper response
Upload a user-defined php.ini to your webroot containing the following line:
default_charset = ""

Cannot modify header information - headers already sent in WordPress [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Headers already sent by PHP
When I go into wp-admin on www.newswars.org, I see the following error:
Warning: Cannot modify header information - headers already sent by (output started at /home/newswars/public_html/wp-content/themes/videoplus/functions.php:38) in /home/newswars/public_html/wp-includes/option.php on line 563
Warning: Cannot modify header information - headers already sent by (output started at /home/newswars/public_html/wp-content/themes/videoplus/functions.php:38) in /home/newswars/public_html/wp-includes/option.php on line 564
Can you please help?
EDIT: Ok its this that is causing me the problem.
$user_ej = wp_get_current_user();
if ($user_ej->roles[0] == 'contributor')
{ ?>
This is 36-38 lines. For some reason its getting all messed up. Still I'm not quite sure what the problem is. I tried removing ?> but that gave me a syntax error. I'm at a loss. It is definitely the problem area as it only comes up when someone logs in a 'contributor'.
<?php
// Translations can be filed in the /lang/ directory
load_theme_textdomain( 'themejunkie', TEMPLATEPATH . '/lang' );
require_once(TEMPLATEPATH . '/includes/sidebar-init.php');
require_once(TEMPLATEPATH . '/includes/custom-functions.php');
require_once(TEMPLATEPATH . '/includes/post-thumbnails.php');
require_once(TEMPLATEPATH . '/includes/theme-postmeta.php');
require_once(TEMPLATEPATH . '/includes/theme-options.php');
require_once(TEMPLATEPATH . '/includes/theme-widgets.php');
require_once(TEMPLATEPATH . '/functions/theme_functions.php');
require_once(TEMPLATEPATH . '/functions/admin_functions.php');
function wpr_snap($atts, $content = null) {
extract(shortcode_atts(array(
"snap" => 'http://s.wordpress.com/mshots/v1/',
"url" => 'http://www.catswhocode.com',
"alt" => 'My image',
"w" => '400', // width
"h" => '300' // height
), $atts));
$img = '<img src="' . $snap . '' . urlencode($url) . '?w=' . $w . '&h=' . $h . '" alt="' . $alt . '"/>';
return $img;
}
add_shortcode("snap", "wpr_snap");
$user_ej = wp_get_current_user();
if ($user_ej->roles[0] == 'contributor')
{ ?>
<style type="text/css">
#menu-dashboard, #toplevel_page_wpcf7, #menu-tools
{
display:none;
}
</style>
<?php }
add_filter( 'gettext', 'change_post_to_portfolio' );
add_filter( 'ngettext', 'change_post_to_portfolio' );
function change_post_to_portfolio( $translated ) {
$translated = str_ireplace( 'Posts', 'VIDEOS', $translated ); // ireplace is PHP5 only
return $translated;
}
// Uncomment this to test your localization, make sure to enter the right language code.
// function test_localization( $locale ) {
// return "nl_NL";
// }
// add_filter('locale','test_localization');
// Adds categories to pages
add_action('admin_init', 'reg_tax');
function reg_tax() {
register_taxonomy_for_object_type('category', 'page');
add_post_type_support('page', 'category');
}
add_action('admin_footer', 'my_admin_footer');
function my_admin_footer()
{
$uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : NULL ;
$message = NULL;
if ($uri AND strpos($uri,'edit.php'))
{
if (strpos($uri,'post_type=page'))
{
$message = '1.In the ‘Video Embed Code section,’ enter the video embed code. 2.Enter the title and text in the main panel below. 3.Choose which continent and category is most fitting for your video. 4.Press ‘Publish’';
}
else
{
$message = 'ALL VIDEOS';
}
}
elseif ($uri AND strpos($uri,'post-new.php'))
{
if (strpos($uri,'post_type=page'))
{
$message = 'Add pages here';
}
else
{
$message = '1.In the ‘Video Embed Code section,’ enter the video embed code. 2.Enter the title and text in the main panel below. 3.Choose which continent and category is most fitting for your video. 4.Press ‘Publish’';
}
}
elseif ($uri AND strpos($uri,'post.php'))
{
$message = 'THREE';
}
if ($message)
{
?><script>
jQuery(function($)
{
$('<div style="margin-bottom:15px; color:#FF0000;"></div>').text('<?php echo $message; ?>').insertAfter('#wpbody-content .wrap h2:eq(0)');
});
</script><?php
}
}
?>
add_shortcode("snap", "wpr_snap");
$user_ej = wp_get_current_user();
if ($user_ej->roles[0] == 'contributor')
{ ?>
<style type="text/css">
#menu-dashboard, #toplevel_page_wpcf7, #menu-tools
{
display:none;
}
</style>
<?php }
add_filter( 'gettext', 'change_post_to_portfolio' );
add_filter( 'ngettext', 'change_post_to_portfolio' );
isn't inside a function. So it's being called as soon as the file loads. This means all output is sent to the screen immediately This stuff should be inside a function which is then called at the right time (like the other bits).

Text problem in template machine

I have this code:
class template
{
public $template,$prefix,$replace;
function __construct($template, $prefix)
{
$this->prefix = $prefix;
$this->template = $template;
}
public function SetValue($name, $replace)
{
$this->replace["#".$name."#"] = $replace;
}
public function Tempclude($found)
{
$file = "styles/main/".$found[1].'.html';
if(!file_exists($file))
exit("the template '" . $found[1] . "' wasn't found.");
return file_get_contents($file);
}
public function finish($stream = "normal")
{
if($stream == "folder")
$code = file_get_contents("../styles/main/".$this->template.".html");
else
$code = file_get_contents("styles/main/".$this->template.".html");
$code = preg_replace_callback("#<pb:include=\"(.*)\">#iuU", array($this, 'Tempclude'), $code);
if(is_array($this->replace))
$code = str_replace(array_keys($this->replace), $this->replace, $code);
$code = str_replace("\r\n", "", $code);
$code = str_replace(" ", "", $code);
echo $code;
}
}
If I type in the Template some simple text, the page turns white with nothing inside.
What is the problem?
it is no the problem.
Try doing this:
$template = new template("index", "");
$template->SetValue("notice", "notice:");
$template->finish();
and index.html:
<pb:include="header">
hhh
#Slider#
<pb:include="footer">
its work.
if you change index.html to:
<pb:include="header">
<div id="hh">
hhh
</div>
#Slider#
it return a white list with somthing inside.
I have found the unquoted constant shows warning (depends on php configuration, WAMP does)
In the edited code that you have problem with errors, only quote the two constants in the begining it should work okay, test it like this:
$template = new template("index", "");
$template->SetValue("notice", "notice:");
$template->finish();
folder structure: styles/main must be provided. These files must be found inside main: index.html, footer.html, header.html must be privided
When everything okay, please try to delete any uneccessary comments or answers.
Thank you!

Categories