Enforce 'www' prefix with .htaccess

On our Windows/ColdFusion servers at www.gowesthosting.com we run Helicon APE (and on our older servers, ISAPI Rewrite, also by Helicon) which lets you use standard Apache .htaccess files to create rewrite rules for any website. 

Here are a few quick useful snippets for rewriting any URL to include the 'www' prefix. This is good practice, preventing the 'duplicate content' penalty from Google which can occur when a site is available under two addresses, as well as forcing consistency to visitor sessions. This is especially critical in eCommerce sites where a user's session may not be persisted when jumping from a 'www' to 'non-www' page. 

 

RewriteEngine on
rewritecond %{http_host} ^domain.com [NC]
rewriterule ^(.*)$ http://www.domain.com/$1 [R=301,nc]

just replace "domain.com" with your actual domain, and you should see http://yoursite.com/ gets redirected to add the 'www' prefix automatically.

TIP: be sure to use the 'www' anywhere you link to your site, or when connecting any third-party services like PayPal, since a form 'post' from any external source will not be persisted if the page gets redirected. 

 

CKeditor options for Mura CMS (and other CK things)

Now that Mura has been using the new CKeditor (formerly FCKeditor) , I have been looking at the various configuration options available: 

http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html

These configuration options can be added to your styles.js.cfm , stored in the Mura file structure at
[siteid]/includes/themes/[theme]/js/editor/


Start and stop ColdFusion localhost with .bat files (Windows)

Here's a simple trick that saves a few clicks. If you are running a ColdFusion local server on a windows PC, you can start and stop the CF service with a simple bat file.

Make a new text file on your hard drive somewhere (i keep mine right on the desktop), and name it "cfstart.bat" - in your text editor of choice, enter this one line and save the file:

    NET START "coldfusion 9 application server"

(with the quotes, just like that)

You can make another called "cfstop.bat" and, you guessed it, 

    NET STOP "coldfusion 9 application server"

To use the files, on my Windows 7 PC, I just right click and select "Run as administrator", and the service stops or starts up right away. Now instead of running all the time, consuming memory, CF only runs on my local machine when i need it. 

Note: you may also want to remove the ColdFusion service from the list of items that run on startup - use start > run > mscofig to see the list.

 

 

Mura CMS / CKeditor paste as plain text by default

Any developer who uses a CMS with a wysiwyg text editor knows the frustrations of clients pasting content from MS Word and other word processing programs directly into the editor, complete with unwanted styles, and even markup elements, causing all sorts of problems on our otherwise perfectly-formatted pages.

Mura CMS uses the ubiquitous CKeditor (formerly FCK) with a number of features enabled by default, including a "Paste as Plain Text" button. If clients remembered to use this, we would be all set. But, they don't.

Fortunately, there's an easy one-line fix.
Just open up [siteid]\includes\themes\[theme]\js\editor\styles.js

and paste in this line

CKEDITOR.config.forcePasteAsPlainText = true;

That's it. All pasting of content should now be clean, with extra styles and markup removed, just as if you had clicked "paste as plain text" in the editor toolbar. 

Adding Navigation Items to MuraCMS Admin

Here's a quick and easy enhancement you can make to the MuraCMS admin, adding links in the top-level navigation for quick and easy shortcuts to commonly-used sections of Site Manager.

Like so many things in Mura, the hooks already exist for this functionality, you just need to know what to put where. In this case, it is quite simple.

1. First, open up [siteid]/includes/eventhandler.cfc

2. Find the opening line <cfcomponent extends="mura.cfobject">, and paste these lines below it:

<cffunction name="onAdminModuleNav"> <cfargument name="event" /> <cfset var newLinks = ''> <cfsavecontent variable="newLinks"> <li><a href="index.cfm?fuseaction=cArch.list&siteid=... [shortened]">Blog Entries</a></li> <li><a href="index.cfm?fuseaction=cArch.list&siteid=... [shortened]">Photo Gallery</a></li> </cfsavecontent> <cfreturn newLinks /> </cffunction>

3. Change the <li><a> markup as needed, to insert the new links you want to create.
(In my examples above, I just copied the full URL from the admin view I wanted to link to.
There is probably a better way, dynamically generating the admin link by filename, but this works just fine, if your contentIDs stay intact.)

4. Save and upload the eventhandler.cfc, and reload the Mura application from within the admin - you should see the new links appear in your menu.

 

Some official Mura resources: 
http://docs.getmura.com/index.cfm/developer-guides/back-end-development/mapping-events-in-mura/

http://docs.getmura.com/developer-guides/back-end-development/plugins-event

Persist form values on reload w/ jQuery & ColdFusion

