Creating an internal clock within Coldfusion .cfc file to execute scheduled tasks - time

I am needing to do scheduled tasks based off an ever going internal clock. I know this is possible with Javascript, but this solution will need to be hosted within a Application.cfc file. I tried to just use a "Now" function within a OnRequestStart function, however the problem is if I need to let's say send an email at midnight to someone, but no one makes a request at midnight, then the email won't send. I tried to do the same function as well in the OnApplicationStart function, but that will only run once ideally. I was thinking about using the CreateTime method within the OnApplicationStart function, but how would I increment the time in real time, if that makes sense. I hope this is more clear on what is actually needed. Here is some code I tried out, however I am not really sure how to test if this works honestly.
<cffunction NAME="internalclock">
<cfset today = #day(Now())#>
<cfset h = #hour(Now())#>
<cfset m = #minute(Now())#>
<cfset s = #second(Now())#>
<cfset m = #checktime(m)#>
<cfset s = #checktime(s)#>
<cfsetting requestTimeOut = ".5">
</cffunction>
<cffunction NAME="checktime">
<cfif i LESS THAN 10 > i="0"+i
<cfreturn i>
</cfif>
</cffunction>
Edit:
I'm having some issues accessing a variable within a page2.cfc file. The way the data is flowing is that I initialize the variable in an Application.cfc file, rewrite the same variable in page2.cfc, and access the modified variable in page3.cfm. Page3.cfm is just a test to ensure that the variable is in fact defined and updating as expected. I should mention that page2.cfc has a scheduled task on it and runs around every minute. Here is some example code:
Application.cfc
<CFFUNCTION NAME="OnApplicationStart">
<cfset Application.currenttime = 0>
</CFFUNCTION>
page2.cfc
<CFFUNCTION NAME ="Counter">
<cfset Application.currenttime = #Now()#>
</CFFUNCTION>
page3.cfm
<cfoutput>
#Application.currenttime#
</cfoutput>
The error I am getting is that either the current time variable is displaying as 0, or if I change the output to Counter.currenttime it says it's not defined. I am sure I am doing something dumb, but I would appreciate the help.
Thank you all for your help.

This can actually be done via Scheduled Tasks within Coldfusion Administrator. I didn't know that was a thing before actually making this post. My apologies.
Thank you,

Related

Error - Element X is Undefined in Session

Getting this Error
ELEMENT CURRLANGUAGE IS UNDEFINED IN SESSION.
Don't understand why. It was working fine until yesterday
<cfif session.currLanguage eq 'English'>
<cfset session.currLanguage = ''>
</cfif>
Because currLanguage is not defined in the session scope. Womp Womp.
Try this to see what IS defined.
<cfdump var="#SESSION#">
It could be that something is not being set when it should. We'd have to see your code to tell for sure. If you think it's working okay and want to prevent unnecessary error messages in the future, you can do a check like this:
<cfif structKeyExists(SESSION, "currLanguage") AND SESSION.currLanguage is "English">
Logic Logic Logic
</cfif>
Please confirm those too
Please check the value update in the session scope properly.
The session scope will be created based on application name. so if we created the application name as dynamic or updated recently then the session scope will be created as new

Is it possible to force a set of ColdFusion remote access calls through a filter?

Is it possible to send the results of a CFC's remote access functions through a filter?
Something with a component like this:
<cfcomponent>
<cffunction name="foo" access="remote" returnformat="json" securejson="false">
<cfscript>
return {
"a": "<script>alert('l33t');</script>"
};
</cfscript>
</cffunction>
</cfcomponent>
The desired result being returned to the client with values filtered/mapped/reduced/whatever, for example just running values through encodeForHtml:
{
"a": "<script>alert('l33t');</script>"
}
(that escaped sequence might not be exacting, but the gist is there)
The goal being to build some filter implemented somewhere on the server that targets a set of administrator specified components, and without explicit additional code in those components, filters all http responses originating from them.
Preferably entirely from CF, but maybe we can sell the bossman on involving Tomcat / IIS?

ImageScaleToFit - how to implement?

