working on it ...

Filters

Explore Public Snippets

Sort by

Found 93 snippets

    public by boxshadow  1557  0  3  0

    Coldfusion function to substitute bad words entered into a form field for either asterisks or a string of of characters.

    Coldfusion function to substitute bad words entered into a form field for either asterisks or a string of of characters.: filter.cfc
    <cfscript>
    	component output=false {
    		 public filters function init(dsn)
    		 description="Initialize component as an object and store as an application variable. This will 
    		 	make the just a single hit to the database and store the word list in memory to be used anytime."{ 
    			variables.datasource = arguments.dsn;     
    			var q = new query();
    			var badWordQuery = 0;             
    			q.setDatasource(variables.datasource);             
    			q.setName(badWordQuery);             
    			var qResult = q.execute(sql="
    				SELECT 
    					* 
    				FROM
    					badwords 
    				ORDER BY CHAR_LENGTH(strBadWord) DESC 
    			");             
    			badWordQuery = qResult.getResult();
    			variables.badWordList = valuelist(badWordQuery.strBadWord);
    			variables.goodWordList = valuelist(badWordQuery.strReplaceString);
    			return this;
    		}
    		 
    		 public struct function filterWords(required string wordString,boolean scramble){
    		 	var i = 0;
    		 	var newString = arguments.wordString;
    		 	var wordList = "";
    		 	var returnStruct = {};
    		 	var badWord = "";
    		 	var replaceWord = "";
    		 	
    		 	for(i=1;i LTE ListLen(variables.badWordList);i++){
    		 		badWord = trim(listgetat(variables.badWordList,i,","));
    		 		
    		 		if(arguments.scramble EQ 0){
    		 			replaceWord = repeatstring("*", Len(trim(listgetat(variables.goodWordList,i,","))));
    		 		}
    		 		else{
    		 			replaceWord = trim(listgetat(variables.goodWordList,i,","));
    		 		}
    		 		
    		 		if(findnocase(badWord,newString)){
    		 			wordList = listappend(wordList,badWord,",");
    		 		}
    		 		newString = replacenocase(newString,badWord,replaceWord,"ALL");
    		 		
    		 		
    		 	}
    		 	
    		 	returnStruct['oldString'] = arguments.wordString;
    		 	returnStruct['newString'] = newString;
    		 	returnStruct['wordsRemoved'] = ListChangeDelims(wordList, ", ");
    		 	return returnStruct;
    		 }
    		 
    	}
    </cfscript>
    
    

    public by boxshadow  96696  1  3  1

    Function to Format Phone Number with RegEx and Coldfusion

    Function to Format Phone Number with RegEx and Coldfusion: formatPhone.cfc
    <cfscript>
         component output="false" {
    
            public formatPhone function init(){
                    return this;
                    }
    
    	public string function formatPhone(required string phoneNumber)
    		description="Strips out anything that isn't a number and then takes the first 10 digits and formats them to our spec: (404) 555-1212"
    		output="false" 
    		{
    			var failedReturn = 0;
    			// Strip out everything but the numbers
    			var cleanNumber = REReplaceNoCase(arguments.phoneNumber,"[^0-9]","","All");
    			
    			// area code can't start with a 1 or 0, so remove them if they are at the beginning
    			do{
    				if(Left(cleanNumber,1) EQ 1 OR Left(cleanNumber,1) EQ 0){
    					cleanNumber = right(cleanNumber,len(cleanNumber) - 1);
    				}
    			}
    			while(left(cleanNumber,1) EQ 1 OR left(cleanNumber,1) EQ 0);
    			
    			// If there are stil 10 or more digits left, lets use the left 10 and drop the rest
    			if(len(cleanNumber) LT 10){
    				return failedReturn;
    			}
    			else{
    				cleanNumber = left(cleanNumber,10);
    			}
    			// Format the 10 digits we have
    			cleanNumber = "(#left(cleanNumber,3)#) #mid(cleanNumber,4,3)#-#right(cleanNumber,4)#";
    			return cleanNumber;		
    		}
         }
    </cfscript>
    
    

    external by halityurttas  1  0  1  0

    Coldfusion object property name flatter with dot notations. Also support index based arrays.

    Coldfusion object property name flatter with dot notations. Also support index based arrays.: ObjectPropertyFlatter.cfc
    <cfcomponent>
        
        <cffunction name="flatten" access="public" returntype="array">
            <cfargument name="data" type="any">
            <cfargument name="flattenArray" type="array" default="#arrayNew(1)#">
            <cfargument name="parentName" type="string" default="">
    
            <cfset arguments.flattenArray = flattenFactory( arguments.data, arguments.flattenArray, arguments.parentName )>
            
            <cfreturn arguments.flattenArray>
        </cffunction>
    
        <cffunction name="flattenFactory" access="public" returntype="array">
            <cfargument name="data" type="any">
            <cfargument name="flattenArray" type="array">
            <cfargument name="parentName" type="string">
    
            <cfif isStruct( arguments.data )>
                <cfreturn this.flattenStruct( arguments.data, arguments.flattenArray, arguments.parentName )>
            </cfif>
            <cfif isArray( arguments.data )>
                <cfreturn this.flattenArray( arguments.data, arguments.flattenArray, arguments.parentName )>
            </cfif>
    
            <cfreturn arguments.flattenArray>
        </cffunction>
    
        <cffunction name="flattenStruct" access="public" returntype="array">
            <cfargument name="data" type="struct">
            <cfargument name="flattenArray" type="array">
            <cfargument name="parentName" type="string">
    
            <cfif arrayContains( arguments.flattenArray, arguments.parentName )>
                <cfset arrayDelete( arguments.flattenArray, arguments.parentName )>
            </cfif>
    
            <cfloop collection="#arguments.data#" item="attr">
                <cfset elementName = ( len( arguments.parentName ) ? arguments.parentName & "." : "" ) & attr>
                <cfset arrayAppend( arguments.flattenArray, elementName )>
                <cfset arguments.flattenArray = flattenFactory( arguments.data[attr], arguments.flattenArray, elementName )>
            </cfloop>
    
            <cfreturn arguments.flattenArray>
        </cffunction>
    
        <cffunction name="flattenArray" access="public" returntype="array">
            <cfargument name="data" type="array">
            <cfargument name="flattenArray" type="array">
            <cfargument name="parentName" type="string">
    
            <cfloop array="#arguments.data#" index="i" item="attr">
                <cfset elementName = ( len( arguments.parentName ) ? arguments.parentName : "" ) & "[" & i & "]">
                <cfset arrayAppend( arguments.flattenArray, elementName )>
                <cfset arguments.flattenArray = flattenFactory( attr, arguments.flattenArray, elementName )>
            </cfloop>
    
            <cfreturn arguments.flattenArray>
        </cffunction>
    
    </cfcomponent>
    
    

    external by Matthew J. Clemente  4  0  1  0

    Parses an Amazon Resource Name (ARN) and returns its component parts as an object.

    Parses an Amazon Resource Name (ARN) and returns its component parts as an object.: parseArn.cfc
    /**
    * @hint Parses an Amazon Resource Name (ARN) and returns its component parts as an object.
    * This follows the general format of ARNs outlined by Amazon (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html), but does not fully account for all possible formats
    * Derived from https://gist.github.com/gene1wood/5299969edc4ef21d8efcfea52158dd40
    */
    private struct function parseArn( required string arn ) {
      var elements = arn.listToArray( ':', true );
      var result = {
        'original' : arn,
        'arn' : elements[1],
        'partition' : elements[2],
        'service' : elements[3],
        'region' : elements[4],
        'account' : elements[5]
      };
    
      if ( elements.len() >= 7 ) {
        result[ 'resourcetype' ] = elements[6];
        result[ 'resource' ] = elements[7];
      } else if ( !elements[6].find( '/' ) ) {
        result[ 'resource' ] = elements[6];
        result[ 'resourcetype' ] = '';
      } else {
        result[ 'resourcetype' ] = elements[6].listFirst( '/' );
        result[ 'resource' ] = elements[6].listRest( '/' );
      }
    
      return result;
    }
    
    

    external by bcswartz  6  0  1  0

    Simple ColdFusion method for converting letters to number in American phone numbers

    Simple ColdFusion method for converting letters to number in American phone numbers: converterUtil.cfc
    public string function convertPhoneLetters(required string oldNumber) {
      var newNumber= arguments.oldNumber;
      var regArray= [
        "[A-Ca-c]",
        "[D-Fd-f]",
        "[G-Ig-i]",
        "[J-Lj-l]",
        "[M-Om-o]",
        "[P-Sp-s]",
        "[T-Vt-v]",
        "[W-Zw-z]"
      ];
    
      var resultArray= [
        2,3,4,5,6,7,8,9
      ];
    		
      for (var x=1; x <= ArrayLen(regArray); x++) {
        newNumber= ReReplace(newNumber,regArray[x],resultArray[x],"all");
      }
    		
      return newNumber;
    }
    
    

    external by bcswartz  3  0  1  0

    CSRF protection example in a ModelGlue-based ColdFusion app, part 1

    CSRF protection example in a ModelGlue-based ColdFusion app, part 1: mgAuth.cfc
    <cffunction name="secureTransmissionURL" access="public" returntype="void" output="false">
        <cfargument name="event" type="any">
        <cfif arguments.event.valueExists("token") EQ false>
            <cfset session.token= CreateUUID()>
        </cfif>
        <cfset arguments.event.setValue("secureMyself","index.cfm?token=" & Hash(session.token,"SHA-256") & "&" & arguments.event.getValue("eventValue") & "=")>
    </cffunction>
    	
    <cffunction name="validateTransmissionURL" access="public" returntype="void" output="false">
        <cfargument name="event" type="any">
        <cfif arguments.event.valueExists("token") EQ false>
            <cfset arguments.event.setValue("validationProblem","noToken")>
            <cfset arguments.event.addResult("invalidTransmission")>
        <cfelseif arguments.event.getValue("token") NEQ Hash(session.token,"SHA-256")>
            <cfset arguments.event.setValue("validationProblem","tokenMismatch")>
            <cfset arguments.event.addResult("invalidTransmission")>
        </cfif>
    </cffunction>
    
    

    external by Brian Swartzfager  3  0  1  0

    Configure environment-specific settings with ModelGlue and ColdSpring, part 1

    Configure environment-specific settings with ModelGlue and ColdSpring, part 1: appConfig.cfc
    <cfcomponent displayname="appConfig" hint="I provide the configuration settings for the application dependent on where the application is running.">
    
        <cffunction name="init" access="public" returntype="any" hint="I accept all of the possible setting configurations">
            <cfargument name="universalSettings" type="struct" required="true" hint="A struct of all of the configuration settings that are true regardless of environment" />
            <cfargument name="localSettings" type="struct" required="true" hint="A struct of all of the configuration settings for the local environment" />
            <cfargument name="remoteSettings" type="struct" required="true" hint="A struct of all of the configuration settings for the remote environment" />
            <cfset var loc= StructNew()>
            <cfset variables.config= StructNew()>
            <cfloop collection="#arguments.universalSettings#" item="loc.ukey">
                <cfset variables.config[loc.ukey]= arguments.universalSettings[loc.ukey]>
            </cfloop>	
    		
            <cfset loc.env= determineEnvironment()>
    		
            <cfloop collection="#arguments[loc.env]#" item="loc.ekey">
                <cfset variables.config[loc.ekey]= arguments[loc.env][loc.ekey]>
            </cfloop>
    		
            <cfreturn this />
        </cffunction>
    	
        <cffunction name="determineEnvironment" access="private" output="false" returntype="string" hint="I determine the application environment">
            <cfif Left(cgi.cf_template_path,6) EQ "/Users">
                <cfreturn "localSettings" />
            <cfelse>
                <cfreturn "remoteSettings" />
            </cfif>
        </cffunction>
    	
        <cffunction name="getConfig" access="public" output="false" returntype="any" hint="I return a config setting">
            <cfargument name="configName" type="string" required="true" hint="The name of the configuration setting">
            <cfreturn variables.config[arguments.configName]>
        </cffunction>
    	
        <cffunction name="setConfig" access="public" output="false" returntype="void" hint="I set a config setting">
            <cfargument name="configName" type="string" required="true" hint="The name of the configuration setting">
            <cfargument name="configValue" type="any" required="true" hint="The value/data to store in the configuration setting">
            <cfset variables.config[arguments.configName]= arguments.configValue>
        </cffunction>
    	
    </cfcomponent>
    
    

    external by noedlm  3  0  1  0

    Coldfusion: Perks of iterating through structures and arrays using .each()

    Coldfusion: Perks of iterating through structures and arrays using .each(): using-for-in-loops.cfc
    json = getPayload();
    courses = deserializeJson(json); //this returns an array of structs
    
    for(course in courses) {
        importClass(course);
    }
    
    function importClass(required struct course) {
        queryObject = new query(datasource);
        queryObject.addParam(name="fieldA", value=arguments.course["fieldA"]);
        queryObject.addParam(name="fieldB", value=arguments.course["fieldB"]);
        queryObject.addParam(name="fieldC", value=arguments.course["fieldC"]);
           
        //build and execute insert/update query
    }
    
    
    

    external by obxpete  22  0  1  0

    AWS CloudSearch File/Data upload/update example in ColdFusion

    AWS CloudSearch File/Data upload/update example in ColdFusion: cfAWSCloudSearchExample.cfc
    // Create basic AWS credentials  properties
    BasicAWSCredentials = createObject("java", 'com.amazonaws.auth.BasicAWSCredentials').init(yourAccessKey, YourSecretKey);
    
    // turn credentials into a provider object
    AWSCredentialsProviderObj = createObject("java", "com.amazonaws.auth.AWSStaticCredentialsProvider").init(BasicAWSCredentials);
    
    // documents endpoint
    serviceEndpoint = 'search-mydomain-myendpointstring.us-east-1.cloudsearch.amazonaws.com';
    signingRegion = 'us-east-1';
    
    
    // create our client
    AmazonCloudSearchDomainClient = createObject("java", "com.amazonaws.services.cloudsearchdomain.AmazonCloudSearchDomainClient").init(BasicAWSCredentials);
    
    AmazonCloudSearchDomainClient.setEndpoint(serviceEndpoint);
    
    //https://fromraj.wordpress.com/2017/04/03/searching-pdf-content-aws-cloudsearch/
    
    // create a valid stream of files
    FileName = expandPath('/work/testCloudsearch.json');
    inputFile = createObject("java", "java.io.File").init(filename);
    InputStreamObj = createObject("java", "java.io.FileInputStream").init(inputFile);
    
    // create and populate our AWS upload documents request Object
    uploadDocumentsRequestObj = CreateObject('java', 'com.amazonaws.services.cloudsearchdomain.model.UploadDocumentsRequest').init();
    
    uploadDocumentsRequestObj.setDocuments(InputStreamObj);
    uploadDocumentsRequestObj.setContentType("application/json");
    uploadDocumentsRequestObj.setContentLength(inputFile.length());
    
    // fire away!
    AmazonCloudSearchDomainClient.uploadDocuments(uploadDocumentsRequestObj);
    
    

    external by Edward Ballisty  13  0  1  0

    Mura SSO

    Mura SSO: eventHandler.cfc
    function onSiteRequestStart($) {
    	if (external_service_gives_successful_login_message) {
    		userBean = $.getBean('user').loadBy(username=oAuth.prsId, $.event('siteID'));
    		userBean.setUsername(oAuth.prsId);
    		userBean.setPassword(oAuth.prsId & 'RANDOMREALLYCOMPLICATEDSTRING');
    		userBean.setFname(oAuth.firstName);
    		userBean.setLname(oAuth.lastName);
    		userBean.setEmail(oAuth.emailAddress);
    		userBean.save();
    
    		// log the user in
    		$.event("username", oAuth.prsId);
    		$.event("password", oAuth.prsId & "RANDOMREALLYCOMPLICATEDSTRING");
    
    		$.getBean('loginManager').login($.event().getAllValues(),'');
    	}
    }
    
    
    • Public Snippets
    • Channels Snippets