Wednesday, 30 October 2013

CFSCRIPT ColdFusion Cheat Sheet

FOR Loop
for (i=1;i LTE ArrayLen(array);i=i+1) {
 WriteOutput(array[i]);
}
User Defined Function (UDF)
function funky(mojo) {
 var dojo = 0;
 if (arguments.mojo EQ dojo) {
  return "mojo";
 }
 else { return "no-mojo"; }
}
Switch Case
switch(fruit) {
    case "apple":
         WriteOutput("I like Apples");
         break;
    case "orange":
         WriteOutput("I like Oranges");
         break;
    default: 
         WriteOutput("I like fruit");
}
FOR IN Loop
struct = StructNew();
struct.one = "1";
struct.two = "2";
for (key in struct) {
 WriteOutput(key);
}
//OUTPUTS onetwo
If / Else If / Else
if (fruit IS "apple") {
 WriteOutput("I like apples");
}
else if (fruit IS "orange") {
 WriteOutput("I like oranges");
}
else {
 WriteOutput("I like fruit");
}
Try / Catch / Throw / Finally / Rethrow
try {
 //throw CF9+
 throw(message="Oops", detail="xyz");
} catch (any e) {
 WriteOutput("Error: " & e.message);
 rethrow; //CF9+
} finally { 
 //CF9+
 WriteOutput("I run even if no error");
}
Transactions CF9+
transaction {
 //do stuff
 if (good) {
  transaction action="commit";
 else {
  transaction action="rollback";
 }
}
Single Line Comments
mojo = 1; //THIS IS A COMMENT
Multi-Line Comments
/* This is a comment
 that can span
 multiple lines
*/
While Loop
x = 0;
while (x LT 5) {
 x = x + 1;
 WriteOutput(x);
}
//OUTPUTS 12345
Do / While Loop
x = 0;
do {
 x = x+1;
 WriteOutput(x);
} while (x LTE 0);
// OUTPUTS 1
Set A Variable
foo = "bar";
CFSCRIPT Block
<cfscript>
if (foundeo IS "consulting") {
  //...
}
</cfscript>
CFInclude CF9+
include "template.cfm";
CFScript Component CF9+
component extends="Fruit" output="false" {
 
 property name="variety" type="string";
 
 public boolean function isGood() { 
  return true;
 }
 
 private void eat(required numeric bites) {
  //do stuff
 }
}
Tip: Don't forget to put a semicolon; at the end of each statement.

Bash Programming Cheat Sheet

A quick cheat sheet for programmers who want to do shell scripting. This is not intended to teach programming, etc. but it is intended for a someone who knows one programming language to begin learning about bash scripting.

Basics

All bash scripts must tell the o/s what to use as the interpreter. The first line of any script should be:

#!/bin/bash

You must make bash scripts executable.

chmod +x filename


Variables

Create a variable - just assign value. Variables are non-datatyped (a variable can hold strings, numbers, etc. with out being defined as such).

varname=value

Access a variable by putting $ on the front of the name

echo $varname

Values passed in from the command line as arguments are accessed as $# where #= the index of the variable in the array of values being passed in. This array is base 1 not base 0.
command var1 var2 var3 .... varX
$1 contains whatever var1 was, $2 contains whatever var2 was, etc.

Built in variables:
$1-$N Stores the arguments (variables) that were passed to the shell program from the command line.
$? Stores the exit value of the last command that was executed.
$0 Stores the first word of the entered command (the name of the shell program).
$* Stores all the arguments that were entered on the command line ($1 $2 ...).
"$@" Stores all the arguments that were entered on the command line, individually quoted ("$1" "$2" ...).

Quote Marks

Regular double quotes ("like these") make the shell ignore whitespace and count it all as one argument being passed or string to use. Special characters inside are still noticed/obeyed.

Single quotes 'like this' make the interpreting shell ignore all special characters in whatever string is being passed.

The back single quote marks (`command`) perform a different function. They are used when you want to use the results of a command in another command. For example, if you wanted to set the value of the variable contents equal to the list of files in the current directory, you would type the following command: contents=`ls`, the results of the ls program are put in the variable contents.

Logic and comparisons

A command called test is used to evaluate conditional expressions, such as a if-then statement that checks the entrance/exit criteria for a loop.

test expression
Or
[ expression ]

Numeric Comparisons


int1 -eq int2 Returns True if int1 is equal to int2.
int1 -ge int2 Returns True if int1 is greater than or equal to int2.
int1 -gt int2 Returns True if int1 is greater than int2.
int1 -le int2 Returns True if int1 is less than or equal to int2
int1 -lt int2 Returns True if int1 is less than int2
int1 -ne int2 Returns True if int1 is not equal to int2

String Comparisons

str1 = str2 Returns True if str1 is identical to str2.
str1 != str2 Returns True if str1 is not identical to str2.
str Returns True if str is not null.
-n str Returns True if the length of str is greater than zero.
-z str Returns True if the length of str is equal to zero. (zero is different than null)
File Comparisons


-d filename Returns True if file, filename is a directory.
-f filename Returns True if file, filename is an ordinary file.
-r filename Returns True if file, filename can be read by the process.
-s filename Returns True if file, filename has a nonzero length.
-w filename Returns True if file, filename can be written by the process.
-x filename Returns True if file, filename is executable.


Expression Comparisons

!expression

Returns true if expression is not true
expr1 -a expr2

Returns True if expr1 and expr2 are true. ( && , and )
expr1 -o expr2

Returns True if expr1 or expr2 is true. ( ||, or )



Logic Con't.

If...then

if [ expression ]
then
commands
fi


If..then...else

if [ expression ]
then
commands
else
commands
fi


If..then...else If...else

if [ expression ]
then
commands
elif [ expression2 ]
then
commands
else
commands
fi

Case select

case string1 in
str1)
commands;;
str2)
commands;;
*)
commands;;
esac

