Text

Jan 11, 2013
@ 9:36 am
Permalink

Sublime Text 2 Linux Crack

Hi guys 

Just found a working way to use Sublime 2 on linux so just sharing. 

via root go to folder and: 

Code: Select all
sed ‘s/\x33\x42/\x32\x42/g’ sublime_text > cracked 
rm sublime_text && mv cracked sublime_text 
chmod 777 sublime_text



and use: 

Code: Select all
——-BEGIN LICENSE——- 
Patrick Carey 
Unlimited User License 
EA7E-18848 
4982D83B6313800EBD801600D7E3CC13 
F2CD59825E2B4C4A18490C5815DF68D6 
A5EFCC8698CFE589E105EA829C5273C0 
C5744F0857FAD2169C88620898C3845A 
1F4521CFC160EEC7A9B382DE605C2E6D 
DE84CD0160666D30AA8A0C5492D90BB2 
75DEFB9FD0275389F74A59BB0CA2B4EF 
EA91E646C7F2A688276BCF18E971E372 
——-END LICENSE——-



Enjoy !

(Source: sublimetext.com)


Text

Nov 27, 2012
@ 5:03 am
Permalink
1 note

useful nMap Commands

Nmap is short for Network Mapper. It is an open source security tool for network exploration, security scanning and auditing. However, nmap command comes with lots of options that can make the utility more robust and difficult to follow for new users.

The purpose of this post is to introduce a user to the nmap command line tool to scan a host and/or network, so to find out the possible vulnerable points in the hosts. You will also learn how to use Nmap for offensive and defensive purposes.

nmap in action

nmap in action

More about nmap

From the man page:

Nmap (“Network Mapper”) is an open source tool for network exploration and security auditing. It was designed to rapidly scan large networks, although it works fine against single hosts. Nmap uses raw IP packets in novel ways to determine what hosts are available on the network, what services (application name and version) those hosts are offering, what operating systems (and OS versions) they are running, what type of packet filters/firewalls are in use, and dozens of other characteristics. While Nmap is commonly used for security audits, many systems and network administrators find it useful for routine tasks such as network inventory, managing service upgrade schedules, and monitoring host or service uptime.

It was originally written by Gordon Lyon and it can answer the following questions easily:

  1. What computers did you find running on the local network?
  2. What IP addresses did you find running on the local network?
  3. What is the operating system of your target machine?
  4. Find out what ports are open on the machine that you just scanned?
  5. Find out if the system is infected with malware or virus.
  6. Search for unauthorized servers or network service on your network.
  7. Find and remove computers which don’t meet the organization’s minimum level of security.

Sample setup (LAB)

Port scanning may be illegal in some jurisdictions. So setup a lab as follows:

                              +---------+
        +---------+           | Network |         +--------+
        | server1 |-----------+ swtich  +---------|server2 |
        +---------+           | (sw0)   |         +--------+
                              +----+----+
                                   |
                                   |
                         +---------+----------+
                         | wks01 Linux/OSX    |
                         +--------------------+

Where,

  • wks01 is your computer either running Linux/OS X or Unix like operating system. It is used for scanning your local network. The nmap command must be installed on this computer.
  • server1 can be powered by Linux / Unix / MS-Windows operating systems. This is an unpatched server. Feel free to install a few services such as a web-server, file server and so on.
  • server2 can be powered by Linux / Unix / MS-Windows operating systems. This is a fully patched server with firewall. Again, feel free to install few services such as a web-server, file server and so on.
  • All three systems are connected via switch.

How do I install nmap?

See:

  1. Debian / Ubuntu Linux: Install nmap Software For Scanning Network
  2. CentOS / RHEL: Install nmap Network Security Scanner

#1: Scan a single host or an IP address (IPv4)

### Scan a single ip address ###
nmap 192.168.1.1
 
## Scan a host name ###
nmap server1.cyberciti.biz
 
## Scan a host name with more info###
nmap -v server1.cyberciti.biz
 

Sample outputs:

Fig.01: nmap output

Fig.01: nmap output

#2: Scan multiple IP address or subnet (IPv4)

nmap 192.168.1.1 192.168.1.2 192.168.1.3
## works with same subnet i.e. 192.168.1.0/24
nmap 192.168.1.1,2,3

You can scan a range of IP address too:

nmap 192.168.1.1-20

You can scan a range of IP address using a wildcard:

nmap 192.168.1.*

Finally, you scan an entire subnet:

nmap 192.168.1.0/24

#3: Read list of hosts/networks from a file (IPv4)

The -iL option allows you to read the list of target systems using a text file. This is useful to scan a large number of hosts/networks. Create a text file as follows:
cat > /tmp/test.txt
Sample outputs:

server1.cyberciti.biz
192.168.1.0/24
192.168.1.1/24
10.1.2.3
localhost

The syntax is:

nmap -iL /tmp/test.txt

#4: Excluding hosts/networks (IPv4)

When scanning a large number of hosts/networks you can exclude hosts from a scan:

nmap 192.168.1.0/24 --exclude 192.168.1.5
nmap 192.168.1.0/24 --exclude 192.168.1.5,192.168.1.254

OR exclude list from a file called /tmp/exclude.txt

nmap -iL /tmp/scanlist.txt --excludefile /tmp/exclude.txt

#5: Turn on OS and version detection scanning script (IPv4)

nmap -A 192.168.1.254
nmap -v -A 192.168.1.1
nmap -A -iL /tmp/scanlist.txt 

#6: Find out if a host/network is protected by a firewall

nmap -sA 192.168.1.254
nmap -sA server1.cyberciti.biz

#7: Scan a host when protected by the firewall

nmap -PN 192.168.1.1
nmap -PN server1.cyberciti.biz

#8: Scan an IPv6 host/address

The -6 option enable IPv6 scanning. The syntax is:

nmap -6 IPv6-Address-Here
nmap -6 server1.cyberciti.biz
nmap -6 2607:f0d0:1002:51::4
nmap -v A -6 2607:f0d0:1002:51::4

#9: Scan a network and find out which servers and devices are up and running

This is known as host discovery or ping scan:

nmap -sP 192.168.1.0/24

Sample outputs:

Host 192.168.1.1 is up (0.00035s latency).
MAC Address: BC:AE:C5:C3:16:93 (Unknown)
Host 192.168.1.2 is up (0.0038s latency).
MAC Address: 74:44:01:40:57:FB (Unknown)
Host 192.168.1.5 is up.
Host nas03 (192.168.1.12) is up (0.0091s latency).
MAC Address: 00:11:32:11:15:FC (Synology Incorporated)
Nmap done: 256 IP addresses (4 hosts up) scanned in 2.80 second

#10: How do I perform a fast scan?

nmap -F 192.168.1.1

#11: Display the reason a port is in a particular state

nmap --reason 192.168.1.1
nmap --reason server1.cyberciti.biz

#12: Only show open (or possibly open) ports

nmap --open 192.168.1.1
nmap --open server1.cyberciti.biz

#13: Show all packets sent and received

nmap --packet-trace 192.168.1.1
nmap --packet-trace server1.cyberciti.biz

14#: Show host interfaces and routes

This is useful for debugging (ip command or route command or netstat command like output using nmap)

nmap --iflist

Sample outputs:

