I have this in my RSS feed, in drupal views:
<link>Prueba "con comillas"</link>
I've tried to create a module like this:
function views_without_encoded_preprocess_views_view_views_rss(&$vars) {
if (!empty($vars['rss_feed'])) {
$vars['rss_feed'] = strtr($vars['rss_feed'], array(
''' => ''',
'"' => '"',
'<' => '<',
'>' => '>',
'&' => '&',
'"gt' => '',
));
}
}
but everything is not ok. I continue seeing this part:
<link>Prueba "con comillas"</link>
Only for quotes.
As I see you try to use the Views RSS.
There is a fix that appears to work but it has been tested only at Drupal 6 sites. In Drupal 7 some things changed but try out this one:
Go to views_rss/theme and open the theme.inc
Copy out the entire 'function template_preprocess_views_view_views_rss function, and put it in your theme's template.php.
Change the function name to: function yourthemename_precrocess_views_view_views_rss
Then at line 200 in the original theme, or where it reads '// Add XML element(s) to the item array' insert the following just above:
if (empty($rss_elements)) continue;
// Insert here -- clean up special characters
$rss_elements[0]['value'] = htmlspecialchars_decode(trim(strip_tags(decode_entities( $rss_elements[0]['value'])),"\n\t\r\v\0\x0B\xC2\xA0 "));
$rss_elements[0]['value'] = htmlspecialchars($rss_elements[0]['value'], ENT_COMPAT);
// end of cleaning
// Add XML element(s) to the item array.
$rss_item['value'] = array_merge($rss_item['value'], $rss_elements);
}
Check your RSS.... you might have to flush the cache a few times.
Another thing you could try is htmlspecialchars. It seems to me that the output of the Views RSS fields could use this to force encoding on quotes, apostrophes, and ampersands.
Hope that helps.
Related
When testing my Symfony 2.8 based webpage with Google PageSpeed Insights I am getting warned, that the HTML code is not minified.
This is true, while Assetic takes care of minifying all CSS files and JS scripts, the HTML code itself is quite dirty.
Google recommends to use HTML Minifier, but since this a JavaScript tools it cannot be used as Twig extension, filter, etc., can it?
The Twig docu of the spaceless tag makes clear, that this tag is not meant to minify HTML and furthmore:
If you want to create a tag that actually removes all extra whitespace
in an HTML string, be warned that this is not as easy as it seems to
be (think of textarea or pre tags for instance). Using a third-party
library like Tidy is probably a better idea.
But again I don't see how Tidy could be integrated into the Twig templates, etc.
So, what is the best way, to create minified HTML output with Symfony and Twig?
This is a good question and there isn't a flagship bundle but after a quick search, you have two bundle which could help you:
SemaMinifierBundle
This bundle allows you to minify in one config value all your responses (automatically on KernelResponse event) or, on demand, with a twig extension.
But this bundle is pretty old (3 years) and is not ready for Symfony3.
HtmlCompressorBundle
This bundle is a bit more recent and use the htmlcompressor library.
To achieve this several years later, i created a Subscriber on kernel.response event.
# src/Event/MinificationSubscriber.php
<?php
namespace App\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class MinificationSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
KernelEvents::RESPONSE => ['onKernelResponse', -256]
];
}
public function onKernelResponse($event)
{
if (
$event->getRequestType() != HttpKernelInterface::MAIN_REQUEST
|| $event->getRequest()->get('_route') === 'admin' // don't apply on admin pages
) {
return;
}
$response = $event->getResponse();
$buffer = $response->getContent();
$replace = [
'/<!--[^\[](.*?)[^\]]-->/s' => '',
"/<\?php/" => '<?php ',
"/\n([\S])/" => '$1',
"/\r/" => '',
"/\n/" => '',
"/\t/" => '',
'/ +/' => ' ',
];
if (false !== strpos($buffer, '<pre>')) {
$replace = [
'/<!--[^\[](.*?)[^\]]-->/s' => '',
"/<\?php/" => '<?php ',
"/\r/" => '',
"/>\n</" => '><',
"/>\s+\n</" => '><',
"/>\n\s+</" => '><',
];
}
$buffer = preg_replace(array_keys($replace), array_values($replace), $buffer);
$response->setContent($buffer);
}
}
Based on this post, this other one and this gist.
I've been searching for a possibility to copy my Ghost Blog posts to Wordpress.
So far, I've managed to export all ghost data to a JSON file -- do you know any existing tool to convert it to something Wordpress can import?
If not, and I have to build something myself, would you recommend parsing the JSON to a WXR file or similar, or rather import into Wordpress' DB directly?
Thanks in advance!
K.
I migrated a Ghost blog to Wordpress by reading in the Ghost JSON export, massaging it a little and using wp_insert_post to import the posts.
This code should be placed in your theme's functions.php file - you can export your Ghost posts (GhostData.json) at http://example.com/ghost/debug/.
Note: example below doesn't import all data, but most key fields.
/**
* A function used to programmatically create a post in WordPress.
*
* http://tommcfarlin.com/programmatically-create-a-post-in-wordpress/
*
* #returns post ID if successful
* -1 if the post was never created
* -2 if a post with the same title exists
*/
function create_wp_post ($post_details) {
// Initialize the page ID to -1. This indicates no action has been taken.
$post_id = -1;
$post = get_page_by_title($post_details['title'], 'OBJECT', 'post');
// If the page title doesn't already exist, then insert the post
if (is_null($post)) {
// Set the post ID so that we know the post was created successfully
$post_id = wp_insert_post(
array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => $post_details['author'],
'post_content' => $post_details['content'],
'post_date' => $post_details['date'],
'post_date_gmt' => $post_details['date_gmt'],
'post_name' => $post_details['slug'],
'post_status' => $post_details['status'],
'post_title' => $post_details['title'],
'post_type' => 'post',
'tags_input' => $post_details['tags_input']
)
);
// Page title already exists, return error
} else {
$post_id = -2;
}
}
/**
* A function used to filter Ghost blog posts into Wordpress format.
*/
function filter_ghost_posts () {
$posts = json_decode(file_get_contents('GhostData.json'), true);
if ($posts) {
foreach ($posts['data']['posts'] as $post) {
$post_details = array(
'author' => $post['author_id'],
'date' => date('Y-m-d H:i:s', $post['published_at'] / 1000),
'date_gmt' => gmdate('Y-m-d H:i:s', $post['published_at'] / 1000),
'id' => $post['id'],
'content' => $post['html'],
'status' => $post['status'],
'slug' => $post['slug'],
'title' => $post['title']
);
// Status
// Fix discrepancy in naming between Ghost and Wordpress
if ($post_details['status'] === 'published') {
$post_details['status'] = 'publish';
}
// Tags
$post_tags_list = [];
foreach ($posts['data']['posts_tags'] as $post_tags) {
if ($post['id'] === $post_tags['post_id']) {
$post_tags_id = $post_tags['tag_id'];
array_push($post_tags_list, $posts['data']['tags'][$post_tags_id]['name']);
}
}
if (count($post_tags_list) > 0) {
$post_details['tags_input'] = implode(',', $post_tags_list);
}
$post_id = create_wp_post($post_details);
if ($post_id == -1 || $post_id == -2) {
// Error handling here
}
}
}
}
add_filter('after_setup_theme', 'filter_ghost_posts');
My recommendation would be to use Google Refine to import the JSON, and export a CSV, then use WP Ultimate CSV Importer Plugin to import it into your WordPress site. Hope this helps.
The question is quite old, but as of 2017 I still wasn't able to find a solution for Ghost > WP posts migration. What I did is:
Export JSON data, as described here - https://help.ghost.org/hc/en-us/articles/224112927-Import-Export-Data
Change a few JSON fields, like title, markdown... to post_title and post_content etc. (list of WP post fields is here - https://codex.wordpress.org/Class_Reference/WP_Post), and remove a few unneeded ones, like update_at or amp. What I left with was:
ID
post_title
post_name
post_content
post_status
meta_title
meta_description
post_author
post_date
Remove other JSON fields/structure, so there's only "posts": []
Use JSON to CSV converter, like this one - https://konklone.io/json/ and download CSV result file.
Now, when you have a CSV file, install WordPress CSV Importer plugin - https://wordpress.org/plugins/wp-ultimate-csv-importer/ (or similar)
Upload CSV file to the importer, check if fields are selected correctly.
Enjoy the imported posts on your WP dashboard ;)
Notice:
Ghost does not enable image exporting with other data (as of 31/01/2017).
You may wish to change "post_status" from "publish" to "pending", so posts are not published right away, before you edit them properly ;)
In case anyone is looking for this in future:
You could use the ghost-to-wp npm package. This will convert the JSON file you get as an export from Ghost into a WordPress-ready WXR file that can be directly imported into WordPress:
$ npm i -g ghost-to-wp
$ ghost-to-wp yourghostexport.json
As noted by #lomza there is still no way to nicely export images as part of the Ghost file so you will have to migrate images manually.
Disclosure: I am the author of ghost-to-wp.
I tried various importers and the best solution ended up just importing directly from RSS URL like https://myghostblog.com/rss/ with import-xml-feed plugin.
P.S. Keep pagination in mind. Your RSS link might show only first page of posts by default, and so for importing other pages you'll have to manually add /2/ /3/ to the URL and importing each separately. (At least, that's what I needed to do.)
I have installed my own custom theme to xenforo. In my template.xml file i can see the usage of some variable like {$requestPaths.fullBasePath} in the head section. If i want use another variable like these in the header section, where should i defined this variable and from where we can assign values o that variable?
You can do that in the controller, something similar to this:
$viewParams = array(
'variableName' => $variableValue,
'variableName2' => $someOtherValue,
'someArray' => array(
'foo' => 'bar'
)
);
return $this->responseView('MyAddOn_ViewPublic_SomeViewClass', 'some_template', $viewParams);
Then in your template, you can use those variables with the curly syntax:
{$variableName} // output $variableValue with html escaped
{xen:raw $variableName2} // output $someOtherValue
{$someArray.foo} // output "bar"
There are other ways to pass variables to template too: using template_create event listener or <xen:container /> but that's quite complicated. For more information regarding add-on development, read here.
I am in need of assistance with the following problem. There is an application that I co-wrote and currently manage that is written in a combination C and Haskell. The application can be customized and configured via a single XML file. It is a back-end application with no user interface. We have been asked to provide a graphical interface to this application via a web interface. Each configuration option is a form field in the html form like this
configuration1 string1
configuration2 string2
etc
etc
The graphical front end must be a web form that converts the data the user has entered to an XML file that contains the application settings. When the user saves the form, the changes are written to the XML file. When the user opens the form, the configuration from the XML file is displayed in the HTML form fields.
Our team deals with purely back-end stuff and we know nothing of GUIs and the like. The restriction we have is that the front end must be written in Perl and use the LibXML module to conform with company standards. Our team is purely C and Haskell and this is the first request we have ever received for something like that. I would appreciate any help you can provide. If you can include code examples as elaborate as possible it would be a significant help. We know very little Perl but with a clear enough example we can do it. The team that would normally handle this type of stuff is being restructured and we can't wait as we need to get this interface up as quickly as possible.
Thank you.
Don't do this yourself. You don't know Perl or web-apps and the restrictions you mention regarding libxml are probably only one of several. Every tiny configuration and typing mistake will take you hours or days to figure out. You'll end up miserable and stressed, and so will the users.
Someone from your web team could produce a simple form with supporting tests and documentation in a day. You can then extend and bug-fix secure in the knowledge you start from a working app.
If you can't get someone in-house, you cold hire a coder, but do everything you can to get it done in-house first. Don't do this yourself.
To the OP: you did not describe the configuration format properly, an XML fragment would have helped us. As it is you will probably have to modify the solution below to match your format.
I assumed a the following format:
<conf>
<option><name>configuration1</name><value>string1 modified</value></option>
<option><name>configuration2</name><value>string2 re-modded</value></option>
<option><name>configuration3</name><value>string3</value></option>
</conf>
Code that would process this format would be:
#!/usr/bin/perl
use strict;
use warnings;
use CGI qw( -nosticky -utf8 :standard form );
use XML::LibXML;
my $CONF="/web/data/conf.xml"; # or wherever your XML is located
# dispatch table, action => code to process it
my $dispatch= { display => \&display_conf,
edit => \&display_edit_form,
save => \&save_edits,
};
# action is "what to do"
my $action= param( 'action') || 'display';
$dispatch->{$action}->() || exit_error( "wrong action");
exit;
# load the XML and build a table to display it
sub display_conf
{ my $conf= XML::LibXML->load_xml( location => $CONF);
my $content;
foreach my $option ($conf->findnodes( '/conf/option'))
{ $content .= Tr( td( $option->findvalue( './name')),
td( $option->findvalue( './value'))
);
}
$content= table( $content);
# add a link to the edit form
$content .= p( a({ href => url() . '?action=edit' }, 'edit'));
output( $content);
}
# load the XML and build a form that will let you edit it
sub display_edit_form
{ my $conf= XML::LibXML->load_xml( location => $CONF);
my $content;
foreach my $option ($conf->findnodes( '/conf/option'))
{ $content .= Tr( td( $option->findvalue( './name')),
td( input( { type => "text", size => 40,
name => $option->findvalue( 'name'),
value => $option->findvalue( './value')}
)
)
);
}
$content= table( $content);
$content= form( { action => url() },
hidden( { name => 'action', value => 'save', override => 1 }),
$content,
submit( 'Save'),
);
output( $content);
}
# load the XML, go through all options, update the value from the form,
# save the XML, display it value, from the form
sub save_edits
{ my $conf= XML::LibXML->load_xml( location => $CONF);
foreach my $option ($conf->findnodes( '/conf/option'))
{ my $new_value= param( $option->findvalue( './name'));
my( $value_node)= $option->findnodes( './value');
$value_node->removeChildNodes();
$value_node->appendText( $new_value);
}
$conf->toFile( $CONF);
display_conf();
}
# placeholder,
sub exit_error
{ my $message= shift;
print header(), p($message);
}
# output subs, load the template, inject the content and output (with header)
sub output
{ my $content= shift;
print header(), fill_in_string( template(), content => $content );
}
sub fill_in_string
{ my( $template, %param)= #_;
$template=~ s{<<(\w+)>>}{$param{$1}}g;
return $template;
}
sub template
{ return join '', <DATA>; }
# template, very simple
__DATA__
<html>
<head>
<title>Configuration Editor</title>
</head>
<body>
<h1>Configuration Editor</h1>
<h2>Configuration</h2>
<<content>>
</h2>
</body>
</html>
Deployement: put the code somewhere it can be run as CGI, and make sure conf.xml can be read and written by the web server. It's probably better to put it outside of the web tree.
This is in a way prehistorical Perl. CGI is widely considered archaic and there are more modern and fancy options available in Perl. If your configuration is more complex than a key/value list, if you want to have custom help for each field or if you need to use a more complex template to conform to your company's look'n feel, then web Frameworks like Dancer or Mojolicious would be better suited than the simple solution above.
OTOH it works, and I this is still how I write a lot of small tools, that have a few internal users and don't need much in terms of UI.
To the people who suggested that this is too complex to do for people not familiar with Perl, way to go guys! This is not rocket science. It's the kind of code that gets people to start with Perl, why wouldn't we help with writing it? This is in fact a perfect illustration of The Reluctant Perl Programmer.
I am working for a company who use tabulated html/JS interfaces. These are home grown (real honest to god s) with query events attached to each cell. For the old usage they were suitable, but the interactions required between rows and cells are becoming much more complex on the client side. Specifically they want both server and client side validation.
To facilitate this, the devs I report to are super keen on Zend_Forms, and insist that to use a framework like ExtJS, they don't want to have to write back end and front end code twice (please ignore that if it's all home grown they'll have to do this anyway).
So with that in mind, I'm trying to leverage Zend_Form decorators to create Ext.grid.Panel column defintions. For this, I would need to use decorators to export an array (and then json it using the ViewHelper), or render a JSON string directly.
So this would be something like:
$dateElement = new Zend_Form_Element_Text('startDate', array(
'label' => 'Start Date',
'validators' => array(
new Zend_Validate_Date()
)
));
echo (string)$dateElement;
would output:
{ text: 'Start Date', dataIndex:'startDate', xtype:'datecolumn'}
or (obviously not with string cast, but maybe with ->toArray() or something):
array( 'text' => 'Start Date', 'dataIndex' => 'startDate', 'xtype' => 'datecolumn')
I think if I could get it to this stage, I could get what I need out of it.
Has anyone here tried to do anything similiar to this (getting a JSON/XML/other markups output, rather than HTML from Zend_Forms using Decorators) or if they could point me to any resources?
I think I have a solution...
Make a decorator similar to this:
class My_Form_JSON_Decorator extends Zend_Form_Decorator_Abstract{
protected $xtype;
protected $dataIndex;
public function __construct($dataIndex,$xtype){
$this->xtype=$xtype;
$this->dataIndex=$dataIndex;
}
public function render($content){
$element=$this->getElement();
$label=$element->getLabel
//if you need errors here too do the same with $element->getMessages();
return 'array ("text"=>"'.$label.'","dataIndex"=>"'.$this->dataIndex.'","datecolumn"=>"'.$this->xtype.'")';
}
}
Then, on the form, use something similar to this:
$dateElement = new Zend_Form_Element_Text('startDate', array(
'label' => 'Start Date',
'validators' => array(
new Zend_Validate_Date()
)
$dateElement->setDecorators(array(
new My_Form_JSON_Decorator("startDate","datecolumn");
));
And finally, on the View, you should have this:
{
Date: <?php echo $this->form->startDate; ?>,
}
I didn't tried the code above but, I did it with a similar code I used once when I needed to change Decorators of a Form.
It could not be all correct but, I think that it shows you a way of doing that.
Good work =)