A designer friend presented me with a somewhatlong and complicated HTML form. It is a survey/contest entry for employees of a specific industry, with dozens of fields which include regular text inputs, text areas, and radio buttons.

My task is to create a routine to submit this form via e-mail and store the contents in the database. ColdFusion makes that easy with the built-in #form# scope. And for validation, I simply made his HTML < form > into a <cfform>, and all of the <input> and < textarea > elements into <cfinput> and <cftextarea>, adding 'required="true"' and a validation rule and/or message for each. Whipping up a quick server-side validation for the required fields was also a snap with CF.

Then it occurred to me - if there is in fact some error with the user submission, we will return the user to the form showing an error message at the top of the page.

However, unless we somehow persist the values that were entered, the form will be blank, and the user will no doubt be a little frustrated. This is a long form!

one method would be to create <cfparam> values for each element in the form, and then give each input the a value like value='#form.thisFieldName#" - that's common practice, and works great, but I don't want to do the tedious work. Also, I will be passing this form back to the designer, and don't want him to have to create the default value if he decides to change the names of any inputs, or at other input to the form.

So, I came up with this.

Assuming you already have jQuery in your page, this little block of code will loop through all of the posted values in the ColdFusion form scope, then, using jQuery, will assign the given value to any form element with a matching "name" attribute, allowing us to easily re-populate all the form fields in the page, in one fell swoop with javascript.

Since i only had input / textarea / select / radio button inputs, this just handles those types, but could easily be ammended to include checkboxes and more.

<!--- if form scope exists --->
<cfif isDefined('form.fieldnames')>
    <cfsavecontent variable="hcode">
    <script type="text/javascript">
    $(document).ready(function(){
    <cfloop list="#form.fieldNames#" index="ff">
    <cfset rawVal = form[ff]>
    <cfset ffVal = jsStringFormat(form[ff])>
    <cfoutput>
    $('input[type="text"][name="#lcase(ff)#"]').val('#ffval#');
    $('select[name="#lcase(ff)#"]').val('#ffval#');
    $('textarea[name="#lcase(ff)#"]').text('#ffval#');
    $('input[type="radio"][name="#lcase(ff)#"][value="#rawval#"]').attr('checked','checked');
    </cfoutput>
    </cfloop>
    //end jQuery
    });
    </script>
    </cfsavecontent>
<cfhtmlhead text="#hcode#">
</cfif>


Yes, this makes a big long looped jQuery script in the head of the user's page. But in this instance, it is working perfectly, with no noticeable slowing of page load, or other drawbacks that i can see.

HTML Formatter ColdFusion-friendly code cleanup tool

No matter how clean your code, there's something to be said for a fast, clean pre-launch cleanup with a reliable code formatter . My favorite by far is the HTML Formatter from LogicHammer.com:  http://www.logichammer.com/html-formatter/

Complete with a full set of ColdFusion-friendly options, this simple tool makes cleaning your code a snap. I use it as I'm working, to clean up the work-so-far at any point, and before final launch to make sure the production code will be as easy as possible to maintain and revisit later on. It is a standalone executable, which means there's no installation, and you can put in anywhere you like on your hard drive.

I simply create a taskbar shortcut on my Windows PC and drag the files I want to clean directly from the 'project' view in Eclipse onto the icon - couldn't be faster, simpler or easier. I prefer to have my original files altered, with the originals automatically put in a specified backup location - you can also assign the option to leave the original alone and create a cleaned-up copy.

Among other fav features, HTML Formatter ships with a simple text-based config file which makes it incredibly easy to specify tags to ignore or to indent, and file extensions to be formatted or skipped ( you can run the formatting on specific files, or an entire directory).

For only $14.99 you get all the features and 2 years of updates (there is also an 8.99 version with a basic feature set). The program's developer has answered every question I ask directly and has been very helpful with customizations, even building in some features I requested a while back (for the record - I'm not affiliated with logichammer in any way, just very pleased with this slick little tool).

mySQL str_to_date converts text formatted dates and times to real SQL timestamps

I am working on a site where dates have been stored as text strings in a mySQL database, such as '2009-10-17' , and I need to create a 'search by date' function where a given start and end date can be compared to the date stored in the database. In other words, i need to convert the text-formatted date to a real 'datetime' value , that can be compared with (greater than) and (less than) logic within the query itself.

Like all things CF/mySQL , there are usually multiple ways to get things done. After kicking it around a few different ways, I settled on mySQL's built-in "str_to_date" function as the easiest and most efficient solution.

The str_to_date()  function takes two arguments: the string that is to be converted, and a format string, which uses the same syntax as mysql date_format() and other related mySQL date functions.

Since the dates are entered in 'yyyy-mm-dd' format, my format string is" %Y-%m-%d "
(Note the capital Y which signifies a 4-digit year)