Starting Nmap 5.00 ( http://nmap.org ) at 2012-11-27 02:01 IST
************************INTERFACES************************
DEV    (SHORT)  IP/MASK          TYPE        UP MAC
lo     (lo)     127.0.0.1/8      loopback    up
eth0   (eth0)   192.168.1.5/24   ethernet    up B8:AC:6F:65:31:E5
vmnet1 (vmnet1) 192.168.121.1/24 ethernet    up 00:50:56:C0:00:01
vmnet8 (vmnet8) 192.168.179.1/24 ethernet    up 00:50:56:C0:00:08
ppp0   (ppp0)   10.1.19.69/32    point2point up
 
**************************ROUTES**************************
DST/MASK         DEV    GATEWAY
10.0.31.178/32   ppp0
209.133.67.35/32 eth0   192.168.1.2
192.168.1.0/0    eth0
192.168.121.0/0  vmnet1
192.168.179.0/0  vmnet8
169.254.0.0/0    eth0
10.0.0.0/0       ppp0
0.0.0.0/0        eth0   192.168.1.2
 

#15: How do I scan specific ports?

map -p [port] hostName
## Scan port 80
nmap -p 80 192.168.1.1
 
## Scan TCP port 80
nmap -p T:80 192.168.1.1
 
## Scan UDP port 53
nmap -p U:53 192.168.1.1
 
## Scan two ports ##
nmap -p 80,443 192.168.1.1
 
## Scan port ranges ##
nmap -p 80-200 192.168.1.1
 
## Combine all options ##
nmap -p U:53,111,137,T:21-25,80,139,8080 192.168.1.1
nmap -p U:53,111,137,T:21-25,80,139,8080 server1.cyberciti.biz
nmap -v -sU -sT -p U:53,111,137,T:21-25,80,139,8080 192.168.1.254
 
## Scan all ports with * wildcard ##
nmap -p "*" 192.168.1.1
 
## Scan top ports i.e. scan $number most common ports ##
nmap --top-ports 5 192.168.1.1
nmap --top-ports 10 192.168.1.1
 

Sample outputs:

Starting Nmap 5.00 ( http://nmap.org ) at 2012-11-27 01:23 IST
Interesting ports on 192.168.1.1:
PORT     STATE  SERVICE
21/tcp   closed ftp
22/tcp   open   ssh
23/tcp   closed telnet
25/tcp   closed smtp
80/tcp   open   http
110/tcp  closed pop3
139/tcp  closed netbios-ssn
443/tcp  closed https
445/tcp  closed microsoft-ds
3389/tcp closed ms-term-serv
MAC Address: BC:AE:C5:C3:16:93 (Unknown)
 
Nmap done: 1 IP address (1 host up) scanned in 0.51 seconds
 

#16: The fastest way to scan all your devices/computers for open ports ever

nmap -T5 192.168.1.0/24

#17: How do I detect remote operating system?

You can identify a remote host apps and OS using the -O option:

 
nmap -O 192.168.1.1
nmap -O  --osscan-guess 192.168.1.1
nmap -v -O --osscan-guess 192.168.1.1

Sample outputs:

Starting Nmap 5.00 ( http://nmap.org ) at 2012-11-27 01:29 IST
NSE: Loaded 0 scripts for scanning.
Initiating ARP Ping Scan at 01:29
Scanning 192.168.1.1 [1 port]
Completed ARP Ping Scan at 01:29, 0.01s elapsed (1 total hosts)
Initiating Parallel DNS resolution of 1 host. at 01:29
Completed Parallel DNS resolution of 1 host. at 01:29, 0.22s elapsed
Initiating SYN Stealth Scan at 01:29
Scanning 192.168.1.1 [1000 ports]
Discovered open port 80/tcp on 192.168.1.1
Discovered open port 22/tcp on 192.168.1.1
Completed SYN Stealth Scan at 01:29, 0.16s elapsed (1000 total ports)
Initiating OS detection (try #1) against 192.168.1.1
Retrying OS detection (try #2) against 192.168.1.1
Retrying OS detection (try #3) against 192.168.1.1
Retrying OS detection (try #4) against 192.168.1.1
Retrying OS detection (try #5) against 192.168.1.1
Host 192.168.1.1 is up (0.00049s latency).
Interesting ports on 192.168.1.1:
Not shown: 998 closed ports
PORT   STATE SERVICE
22/tcp open  ssh
80/tcp open  http
MAC Address: BC:AE:C5:C3:16:93 (Unknown)
Device type: WAP|general purpose|router|printer|broadband router
Running (JUST GUESSING) : Linksys Linux 2.4.X (95%), Linux 2.4.X|2.6.X (94%), MikroTik RouterOS 3.X (92%), Lexmark embedded (90%), Enterasys embedded (89%), D-Link Linux 2.4.X (89%), Netgear Linux 2.4.X (89%) Aggressive OS guesses: OpenWrt White Russian 0.9 (Linux 2.4.30) (95%), OpenWrt 0.9 - 7.09 (Linux 2.4.30 - 2.4.34) (94%), OpenWrt Kamikaze 7.09 (Linux 2.6.22) (94%), Linux 2.4.21 - 2.4.31 (likely embedded) (92%), Linux 2.6.15 - 2.6.23 (embedded) (92%), Linux 2.6.15 - 2.6.24 (92%), MikroTik RouterOS 3.0beta5 (92%), MikroTik RouterOS 3.17 (92%), Linux 2.6.24 (91%), Linux 2.6.22 (90%) No exact OS matches for host (If you know what OS is running on it, see http://nmap.org/submit/ ).
TCP/IP fingerprint:
OS:SCAN(V=5.00%D=11/27%OT=22%CT=1%CU=30609%PV=Y%DS=1%G=Y%M=BCAEC5%TM=50B3CA
OS:4B%P=x86_64-unknown-linux-gnu)SEQ(SP=C8%GCD=1%ISR=CB%TI=Z%CI=Z%II=I%TS=7
OS:)OPS(O1=M2300ST11NW2%O2=M2300ST11NW2%O3=M2300NNT11NW2%O4=M2300ST11NW2%O5
OS:=M2300ST11NW2%O6=M2300ST11)WIN(W1=45E8%W2=45E8%W3=45E8%W4=45E8%W5=45E8%W
OS:6=45E8)ECN(R=Y%DF=Y%T=40%W=4600%O=M2300NNSNW2%CC=N%Q=)T1(R=Y%DF=Y%T=40%S
OS:=O%A=S+%F=AS%RD=0%Q=)T2(R=N)T3(R=N)T4(R=Y%DF=Y%T=40%W=0%S=A%A=Z%F=R%O=%R
OS:D=0%Q=)T5(R=Y%DF=Y%T=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)T6(R=Y%DF=Y%T=40%W=
OS:0%S=A%A=Z%F=R%O=%RD=0%Q=)T7(R=N)U1(R=Y%DF=N%T=40%IPL=164%UN=0%RIPL=G%RID
OS:=G%RIPCK=G%RUCK=G%RUD=G)IE(R=Y%DFI=N%T=40%CD=S)
Uptime guess: 12.990 days (since Wed Nov 14 01:44:40 2012)
Network Distance: 1 hop
TCP Sequence Prediction: Difficulty=200 (Good luck!)
IP ID Sequence Generation: All zeros
Read data files from: /usr/share/nmap
OS detection performed. Please report any incorrect results at http://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 12.38 seconds
           Raw packets sent: 1126 (53.832KB) | Rcvd: 1066 (46.100KB)

See also: Fingerprinting a web-server and a dns server command line tools for more information.

#18: How do I detect remote services (server / daemon) version numbers?

nmap -sV 192.168.1.1

Sample outputs:

Starting Nmap 5.00 ( http://nmap.org ) at 2012-11-27 01:34 IST
Interesting ports on 192.168.1.1:
Not shown: 998 closed ports
PORT   STATE SERVICE VERSION
22/tcp open  ssh     Dropbear sshd 0.52 (protocol 2.0)
80/tcp open  http?
1 service unrecognized despite returning data.

#19: Scan a host using TCP ACK (PA) and TCP Syn (PS) ping

If firewall is blocking standard ICMP pings, try the following host discovery methods:

nmap -PS 192.168.1.1
nmap -PS 80,21,443 192.168.1.1
nmap -PA 192.168.1.1
nmap -PA 80,21,200-512 192.168.1.1

#20: Scan a host using IP protocol ping

nmap -PO 192.168.1.1

#21: Scan a host using UDP ping

This scan bypasses firewalls and filters that only screen TCP:

nmap -PU 192.168.1.1
nmap -PU 2000.2001 192.168.1.1

#22: Find out the most commonly used TCP ports using TCP SYN Scan

 
### Stealthy scan ###
nmap -sS 192.168.1.1
 
### Find out the most commonly used TCP ports using TCP connect scan (warning: no stealth scan)
### OS Fingerprinting ###
nmap -sT 192.168.1.1
 
### Find out the most commonly used TCP ports using TCP ACK scan
nmap -sA 192.168.1.1
 
### Find out the most commonly used TCP ports using TCP Window scan
nmap -sW 192.168.1.1
 
### Find out the most commonly used TCP ports using TCP Maimon scan
nmap -sM 192.168.1.1
 

#23: Scan a host for UDP services (UDP scan)

Most popular services on the Internet run over the TCP protocol. DNS, SNMP, and DHCP are three of the most common UDP services. Use the following syntax to find out UDP services:

nmap -sU nas03
nmap -sU 192.168.1.1

Sample outputs:

 
Starting Nmap 5.00 ( http://nmap.org ) at 2012-11-27 00:52 IST
Stats: 0:05:29 elapsed; 0 hosts completed (1 up), 1 undergoing UDP Scan
UDP Scan Timing: About 32.49% done; ETC: 01:09 (0:11:26 remaining)
Interesting ports on nas03 (192.168.1.12):
Not shown: 995 closed ports
PORT     STATE         SERVICE
111/udp  open|filtered rpcbind
123/udp  open|filtered ntp
161/udp  open|filtered snmp
2049/udp open|filtered nfs
5353/udp open|filtered zeroconf
MAC Address: 00:11:32:11:15:FC (Synology Incorporated)
 
Nmap done: 1 IP address (1 host up) scanned in 1099.55 seconds
 

#24: Scan for IP protocol

This type of scan allows you to determine which IP protocols (TCP, ICMP, IGMP, etc.) are supported by target machines:

nmap -sO 192.168.1.1

#25: Scan a firewall for security weakness

The following scan types exploit a subtle loophole in the TCP and good for testing security of common attacks:

 
## TCP Null Scan to fool a firewall to generate a response ##
## Does not set any bits (TCP flag header is 0) ##
nmap -sN 192.168.1.254
 
## TCP Fin scan to check firewall ##
## Sets just the TCP FIN bit ##
nmap -sF 192.168.1.254
 
## TCP Xmas scan to check firewall ##
## Sets the FIN, PSH, and URG flags, lighting the packet up like a Christmas tree ##
nmap -sX 192.168.1.254
 

See how to block Xmas packkets, syn-floods and other conman attacks with iptables.

#26: Scan a firewall for packets fragments

The -f option causes the requested scan (including ping scans) to use tiny fragmented IP packets. The idea is to split up the TCP header over
several packets to make it harder for packet filters, intrusion detection systems, and other annoyances to detect what you are doing.

nmap -f 192.168.1.1
nmap -f fw2.nixcraft.net.in
nmap -f 15 fw2.nixcraft.net.in
## Set your own offset size with the --mtu option ##
nmap --mtu 32 192.168.1.1

#27: Cloak a scan with decoys

The -D option it appear to the remote host that the host(s) you specify as decoys are scanning the target network too. Thus their IDS might report 5-10 port scans from unique IP addresses, but they won’t know which IP was scanning them and which were innocent decoys:

nmap -n -Ddecoy-ip1,decoy-ip2,your-own-ip,decoy-ip3,decoy-ip4 remote-host-ip
nmap -n -D192.168.1.5,10.5.1.2,172.1.2.4,3.4.2.1 192.168.1.5

#28: Scan a firewall for MAC address spoofing

 
### Spoof your MAC address ##
nmap --spoof-mac MAC-ADDRESS-HERE 192.168.1.1
 
### Add other options ###
nmap -v -sT -PN --spoof-mac MAC-ADDRESS-HERE 192.168.1.1
 
 
### Use a random MAC address ###
### The number 0, means nmap chooses a completely random MAC address ###
nmap -v -sT -PN --spoof-mac 0 192.168.1.1
 

#29: How do I save output to a text file?

The syntax is:

nmap 192.168.1.1 > output.txt
nmap -oN /path/to/filename 192.168.1.1
nmap -oN output.txt 192.168.1.1

#30: Not a fan of command line tools?

Try zenmap the official network mapper front end:

Zenmap is the official Nmap Security Scanner GUI. It is a multi-platform (Linux, Windows, Mac OS X, BSD, etc.) free and open source application which aims to make Nmap easy for beginners to use while providing advanced features for experienced Nmap users. Frequently used scans can be saved as profiles to make them easy to run repeatedly. A command creator allows interactive creation of Nmap command lines. Scan results can be saved and viewed later. Saved scan results can be compared with one another to see how they differ. The results of recent scans are stored in a searchable database.

You can install zenmap using the following apt-get command:
$ sudo apt-get install zenmap
Sample outputs:

[sudo] password for vivek:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
  zenmap
0 upgraded, 1 newly installed, 0 to remove and 11 not upgraded.
Need to get 616 kB of archives.
After this operation, 1,827 kB of additional disk space will be used.
Get:1 http://debian.osuosl.org/debian/ squeeze/main zenmap amd64 5.00-3 [616 kB]
Fetched 616 kB in 3s (199 kB/s)
Selecting previously deselected package zenmap.
(Reading database ... 281105 files and directories currently installed.)
Unpacking zenmap (from .../zenmap_5.00-3_amd64.deb) ...
Processing triggers for desktop-file-utils ...
Processing triggers for gnome-menus ...
Processing triggers for man-db ...
Setting up zenmap (5.00-3) ...
Processing triggers for python-central ...

Type the following command to start zenmap:
$ sudo zenmap
Sample outputs

Fig.02: zenmap in action

Fig.02: zenmap in action


Text

Nov 4, 2012
@ 9:09 am
Permalink

m’kay Jade/HAML Style DOM Builder

Better than templates

 fgnass 22 February 2012

When I saw a project called Jade for jQuery being featured on DailyJS yesterday I thought I should take the time and promote my lightweight Jade/HAML-style DOM builder I wrote some month ago.

In his jQuery Roundup Alex Young writes about jQuery and Jade:

Seeing as both of these technologies are all about CSS selectors, I’ve always felt like it makes sense to use them together.

I agree that using CSS selectors not only to query but also to create elements makes a lot of sense. But using a rather huge templating library like Jade on the client feels just wrong.

What I wanted instead was a jQuery-flavored wrapper around the native DOM API that made it easy to create DOM trees leveraging CSS selectors the same way Jade and HAML do.

Neil Jenkins makes some excellent points why using the DOM instead of templates is a good idea:

  • No need to query the DOM, as you can just save references to nodes you’ll need later as you create them
  • No escaping worries; zero chance of XSS bugs
  • JSHint will validate your syntax
  • Flexibility to use the full power of JS; easily call other functions to generate parts of your DOM tree

He has also written a JsPerf test that shows that using the DOM API is up to 50% faster than using innerHTML in modern browsers.

Let’s build some elements m’kay

M’kay is a tiny (556 bytes) plugin for jQuery or Zepto.js. You can use it like this:

var items = 'Click on one of these'.split(' '); $('body').mk('#message') .mk('a.big', "M'kay on GitHub").attr('href', 'https://github.com/fgnass/mkay')._ .mk('ul', $.map(items, function(text) { return $.mk('li.item', text).click(function() { alert(text); }); })); 

This will generate the following HTML and add a click listener to each item:

<div id="message"> <a class="big" href="https://github.com/fgnass/mkay">M'kay on GitHub</a> <ul> <li class="item">Click</li> <li class="item">on</li> <li class="item">one</li> <li class="item">of</li> <li class="item">these</li> </ul> </div> 

You can play with the example above here on JsFiddle. For sources, tests and documentation please refer to the GitHub project page.

(Source: raw.github.com)


Text

Oct 14, 2012
@ 5:42 pm
Permalink

Understanding Javascript’s “this”

Conceptual Overview of this

When a function is created, a keyword called this is created (behind the scenes), which links to the object in which the function operates. Said another way, this is available to the scope of its function, yet is a reference to the object of which that function is a property/method.

Let’s take a look at this object:

1
2
3
4
5
6
7
8
9
<!DOCTYPE html><html lang="en"><body><script>
var cody = {
  living:true,
  age:23,
  gender:'male',
  getGender:function(){return cody.gender;}
};
console.log(cody.getGender()); // logs 'male'
</script></body></html>

Notice how inside of the getGender function, we are accessing the gender property using dot notation (e.gcody.gender) on the cody object itself. This can be rewritten using this to access the cody object because this points to the cody object.

1
2
3
4
5
6
7
8
9
<!DOCTYPE html><html lang="en"><body><script>
var cody = {
  living:true,
  age:23,
  gender:'male',
  getGender:function(){return this.gender;}
};
console.log(cody.getGender()); // logs 'male'
</script></body></html>

The this used in this.gender simply refers to the cody object on which the function is
operating.

The topic of this can be confusing, but it does not have to be. Just remember that, in general, this is used inside of functions to refer to the object the function is contained within, as opposed to the function itself (exceptions include using the new keyword or call() and apply()).

Important Notes

  • The keyword this looks and acts like any other variable, except you can’t modify it.
  • – As opposed to arguments and any parameters sent to the function, this is a keyword (not a property) in the call/activation object.

How is the Value of this Determined?

The value of this, passed to all functions, is based on the context in which the function is called at runtime. Pay attention here, because this is one of those quirks you just need to memorize.

The myObject object in the code below is given a property called sayFoo, which points to the sayFoofunction. When the sayFoo function is called from the global scope, this refers to the window object. When it is called as a method of myObjectthis refers to myObject.

Since myObject has a property named foo, that property is used.

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html><html lang="en"><body><script>
var foo = 'foo';
var myObject = {foo: 'I am myObject.foo'};
var sayFoo = function() {
  console.log(this['foo']);
};
// give myObject a sayFoo property and have it point to sayFoo function
myObject.sayFoo = sayFoo;
myObject.sayFoo(); // logs 'I am myObject.foo' 12
sayFoo(); // logs 'foo'
</script></body></html>

Clearly, the value of this is based on the context in which the function is being called. Consider that bothmyObject.sayFoo and sayFoo point to the same function. However, depending upon where (i.e. the context) sayFoo() is called from, the value of this is different.

If it helps, here is the same code with the head object (i.e window) explicitly used.

1
2
3
4
5
6
7
8
<!DOCTYPE html><html lang="en"><body><script>
window.foo = 'foo';
window.myObject = {foo: 'I am myObject.foo'};
window.sayFoo = function() { ! console.log(this.foo); };
window.myObject.sayFoo = window.sayFoo;
window.myObject.sayFoo();
window.sayFoo();
</script></body></html>

Make sure that as you pass around functions, or have multiple references to a function, you realize that the value of this will change depending upon the context in which you call the function.

Important Note

  • All variables except this and arguments follow lexical scope.

The this Keyword Refers to the Head Object in Nested Functions

You might be wondering what happens to this when it is used inside of a function that is contained inside of another function. The bad news is in ECMA 3, this loses its way and refers to the head object (windowobject in browsers), instead of the object within which the function is defined.


In the code below, this inside of func2 and func3 loses its way and refers not to myObject but instead to the head object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html><html lang="en"><body><script>
var myObject = {
  func1:function() {
     console.log(this); //logs myObject
     varfunc2=function() {
        console.log(this); //logs window, and will do so from this point on
        varfunc3=function() {
           console.log(this); //logs window, as it’s the head object
        }();
     }();
  }
};
myObject.func1();
</script></body></html>

The good news is that this will be fixed in ECMAScript 5. For now, you should be aware of this predicament, especially when you start passing functions around as values to other functions.

Consider the code below and what happens when passing an anonymous function to foo.func1. When the anonymous function is called inside of foo.func1 (a function inside of a function) the this value inside of the anonymous function will be a reference to the head object.

1
2
3
4
5
6
7
8
9
<!DOCTYPE html><html lang="en"><body><script>
var foo = {
  func1:function(bar){
    bar(); //logs window, not foo
    console.log(this);//the this keyword here will be a reference to foo object
  }
};
foo.func1(function(){console.log(this)});
</script></body></html>

Now you will never forget: the this value will always be a reference to the head object when its host function is encapsulated inside of another function or invoked within the context of another function (again, this is fixed in ECMAScript 5).


Working Around the Nested Function Issue

So that the this value does not get lost, you can simply use the scope chain to keep a reference to this in the parent function. The code below demonstrates how, using a variable called that, and leveraging its scope, we can keep better track of function context.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html><html lang="en"><body><script>
var myObject = {
  myProperty:'Icanseethelight',
    myMethod:function() {
   var that=this; //store a reference to this (i.e.myObject) in myMethod scope varhelperFunctionfunction(){//childfunction
   var helperFunction function() { //childfunction
      //logs 'I can see the light' via scope chain because that=this
           console.log(that.myProperty); //logs 'I can see the light'
           console.log(this); // logs window object, if we don't use "that"
        }();
    }
}
myObject.myMethod(); // invoke myMethod
</script></body></html>

Controlling the Value of this

The value of this is normally determined from the context in which a function is called (except when thenew keyword is used – more about that in a minute), but you can overwrite/control the value of this usingapply() or call() to define what object this points to when invoking a function. Using these methods is like saying: “Hey, call X function but tell the function to use Z object as the value for this.” By doing so, the default way in which JavaScript determines the value of this is overridden.

Below, we create an object and a function. We then invoke the function via call() so that the value ofthis inside the function uses myObject as its context. The statements inside the myFunction function will then populate myObject with properties instead of populating the head object. We have altered the object to which this (inside of myFunction) refers.

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html><html lang="en"><body><script>
var myObject = {};
var myFunction = function(param1, param2) {
  //setviacall()'this'points to my Object when function is invoked
  this.foo = param1;
  this.bar = param2;
  console.log(this); //logs Object{foo = 'foo', bar = 'bar'}
};
myFunction.call(myObject, 'foo', 'bar'); // invoke function, set this value to myObject
console.log(myObject) // logs Object {foo = 'foo', bar = 'bar'}
</script></body></html>

In the example above, we are using call(), but apply() could be used as well. The difference between the two is how the parameters for the function are passed. Using call(), the parameters are just comma separated values. Using apply(), the parameter values are passed inside of an array. Below, is the same idea, but using apply().

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html><html lang="en"><body><script>
var myObject = {};
var myFunction = function(param1, param2) {
  //set via apply(), this points to my Object when function is invoked
  this.foo=param1;
  this.bar=param2;
  console.log(this); // logs Object{foo='foo', bar='bar'}
};
myFunction.apply(myObject, ['foo', 'bar']); // invoke function, set this value
console.log(myObject); // logs Object {foo = 'foo', bar = 'bar'}
</script></body></html>

What you need to take away here is that you can override the default way in which JavaScript determines the value of this in a function’s scope.


Using the this Keyword Inside a User-Defined Constructor Function

When a function is invoked with the new keyword, the value of this — as it’s stated in the constructor — refers to the instance itself. Said another way: in the constructor function, we can leverage the object viathis before the object is actually created. In this case, the default value of this changes in a way not unlike using call() or apply().

Below, we set up a Person constructor function that uses this to reference an object being created. When an instance of Person is created, this.name will reference the newly created object and place a property called name in the new object with a value from the parameter (name) passed to the constructor function.

1
2
3
4
5
6
7
<!DOCTYPE html><html lang="en"><body><script>
var Person = function(name) {
  this.name = name || 'johndoe'; // this will refer to the instanc ecreated
}
var cody = new Person('Cody Lindley'); // create an instance, based on Person constructor
console.log(cody.name); // logs 'Cody Lindley'
</script></body></html>

Again, this refers to the “object that is to be” when the constructor function is invoked using the newkeyword. Had we not used the new keyword, the value of this would be the context in which Person is invoked — in this case the head object. Let’s examine this scenario.

1
2
3
4
5
6
7
8
<!DOCTYPE html><html lang="en"><body><script>
var Person = function(name) {
  this.name=name||'johndoe';
}
var cody = Person('Cody Lindley'); // notice we did not use 'new'
console.log(cody.name); // undefined, the value is actually set at window.name
console.log(window.name); // logs 'Cody Lindley'
</script></body></html>

The Keyword this Inside a Prototype Method Refers to a Constructor instance

When used in functions added to a constructor’s prototype property, this refers to the instance on which the method is invoked. Say we have a custom Person() constructor function. As a parameter, it requires the person’s full name. In case we need to access the full name of the person, we add awhatIsMyFullName method to the Person.prototype, so that all Person instances inherit the method. When using this, the method can refer to the instance invoking it (and thus its properties).

Here I demonstrate the creation of two Person objects (cody and lisa) and the inheritedwhatIsMyFullName method that contains the this keyword to access the instance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html><html lang="en"><body><script>
var Person = function(x){
    if(x){this.fullName = x};
};
Person.prototype.whatIsMyFullName = function() {
    return this.fullName; // 'this' refers to the instance created from Person()
}
var cody = new Person('cody lindley');
var lisa = new Person('lisa lindley');
// call the inherited whatIsMyFullName method, which uses this to refer to the instance
console.log(cody.whatIsMyFullName(), lisa.whatIsMyFullName());
/* The prototype chain is still in effect, so if the instance does not have a
fullName property, it will look for it in the prototype chain.
Below, we add a fullName property to both the Person prototype and the Object
prototype. See notes. */
Object.prototype.fullName = 'John Doe';
var john = new Person(); // no argument is passed so fullName is not added to instance
console.log(john.whatIsMyFullName()); // logs 'John Doe'
</script></body></html>

The take away here is that the keyword this is used to refer to instances when used inside of a method contained in the prototype object. If the instance does not contain the property, the prototype lookup begins.

Notes

- If the instance or the object pointed to by this does not contain the property being referenced, the same rules that apply to any property lookup get applied and the property will be “looked up” on the prototype chain. So in our example, if the fullName property was not contained within our instance then fullNamewould be looked for at Person.prototype.fullName then Object.prototype.fullName.

(Source: net.tutsplus.com)


Link

Oct 10, 2012
@ 7:59 am
Permalink

JOX - Code Editor »

JOX: JavaScript Object X-Change

A Simple One Document Code Editor with all the Text/Code Editing Functionality you would expect from a Web Based Editor/IDE.

CTRL-S: Saves Current Doc

CTRL-I: Import Code from a friend’s Project 


Text

Sep 12, 2012
@ 10:35 am
Permalink

Dynamic HTML/CSS Tooltips using jQuery.

Below is a simple script I wrote to Turn all Anchor Tag Titles into Dynamic HTML/CSS tooltips that can be styled…

jQuery.noConflict()//remove this if jQuery is your only JS framework.

var customClass ””//custom css class for styling tooltips
var elementType ‘div’//what kind of Tag, you may want to use ‘divs’?

jQuery(function(){
    jQuery(‘a’).each(function(){
        var currentName ””;
        //current title
        var currentTitle jQuery(this).attr(‘title’)

        if (currentTitle){
            //unique id built from title
            currentName domIdFromString(currentTitle);            
            //insert new div below target link
            jQuery(this).after(
                //build new div to insert
                jQuery(‘<’+elementType+‘>’)
                    .attr(‘id’,currentName//set dynamic/unique id
                    .addClass(customClass//custom css/class
                    .html(currentTitle//title content
                .css({‘display’:‘none’}//hide
            );
            //store dynamic title id
            jQuery(this).attr(‘data-title-id’,currentName);
            //mouse enter
            jQuery(this).mouseover(function(){
                //reference dynamic title id
                var myId ’#’+jQuery(this).attr(‘data-title-id’);
                jQuery(myId).fadeIn(‘slow’);
            });
            //mouse out/leave
            jQuery(this).mouseleave(function(){
                var myId ’#’+jQuery(this).attr(‘data-title-id’);
                jQuery(myId).fadeOut();
            });
        
            jQuery(this).attr(‘title’,)//clear regular title
        }
        
    });
});
    
    
    
function domIdFromString(myStr){
    myStr+=Math.random();
    myStr=myStr.toLowerCase();
    myStr=myStr.replace(/ /g,””);
    myStr=myStr.replace(/[^a-zA-Z0-9]+/g,””);
    return myStr;
}

(Source: jsfiddle.net)


Text

Aug 29, 2012
@ 5:47 pm
Permalink

How to Create A Trax Application

Step 1 - Getting the source code.

download:

 http://www.phpontrax.com/downloads

check out of svn:

svn co svn://svn.phpontrax.com/trax_repository/trax/trunk trax 

Step 2 - Untar / Checkout into your home directory.

There are 2 folders “trax” and “public”. You can rename public to public_html or what ever your Document Root is on your server. Typically you will have your trax folder on the same level as the public / public_html folder so its not accessible via the web for security. 

If my accounts home folder was /home/john, then the directory structure would probably look something like this:

/home/
   john/
      trax/
         app/
            controllers/
            helpers/
            models/
            views/
               layouts/
         components/
         config/
         db/
         doc/ <= this is for phpDoc generated output
         lib/
         log/
         script/
         tutorials/ <= this is for phpDoc tutorials that go with generated output
         vendor/
            PEAR/ (this is optional, should already be installed in servers php lib dir)
            trax/
      public/
         images/
         javascripts/
         stylesheets/

Step 3 - Input settings for your application.

There are only a few things that need to be set for Trax to work properly. The first thing is in your public / public_html folder there is a .htaccess file. Open that file in the editor of your choice and you need to change two things: 
1. You have to let Trax know where your PEAR installation is so it can use PEAR::DB and PEAR:Mail_mime. Edit the file config/environments.php and set where your php libs directory is at, the directory where your PEAR install is located.

# include path for your php libs (PEAR etc)
define("PHP_LIB_ROOT",      "/usr/local/lib/php");


2. Change part below “:/home/<username>/trax/config” to be whatever the full path to your trax config folder is. For this example it would be “:/home/john/trax/config”.

.htaccess Before:

# php include_path to Trax config directory
php_value include_path .:/home/<username>/trax/config

.htaccess After:

# php include_path to Trax config directory
php_value include_path .:/home/john/trax/config

Only other thing to setup is if your going to use a database then put in the database settings. The config file for the database is in trax/config/database.ini. Again open database.ini and change the apropriate settings.
Depending on what mode Trax is in it will use the corresponding database settings.

[development]
  phptype = mysql
  database = mydatabase_development <= change
  hostspec = localhost
  username = root <= change
  password = ***** <= change
  persistent = true

[test]
  use = development  <= this can be used on any level to use other levels settings

[production]
  phptype = mysql
  database = database
  hostspec = localhost
  username = root
  password =
  persistent = true

Step 4 - Chown logs.

In order for your webserver to be able to write to the log files for Trax you have to do one of the following things.

First cd to the trax folder then do one of the following:

1. Chown the logs folder to the webserver user (www, apache, etc).

chown -R www logs

2. Chmod the logs folder so the world can write to it (777).

chmod -R 777 logs 

Step 5 - Creating Models, Controllers, and Views.

Now that you have steps 1-3 done you should be able to go in your browser to your domain.com and see the default Trax Congradulations page. If that works then you are ready to start using Trax to build your application. In the trax/scripts folder there is a file named generate.php. That file is a commandline php script to generate Models, Controllers, and Views.

If you type at the commandline ./generate.php controller or ./generate.php model it will show you helps on the correct syntax. 

Creating a Model ( model names should always be singular ):

[root@bsd1 /home/john/trax/script]# ./generate.php model
Usage: ./generate.php model ModelName
Description:
        The model generator creates functions for a new model.
        The generator takes a model name as its argument.  The model name may be
        given in CamelCase or under_score and should not be suffixed with 'Model'.
        The generator creates a model class in app/models.
Example:
        ./script/generate.php model Account
        This will create an Account model:
                Model:      app/models/account.php

Creating a controller:

[root@bsd1 /home/john/trax/script]# ./generate.php controller
Usage: ./generate.php controller ControllerName [view1 view2 ...]

Description:
        The controller generator creates functions for a new controller and its views.

        The generator takes a controller name and a list of views as arguments.
        The controller name may be given in CamelCase or under_score and should
        not be suffixed with 'Controller'.  To create a controller within a
        module, specify the controller name as 'folder/controller'.
        The generator creates a controller class in app/controllers with view
        templates in app/views/controller_name.

Example:
        ./script/generate.php controller CreditCard open debit credit close

        Credit card controller with URLs like /credit_card/debit.
                Controller: app/controllers/credit_card_controller.php
                Views:      app/views/credit_card/debit.phtml [...]

Folders Example:
        ./script/generate.php controller 'admin/credit_card' suspend late_fee

        Credit card admin controller with URLs /admin/credit_card/suspend.
                Controller: app/controllers/admin/credit_card_controller.php
                Views:      app/views/admin/credit_card/suspend.phtml [...]

Step 6 - Setup routing.

In Trax you can define what are called “routes”. A route is a specific url that gets translated into a certain controller and action. The standard format of the url is domain.com/controller/action/id. Controller being the controller to load, action being the method in the controller to run, and id being the passed in id if any. You don’t need to do anything here except if you want to define special cases where they type one url and it loads a different controller, An example is if you want Trax to handle the root URL meaning nothing after domain.com. This is done by the adding the following to config/routes.php

$router->connect( "", array(":controller" => "home") );

The above will route for the URL domain.com (the root of the domain). It will load the controller “home” and the default action “index”. 

Another example of routing is say I want a specific name to goto a certain product in my catalog, a shirt called cool shirt, but I don’t want to have to type domain.com/catalog/show/25 and instead want to just be able to type domain.com/coolshirt. The below example shows how to do this.

$router->connect( "coolshirt", array(":controller"=>"catalog",":action"=>"show",":id"=>"25") );

(Source: svn.phpontrax.com)


Text

May 17, 2012
@ 5:52 pm
Permalink

PHP EMAIL/imap client functions

Writing a mail client that handles attachments with PHP

When you think about writing a mail client in PHP, beware it’s fuzzy because of missing documentation on the imap functions in PHP.
PHP uses the imap functions to fetch and handle mailboxes (also POP3) just a matter of how you connect to your mailaccount.

Making the connection

<?
   $ServerName = "{localhost/imap:143}INBOX"; // For a IMAP connection    (PORT 143)
   $ServerName = "{localhost/pop3:110}INBOX"; // For a POP3 connection    (PORT 110)
   
   $UserName = "YOUR USERNAME";
   $PassWord = "YOUR PASSWORD";
   
   $mbox = imap_open($ServerName, $UserName,$PassWord) or die("Could not open Mailbox - try again later!"); 
?>

Now we’ve got a connection to the mailbox.

To retrieve some content from a mailbox we now always use the object $mbox which has many features and almost any of these are more or less documented. You can always find information about it on www.php.netsearch in functions for imap.

Now to an example on how to retrieve a list of all messages:

Message list

<?
   $ServerName = "{localhost/imap:143}INBOX"; // For a IMAP connection    (PORT 143)
   //$ServerName = "{localhost/pop3:110}INBOX"; // For a POP3 connection    (PORT 110)
   
   $UserName = "YOUR USERNAME";
   $PassWord = "YOUR PASSWORD";
   
   $mbox = imap_open($ServerName, $UserName,$PassWord) or die("Could not open Mailbox - try again later!");
   
   if ($hdr = imap_check($mbox)) {
	   echo "Num Messages " . $hdr->Nmsgs ."\n\n<br><br>";
   	$msgCount = $hdr->Nmsgs;
   } else {
   	echo "failed";
   }
   $MN=$msgCount;
   $overview=imap_fetch_overview($mbox,"1:$MN",0);
   $size=sizeof($overview);
   
   echo "<table border=\"0\" cellspacing=\"0\" width=\"582\">";
   
   for($i=$size-1;$i>=0;$i--){
   	$val=$overview[$i];
		$msg=$val->msgno;
   	$from=$val->from;
  		$date=$val->date;
		$subj=$val->subject;
   	$seen=$val->seen;
   
	   $from = ereg_replace("\"","",$from);
   
	   // MAKE DANISH DATE DISPLAY
   	list($dayName,$day,$month,$year,$time) = split(" ",$date); 
		$time = substr($time,0,5);
   	$date = $day ." ". $month ." ". $year . " ". $time;
   
   	if ($bgColor == "#F0F0F0") {
   		$bgColor = "#FFFFFF";
   	} else {
			$bgColor = "#F0F0F0";
		}
   
		if (strlen($subj) > 60) {
   		$subj = substr($subj,0,59) ."...";
		}
   
   	echo "<tr bgcolor=\"$bgColor\"><td colspan=\"2\">$from</td><td colspan=\"2\">$subj</td>
   		 <td class=\"tblContent\" colspan=\"2\">$date</td></tr>\n";
   }
	echo "</table>";
   imap_close($mbox);
?>

This produces a message list where you can read the subject and the date and time for arrival in you mailbox.

The main PHP function used is the imap_fetch_overview($mbox,”1:$MN”,0); in this example it tells PHP to fetch message 1 to $MN ($msgCount = the last message from the connection $mbox).

For each message we retrieve in the main “for loop” some properties.
Thats made with: 
$val=$overview[$i];
$msg=$val->msgno;
$from=$val->from;
$date=$val->date;
$subj=$val->subject;
$seen=$val->seen;

$msg is getting the message number that identifies a single message from the mailbox. The first one is 1
$from is getting the senders name
$date is getting the date and time of the arrival in your mailbox.
$subj is getting the subject of the message
$seen is either 0 or 1 if 1 the message body has been retrieved earlier.

Thats practically all we need to know for now to produce a list of all the messages.
The seen property is not used in my example but you could implement it easily with an if statement that writes a not seen message (with property of 0) in bold if you want an overview over new messages especially if you are connecting to a IMAP account.

Now we’ll take a look on how to retrive the body of the message.

Body retrieval

To retrieve the body of a message I use a nice script posted in www.php.net I thank the author :-)

<?
   function get_mime_type(&$structure) {
   $primary_mime_type = array("TEXT", "MULTIPART","MESSAGE", "APPLICATION", "AUDIO","IMAGE", "VIDEO", "OTHER");
   if($structure->subtype) {
   	return $primary_mime_type[(int) $structure->type] . '/' .$structure->subtype;
   }
   	return "TEXT/PLAIN";
   }
   function get_part($stream, $msg_number, $mime_type, $structure = false,$part_number    = false) {
   
   	if(!$structure) {
   		$structure = imap_fetchstructure($stream, $msg_number);
   	}
   	if($structure) {
   		if($mime_type == get_mime_type($structure)) {
   			if(!$part_number) {
   				$part_number = "1";
   			}
   			$text = imap_fetchbody($stream, $msg_number, $part_number);
   			if($structure->encoding == 3) {
   				return imap_base64($text);
   			} else if($structure->encoding == 4) {
   				return imap_qprint($text);
   			} else {
   			return $text;
   		}
   	}
   
		if($structure->type == 1) /* multipart */ {
   		while(list($index, $sub_structure) = each($structure->parts)) {
   			if($part_number) {
   				$prefix = $part_number . '.';
   			}
   			$data = get_part($stream, $msg_number, $mime_type, $sub_structure,$prefix .    ($index + 1));
   			if($data) {
   				return $data;
   			}
   		} // END OF WHILE
   		} // END OF MULTIPART
   	} // END OF STRUTURE
   	return false;
   } // END OF FUNCTION
   
?> 

The function get_part() needs 3 parameters.
1. Mailbox connection (e.g. $mbox from my connection example)
2. Message number to look up (e.g. $msg from my message list example)
3. A content type to check for

In my following example I’ll check for the content types of TEXT/PLAIN and TEXT/HTML which are the common MIME of an email message body. However when it comes to attachments you simply don’t know what MIME the attachment has. This gives us a problem we’ll deal with in a very short time. - Hang on!

To get the message body we invoke the function get_part() like this:

 <?
   // GET TEXT BODY
   $dataTxt = get_part($mbox, $msgno, "TEXT/PLAIN");
   
   // GET HTML BODY
   $dataHtml = get_part($mbox, $msgno, "TEXT/HTML");
   
   if ($dataHtml != "") {
	   $msgBody = $dataHtml;
   	$mailformat = "html";
   } else {
   	$msgBody = ereg_replace("\n","<br>",$dataTxt);
   	$mailformat = "text";
   }
	// To out put the message body to the user simply print $msgBody like this.
   
   if ($mailformat == "text") {
   	echo "<html><head><title>Messagebody</title></head><body    bgcolor=\"white\">$msgBody</body></html>";
   } else {
   	echo $msgBody; // It contains all HTML HEADER tags so we don't have to make them.
   }
?> 

To make the text-body more userfriendly in our browser we could make it more HTML-like if we would replace all URLs with an actual HYPERLINK on. And sometimes messages in HTML are sent with a character encoding that looks very weird because the HTML is posted raw from some email clients, we’ll also change that.

To do that we use this replacement statements:

 function transformHTML($str) {
   if ((strpos($str,"<HTML") < 0) || (strpos($str,"<html")    < 0)) {
  		$makeHeader = "<html><head><meta http-equiv=\"Content-Type\"    content=\"text/html; charset=iso-8859-1\"></head>\n";
   	if ((strpos($str,"<BODY") < 0) || (strpos($str,"<body")    < 0)) {
   		$makeBody = "\n<body>\n";
   		$str = $makeHeader . $makeBody . $str ."\n</body></html>";
   	} else {
   		$str = $makeHeader . $str ."\n</html>";
   	}
   } else {
   	$str = "<meta http-equiv=\"Content-Type\" content=\"text/html;    charset=iso-8859-1\">\n". $str;
   }
   	return $str;
 }
   
 if ($dataHtml != "") {
	$msgBody = transformHTML($dataHtml);
 } else {
   $msgBody = ereg_replace("\n","<br>",$dataTxt);
   $msgBody = preg_replace("/([^\w\/])(www\.[a-z0-9\-]+\.[a-z0-9\-]+)/i","$1http://$2",    $msgBody);
   $msgBody = preg_replace("/([\w]+:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/i","<A    TARGET=\"_blank\" HREF=\"$1\">$1</A>", $msgBody);
   $msgBody = preg_replace("/([\w-?&;#~=\.\/]+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?))/i","<A    HREF=\"mailto:$1\">$1</A>",$msgBody);
 }

With this replacement you’ll see real hyperlinks in the text-body. And now comes the fuzzy part - attachmenthandling.

Attachment handling

Attachments are parts of a messagebody if the messagebody contains 2 or more parts there should be a file attached to the message. Though Outlook 2000 and Outlook Express have support for “Stationary” - embedded HTML layout with images and so. This is really painful to make visible in the HTML body. I’ve not made it work YET!

First we’ll make a list of the attachments from a message.
In my example it’s a FORM SELECT box.

<?
   $struct = imap_fetchstructure($mbox,$msgno);
   $contentParts = count($struct->parts);
   
   if ($contentParts >= 2) {
	   for ($i=2;$i<=$contentParts;$i++) {
   	$att[$i-2] = imap_bodystruct($mbox,$msgno,$i);
   	}
   	for ($k=0;$k<sizeof($att);$k++) {
   		if ($att[$k]->parameters[0]->value == "us-ascii" || $att[$k]->parameters[0]->value    == "US-ASCII") {
   			if ($att[$k]->parameters[1]->value != "") {
   				$selectBoxDisplay[$k] = $att[$k]->parameters[1]->value;
   			}
   		} elseif ($att[$k]->parameters[0]->value != "iso-8859-1" &&    $att[$k]->parameters[0]->value != "ISO-8859-1") {
   			$selectBoxDisplay[$k] = $att[$k]->parameters[0]->value;
   		}
   	}
   }
   
   if (sizeof($selectBoxDisplay) > 0) {
   	echo "<select name=\"attachments\" size=\"3\" class=\"tblContent\"    onChange=\"handleFile(this.value)\" style=\"width:170;\">";
   	for ($j=0;$j<sizeof($selectBoxDisplay);$j++) {
   		echo "\n<option value=\"$j\">". $selectBoxDisplay[$j]    ."</option>";
   	}
   	echo "</select>";
   }
?>

Now we’ve made a selectbox with the attached files listed.
The thing is now - well it’s a beautiful list but we want to by able to download the files. To force download of HTML file instead of have it opened in the browser window we need to use a state of the art browser like Microsoft Internet Explorer 5.5 or later. This browser can make use of a Content-Disposition header which can hold an attachment so the browser will prompt with a Save file dialog box. But as I’ve seen on www.w3c.orgthis is going to be a standard. So we can only hope Netscape/Mozilla will support it soon. I don’t know if Netscape 6 supports it in some way. I haven’t made my example work in any other browser than MSIE 5.5 and 6. Now to the download file stuff.

The selectbox has a onChange eventhandler, if you click on a file in the selectbox the handleFile javascript function is triggered.
Here is the javascript:

<script language="JavaScript">
   var b;
   browser = navigator.appName;
   if (browser == "Microsoft Internet Explorer") {
   	b = "ie";
   } else {
   	b = "other";
   }
   
   function handleFile(nr) {
   	if (b != "ie") {
   		alert("This feature is currently only available for Microsoft Internet Explorer 5.5+ users\n\nWait for an update!");
   	} else {
   		check = confirm("Do you want to download the file ?");
   		if (check) {
   			setTimeout("this.location.reload()",8000);
   			location.href="gotodownload.php?download=1&file="+ nr +"&msgno=<?= $msgno ?>";
   		} else {
   			location.reload();
   		}
   	}
   }
</script>

The script asks you whether you want to download the file. If you click the OK button you’ll be redirected to the file gotodownload.php. The redirect has 3 parameters in the querystring: download=1 to force a download, file=”+ nr the attached file you clicked (selected) in the selectbox and finally the message number that identifies the message that holds the attached file.

The file gotodownload.php looks like this.

<?
   if ($download == "1") {
   	$strFileName = $att[$file]->parameters[0]->value;
   	$strFileType = strrev(substr(strrev($strFileName),0,4));
   	$fileContent = imap_fetchbody($mbox,$msgno,$file+2);
   	downloadFile($strFileType,$strFileName,$fileContent);
   }
   
   function downloadFile($strFileType,$strFileName,$fileContent) {
   	$ContentType = "application/octet-stream";
   
   	if ($strFileType == ".asf") 
   		$ContentType = "video/x-ms-asf";
   	if ($strFileType == ".avi")
   		$ContentType = "video/avi";
   	if ($strFileType == ".doc")
   		$ContentType = "application/msword";
   	if ($strFileType == ".zip")
   		$ContentType = "application/zip";
   	if ($strFileType == ".xls")
   		$ContentType = "application/vnd.ms-excel";
   	if ($strFileType == ".gif")
   		$ContentType = "image/gif";
   	if ($strFileType == ".jpg" || $strFileType == "jpeg")
   		$ContentType = "image/jpeg";
   	if ($strFileType == ".wav")
   		$ContentType = "audio/wav";
   	if ($strFileType == ".mp3")
   		$ContentType = "audio/mpeg3";
   	if ($strFileType == ".mpg" || $strFileType == "mpeg")
   		$ContentType = "video/mpeg";
   	if ($strFileType == ".rtf")
   		$ContentType = "application/rtf";
   	if ($strFileType == ".htm" || $strFileType == "html")
   		$ContentType = "text/html";
   	if ($strFileType == ".xml") 
   		$ContentType = "text/xml";
   	if ($strFileType == ".xsl") 
   		$ContentType = "text/xsl";
   	if ($strFileType == ".css") 
   		$ContentType = "text/css";
   	if ($strFileType == ".php") 
   		$ContentType = "text/php";
   	if ($strFileType == ".asp") 
   		$ContentType = "text/asp";
   	if ($strFileType == ".pdf")
   		$ContentType = "application/pdf";
   
	header ("Content-Type: $ContentType"); 
	header ("Content-Disposition: attachment; filename=$strFileName; size=$fileSize;"); 
	
	// Updated oktober 29. 2005
	if (substr($ContentType,0,4) == "text") {
	echo imap_qprint($fileContent);
	} else {
	echo imap_base64($fileContent);
	}
    }
?>

You’ll see that you’re actually not being redirected to the file called gotodownload.php instead you’ll be prompted with a Save file dialog if you’re using Microsoft Internet Explorer 5.5 or later.

In most cases you can download the file. Sometimes it won’t and I’m still on the hunt why!
I have som concerns in the Microsoft Windows/MSIE system making somekind of nothing when you’re downloading files associated with programs that are trying to be opened directly from the browser session. What happens if it fails is that you can see the browser is loading something but you’re never asked where on your filesystem to store the file.

After all I hope you find my examples useful.
Anyways feel free to question me: php-dev(at)steffer(dot)dk

Thank you for letting me take your time
C ya ‘round 
Kevin Steffer
(a.k.a.: Echelon, EchelonDK, gutter|echelon, focusman, focusman7, ksteffer, mac_that_dog …. look @ #linuxhelp on Undernet IRC)

I’ve started a discussion thread on this subject - be helpful - contribute if you want.
Go to discussion

See more articles by Kevin Steffer Overview


Text

Apr 2, 2012
@ 9:12 am
Permalink

Post Thumbnails in Wordpress

Post Thumbnails

Post Thumbnail is a theme feature introduced with Version 2.9. Thumbnail is an image that is chosen as the representative image for Posts, Pages or Custom Post Types. The display of this images is up to the theme. This is especially useful for “magazine-style” themes where each post has an image.

Enabling Support for Post Thumbnails

Themes have to declare their support for post images before the interface for assigning these images will appear on the Edit Post and Edit Page screens. They do this by putting the following in their functions.php file:

if ( function_exists( 'add_theme_support' ) ) { 
  add_theme_support( 'post-thumbnails' ); 
}

Note: To enable Post Thumbnails only for specific post types see add_theme_support()

Setting a Post Thumbnail

If your theme was successful in adding support for Post Thumbnails the “Featured Image” metabox will be visible on the on the Edit Post and Edit Page screens. If it isn’t, make sure “Featured Image” is enabled in the screen options on the top right.

Featured Image Metabox

Featured image metabox

After clicking the “Set featured image” link follow the same steps as inserting images in Posts and Pages. But instead of the “Insert into Post” button use the “Use as featured image” link next to it, to set the Post Thumbnail.

image insert button

Insert image button

Function Reference

Template Tags

Other Functions

Examples

Default Usage

<?php 
if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
  the_post_thumbnail();
} 
?>
<?php the_content(); ?>

Note: To return the Post Thumbnail for use in your PHP code instead of displaying it, use: get_the_post_thumbnail()

Linking to Post or Larger Image

To link the Post Thumbnail to the Post permalink or a larger image see the examples in the_post_thumbnail()

Thumbnail Sizes

The default image sizes of WordPress are “thumbnail”, “medium”, “large” and “full” (the image you uploaded). These image sizes can be configured in the WordPress Administration Media panel under Settings > Media. This is how you use these default sizes withthe_post_thumbnail():

the_post_thumbnail();                  // without parameter -> Thumbnail

the_post_thumbnail('thumbnail');       // Thumbnail (default 150px x 150px max)
the_post_thumbnail('medium');          // Medium resolution (default 300px x 300px max)
the_post_thumbnail('large');           // Large resolution (default 640px x 640px max)

the_post_thumbnail( array(100,100) );  // Other resolutions

Set the Post Thumbnail Size

To be used in the current Theme’s functions.php file.

Set the default Post Thumbnail size by resizing the image proportionally (that is, without distorting it):

set_post_thumbnail_size( 50, 50 ); // 50 pixels wide by 50 pixels tall, resize mode

Set the default Post Thumbnail size by cropping the image (either from the sides, or from the top and bottom):

set_post_thumbnail_size( 50, 50, true ); // 50 pixels wide by 50 pixels tall, crop mode

Add New Post Thumbnail Sizes

Example of a new Post Thumbnail size named “category-thumb”.

To be used in the current Theme’s functions.php file.

add_image_size( 'category-thumb', 300, 9999 ); //300 pixels wide (and unlimited height)

Here is an example of how to use this new Post Thumbnail size in theme template files.

<?php the_post_thumbnail( 'category-thumb' ); ?>

Example of functions.php

if ( function_exists( 'add_theme_support' ) ) { 
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 150, 150, true ); // default Post Thumbnail dimensions (cropped)

// additional image sizes
// delete the next line if you do not need additional image sizes
add_image_size( 'category-thumb', 300, 9999 ); //300 pixels wide (and unlimited height)
}

Styling Post Thumbnails

Post Thumbnails are given a class “wp-post-image”. They also get a class depending on the size of the thumbnail being displayed You can style the output with these CSS selectors:

img.wp-post-image
img.attachment-thumbnail
img.attachment-medium
img.attachment-large
img.attachment-full

You can also give Post Thumbnails their own class.
Display the Post Thumbnail with a class “alignleft”:

<?php the_post_thumbnail('thumbnail', array('class' => 'alignleft')); ?>

Source File


Text

Jan 23, 2012
@ 12:06 pm
Permalink
67 notes

Active Record Associations in the PHPonTRAX framework.

Active Record Table Associations

belongs_to / has_one

Both express a 1-1 relationship, the difference is mostly where to place the foreign key, which goes on the table for the class saying belongs_to. For belongs_to the foreign key from another table is in this table. For has_one there is a foreign key in another table to this table. Association names should be singular for both assoiation types.

Example:

class Post extends ActiveRecord {
    public $has_one = "author"; # <= singular name
}

class Author extends ActiveRecord {
    public $belongs_to = "post"; # <= singular name
}

The tables for these classes could look something like:

  CREATE TABLE posts (
    id int(11) NOT NULL auto_increment,
    title varchar default NULL,
    PRIMARY KEY  (id)
  )

  CREATE TABLE authors (
    id int(11) NOT NULL auto_increment,
    post_id int(11) default NULL,
    name varchar default NULL,
    PRIMARY KEY  (id)
  )

has_many

This expresses a 1-M relationship. There should be a foreign key in another table to this table where there are many records in that table linking to this table. Association names should be plural

Example:

class User extends ActiveRecord {
    public $has_many = "notes"; # <= plural name
}

class Note extends ActiveRecord {
    public $belongs_to = "user";  # <= singular name  
}

The tables for these classes could look something like:

  CREATE TABLE users (
    id int(11) NOT NULL auto_increment,
    fist_name varchar default NULL,
    last_name varchar default NULL,
    PRIMARY KEY  (id)
  )

  CREATE TABLE notes (
    id int(11) NOT NULL auto_increment,
    user_id int(11) default NULL,
    note_text text default NULL,
    PRIMARY KEY  (id)
  )

has_and_belongs_to_many ( habtm )

This expresses a M-M relationship. There should be three tables. Two tables with a third joining table. Association names should be plural. The joining table name must be named table1_table2plural names for both in alphabetical order

Example:

class Product extends ActiveRecord {
    public $has_and_belongs_to_many = "categories"; # <= plural name
}

class Category extends ActiveRecord {
    public $has_and_belongs_to_many = "products"; # <= plural name  
}

The tables for these classes could look something like:

  CREATE TABLE products (
    id int(11) NOT NULL auto_increment,
    sku varchar default NULL,
    name varchar default NULL,
    price DECIMAL(9,2) NOT NULL,
    PRIMARY KEY  (id)
  )

  CREATE TABLE categories (
    id int(11) NOT NULL auto_increment,
    name varchar default NULL,
    PRIMARY KEY  (id)
  )

  CREATE TABLE categories_products (
    category_id int(11) NOT NULL auto_increment,
    product_id int(11) default NOT NULL
  )

Notes

If you need to define more that one of any of the above associations in the same model class, you can do the following:

public $belongs_to = "assoc1,assoc2,assoc3,etc....";  

If you need to specify additional parameters with the association beside just the name you will have to define it as follows:

public $belongs_to = array("assoc1" => array("foreign_key"=> "weird_key"),
                           "assoc2" => null,
                           "assoc3" => array("conditions" => "age > 25"),
                           etc ...
                          ); 

(Source: svn.phpontrax.com)