I'm new to Railo, moving away from ColdFusion 8 where my site used to used to use cfx_imagecr3.
I believe Railo has ImageScaleToFit but I'm not sure if I'm using it correctly or if I need to add some kind of class/component? I've added it between a cfscript but i get 'invalid variable declaration' which doest make any sense to me. Any help appreciated.
I'm running railo-4.0.0.013 on ubuntu 12.04
<cfscript>
imageScaletoFit('/home/images/testimage.jpg','90','114','highestPerformance');
</cfscript>
You need to first load the image into a variable, then use that variable name inside ImageScaletoFit, like so:
<cfimage name="ImgVariable" source="/home/images/testimage.jpg" />
<cfset imageScaletoFit(ImgVariable,'90','114','highestPerformance') />
(This isn't specific to Railo - the function exists and works the same way in CF8+)

Is it possible to parse contents of ColdFusion 9.0.1 cached memory?

I've been blind sided by the change from CF8 to 9 where write to disk caching is no longer possible without creating a custom cache or some other drastic workarounds that are not worth the effort.
At this time I've abandoned trying to convert the application to uphold, if possible, the same method of writing the contents of a cache file into a static cfm file. I'm more curious now that I've dug into it a bit deeper. I'm looking for someone that has more experience with this than myself.
What I'd like to understand or know how to do with template cache is:
Be able to target a template in default or custom cache and flush it without clearing the entire cache.
View or parse the contents of a particular cached template either out of curiosity or debug approach.
This was the code I was tooling with, requires CF 9.0.1 due to some cache memory functions that are not available in 9.0 due to the addition of EhCache 2.0 I believe.
<cftry>
<cfcache action='serverCache' timeout='#CreateTimeSpan(0,0,0,10)#' stripwhitespace='true'
usequerystring='true'>
Stuff to cache.
<br/>
<cfoutput>#now()#</cfoutput>
<br/>
</cfcache>
<!--- Get the cached contents --->
<cfdump var="#cacheGetProperties()#">
<cfdump var="#getAllTemplateCacheIds()#">
<!---Locate a single cached item --->
<cfscript>
cacheArray = getAllTemplateCacheIds();
WriteOutput("Before<br/>");
for(i=1;i LTE ArrayLen(cacheArray);i=i+1)
{
writeOutput(cacheArray[i] & "<br/>");
if(FindNoCase(scriptPath, cacheArray[i]))
{
//expect only to find min and max one per string so no need to worry about out of bounds
cacheIDSubStr = REFind("[a-fA-F\d]{32}(?=_LINE:\d*$)",cacheArray[i],1,1);
cacheID = Mid(cacheArray[i],CacheIDSubStr.pos[1],CacheIDSubStr.len[1]);
//Failure to delete cache expected fireworks
//WriteOutput(cacheID&"<br/>");
//cacheObject = CacheGet(cacheID);
//CacheRemove(cacheID);
templateCache = cacheGetSession("template");
//Tooling around with the exposed guts of cacheGetSession
WriteDump(templateCache.getKeys());
}
}
</cfscript>
<cfcatch type="Any">
<cfscript>
writeoutput("Error:" & cfcatch.message);
</cfscript>
</cfcatch>
</cftry>
No errors should exist, but it was edited from the original to post here.
The secret is in the CF 9.0.1 function cacheGetSession(), along with the amending of the other functions to take a key as a parameter.
The following code will only work in 9.0.1.
Assuming:
<cfcache action="serverCache" timeout="#CreateTimeSpan(0,0,0,10)#" stripwhitespace="true" usequerystring="true">
Stuff to cache in the default store.
<br/>
<cfoutput>#Now()#</cfoutput>
</cfcache>
<cfcache action="serverCache" key="myCustomCache" timeout="#CreateTimeSpan(0,0,0,10)#" stripwhitespace="true" usequerystring="true">
Stuff to cache in the 'myCustomCache' store.
<cfoutput>#Now()#</cfoutput>
</cfcache>
Accessing the identifiers of the cache separately
Default (Template):
<cfdump var=#getAllTemplateCacheIds()#>
myCustomCache:
<cfdump var=#cacheGetSession('myCustomCache',true).getKeys()#>
Reading the data of the custom cache
<cfset keys = cacheGetSession('myCustomCache',true).getKeys() />
<cfcache key="myCustomCache" action="get" name="dataInCache" id="#keys[1]#">
<cfdump var=#dataInCache#>
Flushing the custom cache independently of the default
<cfset cacheRemove(keys[1],true,'myCustomCache')>
Sadly, documentation is not at its best with regards to the functionality that snuck in with 9.0.1. Luckily, the CF userbase is good at digging this stuff out, namely Rob-Brooks Bilson, who has a number of great articles on CF and caching in general.
Couple of caveats you should remember in working with the cache in this fashion:
These calls tie to EhCache under the hood, which is Java, and may return NULLs if you try to access keys that don't exist. Wrap your results in IsNull() to validate.
cacheGetSession() is misleading (as Rob points out on his blog), you may think you are retrieving session-related cache data as it applies to your app, but that is not the case--it is server-wide, and you will see other cache's keys in a share app environment.
So, take care to flush the appropriate data...

Using ColdFusion to save an uploaded image to the server

I'm being stymied by what I thought would be the relatively simple task of creating functionality to allow users to upload a picture to a server directory and am looking for some help.
I have a simple form with a straightforward interface, passing a variable named 'imagedata' which is the data passed from a file input, a variable named 'name' which is a specified image name, and a variable named 'imagetype' which passes a file extension.
The code I'm using in the function (handler) to save this file is as follows:
<cfset form.imageName = form.name & "." & form.imagetype />
...
<cffile action="write" file="#sitepath#storage/bannerImages/#form.imagename#" output="#form.imageData#" />
This apparently won't work; it will save a file with the correct name, but does not save the file correctly and doesn't render as an image. I would think that this is something relatively simple, and I would think I've overlooked something because I'm not finding anything on google, which is odd. Help with this problem would be appreciated.
Don't use action="write", use action="upload".
Example:
<cffile
action = "upload"
fileField = "ImageData"
destination = "/tmp/uploads"
accept = "image/jpg"
nameConflict = "MakeUnique"
/>
This will place the file in /tmp/uploads (use for example d:/tmp/uploads on Windows) - which is a directory not accessible online.
At this point, you must verify that the file is what it claims to be - an image file of appropriate dimensions and filesize, and not a masked EXE nor embedded ZIP.
Once you are happy the file is safe for hosting on your server, you can then move it to the appropriate directory and set the name to what was chosen.
Something like...
<cfif cffile.FileWasSaved>
<cfset UploadedFileName = cffile.ServerDirectory & '/' & cffile.ServerFile />
<cfif NOT IsImageFile( UploadedFileName )>
<cfthrow message="Uploaded file not an image." />
</cfif>
<!--- INFO: Checks if zip embedded in image. --->
<cftry>
<cfzip action="list" file="#UploadedFileName#" name="tmp"/>
<cfthrow message="Embedded zip files not allowed."/>
<!--- TODO: Verify correct exception type for CF: --->
<cfcatch type="java.util.zip.zipexception"></cfcatch>
</cftry>
<!---
TODO: Validate any necessary business rules
(e.g. image not too large, etc)
--->
<cfelse>
<cfthrow message="File Upload Error"/>
</cfif>
<cfif refind('\W',Form.Name)>
<cfthrow message="Invalid Name specified. Only alphanumerics allowed."/>
</cfif>
<cfif NOT ListFindNoCase('PNG,JPG,GIF',Form.ImageType)>
<cfthrow message="Invalid FileType specified. Must be PNG/JPG/GIF"/></cfif>
</cfif>
<cffile
action = "rename"
source = "#UploadedFileName#"
destination = "#sitepath#storage/bannerImages/#Form.Name#.#Form.ImageType#"
/>
That code is untested, and - as with everything you run on your servers, but especially so with code involving client uploads - make sure you understand what it is doing before using it.
There is plenty of valuable information on Adobe LiveDocs and on the various CF blogs that is worth spending some time digesting.

Resources