Filtering user input as CSS - php

I'm providing a way for my users to change the CSS of their user pages by entering some CSS in their settings page. Here is the HTML:
<textarea class="code" name="Settings[css]"></textarea>
In the controller:
$model = new Profile;
$model->css = $_POST['Settings']['css'];
I currently don't validate the input for the CSS field. I was wondering if I could filter the CSS so that they couldn't put harmful code in to the page. For example, they could do:
</style>
Now I can put bad code in to your page
I don't think purifying css with HTMLpurifier would be appropriate because CSS usually contains special characters, but correct me if I'm wrong.
Thanks

This has nothing to do with Yii in any shape of form.
The "invalid code" that you provided in example could be easily removed, if you include the User CSS as an external file.
And that is not all they can do with CSS. You should manually remove following entries:
line containing behavior: url( .. )
all instances where !important is used
entries which contain selectors to specific ID, like #ads and #logo

strip_tags() can remove html tags from the input, though I don't think it's the only thing you have to worry about.
An easier solution may be to load this style through an external stylesheet (<link rel="stylesheet" type="text/css" href="userstyle.php?uid=1235" />) instead of an inline style block, that way there's no way to break out.

You could try a php css parser like this:
https://github.com/sabberworm/PHP-CSS-Parser
But I can't tell you anything about the quality of code it produces or how it handles problems with input.
What I do know is that LESS has good debugging usually.
If you use the LESS php class you could build a system where the $_POST['Settings']['css'] is used to create valid CSS. Or if errors occur you can catch them and return that to the browser.
Yes this effectively enables you to use LESS syntax in the field but I don't see the harm in that. LESS is in some ways stricter in the syntax of CSS through, requiring semicolons regardless of if its the last property in the list and extra characters can also trigger errors.
The debugging information for the javascript version is pretty solid though, I can't personally vouch for the PHP class since I only use the JS, but from what I hear its the second best thing after the JS.
http://leafo.net/lessphp/
http://lesscss.org/

Related

PHP automatic footnote and endnote generator

This is more of a general information question involving endnotes than a "check my code" one. That's because I can find almost no (useful) information on the subject and don't have the skills to create this myself. But I still think it's useful to create a general brainstorm session / forum thread on the net about this.
The issue: I've written about 60 articles, a dozen of them book-length or near book-length on a site that has been manually designed with HTML5, CSS3, jquery and PHP - the latter two mainly with pre-existing code. I'm very happy with it except for one thing: endnotes! It takes forever to update them.
An average article has 120 endnotes (up to 550). It happens frequently, especially during the writing/proofreading process, that I need to add more information or want an additional endnote. That means anywhere from 2 to 30 minutes of copy-pasting "[113]s", "[114]s" around. It's hopelessly inefficient.
Ordinarily I dislike the uninspirational Wiki CMS platforms, but they have one huge benefit: cite.php plugins. Like this one:
https://www.mediawiki.org/wiki/Special:ExtensionDistributor?extdist_name=Cite&extdist_version=REL1_26&extdist_submit=
Once you have this, you just put an URL between <ref> </ref> and an endnotes gets automatically generated below a {{reflist}} tag. It's explained here:
https://en.wikipedia.org/wiki/Help:Footnotes
Footnotes are created using the Cite.php software extension. This
extension adds the HTML-like elements <ref>...</ref>, <references />
and <references>...</references>. The elements are also used in a
number of templates; for example, it is becoming more common to use
{{reflist}} rather than <references /> as it can style the reference
list.
I've checked out the plugin and it, of course, is much more than just a few lines of PHP.
My main question is if anyone is aware if this type of code has been created for custom designed websites. Or if someone has an idea how to program this manually? If it's not too hard, I might try it myself in the near future or hire a programmer.
P.S. I did study HTML5 solutions for endnotes in the past. Can't remember the details, but they were terrible. It's crucial to have one type of tag, with each one generating a new automatic endnote.
{{ }} is not standard HTML tags, but usually in some modern MVC frameworks they are used as replacement for PHP syntax like echo $foodNote which is the same as {{ $foodNote }}.
A MVC framework like Laravel use it as part of blade template.
But in the provided link you have in your question, the {{reflist}} is just referring to the content inside the tags like <ref>Content of the reference</ref>.
The provided Cite.php helper file is parsing the content inside tags like <ref>...</ref> to variable reflist inside a curly braces with the same content.
It should be not very difficult to program such thing.
Here is a simple PHP script to handle footnotes automatically. The only significant caveat is that your web page file name must end in .php or .phtml (not all web servers support .phtml). This is no problem because the web server will treat the file exactly as a .html file, except it watches for PHP tags so it can process the embedded PHP scripts.
Here is the script.
<?php
function footnote($footnote){
global $Footnotes, $FootnoteCount;
$FootnoteCount++;
$Footnotes[$FootnoteCount] = "$footnote";
print "<sup>$FootnoteCount</sup>";
}
function PrintFootnotes(){
  global $Footnotes, $FootnoteCount;
for($i = 1;$i < $FootnoteCount + 1;$i++){
  print "<sup>$i</sup>$Footnotes[$i]<br />";
  }
}
?>
You can put the script at the top of each page.
Better yet, save the script in a file named FootnoteFunctions.php. Of course, you can name it what you want or put it in a file with other functions. Just change the following include as appropriate. Next, put the following in the head of your HTML document:
<?php include("FootnoteFunctions.php"); ?>
Put this where you want the footnotes to appear at the bottom of the page:
<?php PrintFootnotes(); ?>
To create a footnote insert the following where you want the footnote number in the text (with your text between the quotes):
<?php footnote("footnote text here") ?>
That's it.
You can embellish the script as desired. For example, to pop up the footnote text as a tooltip, add title="$footnote" to the tag. You can also put a table tag, etc, in the printing function to make the footnote numbers and text line up nicely.
Here is my page explaining line by line how the script works. It also has an embellished version with the features mentioned above.
https://vocademy.net/textbooks/WebDatabase/Footnotes/PageSetup.php?Page=3&CourseDirectory=WebDatabase