string1 is compared to str1 and str2. If one of these strings matches string1, the commands up until the double semicolon (; ;) are executed. If neither str1 nor str2 matches string1, the commands associated with the asterisk are executed. This is the default case condition because the asterisk matches all strings.

Iteration (Loops)

for var1 in list
do
commands
done

This executes once for each item in the list. This list can be a variable that contains several words separated by spaces (such as output from ls or cat), or it can be a list of values that is typed directly into the statement. Each time through the loop, the variable var1 is assigned the current item in the list, until the last one is reached.

while [ expression ]
do
commands
done

until [ expression ]
do
commands
done

Functions

Create a function:

fname(){
commands
}


Call it by using the following syntax: fname

Or, create a function that accepts arguments:

fname2 (arg1,arg2...argN){
commands
}

And call it with: fname2 arg1 arg2 ... argN

Apache Cheat Sheet

Setup a Virtual Domain

NameVirtualHost *
<VirtualHost *>
  DocumentRoot /web/example.com/www
  ServerName www.example.com
  ServerAlias example.com
  CustomLog /web/example.com/logs/access.log combined
  ErrorLog /web/example.com/logs/error.log
</VirtualHost>

Include another conf file

Include /etc/apache/virtual-hosts/*.conf

Hide apache version info

ServerSignature Off
ServerTokens Prod

Custom 404 Error message

ErrorDocument 404 /404.html

Create a virtual directory (mod_alias)

Alias /common /web/common

Perminant redirect (mod_alias)

Redirect permanent /old http://example.com/new

Create a cgi-bin

ScriptAlias /cgi-bin/ /web/cgi-bin/

Process .cgi scripts

AddHandler cgi-script .cgi

Add a directory index

DirectoryIndex index.cfm index.cfm

Turn off directory browsing

Options -Indexes

Turn on directory browsing

<Location /images>
  Options +Indexes
</Location>

Create a new user for basic auth (command line)

htpasswd -c /etc/apacheusers

Apache basic authentication

AuthName "Authentication Required"
AuthType Basic
AuthUserFile /etc/apacheusers
Require valid-user

Only allow access from a specific IP

Order Deny,Allow
Deny from all
Allow from 127.0.0.1

Only allow access from your subnet

Order Deny,Allow
Deny from all
Allow from 176.16.0.0/16
mod_rewrite

Turn on the rewrite engine

RewriteEngine On

Redirect /news/123 to /news.cfm?id=123

RewriteRule ^/news/([0-9]+)$ /news.cfm?id=$1 [PT,L]

Redirect www.example.com to example.com

RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^(.*)$ http://example.com$1 [R=301,L]

htaccess Cheatsheet

Here is a simple cheatsheet for the .htaccess file:
Enable Directory Browsing
Options +Indexes
## block a few types of files from showing
IndexIgnore *.wmv *.mp4 *.avi
Disable Directory Browsing
Options All -Indexes
Customize Error Messages
ErrorDocument 403 /forbidden.html
ErrorDocument 404 /notfound.html
ErrorDocument 500 /servererror.html
Get SSI working with HTML/SHTML
AddType text/html .html
AddType text/html .shtml
AddHandler server-parsed .html
AddHandler server-parsed .shtml
# AddHandler server-parsed .htm
Change Default Page (order is followed!)
DirectoryIndex myhome.htm index.htm index.php
Block Users from accessing the site
<limit GET POST PUT>
order deny,allow
deny from 202.54.122.33
deny from 8.70.44.53
deny from .spammers.com
allow from all
</limit>
Allow only LAN users
order deny,allow
deny from all
allow from 192.168.0.0/24
Redirect Visitors to New Page/Directory
Redirect oldpage.html http://www.domainname.com/newpage.html
Redirect /olddir http://www.domainname.com/newdir/
Block site from specific referrers
RewriteEngine on
RewriteCond %{HTTP_REFERER} site-to-block\.com [NC]
RewriteCond %{HTTP_REFERER} site-to-block-2\.com [NC]
RewriteRule .* - [F]
Block Hot Linking/Bandwidth hogging
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com/.*$ [NC]
RewriteRule \.(gif|jpg)$ - [F]
Want to show a “Stealing is Bad” message too?
Add this below the Hot Link Blocking code:
RewriteRule \.(gif|jpg)$ http://www.mydomain.com/dontsteal.gif [R,L]
Stop .htaccess (or any other file) from being viewed
<files file-name>
order allow,deny
deny from all
</files>
Avoid the 500 Error
# Avoid 500 error by passing charset
AddDefaultCharset utf-8
Grant CGI Access in a directory
Options +ExecCGI
AddHandler cgi-script cgi pl
# To enable all scripts in a directory use the following
# SetHandler cgi-script
Password Protecting Directories
Use the .htaccess Password Generator and follow the brief instructions!
Change Script Extensions
AddType application/x-httpd-php .gne
gne will now be treated as PHP files! Similarly, x-httpd-cgi for CGI files, etc.
Use MD5 Digests
Performance may take a hit but if thats not a problem, this is a nice option to turn on.
ContentDigest On
The CheckSpelling Directive
From Jens Meiert: CheckSpelling corrects simple spelling errors (for example, if someone forgets a letter or if any character is just wrong). Just add CheckSpelling On to your htaccess file.
The ContentDigest Directive
As the Apache core features documentation says: “This directive enables the generation of Content-MD5 headers as defined in RFC1864 respectively RFC2068. The Content-MD5 header provides an end-to-end message integrity check (MIC) of the entity-body. A proxy or client may check this header for detecting accidental modification of the entity-body in transit.
Note that this can cause performance problems on your server since the message digest is computed on every request (the values are not cached). Content-MD5 is only sent for documents served by the core, and not by any module. For example, SSI documents, output from CGI scripts, and byte range responses do not have this header.”
To turn this on, just add ContentDigest On.
Enable Gzip – Save Bandwidth
# BEGIN GZIP
<ifmodule mod_deflate.c>
# Combine the below two lines - I've split it up for presentation
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css
  application/x-javascript application/javascript
</ifmodule>
# END GZIP
Turn off magic_quotes_gpc
# Only if you use PHP
<ifmodule mod_php4.c>
php_flag magic_quotes_gpc off
</ifmodule>
Set an Expires header and enable Cache-Control
<ifmodule mod_expires.c>
  ExpiresActive On
  ExpiresDefault "access plus 1 seconds"
  ExpiresByType text/html "access plus 7200 seconds"
  ExpiresByType image/gif "access plus 518400 seconds"
  ExpiresByType image/jpeg "access plus 518400 seconds"
  ExpiresByType image/png "access plus 518400 seconds"
  ExpiresByType text/css "access plus 518400 seconds"
  ExpiresByType text/javascript "access plus 216000 seconds"
  ExpiresByType application/x-javascript "access plus 216000 seconds"
</ifmodule>

<ifmodule mod_headers.c>
  # Cache specified files for 6 days
  <filesmatch "\.(ico|flv|jpg|jpeg|png|gif|css|swf)$">
  Header set Cache-Control "max-age=518400, public"
  </filesmatch>
  # Cache HTML files for a couple hours
  <filesmatch "\.(html|htm)$">
  Header set Cache-Control "max-age=7200, private, must-revalidate"
  </filesmatch>
  # Cache PDFs for a day
  <filesmatch "\.(pdf)$">
  Header set Cache-Control "max-age=86400, public"
  </filesmatch>
  # Cache Javascripts for 2.5 days
  <filesmatch "\.(js)$">
  Header set Cache-Control "max-age=216000, private"
  </filesmatch>
</ifmodule>

Tuesday, 29 October 2013

Horde webmail attachments not going though in Plesk 11.5

Horde is a common Webmail used for plesk panels. If  you encounter the problem with the following description.

Problem: Horde webmail attachements sent are not receiving at the destination end.

The problem could be due to permission issue of horde temp directories.
Please use the following command after login as root to resolve the issue.

----------------------------------------------------------------------------------------
[root@server]# chown -R horde_sysuser:horde_sysgroup /tmp/.horde
[root@server]# chown -R horde_sysuser:horde_sysgroup /tmp/.horde/*
----------------------------------------------------------------------------------------


Hope this post has helped you

rzm

Thursday, 12 September 2013

Command: ps


  1) What is difference between ps -ef and ps -auxwww?

ps -ef will omit process with very long command line while ps -auxwww will list those process as well.
I have faced this issue while ago where one culprit process was not visible by execute ps –ef command and we are wondering which process is holding the file.

What is the difference between Swapping and Paging? (Unix)


Swapping:
Whole process is moved from the swap device to the main memory for execution. Process size must be less than or equal to the available main memory. It is easier to implementation and overhead to the system. Swapping systems does not handle the memory more flexibly as compared to the paging systems.
Paging:
Only the required memory pages are moved to main memory from the swap device for execution. Process size does not matter. Gives the concept of the virtual memory. It provides greater flexibility in mapping the virtual address space into the physical memory of the machine. Allows more number of processes to fit in the main memory simultaneously. Allows the greater process size than the available physical memory. Demand paging systems handle the memory more flexibly.