My query now looks something like this - note the second line:

SELECT
str_to_date(aa.date_published,'%Y-%m-%d') as articleDate,
aa.title, aa.ID,
aa.author,
aa.article
FROM articles_table ...

This converts the date, 2009-10-17,
to a datetime stamp,
{ts '2009-09-17 00:00:00'},
which can now be used for any type of date comparisons.

To keep things clean, if an article happens to be entered with a different format that does not match our format pattern (i.e. somebody types in '10/17/09'),  str_to_date() will simply return an empty string in that column, rather than throwing an error.

The mySQL specification for this and other functions is here:
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_str-to-date

 

 

 

New TinyMCE lets you paste as plain text automatically

When building web applications, one of the most common functions involves allowing a site administrator to add or edit content on a page via some sort of 'wysiwyg' (what you see is what you get) editor. My tool of choice for this purpose is the very versatile, relatively light TinyMCE ( tinymce.moxiecode.com)

As great as these tools are, it is inevitable that the average site administrator will want to copy and paste some text from a word processing function like MS Word or WordPerfect, both of which add invisible formatting to the copy-and-pasted text, which in turn can really mess up even the best of web designs.

TinyMCE has had a very nice 'paste from word' plugin for as long as I can remember, but it still requires the user to click a tiny icon for the 'paste from word' popup, and then paste their text into that. ( There is also a 'paste as plain text' option which removes all formatting just as if you'd copied into notepad first, then pasted into the web form). So, even with these great options, I still find myself answering more than a few support calls related to text not looking quite like it should (or worse) when copying from Word.

Much to my delight, I've found a much better solution - the newest version of TinyMCE has the "paste" plugin built in, and it now includes options for cleaning up the text automatically when pasting right into the main text box (without needing to use the littlepopup icons).

As seen on the paste plugin page (TinyMCE:Plugins/paste - Moxiecode Documentation Wiki) you simply need to include 'paste' in the list of plugins when initializing the tinyMCE script, and then can call the cleanup options like this:

            paste_auto_cleanup_on_paste : true,
            paste_remove_styles: true,
            paste_remove_styles_if_webkit: true,
            paste_strip_class_attributes: true,

This runs the 'paste from word' function automatically, then removes any remaining inline style and class attributes , leaving you with nice clean paragraph-formatted html.

so, whether your clients remember to use that little button or not, whatever they paste (via ctrl+v on their keyboards) will be stripped clean, ready to be shown in pristine valid html format on your site.

How to show changed input and select fields with jQuery

Here are a few quick easy jquery functions that will add a class of 'changed' to any input or select box if it is changed, and will remove that class if the value is reset to the default.



        // inputs
        $('form.myForm :input').change(function(){
        var defval = $(this)[0].defaultValue;
        if ($(this).val()!=defval){
            $(this).addClass('changed');
        } else {
             $(this).removeClass('changed');
        }
        }).keyup(function(){
             $(this).trigger('change');
        });

        // select boxes
        $('form.myForm select').change(function(){
        var defval = $(this).find('option[defaultSelected=true]').val();
        if ($(this).val()!=defval){
            $(this).addClass('changed');
        } else {
             $(this).removeClass('changed');
        }
        }).keyup(function(){
             $(this).trigger('change');
        });

Note in both cases we use keyup (onkeyup) to trigger the 'change' event. This allows the browser to show the changed class as soon as the user changes the value using a keyboard, rather than 'onblur'.

How to find Specific Column Names or Types in a mySQL Database

I'm working on a rather extensive CMS admin application, and need to make some adjustments to all of the "sort" fields in the database. Many of the tables have either a 'sort' or 'sort_order' (and in one case, I think I saw 'SortOrder'), and I need hunt them down, creating a list of column names and table names so i can quickly find the columns I want to edit.

I could open each table one by one, and look for those column names... but of course, there's a much better way:


SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE lower(column_name) LIKE '%sort%'
AND TABLE_SCHEMA='//my database name here//'

This returns a perfectly formatted query of table names and column names, along with the 'data type' for any column containing 'sort' (or 'Sort'). Now it will be a snap to make my changes to all of the numeric sort fields in the entire database.

The query can be modified to return all sorts of useful info, such as all columns in the entire database:


SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA='//my database name here//'

or all columns with a specific data type


SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA='//my database name here//'
AND DATA_TYPE='varchar'

And then, if you wanted to get really lazy, er, creative... you can loop the results of that query, and 'do stuff' to all of the columns automatically with just a few more lines:


alter table #table_Name# modify #column_name# VARCHAR(55) ;

(this would set the size of your varchar field to 55 characters, for example)

More Entries

blogcfc 5.9.1.002 by raymond camden
contact michael evangelista