Access background image in Wordpress

I'm currently turning a HTML page into a WordPress theme. Throughout the site I have a series of divs that use CSS backgrounds. What is the best practice for linking those images, so the user can change them as they please?
For reference, in the HTML, I have: background-image:url(/site/sprite.png);
You can use custom fields. If you don't know how to make them or you want an easy and robust way to manage them you can find the "Advanced Custom Fields" plugin in the wordpress.org plugin repository. It's free and it's very nice.
The way you would use custom fields here is because you will set those backgrounds with inline style to your theme. Otherwise "the user" will have to know how to change a CSS line of code (not very practical).
If you set them inline they would look something like this:
<div id="divBackground01" style="background: url(<?php echo get_post_meta('$post->ID','div-bg-01',true); ?>);>
</div>
Another option that I've seen people do is make the CSS file in a PHP file... you would use something like:
<style>
#divBackground01 {
background: url(<?php echo get_post_meta('$post->ID','div-bg-01',true); ?>);
}
</style>
Note that it's using PHP because the file would actually be a PHP file... otherwise you can't use PHP in a CSS file. Not sure that it's a very good practice to do this, but it's something doable as another option if you want.
Best to stick with adding the background style inline with the custom field. You can use PHP to make it conditional if needed and you can probably setup 1 post (so you have single ID) with all the custom fields... or whatever way you would prefer to present it to the user is your choice.

Simulate PHP Include Without PHP

I want to include the same navigation menu on multiple pages, however I do not have PHP support, nor can I affect my server in any other way.
I want to avoid simply copying and pasting the html onto all the pages as this would make updating the menu a pain.
The two options I can think of are as follows:
1) Have all the content exist on one page, then determine which content to show based on a keyword appended to the url:
example.com/index?home
example.com/index?news
2) Include a javascript file that has a function that writes the menu out and call the function on each page
function setupMenu() {
$("#nav").html("<ul class='nav'><li>home</li><li>news</li></ul>");
}
With Option 1, the updating process would consist of editing one nav menu on the one page
With Option 2, updating would mean changing the function in the javascript file
My concern with Option 1 is that the page would have to load a lot of content that it wouldn't need to display. My concern for Option 2 may seem trivial but it is that the code can get messy.
Are there any reasons doing it one way would be better than the other? Or is there a third superior option that I'm missing?
You have a few options, each with its own advantages and drawbacks:
Server Side Includes, or SSI. If you don't have PHP there's a good chance you don't have SSI either, and this option requires some irritating mucking-about with your .htaccess file. Check Dominic P.'s answer for a writeup of SSI. The benefit of SSI over JavaScript or Frames is that it doesn't require the user to have JS enabled - which a lot of users don't - and it also doesn't present any navigational difficulties.
Frames. You could either use standard frames to put the navigation in its own separate file, and with the correct styling it would be seamless. You could also use an iframe to place your navigation in an arbitrary part of the site, like a sidebar or whatever. The downside to frames, particularly standard frames, is that they tend to make bookmarking, links and the forward/back buttons behave oddly. On the upside, frames don't need browser compliance or server support.
JavaScript. You can refer to any of the other answers for excellent explanations of the JS solution, particularly if you're using jQuery. However, if your site isn't otherwise dynamic enough that your users will want to have JavaScript enabled, this will mean that a large number of your viewers will not see the menu at all - bad, definitely.
-
Yes use .load jQuery ajax function
$('#result').load('ajax/menu.html');
That way your code stays clean, and you can just edit the includes in seperate HTML files just like PHP.
You should consider AJAX for this task. Include a third party library like jQuery and load the separate HTML files inside placeholders, targeting them by ID.
E.g, in your main HTML page:
<div id="mymenu"></div>
Also, in your main HTML, but in the HEAD section:
$('#mymenu').load('navigation.html');
But your best bet would be to switch to a hosting that supports PHP or any other server-side includes. This will make your life a lot easier.
Check out Server Side Includes. I don't have a whole lot of experience with them, but from what I recall, they are designed to be a solution to just your problem.
Server-side includes: http://www.freewebmasterhelp.com/tutorials/ssi/
You can use HTML Imports http://w3c.github.io/webcomponents/spec/imports/
Here is an example from http://www.html5rocks.com/en/tutorials/webcomponents/imports/
warnings.html contains
<div class="warning">
<style scoped>
h3 {
color: red;
}
</style>
<h3>Warning!</h3>
<p>This page is under construction</p>
</div>
<div class="outdated">
<h3>Heads up!</h3>
<p>This content may be out of date</p>
</div>
Then index.html could contain
<head>
<link rel="import" href="warnings.html">
</head>
<body>
...
<script>
var link = document.querySelector('link[rel="import"]');
var content = link.import;
// Grab DOM from warning.html's document.
var el = content.querySelector('.warning');
document.body.appendChild(el.cloneNode(true));
</script>
</body>

Making a string safe by removing all javascript codes and events

I want to remove all javascript codes from a string that contains html code.
For example these are some unwanted javascript codes that may cause problems on your website:
<div onmouseover='window.location = "http://To-Undesirable-Location"'></div>
or
<img onload='window.location = "http://To-Undesirable-Location"'></img>
or
<script language="javascript> ...unwanted code... </script>
Since hackers can use this js functions to redirect your page to some unwanted pages I wonder why there are not some good source to make this type of content safe... On any website there are usually a simple WYSIWYG editor that users can put their html content inside it.
Thanks
I've heard good things on Stack Overflow about HTML Purifier.

PHP library to create inlined CSS from files or from <style> tags?

I would like a library to create inlined CSS+HTML from .html and .css files or from an HTML file with tags in the head. I would prefer a PHP library if possible.
By inlined CSS I mean something like
<span style="font: bla bla bla">Hi There!</span>
versus
<style>
.greeting { font: bla bla bla; }
</style>
I often need to put HTML into emails and this would simplify the process greatly.
If anyone is interested, my current solution (for stuff that isn't restyled often) is to use the Smarty templating engine to create the document, and to assign the style="" part to a variable inside the template.
Then I can use that variable in each tag (like <td {$td_style}> (FYI - {$variable} is how smarty variables are inserted into a template) and have it generate the appropriate email-friendly HTML.
However I want something that is more general, and for which I can just feed it some HTML and CSS rather than have to convert all of it to a smarty template.
Does anyone know if a library like this exists?
Although I don't know of a library that handles this, if you're set on PHP, you could do this fairly easily I would think by using CSSTidy to parse the CSS, and then using an XML parser (ideal if your code is well-formed--maybe SimpleXML or the DOM extension) or one of the PHP-based HTML parsers I see out there to parse the HTML, so you can alter the HTML via DOM methods according to CSS rules.
If you don't need it tied into a PHP process though, I recommend going with JavaScript for almost anything like this, since it can work in the client-side (and in different environments) and be a handy tool for anyone wishing to do this; you should be able to parse the CSS using http://glazman.org/JSCSSP/ and then using DOMParser() and the IE equivalent as needed (for XHTML) or use innerHTML, this htmlparser, or any other HTML Parsers.
Btw, I know <style> works in emails since my add-on Color Source injects them to get syntax highlighting in emails, though I guess you were only saying it is more complicated for you to do it that way.

Categories