Thursday, October 4, 2007

Automatic Backup Data To TAPE

If you want run scheduler for backup your data from disk to tape, please follow its steps below. Make sure your tape drive(s) is installed properly.

Check with command below assume that your tape drive(s) is /dev/st0 or /dev/nst0 or /dev/tape. Before run this command please insert tape into drive.

[root@intranet~]# mt -f /dev/st0 status

SCSI 2 tape drive:
File number=0, block number=0, partition=0.
Tape block size 512 bytes. Density code 0x40 (DLT1 40 GB, or Ultrium).
Soft error count since last status=0
General status bits on (41010000):
BOT ONLINE IM_REP_EN


If your tape drive is OK then please create script to backup your data and place into one location or path.

# vi backup.sh

#!/bin/sh
###################################
# Konang Supian #
# 04 Okt 2007 MDGTI #
###################################
# File naming : day.month.year
suffix=$(date +%d.%m.%Y)
# Path to save file
echo Creating New Directory ....
dir=/usr/backup
dir1=$dir/$suffix
/bin/mkdir -p $dir1
# Daily Backup DB Mysql
echo Compressing DB MySQL ....
/bin/tar -zcf $dir1/mysql.$suffix.tar.gz /var/lib/mysql
# Daily Backup Source Program
echo Compressing Source Program ....
/bin/tar -zcf $dir1/source.$suffix.tar.gz /aplikasi
# Daily Backup DNS Zone
echo Compressing DNS Zone Data ....
/bin/tar -zcf $dir1/named.$suffix.tar.gz /var/named/chroot/var/named
# Writes to TAPE
echo FULL BACUP TO TAPE ....
/bin/tar cvf /dev/st0 $dir
echo ------------
echo FINISH REK
echo ------------



Edit your crontab :

# crontab -e

# Backup Harian DB Mysql, Source Program & DNS - pukul 05:00 pagi
0 5 * * * /root/backup.sh

[LIST TAPE]
#
/bin/tar -tvf /dev/st0

Example:
[root@intranet~]# tar -tvf /dev/st0

drwxr-xr-x root/root 0 2007-10-04 10:09:16 usr/backup/04.10.2007/
-rw-r--r-- root/root 12409437 2007-10-04 10:36:25 usr/backup/04.10.2007/mysql.04.10.2007.tar.gz
-rw-r--r-- root/root 228892698 2007-10-04 10:36:46 usr/backup/04.10.2007/source.04.10.2007.tar.gz


[EXTRACT TAPE]
# /bin/tar -xvf /dev/st0

[REWIND & EJECT TAPE]
# /bin/mt -f /dev/st0 rewoffl

Wednesday, September 26, 2007

Create LDAP Addressbook from Qmail Account

#!/usr/bin/perl

# Filename: import.pl
# Create LDAP addressbook or account by read vpopmail database on MYSQL
# konangsupian@gmail.com
# 13 Okt 2006
# ------------------------
# Updated Sept 2007
# Command shell to get realname & username from vpopmail database.
# mysql -u vpopmail -pmyvpopmailpasswd -e "use vpopmail; select pw_gecos,pw_name from mycompany_com;" > mycompany.txt


$ou = "addressbook";
open(LOGFILE,"mycompany.txt") or die("Could not open file.");
while (<LOGFILE>) {
chop($_);
@pisah = split("\t",$_);
$email = $pisah[1]."\@mycompany\.com";
$realname = $pisah[0];
@name = split(" ",$realname);
$var = "";
$var .= "\r\n\r\n";
$var .= "dn: cn=$realname ($email),ou=$ou,dc=mycompany,dc=com\r\n";
$var .= "objectClass: top\r\n";
$var .= "objectClass: person\r\n";
$var .= "objectClass: organizationalPerson\r\n";
$var .= "objectClass: inetOrgPerson\r\n";
#$var .= "objectClass: user\r\n";
$var .= "cn: $realname ($email)\r\n";
$var .= "givenName: $realname\r\n";
$var .= "sn: $name[0]\r\n";
$var .= "mail: $email\r\n";
$var .= "physicalDeliveryOfficeName: Gd. Kwarnas Pramuka Jl. Medan Merdeka Timur No. 6 Jakarta\r\n";
$var .= "postalAddress: Gd. Kwarnas Pramuka Jl. Medan Merdeka Timur No. 6 Jakarta\r\n";
$var .= "o: MYCOMPANY\r\n";
$var .= "l: Jakarta\r\n";
$var .= "ou: $ou\r\n";
$var .= "st: DKI\r\n";
$var .= "postalCode: 10110\r\n";
$var .= "telephoneNumber: +62-21-12345\r\n";
$var .= "facsimileTelephoneNumber: +62-21-54321\r\n";
$var .= "pager: +62-\r\n";
$var .= "mobile: +62-\r\n";
$var .= "homePhone: +62-\r\n";
#$var .= "associatedDomain: internaldomain.com\r\n";
#$var .= "ou: mdgti\r\n";
#$var .= "userPassword: {MD5}yFfXwwYLUsJXeqTg==\r\n";
print $var;
}
close($LOGFILE);

# End of import.pl


Action on shell
# ./import.pl > mycompany.ldif

Import data to LDAP with command :
# ldapadd -x -v -c -D "dc=mycompany,dc=com" -W < mycompany.ldif
Enter password: ********

*** Done ****


Sunday, September 23, 2007

Qmail Cluster ? Qmail Partitioning ? Qmail - Postfix Collaboration

Why I use questions on title above?
Because I' m not sure with my concept below is called Qmail Cluster.
Clustering that I get from here is :


CLUSTERING - Clustering is a technology using two or more computers that function together as a single entity for fault tolerance and load balancing. This can increase reliability and uptime in a client/server environment. One computer will sense when another computer is failing or getting bogged down and will take over full operation or just some of its tasks, depending on whether it's a complete fail-over design or just load balancing.

I agree that my design below on picture is called Qmail Partitioning because in my design there is no fail over function and or take over function. In my design only separate a single domain into some server that separated by location on same WAN/MPLS.

I am not writing completely because I assume you are Linux/Unix system administrator so you can get complete of Qmail and Postfix resources at their official site :

http://www.qmail.org/
http://www.lifewithqmail.org/
http://www.postfix.org/



Qmail Cluster, Qmail Partitioning, Qmail - Postfix CollaborationNote : my design above is already tested and running well.

Please review my design above and drop your comment below.

Wednesday, September 19, 2007

Configure Awstats for Qmail Log

You may have Qmail statistic before read this article. I don't know what you have is better or similar with this one, Awstats Qmail log analyzer. But if you have time you may try this one.

To create Awstats to analyze Qmail Log you have to prepare :

  1. Log repository, put on crontab and will grep qmail log every 10 minutes. May this not accurate because the log can be duplicate but you can sort this for unique row. Place this log at /var/log/awstats.qmail

    [getlog.sh]
    #!/bin/sh
    #!/bin/sh
    cat /var/log/qmail/qmail-pop3d/current > /var/log/awstats.qmail
    cat /var/log/qmail/qmail-send/current >> /var/log/awstats.qmail
    cat /var/log/qmail/qmail-smtpd/current >> /var/log/awstats.qmail


  2. Awstats, download this cute statistics from http://awstats.sourceforge.net/
  3. Get the script tools that will be used for at ../path/to/awstats/tools. You only need maillogconvert.pl script.
  4. Create the small program from Phil Hagen named "qmail2awstats.pl" and
    [qmail2awstats.pl]
    #!/usr/bin/perl
    # written by phil hagen on 27sep03

    while (<>) {
    @months = ('NUL', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); $hostname = `hostname`;
    # $hostname = `hostname -s`;
    chomp $hostname;
    $line = $_;
    $line =~ s/\d{4}-(\d{2})-(\d{2}) (\d{2}:\d{2}:\d{2}).\d{9} (.*)/$months[$1] $2 $3 $hostname qmail: 0000000000.000000 $4/; print $line;
    }

  5. Edit the Awstats configuration that placed or may have to create at /etc/awstats/awstats.mail.conf that called only short name "mail" later in awstats command.

    [/etc/awstats/awstats.mail.conf]
    LogFile="/usr/local/bin/tai64nlocal < /var/log/awstats.qmail |\
    /var/www/htdocs/awstats/tools/qmail2awstats.pl | \
    /var/www/htdocs/awstats/tools/maillogconvert.pl standard | "

    SiteDomain="mail.mydomain.com"
    HostAliases="mail.mydomain.com"
    DirData="/data/awstats"
    DirCgi="/awstats"
    DirIcons="/awstatsicons"
    AllowToUpdateStatsFromBrowser=0
    AllowFullYearView=2
    LogType=M
    LogFormat="%time2 %email %email_r %host %host_r %method %url %code %bytesd"
    LevelForBrowsersDetection=0
    LevelForOSDetection=0
    LevelForRefererAnalyze=0
    LevelForRobotsDetection=0
    LevelForWormsDetection=0
    LevelForSearchEnginesDetection=0
    LevelForFileTypesDetection=0
    ShowMenu=1
    ShowSummary=HB
    ShowMonthStats=HB
    ShowDaysOfMonthStats=HB
    ShowDaysOfWeekStats=HB
    ShowHoursStats=HB
    ShowDomainsStats=0
    ShowHostsStats=HBL
    ShowAuthenticatedUsers=0
    ShowRobotsStats=0
    ShowEMailSenders=HBML
    ShowEMailReceivers=HBML
    ShowSessionsStats=0
    ShowPagesStats=0
    ShowFileTypesStats=0
    ShowFileSizesStats=0
    ShowBrowsersStats=0
    ShowOSStats=0
    ShowOriginStats=0
    ShowKeyphrasesStats=0
    ShowKeywordsStats=0
    ShowMiscStats=0
    ShowHTTPErrorsStats=0
    ShowSMTPErrorsStats=1

    Why the awstats configuration must be at /etc/awstats ? Here is the DOC:

    # AWSTATS CONFIGURE FILE 6.6
    #-----------------------------------------------------------------------------
    # Copy this file into awstats.www.mydomain.conf and edit this new config file
    # to setup AWStats (See documentation in docs/ directory).
    # The config file must be in /etc/awstats, /usr/local/etc/awstats or /etc (for
    # Unix/Linux) or same directory than awstats.pl (Windows, Mac, Unix/Linux...)
    # To include an environment variable in any parameter (AWStats will replace
    # it with its value when reading it), follow the example:
    # Parameter="__ENVNAME__"
    # Note that environment variable AWSTATS_CURRENT_CONFIG is always defined with
    # the config value in an AWStats running session and can be used like others.
    #-----------------------------------------------------------------------------


  6. Create directory to save the log data
    # mkdir -p /data/awstats

  7. Add and change the cgi alias on apache, the configuration is :
    ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"

    <Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Order allow,deny
    Allow from all
    </Directory>

    Alias /awstatsclasses "/var/www/htdocs/awstats/wwwroot/classes/"
    Alias /awstatscss "/var/www/htdocs/awstats/wwwroot/css/"
    Alias /awstatsicons "/var/www/htdocs/awstats/wwwroot/icon/"
    ScriptAlias /awstats/ "/var/www/htdocs/awstats/wwwroot/cgi-bin/"

    <Directory "/var/www/htdocs/awstats/wwwroot">
    Options None
    AllowOverride None
    Order allow,deny
    Allow from all
    </Directory>

    Restart apache.
  8. Create and or add in crontab :
    #Awstats mail statistics
    */10 * * * * /var/www/htdocs/awstats/tools/getlog.sh
    */15 * * * * /var/www/htdocs/awstats/wwwroot/cgi-bin/awstats.pl -update -config=mail > /dev/null

  9. Run at your browser to access your mail statistics :
    http://www.mydomain.com/awstats/awstats.pl?config=mail

  10. Done.

    Awstats for Qmail

Sunday, September 16, 2007

Squid & Dansguardian the proxy and web content filter

If you have huge network with huge users that can be categorized "the creative users" so make you unhappy with your bandwidth usage that in fact is for unproductive uses.

You can choose this solution by combination of using Squid proxy (http://www.squid-cache.org/) and Dansguardian (http://dansguardian.org/) as a web content filtering. As my exeperience you can use of any Squid stable release. For Dansguardan I suggest you to use the old version reason by the speed performance. I use the version dansguardian-2.8.0.6.source.tar.gz and this is the best performance of Dansguardian.

Here you will find the Dansguardian and Squid configuration. For example below the Dansguardian listen on port 3128 on IP address 10.80.123.202 and the Squid Proxy listen on port 33445 on the same IP.


[ Dansguardian ]
....
# Network Settings
#
# the IP that DansGuardian listens on. If left blank DansGuardian will
# listen on all IPs. That would include all NICs, loopback, modem, etc.
# Normally you would have your firewall protecting this, but if you want
# you can limit it to only 1 IP. Yes only one.
# The Dansguardian IP address itself
filterip = 10.80.123.202

# the port that DansGuardian listens to.
# Port-nya DansGuardian
filterport = 3128

# the ip of the proxy (default is the loopback - i.e. this server)
proxyip = 10.80.123.202

# the port DansGuardian connects to proxy on
# Port-nya SQUID
proxyport = 33445
....


For default configuration you will get good filtering performance. But if you have own rule will be added please look at the Dansguardian config file at /etc/dansguardian. List of the file is below:

bannedextensionlist
bannediplist
bannedmimetypelist
bannedphraselist
bannedregexpurllist
bannedsitelist
bannedsitelist.processed
bannedurllist
banneduserlist
blacklists/
contentregexplist
dansguardian.conf
dansguardianf1.conf
ep.allow
ep.strict
exceptioniplist
exceptionphraselist
exceptionsitelist
exceptionurllist
exceptionuserlist
filtergroupslist
greysitelist
greyurllist
languages/
logrotation*
phraselists/
pics
transparent1x1.gif
weightedphraselist

EXAMPLE
# Block friendster images on bannedregexpurllist
(^|[\?+=&/])(photos.*\.friendster\..*/.*)([\?+=&/]|$)

# Block site on bannedsitelist
www.kaskus.us
www.tigerhorn.com
photos.friendster.com
... etc

---------

For Squid there is nothing special configuration. You may change your default squid port to unusual port used by. For example you can change to port 33445.

[Squid]
....
http_port 33445
....

Thursday, September 13, 2007

Mounting NTFS File System on Linux

How to mount your NTFS drive into your Linux Box? Find the steps below :

  1. Download ntfs-3g from http://www.ntfs-3g.org/
    The NTFS-3G driver is an open source, freely available read/write NTFS driver for Linux, FreeBSD, Mac OS X, NetBSD, and Haiku. It provides safe and fast handling of the Windows XP, Windows Server 2003, Windows 2000 and Windows Vista file systems. Most POSIX file system operations are supported, with the exception of full file ownership and access right support.

  2. Compile the source
    # tar -zxvf ntfs-3g-1.913.tgz
    # cd ntfs-3g-1.913
    # ./configure
    # make
    # make check
    # make install

    The program path is /usr/local/bin/

  3. Check your disk partition
    [root@konang]# /sbin/fdisk -l
    Disk /dev/sda: 80.0 GB, 80000000000 bytes
    255 heads, 63 sectors/track, 9726 cylinders
    Units = cylinders of 16065 * 512 = 8225280 bytes

    Device Boot Start End Blocks Id System
    /dev/sda1 1 4 32098+ de Dell Utility
    /dev/sda2 * 5 3350 26876745 7 HPFS/NTFS
    /dev/sda3 3351 9725 51207187+ f W95 Ext'd (LBA)
    /dev/sda5 3351 8429 40797036 7 HPFS/NTFS
    /dev/sda6 8430 8462 265041 83 Linux
    /dev/sda7 8463 8593 1052226 82 Linux swap / Solaris
    /dev/sda8 8594 9725 9092758+ 83 Linux

  4. Create mount directory
    # mkdir -p /mnt/windows-c
    # mkdir -p /mnt/windows-d

  5. Put into RC file /etc/rc.d/rc.local (load automatically when reboot)
    mount -t ntfs-3g /dev/sda2 /mnt/windows-c
    mount -t ntfs-3g /dev/sda5 /mnt/windows-d

  6. Test
    # df
    [root@konang]# df
    Filesystem 1K-blocks Used Available Use% Mounted on
    /dev/sda8 8807924 7444172 909116 90% /
    /dev/sda6 256666 15646 227768 7% /boot
    tmpfs 233164 0 233164 0% /dev/shm
    /dev/sda1 32018 7322 24696 23% /mnt/flashdisk
    /dev/sda2 26876744 17725572 9151172 66% /mnt/windows-c
    /dev/sda5 40797032 16751732 24045300 42% /mnt/windows-d

  7. List
    # cd /mnt/windows-c
    # ls -asl /mnt/windows-c

    [root@konang]# ls -asl /mnt/windows-c
    total 773752
    12 drwxrwxrwx 1 root root 12288 Sep 13 19:02 .
    8 drwxr-xr-x 9 root root 4096 Aug 10 15:42 ..
    1 -rwxrwxrwx 1 root root 257 Aug 22 2006 adaaja.csv
    8 drwxrwxrwx 1 root root 8192 Mar 9 2007 Alfresco
    8 drwxrwxrwx 1 root root 8192 Jun 15 2006 apache
    0 drwxrwxrwx 1 root root 0 Feb 8 2006 apachefriends
    0 -rwxrwxrwx 1 root root 0 Aug 11 2004 AUTOEXEC.BAT
    1 -rwxrwxrwx 1 root root 211 Dec 12 2005 boot.ini
    0 -rwxrwxrwx 1 root root 0 Aug 11 2004 CONFIG.SYS
    8 drwxrwxrwx 1 root root 8192 Feb 7 2006 dell
    4 -rwxrwxrwx 1 root root 3696 Nov 19 2005 dell.sdr
    4 drwxrwxrwx 1 root root 4096 Aug 6 09:26 Documents and Settings
    4 drwxrwxrwx 1 root root 4096 Nov 19 2005 DRIVERS
    4 drwxrwxrwx 1 root root 4096 Jul 24 13:28 EasyEclipse-for-LAMP-1.2..
  8. Done

Sunday, September 9, 2007

Squirrelmail with OpenLDAP Addressbook

How Squirrelmail access LDAP server addressbook? In this case you have OpenLDAP server but not an Active Directory !

  • First you must have OpenLDAP service installed on your Linux Box. You can get it free from http://www.openldap.org/software/download/
  • Your PHP must be compiled include LDAP component. You just add --with-ldap when compiling PHP from source.
  • Configure it and specify the OU schema and Addressbook schema in LDIF format.

Please find the steps below:


[/etc/openldap/slapd.conf]
#### SECURITY SETTING ###
disallow bind_anon

#######################################################################
# BDB database definitions
#######################################################################

database bdb
suffix "dc=mycompany,dc=com"
rootdn "dc=mycompany,dc=com"
rootpw {SSHA}UWPj+&**%$^*(7987897*&%*^&*^
directory /var/openldap-data
index objectClass eq


[Addressbook OU]
dn: ou=addressbook,dc=mycompany,dc=com
objectClass: top
objectClass: organizationalUnit
ou: addressbook
userPassword: {SHA}7lUIYUIYKJHKYIYtTkXU=



[Addressbook LDIF]
dn: cn=My Name (myname@mycompany.com),ou=addressbook,dc=mycompany,dc=com
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
cn: My Name (myname@mycompany.com)
givenName: My Name
sn: My Name
mail: myname@mycompany.com
physicalDeliveryOfficeName: G.Kwarnas
postalAddress: G.Kwarnas
o: mycompany
l: -
ou: addressbook
st: -
postalCode: 10110
telephoneNumber: 1696
facsimileTelephoneNumber: +62-21
pager: +62-21
mobile: +62-21
homePhone: +62-21


How to load LDIF data into OpenLDAP server?
From the Linux shell please type the following command (example the file is "addressbook-2.ldif.txt") :

shell# ldapadd -x -v -c -D "dc=mycompany,dc=com" -W < addressbook-2.ldif.txt

Now is the time to configure Squirrelmail config file. Please add the following script to link your webmail with OpenLDAP server:

[Squirrelmail config.php]
$ldap_server[0] = array(
'host' => '10.80.123.203',
'base' => 'ou=addressbook,dc=mycompany,dc=com',
'name' => 'LDAP: Addressbook Global',
'binddn' => 'ou=addressbook,dc=mycompany,dc=com',
'bindpw' => 'mycompany',
'filter' => '(objectclass=*)',
'protocol' => 3,
'limit_scope' => false,
'listing' => true,
'search_tree' => true,
'starttls' => false
);


Yes! Now your webmail connected with OpenLDAP addressbook.

Thursday, September 6, 2007

Building IM Server by Openfire 3.3.2 - Jabber

You want the IM server at your office ? Use the the Openfire IM server. This software is free and great. How to install this one ? Its very easy.

  1. Download source at: http://www.igniterealtime.org/downloads/index.jsp
  2. tar -zxvf openfire_3_3_X.tar.gz
  3. cd openfire_3_3_X/bin/
  4. Run this server by command: openfire start
    If you want autostart please put this on /etc/rc.d/rc.local (For Linux platform) :
    For example : /data/ftp/mti/software/linux-app/openfire/bin/openfire start
  5. Open web based admin management, example : http://10.80.123.203:9090/
    Login as : admin, Password: password
    Here you go for anything. Create user, configure port, service, user management and etc.
  6. Please try to connect to Openfire server using Kopete or Meebo (must be IP public, Jabber program, format: username@ip-public-your-open-fire-server)
  7. Enjoy it !
  8. You can install various plugins just only select them !
Here is the text from official website of OpenFire :

Openfire (formerly Wildfire) is a real time collaboration (RTC) server dual-licensed under the Open Source GPL and commercially. It uses the only widely adopted open protocol for instant messaging, XMPP (also called Jabber). Openfire is incredibly easy to setup and administer, but offers rock-solid security and performance.

Latest Build 3.3.2
Downloads 890,847
License Open Source GPL or Commercial
Platforms Windows, Linux,
Unix, Mac OS X


Tuesday, September 4, 2007

Force wallpaper & screen saver by Windows Active Directory

How to force wallpaper & screen saver by Windows Active Directory ?

  1. Menu Start
  2. Programs
  3. Administrative Tools
  4. Active Directory Users & Computers
  5. Right click -> your local domain (example mynetwork.com)
  6. Properties
  7. Choose control tab "Group Policy"
  8. Double click "Default Domain Policy"
  9. You will get window of "Group Policy" and there is 2 main items on root tree, "Computer Configuration" and "User Configuration".
  10. Choose the "User Configuration".
  11. You will get on tree : "Software Settings", "Windows Settings" and "Administrative Templates"
  12. Choose "Administrative Templates" tree.
Next ...

[Force Wallpaper]
  1. In the Administrative Templates, Click Desktop
  2. Click "Active Desktop"
  3. Please enable :
  4. - Enable Active Desktop -> enabled
  5. - Prohibit Changes -> enabled
  6. - Active Desktop Wallpaper -> enabled
  7. * Type your wallpaper path file :
  8. * Example : \\10.20.2.2\wallscr\er_wall.jpg
  9. * Choose wallpaper style : strech

Next ...


[Force Screensaver]
  1. In the Administrative Templates Click Control Panel
  2. Click Display
  3. - Prevent changing wallpaper -> enabled
  4. - Screen Saver -> enabled
  5. - Screen saver executable name -> enabled
  6. * Type your screensaver path file :
  7. * Example: \\10.20.2.2\wallscr\er_scr.scr
  8. - Screen saver time out -> enabled
  9. * Set time out (in second)
  10. Please user to logout and login again (2 times)
  11. Finish


Monday, September 3, 2007

SSH Tunneling

You have a trouble when you got your localhost (your computer) has no route to XWindows public server (linux, unix base). Your computer only has route to one of computer in the network which has route to public server that you want.
Somebody that ever install Oracle via remote connection will find this problem.

Example:
Your local computer is "localhost"
Your server #1 is private IP "10.80.123.203"
Your server #2 is public IP "203.13x.xxx.xx"

Localhost ----- Server #1 ------- Server #2

|______ XWindows Application _______|
|___________ No Route ______________|


How to get connection via SSH so you can remote your public server include the XWindows application ?

Here are the steps must be done :

SSH tunneling from 10.80.123.203 to public IP 202.13x.xxx.xx
# ssh konang@10.80.123.203 -p 2350
# ssh -L 2211:127.0.0.1:2350 konang@203.13x.xxx.xx -p 2350

SSH tunneling from localhost to 10.80.123.203
# ssh -L 2211:127.0.0.1:2211 konang@10.80.123.203 -p 2350

SSH to 203.13x.xxx.xx via tunnel + forward X
# ssh -X konang@localhost -p 2211

For example on X environment :
# xclock &

You will get "xclock" program from remote 203.13x.xxx.xx

Sunday, September 2, 2007

Custom Microsoft Windows Taskbar Date

I remember when I use this method first time to custom Microsoft Windows 98 Taskbar. This method can be apply too on Windows NT, Windows 2000, Windows XP and Windows 2003. For Windows Vista I am sure this no problem even not tested before. Here is the steps and I hope you are enjoyed.

  1. Click Control Panel.
  2. Double click "Regional and Language Options".
  3. Select (default) "Regional Options" tab.
  4. Click "Customize" next of the Country Language select menu.
  5. Select "Time" tab.
  6. Go to "Time Format".
  7. Default value is : hh:mm change to : 'MYNAME' HH:mm (Note! in the singe quote, 24 hour system), for 12 hour system remove one of "H" letter so became 'MYNAME' H:mm.
  8. Click Apply --> OK --> Apply ... so then you got new taskbar date !

Don't forget to Click Apply / OK, and then you got back to previous window and click Apply and OK to effect the taskbar date. Sorry for uncomplete steps on image above.

Thursday, August 30, 2007

When Oracle Going Down

So what? when you at the night found your Oracle was dead. Trying start Oracle but occuring the error messages:

Thu Aug 30 21:43:16 2007
Errors in file /data/oracle/home/admin/pep/bdump/pep_arc0_31074.trc:
ORA-16014: log 1 sequence# 56 not archived, no available destinations
ORA-00312: online log 1 thread 1: '/data/oracle/data/pep/redo01.log'

Thu Aug 30 21:44:16 2007

ARC1: Archiving not possible: No primary destinations
ARC1: Failed to archive thread 1 sequence 56 (4)

Thu Aug 30 21:48:17 2007

Errors in file /data/oracle/home/admin/pep/bdump/pep_arc1_31076.trc:
ORA-19815: WARNING: db_recovery_file_dest_size of 2147483648 bytes is 100.00% used, and has 0 remaining bytes available.

Thu Aug 30 21:48:17 2007


************************************************************************

You have following choices to free up space from flash recovery area:

1. Consider changing RMAN RETENTION POLICY. If you are using Data Guard,
then consider changing RMAN ARCHIVELOG DELETION POLICY.

2. Back up files to tertiary device such as tape using RMAN
BACKUP RECOVERY AREA command.

3. Add disk space and increase db_recovery_file_dest_size parameter to
reflect the new space.

4. Delete unnecessary files using RMAN DELETE command. If an operating
system command was used to delete files, then use RMAN CROSSCHECK and
DELETE EXPIRED commands.

************************************************************************

Thu Aug 30 21:48:17 2007

Errors in file /data/oracle/home/admin/pep/bdump/pep_arc1_31076.trc:
ORA-19809: limit exceeded for recovery files
ORA-19804: cannot reclaim 48500736 bytes disk space from 2147483648 limit

ARC1: Error 19809 Creating archive log file to '/data/oracle/home/flash_recovery_area/PEP/archivelog/2007_08_30/o1_mf_1_56_1_.arc'


ARC1: Failed to archive thread 1 sequence 56 (19809)


ARCH: Archival stopped, error occurred. Will continue retrying


DONT WORRY

You just make Oracle can be startup and then rebuild your configuration by RESIZE your Archive Log file. The steps are :

[oracle@black]# sqlplus /nolog
SQL> conn / as sysdba
SQL> shutdown abort
ORACLE instance shut down.

SQL> startup nomount pfile="/data/oracle/home/admin/pep/pfile/init.ora.618200774625"
ORACLE instance started.

Total System Global Area 1002438656 bytes
Fixed Size 1223080 bytes
Variable Size 247465560 bytes
Database Buffers 746586112 bytes
Redo Buffers 7163904 bytes

SQL> alter database mount;

Database altered.

SQL> alter database open;

Database altered.

SQL> select * from tab;

Browse : http://your.oracle.web:1158/em/
Please resize your Archive log file and or the other configuraions.

Thursday, August 23, 2007

Mail Gateway - ClamAV & Spamassassin

Description
This system is already test and can receive mail traffic as mail gateway:

  • 200,000 mails/day for FreeBSD Box, default kernel
  • 125,000 mails/day for Linux Box, default kernel
Services
Service Postfix 2.3.4
ClamAV 0.88.6
Amavisd-New 2.4.4
Spamassassin 3.1.7

Download
http://www.postfix.org/download.html
http://www.clamav.net/
http://www.ijs.si/software/amavisd/
http://www.spamassassin.org/

Dependencies
CPAN – Perl Module
# cpan
cpan> install Archive::Tar Archive::Zip Compress::Zlib Convert::TNEF Convert::UUlib MIME::Base64 MIME::Parser Mail::Internet Net::Server Net::SMTP Digest::MD5 IO::Stringy Time::HiRes Unix::Syslog HTML::Parser
cpan> install MD5 LWP Mail::Internet Archive::Tar Archive::Zip IO::Wrap IO::Stringy Unix::Syslog MIME::Words MIME::Head MIME::Body MIME::Entity MIME::Parser Net::SMTP Net::DNS Net::Ping Net::Server Net::Server::PreForkSimple Convert::TNEF Convert::UUlib MIME::Decoder::Base64 MIME::Decoder::Binary MIME::Decoder::Gzip64 MIME::Decoder::NBit MIME::Decoder::QuotedPrint MIME::Decoder::UU Time::HiRes Digest::SHA1 Digest::Nilsimsa Getopt::Long File::Copy Bit::Vector Date::Calc
cpan> install IO::Socket IO::Socket::INET IO::Socket::UNIX
cpan> install Net::SMTP Net::Cmd Net::SMTP Net::Server Net::Server::PreForkSimple
cpan> install DB_File Unix::Syslog File::Tail Archive::Rar Archive::TarGzip Archive::Any
cpan> install Net::DNS Mail::SPF::Query IP::Country Net::Ident IO::Socket::INET6 IO::Socket::SSL
cpan> install Inline::C Mail::ClamAV Mail::SpamAssassin DBI Net::LDAP Authen::SASL SAVI Convert::UUlib Compress::Zlib

Configure
groupadd postdrop
useradd postfix -s /bin/false
groupadd clamav
useradd clamav -g clamav -s /bin/false
mkdir /home/clamav
mkdir -p /home/clamav/amavis
mkdir -p /home/clamav/virusmails
mkdir -p /home/clamav/db
mkdir -p /home/clamav/var
mkdir -p /home/clamav/tmp
mkdir -p /home/clamav/virusdb
chmod 750 /home/clamav/amavis
chown -R clamav.clamav /home/clamav
touch /var/log/clamd.log
touch /var/log/freshclam.log
touch /var/log/clam-update.log
chown clamav.clamav /var/log/clamd.log
chown clamav.clamav /var/log/freshclam.log
chown clamav.clamav /var/log/clam-update.log



Postfix
# tar –zxvf postfix-2.3.4.tar.gz
# make
# make install


ClamAV
# tar –zxvf clamav-0.88.6.tar.gz
# ./configure --sysconfdir=/usr/local/etc --with-dbdir=/home/clamav/virusdb --libdir=/usr --includedir=/usr
# make
# make check
# make install

Amavisd-New
# tar -zxvf amavisd-new-2.x.x.tar.gz
# cd amavisd-new-2.x.x
# cp amavisd /usr/local/sbin/
# chown root /usr/local/sbin/amavisd
# chmod 755 /usr/local/sbin/amavisd


Spamassassin
# tar –zxvf Mail-SpamAssassin-3.1.7.tar.gz
# ./configure
# make
# make install


Exec Path
/usr/local/sbin/amavisd
/usr/local/bin/freshclam -d -c 10 --datadir=/home/clamav/virusdb
/usr/local/sbin/clamd/usr/sbin/postfix start

Config File

/etc/clamd.conf
---------------
AlgorithmicDetection yes
ArchiveLimitMemoryUsage yes
ArchiveMaxCompressionRatio 300
ArchiveMaxFileSize 15M
ArchiveMaxFiles 1500
ArchiveMaxRecursion 10
DatabaseDirectory /home/clamav/virusdb
LeaveTemporaryFiles yes
LogClean yes
LogFile /var/log/clamd.log
LogFileMaxSize 1000M
LogTime yes
PidFile /home/clamav/var/clamd.pid
ScanArchive yes
ScanHTML yes
ScanMail yes
TCPAddr 127.0.0.1
TCPSocket 3310
TemporaryDirectory /var/tmp
User clamav



/etc/amavisd.conf
-----------------
KEY POINT:
$max_servers = 3; # number of pre-forked children (2..15 is common)
$max_requests = 10;
$child_timeout=5*60;
$daemon_user = 'clamav'; # (no default; customary: vscan or amavis)
$daemon_group = 'clamav'; # (no default; customary: vscan or amavis)
$mydomain = 'mydomain.com'; # a convenient default for other settings
$MYHOME = '/home/clamav'; # a convenient default for other settings
$TEMPBASE = "$MYHOME/tmp"; # working directory, needs to be created manually
$ENV{TMPDIR} = $TEMPBASE; # environment variable TMPDIR
$QUARANTINEDIR = "$MYHOME/virusmails";
# $daemon_chroot_dir = $MYHOME; # chroot directory or undef
$db_home = "$MYHOME/db";
$helpers_home = "$MYHOME/var"; # prefer $MYHOME clean and owned by root?
$pid_file = "$MYHOME/var/amavisd.pid";
$lock_file = "$MYHOME/var/amavisd.lock";
#NOTE: create directories $MYHOME/tmp, $MYHOME/var, $MYHOME/db manually
@local_domains_maps = ( [".$mydomain"] );
@mynetworks = qw( 127.0.0.0/8 ::1 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 );
$log_level = 0; # verbosity 0..5
$log_recip_templ = undef; # disable by-recipient level-0 log entries
$DO_SYSLOG = 1; # log via syslogd (preferred)
$SYSLOG_LEVEL = 'mail.debug';
#$enable_db = 1; # enable use of BerkeleyDB/libdb (SNMP and nanny)
#$enable_global_cache = 1; # enable use of libdb-based cache if $enable_db=1
$inet_socket_port = 10024; # listen on this local TCP port(s) (see $protocol)
$inet_socket_bind = '127.0.0.1';
@inet_acl = qw( 127.0.0.1 );
#$unix_socketname = "$MYHOME/amavisd.sock"; # when using sendmail milter
$sa_tag_level_deflt = -6.0; # add spam info headers if at, or above that level
$sa_tag2_level_deflt = 6.0; # add 'spam detected' headers at that level
$sa_kill_level_deflt = 6.0; # triggers spam evasive actions
$sa_dsn_cutoff_level = 10; # spam level beyond which a DSN is not sent
$sa_mail_body_size_limit = 200*1024; # don't waste time on SA if mail is larger
$sa_local_tests_only = 0; # only tests which do not require internet access?
$sa_auto_whitelist = 1; # turn on AWL in SA 2.63 or older (irrelevant
$sa_spam_subject_tag = '***SPAM*** ';
$defang_virus = 1; # MIME-wrap passed infected mail
$defang_banned = 1; # MIME-wrap passed mail containing banned name
# for defanging bad headers only turn on certain minor contents categories:
$defang_by_ccat{+CC_BADH.",3"} = 1; # NUL or CR character in header
$defang_by_ccat{+CC_BADH.",5"} = 1; # header line longer than 998 characters
$defang_by_ccat{+CC_BADH.",6"} = 1; # header field syntax error
# OTHER MORE COMMON SETTINGS (defaults may suffice):
#$myhostname = 'mydomain.com'; # must be a fully-qualified domain name!
$notify_method = 'smtp:[127.0.0.1]:10025';
$forward_method = 'smtp:[10.1.1.1]:25'; # Destination Mailserver
$final_virus_destiny = D_DISCARD;
$final_banned_destiny = D_BOUNCE;
$final_spam_destiny = D_PASS;
$final_bad_header_destiny = D_PASS;

# ### http://www.clamav.net/
['ClamAV-clamd',
\&ask_daemon, ["CONTSCAN {}\n", "127.0.0.1:3310"],
qr/\bOK$/, qr/\bFOUND$/,
qr/^.*?: (?!Infected Archive)(.*) FOUND$/ ],




/etc/freshclam.conf
-------------------
Checks 24
DatabaseDirectory /home/clamav/virusdb
DatabaseMirror database.clamav.net
PidFile /home/clamav/var/freshclam.pid
UpdateLogFile /var/log/freshclam.log



/etc/mail/spamassassin/local.cf
--------------------------------
add_header all Checker-Version SpamAssassin _VERSION_ (_SUBVERSION_) on _HOSTNAME_
add_header all Status _YESNO_, score=_SCORE_ required=_REQD_ tests=_TESTS_ autolearn=_AUTOLEARN_ version=_VERSION_
auto_learn 1
bayes_path /home/clamav/amavis/.spamassassin/bayes
dns_available yes
report_safe 0
required_hits 6.0
rewrite_subject 1
skip_rbl_checks 1
subject_tag *** Spam ***
use_bayes 1


/etc/postfix/main.cf
--------------------
KEY POINT:
header_checks = regexp:/etc/postfix/header_checks
relay_domains = hash:/etc/postfix/relay_domains
smtpd_client_restrictions = hash:/etc/postfix/access
smtpd_delay_reject=no
smtpd_helo_restrictions = hash:/etc/postfix/access
relay_domains = hash:/etc/postfix/relay_domains
smtpd_recipient_restrictions =
#permit_mynetworks,
#reject_non_fqdn_sender,
#reject_non_fqdn_recipient,
#reject_unknown_sender_domain,
#reject_unknown_recipient_domain,
reject_unauth_destination,
reject_rbl_client list.dsbl.org,
permit


/etc/postfix/master.cf
----------------------
KEY POINT:
smtp inet n - n - - smtpd
-o content_filter=smtp-amavis:[127.0.0.1]:10024

smtp-amavis unix - - n - 3 lmtp
-o smtp_data_done_timeout=1200
-o disable_dns_lookups=yes

127.0.0.1:10025 inet n - n - - smtpd
-o content_filter=
-o local_recipient_maps=
-o relay_recipient_maps=
-o smtpd_restriction_classes=
-o smtpd_client_restrictions=
-o smtpd_helo_restrictions=
-o smtpd_sender_restrictions=
-o smtpd_recipient_restrictions=permit_mynetworks,reject
-o mynetworks=127.0.0.0/8
-o strict_rfc821_envelopes=yes



/etc/postfix/access
-------------------
194.67.23.20 REJECT -- MAIL BOMBING --
84.58.99.89 REJECT -- MAIL BOMBING --


/etc/postfix/relay_domains
--------------------------
mydomain.com RELAY


/etc/postfix/header_checks
--------------------------
/^(.*)name\=\"(.*)\.(hta|com|pif|vbs|vbe|js|jse|bat|cmd|vxd|scr|shm|hlp|spl|swf)\"$/ DISCARD ---- File attachment yang akan anda kirim ditolak untuk alasan keamanan - Your attachment file(s) rejected for security reason ----


/etc/postfix/body_checks
------------------------
/^(.*)V I R U S A L E R T/ DISCARD virus
/^(.*)VIRUS NOTIFICATION/ DISCARD virus
/^(.*)Virus Warning Message/ DISCARD virus

Data
/usr/spool/postfix/
/home/clamav/virusdb
/home/clamav/virusmails


Startup
/usr/local/sbin/amavisd
/usr/local/bin/freshclam -d -c 10 --datadir=/home/clamav/virusdb
/usr/local/sbin/clamd/usr/sbin/postfix start

Crontab
# crontab –l
####CLAMD####
0 0 * * * /bin/rm -rf /var/tmp/clamav-*
0 0 * * * /bin/rm /home/clamav/virusmails/*
0 0 * * * /bin/rm -r /home/clamav/tmp/amavis-*

Top Command
Bash# postfix start|stop|restart
Bash# tail –f /var/log/maillog
Bash# telnet localhost 10024 | 3310 | 25

Tuesday, August 21, 2007

Create Drupal Module

Drupal I think is the best CMS to develop a custom applications. Drupal's engine gives you more than you expected. The API and library will reduce your time to develop applications and gears up your business. This below is example to building modules on drupal engine.

Drupal modules at least need 3 files :

  • yourmodule.info
    Contains module descriptions
  • yourmodule.install
    Contains module database structure (depend on you need database or not)
  • yourmodule.module
    The core of your program. Functions and algorithm write down here.
For example your PATH for drupal is :
/usr/local/apache/htdocs/drupal

In this case, your module name is 'phonedir', so ...your own modules should be :
/usr/local/apache/htdocs/drupal/sites/all/modules/phonedir
All of your module's files must be prefix 'phonedir'.

Your drupal configuration file must be placed at:
/usr/local/apache/htdocs/drupal/sites/default/settings.php

Please edit settings.php to add MySQL connection to the another database:

Origin:
$db_url = 'mysql://drupal:passwd_drupal_db@localhost/drupal';
$db_prefix = '';

To :

## Drupal's db
$db_url['default'] = 'mysql://drupal:passwd_drupal_db@localhost/drupal';

## phonedir's db
$db_url['phonedir'] = 'mysql://phonedir:kunamjaya@localhost/phonedir';
$db_prefix = '';



--------------------------------------------
Run the shell scripts:
============================
# mkdir -p /usr/local/apache/htdocs/drupal/sites/all/modules/phonedir
# cd /usr/local/apache/htdocs/drupal/sites/all/modules/phonedir
Create files : phonedir.info, phonedir.install, phonedir.module, phonedir.mysql
# touch phonedir.info
# touch phonedir.install
# touch phonedir.module
# touch phonedir.mysql
phonedir.info
; $Id$
name = Phonedir
description = Phone Directory
package = PEP
project = "drupal"
version = "5.x-1.0"

phonedir.install
<?
// $Id: phonedir.install,v MDGTI PEP 2007/08/01 13:44:08 drumm Exp $

##########################################
# Konang Supian #
# konangsupian@gmail.com #
# 02 Agustus 2007 #
##########################################

/*
Jalankan perintah shell sbb:
============================
mysql -u root -p -e "create database phonedir"
mysql -u root -p phonedir < phonedir.mysql
echo "\$db_url['phonedir'] = 'mysql://phonedir:kunamjaya@localhost/phonedir';" >> ../../../default/settings.php

*/
###################################################
/*

Tambahkan baris berikut (silakan disesuaikan dengan login password MySQL) di file :
/path/to/drupal/sites/default/settings.php

$db_url['default'] = 'mysql://drupal:kunamjaya@localhost/drupal';
$db_url['helpdesk'] = 'mysql://helpdesk:kunamjaya@localhost/helpdesk';
$db_url['phonedir'] = 'mysql://phonedir:kunamjaya@localhost/phonedir';

*/

function phonedir_install() {
switch ($GLOBALS['db_type']) {
case 'mysql':
case 'mysqli':
//db_query("");
break;
}
}

function phonedir_uninstall() {
db_query('DROP TABLE {belomperlu}');
}





phonedir.mysql



/*
Akses command dibawah ini untuk create database dan grant bila belum ada:
#########################################################################
*/

/*
use mysql;
CREATE DATABASE phonedir;
*/

GRANT USAGE ON phonedir.* TO phonedir@localhost;
GRANT ALL ON phonedir.* to phonedir@localhost identified by 'kunamjaya';
flush privileges;

/*
##########################################################################
*/

USE phonedir;

create table ext (
ext_id int auto_increment,
ext_name varchar(40),
ext_jobdesc varchar(30),
ext_div tinyint(3) unsigned,
ext_ext varchar(5),
ext_fax varchar(15),
ext_phone varchar(15),
ext_floor varchar(10),
ext_mail varchar(30),
ext_company tinyint(3) unsigned,
ext_region tinyint(3) unsigned,
PRIMARY KEY (`ext_id`)
) ENGINE=MyISAM;

create table region (
reg_id int auto_increment,
reg_name varchar(30) not null,
reg_status tinyint(3) unsigned default 1,
PRIMARY KEY (`reg_id`),
UNIQUE KEY `reg_name`(`reg_name`)
)ENGINE=MyISAM;

create table prsh (
prsh_id int auto_increment,
prsh_name varchar(30) not null,
prsh_status tinyint(3) unsigned default 1,
PRIMARY KEY (`prsh_id`),
UNIQUE KEY `prsh_name`(`prsh_name`)
)ENGINE=MyISAM;

create table divs (
divs_id int auto_increment,
divs_name varchar(30) not null,
divs_status tinyint(3) unsigned default 1,
PRIMARY KEY (`divs_id`),
UNIQUE KEY `divs_name`(`divs_name`)
)ENGINE=MyISAM;

create table fl (
fl_id int auto_increment,
fl_name varchar(3) not null,
fl_status tinyint(3) unsigned default 1,
PRIMARY KEY (`fl_id`),
UNIQUE KEY `fl_name`(`fl_name`)
)ENGINE=MyISAM;


/*
Dumping data
*/

INSERT INTO `divs` (`divs_id`, `divs_name`, `divs_status`) VALUES (1, 'Kwarnas', 1);
INSERT INTO `divs` (`divs_id`, `divs_name`, `divs_status`) VALUES (2, 'SC', 1);
INSERT INTO `divs` (`divs_id`, `divs_name`, `divs_status`) VALUES (3, 'Keuangan', 1);
INSERT INTO `divs` (`divs_id`, `divs_name`, `divs_status`) VALUES (4, 'Dir Hulu', 1);
INSERT INTO `divs` (`divs_id`, `divs_name`, `divs_status`) VALUES (5, 'PWP', 1);

INSERT INTO `ext` (`ext_name`, `ext_jobdesc`, `ext_div`, `ext_ext`, `ext_fax`, `ext_mail`, `ext_phone`, `ext_floor`) VALUES ('Security lt G', 'Security lt G', '1', '1332', '', '', '', 'G');
INSERT INTO `ext` (`ext_name`, `ext_jobdesc`, `ext_div`, `ext_ext`, `ext_fax`, `ext_mail`, `ext_phone`, `ext_floor`) VALUES ('Pos Depan', 'Pos Depan', '1', '1964', '', '', '', 'G');
INSERT INTO `ext` (`ext_name`, `ext_jobdesc`, `ext_div`, `ext_ext`, `ext_fax`, `ext_mail`, `ext_phone`, `ext_floor`) VALUES ('Storing Listrik', 'Storing Listrik', '1', '1369', ' ', '', '', 'G');
INSERT INTO `ext` (`ext_name`, `ext_jobdesc`, `ext_div`, `ext_ext`, `ext_fax`, `ext_mail`, `ext_phone`, `ext_floor`) VALUES ('Storing AC', 'Storing AC', '1', '1965', '', '', '', 'G');
INSERT INTO `ext` (`ext_name`, `ext_jobdesc`, `ext_div`, `ext_ext`, `ext_fax`, `ext_mail`, `ext_phone`, `ext_floor`) VALUES ('Rec14ionist lt. G', 'Rec14ionist lt. G', '1', '1444', '', '', '', 'G');


INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (1, 'B3', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (2, 'B2', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (3, 'B1', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (4, 'G', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (5, '1', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (6, '2', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (7, '3', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (8, '4', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (9, '5', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (10, '6', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (11, '7', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (12, '8', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (13, '9', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (14, '10', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (15, '11', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (16, '12', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (17, '13', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (18, '14', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (19, '15', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (20, '16', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (21, '17', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (22, '18', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (23, '19', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (24, '21', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (25, '22', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (26, '23', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (27, '24', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (28, '25', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (29, '26', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (30, '27', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (31, '28', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (32, '29', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (33, '30', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (34, '31', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (35, '32', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (36, '33', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (37, '34', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (38, '35', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (39, '36', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (40, '37', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (41, '38', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (42, '39', 1);
INSERT INTO `fl` (`fl_id`, `fl_name`, `fl_status`) VALUES (43, '40', 1);


INSERT INTO `prsh` (`prsh_id`, `prsh_name`, `prsh_status`) VALUES (1, 'MYCOMPANY', 1);
INSERT INTO `prsh` (`prsh_id`, `prsh_name`, `prsh_status`) VALUES (2, 'MYCOMPANY PERSERO', 1);
INSERT INTO `prsh` (`prsh_id`, `prsh_name`, `prsh_status`) VALUES (3, 'PERTAGAS', 1);
INSERT INTO `prsh` (`prsh_id`, `prsh_name`, `prsh_status`) VALUES (4, 'MYCOMPANY PELUMAS', 1);
INSERT INTO `prsh` (`prsh_id`, `prsh_name`, `prsh_status`) VALUES (5, 'REKANAN', 1);


INSERT INTO `region` (`reg_id`, `reg_name`, `reg_status`) VALUES (1, 'Pusat', 1);
INSERT INTO `region` (`reg_id`, `reg_name`, `reg_status`) VALUES (2, 'Sumatera', 1);
INSERT INTO `region` (`reg_id`, `reg_name`, `reg_status`) VALUES (3, 'Jawa', 1);
INSERT INTO `region` (`reg_id`, `reg_name`, `reg_status`) VALUES (4, 'KTI', 1);
INSERT INTO `region` (`reg_id`, `reg_name`, `reg_status`) VALUES (5, 'MYCOMPANY Pusat', 1);




phonedir.module

<?
##########################################
# Konang Supian #
# konangsupian@gmail.com #
# 02 Agustus 2007 #
##########################################

function phonedir_help($section='') {
$output = '';
switch ($section) {
case "admin/help#phonedir":
$output = '<p>'. t("Test buat module"). '</p>';
break;
}
return $output;
}

/*function phonedir_perm() {
return array('PT MYCOMPANY phonedir permission');
}*/

function phonedir_block($op='list', $delta=0) {
if ($op == "list") {
$block[0]["info"] = t("Phonedir");
return $block;
} else if ($op == 'view') {
$block_content = l('Phone Directory', 'phonedir/show') . '<br />';
if ($block_content == '') {
return;
}
$block['subject'] = 'Phonedir';
$block['content'] = $block_content;
return $block;
}
}

/*function phonedir_admin() {
$form['phonedir_maxdisp'] = array(
'#type' => 'textfield',
'#title' => t('Maximum number of links'),
'#default_value' => variable_get('phonedir_maxdisp', 3),
'#size' => 2,
'#maxlength' => 2,
'#description' => t("The maximum number of links to display in the block.")
);
return system_settings_form($form);
}*/

function phonedir_menu() {
$items = array();
/*$items[] = array(
'path' => 'admin/settings/phonedir',
'title' => t('Phonedir module settings'),
'description' => t('Description of your phonedir settings control'),
'callback' => 'drupal_get_form',
'callback arguments' => 'phonedir_admin',
'access' => user_access('access administration pages'),
'type' => MENU_NORMAL_ITEM,
);*/
############ PARENT #########
$items[] = array(
'path' => 'phonedir',
'title' => t('Phone Directory'),
'callback' => 'phonedir_load_search',
'access' => user_access('access phonedir content'),
'type' => MENU_NORMAL_ITEM,
);
########### CHILD ##########
$items[] = array(
'path' => 'phonedir/new',
'title' => t('New Entry'),
'callback' => 'phonedir_load_insert',
'access' => user_access('access phonedir content'),
'type' => MENU_NORMAL_ITEM,
);
$items[] = array(
'path' => 'phonedir/list',
'title' => t('Search'),
'callback' => 'phonedir_load_search',
'access' => user_access('access phonedir content'),
'type' => MENU_NORMAL_ITEM,
);
$items[] = array(
'path' => 'phonedir/show',
'title' => t('Pencarian'),
'callback' => 'phonedir_load_search',
'access' => user_access('content'),
'type' => MENU_HIDDEN,
);
$items[] = array(
'path' => 'phonedir/profile',
'title' => t('Profile'),
'callback' => 'phonedir_load_profile',
'access' => user_access('content'),
'type' => MENU_HIDDEN,
);

return $items;
}



############ GLOBAL FUNCTIONS ##############

function phonedir_sql_array($query,$key,$key_index=null) {
db_set_active('phonedir');
$queryResult = db_query($query);
while ($links = db_fetch_object($queryResult)) {
if ($key_index!=null) {
$myarray[$links->$key_index] = $links -> $key;
} else {
$myarray[] = $links -> $key;
}
}
db_set_active('default');
return $myarray;
}

function phonedir_printfield($table,$field,$field_,$syarat) {
db_set_active('phonedir');
$query_ = "select ".$field." from ".$table." where ".$field_."='".$syarat."'";
$admin_ = mysql_query($query_);
$row_ = mysql_fetch_array($admin_);
if (!$admin_) {
echo mysql_error();
}
db_set_active('default');
return $row_[0];
}

function phonedir_list_data($caption,$table,$field,$syarat,$start,$script,$isnew,$href,$target,$q) {
$content = '';
if ($start > 0) { $anyar = $isnew;}
$show_per_page = 30;
$list_page = 11;
if ($start < $show_per_page) $start = 0;
if ($syarat != "") {
$mynewquery = "select ".$field." from ".$table." ".$syarat." limit $start,$show_per_page";
$mynewquery1 = "select count(*) from ".$table." ".$syarat;
} else {
$mynewquery = "select ".$field." from ".$table." limit $start,$show_per_page";
$mynewquery1 = "select count(*) from ".$table;
}
$result = mysql_query($mynewquery);

#print $mynewquery;

if (!$result) {
print mysql_error();
}
$hasil = mysql_query($mynewquery1);
$hasil = mysql_fetch_row($hasil);
$hasil = $hasil[0];

$content .= '
<table id="tbl-phonedir" width="100%" border="1" cellspacing="1" cellpadding="2">
<tr class="thead"><td colspan="'.mysql_num_fields($result).'">
&nbsp;<b>'.$caption.'</b> <i>('.$hasil.')</i>
</td>
</tr>
<tr class="tcol">';
for ($i = 0; $i< mysql_num_fields($result); $i++) {
$head = mysql_field_name( $result,$i);
$content .= "<td><b>$head</b></td>";
}
$content .= "</tr>";
$myrow = 1;
for ($i=0; $i < $show_per_page; $i++) {
if ($result <> 0 ) { $row_array = mysql_fetch_row($result);}
if ($row_array=="") { break; }
if ($i % 2 == 0) {
$warna = "teven";
} else {
$warna = "todd";
}
$content .= "\r\n<tr class=\"$warna\">\r\n";
for ($j=0; $j<mysql_num_fields($result); $j++) {
if (eregi("accessed",mysql_field_name($result,$j))) {
$row_array[$j] = tanggalan($row_array[$j]);
}
if ($j==0) {
$content .= "<td align=\"center\">";
$content .= ($myrow+$start);
} else {
$content .= "<td align=\"left\">";
if ($href==$j) {
$content .= '<a href="'.$target.'&id='.$row_array[$q].'">'.$row_array[$j].'</a>';
} else {
if (!eregi("STATUS",mysql_field_name($result,$j))) {
$tulis = eregi_replace("\n","<br>",$row_array[$j]);
$content .= $tulis;
}
}
}
$content .= "</td>";
}
$myrow++;
$content .= "</tr>";
}
$content .= phonedir_idx_page($hasil, $show_per_page, $list_page, $start, $script, $anyar, mysql_num_fields($result) , "#dddddd");
$content .= "
</table>";

return $content;
}


function phonedir_idx_page($hasil, $show_per_page, $list_page, $start, $url, $isnew, $colspan, $warna) {
$content = '';
$content .= '
<tr class="tfoot"><td colspan="'.$colspan.'">
';

if ($hasil > 0) {
$counter = 1;
$tmp_start = $start;
$start = 0;
$first = 0;
$last = floor($hasil/$show_per_page)*$show_per_page;
$next = $tmp_start+$show_per_page;
$pembagi = ($next-($show_per_page * ($list_page-1) ));
$pembagi = floor($pembagi / $show_per_page);
if ($pembagi>0) {
$prev=$next-(2*$show_per_page);
$content .= "<a href='$url&start=$first'>&laquo; first</a> <a href='$url&start=$prev'>prev</a> ";
}
if ($hasil <> 0 ) { $content .= "";}
for ($i=0; $i < $hasil; $i++) {
if (($i % $show_per_page) == 0) {
if (($counter % $list_page)==0) {
if ($next>$last) {$next=$last;}
$content .= " <a href='$url&start=$next'>next</a>";
$content .= " <a href='$url&start=$last'>last &raquo;</a>";
break;
}
if ($isnew=="") {
if ($counter>1) {
if ($pembagi>0) {
$list=$counter+$pembagi;
$urllist=($list-1)*$show_per_page;
$content .= "&nbsp;<a href='$url&start=$urllist'>$list</a>&nbsp;";

} else {
$content .= "&nbsp;<a href='$url&start=$start'>$counter</a>&nbsp;";
}
} else {
if ($pembagi>0) {
$list=$counter+$pembagi;
$content .= $list . "&nbsp;";
} else {
$content .= $counter . "&nbsp;";
}
}

} else {
if ($i == $tmp_start ) {
if ($pembagi>0) {
$list=$counter+$pembagi;
$content .= $list . "&nbsp;";
} else {
$content .= $counter . "&nbsp;";
}
} else {
if ($pembagi>0) {
$list=$counter+$pembagi;
$urllist=($list-1)*$show_per_page;
$content .= "&nbsp;<a href='$url&start=$urllist'>$list</a>&nbsp;";
} else {
$content .= "&nbsp;<a href='$url&start=$start'>$counter</a>&nbsp;";
}
}
}
$start= $start + $show_per_page;
$counter = $counter + 1;
}
}
}
$content .= '
</td>
';
return $content;
}


############### INSERT DATA ################

function phonedir_insert_form() {
$divisi_ = phonedir_sql_array('select * from divs','divs_name','divs_id');
$pt_ = phonedir_sql_array('select * from prsh','prsh_name','prsh_id');
$region_ = phonedir_sql_array('select * from region','reg_name','reg_id');
$lantai_ = phonedir_sql_array('select * from fl','fl_name','fl_name');

//$options = array('1' => t('Enabled'), '0' => t('Disabled'));
$form['user'] = array(
'#type' => 'fieldset',
'#title' => t('Data Ekstensi Telepon'),
'#tree' => TRUE,
);
$form['user']['name'] = array(
'#type' => 'textfield',
'#title' => t('Nama Karyawan'),
'#size' => 30,
'#maxlength' => 64,
);
$form['user']['ext'] = array(
'#type' => 'textfield',
'#title' => t('Ext'),
'#size' => 5,
'#maxlength' => 5,
);
$form['user']['jobdesc'] = array(
'#type' => 'textfield',
'#title' => t('Jabatan'),
'#size' => 30,
'#maxlength' => 30,
);
$form['user']['mail'] = array(
'#type' => 'textfield',
'#title' => t('Email'),
'#size' => 30,
'#maxlength' => 30,
);
$form['user']['fax'] = array(
'#type' => 'textfield',
'#title' => t('Fax'),
'#size' => 15,
'#maxlength' => 15,
);
$form['user']['phone'] = array(
'#type' => 'textfield',
'#title' => t('Telepon'),
'#size' => 15,
'#maxlength' => 15,
);
$form['user']['floor'] = array(
'#type' => 'select',
'#title' => t('Lantai'),
'#options' => $lantai_,
);
$form['user']['div'] = array(
'#type' => 'select',
'#title' => t('Divisi'),
'#options' => $divisi_,
);
$form['user']['company'] = array(
'#type' => 'select',
'#title' => t('Nama Perusahaan'),
'#options' => $pt_,
);
$form['user']['region'] = array(
'#type' => 'select',
'#title' => t('Region'),
'#options' => $region_,
);
$form['submit'] = array('#type' => 'submit', '#value' => t('Save'));
return $form;
}

function phonedir_load_insert() {
return drupal_get_form('phonedir_insert_form');
}

function phonedir_insert_form_validate($form_id, $form_values) {
if ($form_values['user']['name'] == '') {
form_set_error('', t('Nama karyawan tidak boleh kosong!'));
}
if ($form_values['user']['ext'] == '') {
form_set_error('', t('Ekstension telpon tidak boleh kosong!'));
}
}

function phonedir_insert_form_submit($form_id, $form_values) {
db_set_active('phonedir');
$result = db_query("INSERT INTO ext (ext_name,ext_jobdesc,ext_div,ext_ext,ext_fax,ext_floor,ext_mail,ext_company,ext_region)
VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s')",
$form_values['user']['name'], $form_values['user']['jobdesc'], $form_values['user']['div'],$form_values['user']['ext'],$form_values['user']['fax'],$form_values['user']['floor'],$form_values['user']['mail'],$form_values['user']['company'],$form_values['user']['region']);
if (!$result) {
drupal_set_message(t('Bermasalah dalam memasukkan data : DUPLIKASI'));
} else {
drupal_set_message(t('Data ekstension telepon karyawan telah berhasil disimpan.'));
}
db_set_active('default');
}


############# SEARCH ##############

function phonedir_search_form() {
$divs__ = array("0"=>'ALL');
$divs___ = phonedir_sql_array('select * from divs','divs_name','divs_id');
$divs_ = array_merge($divs__,$divs___); ## pulldown content
$search = $_GET['search'];
$divs = $_GET['divs']; ## current divs from GET
if (!$qq) $qq = $_GET['qq'];
if (!$start) $start = $_GET['start'];

if ($divs) {
$caption_divs = strtoupper(phonedir_printfield("divs","divs_name","divs_id",$divs));
}

$form['user'] = array(
'#type' => 'fieldset',
'#title' => t('Cari Ekstensi Telepon'),
'#tree' => TRUE,
);
$form['user']['qq'] = array(
'#type' => 'textfield',
'#title' => t('Nama Karyawan'),
'#default_value' => $qq,
'#size' => 30,
'#maxlength' => 64,
'#description' => 'Boleh nama depan, nama tengah atau belakang.',
);
$form['user']['fungsi'] = array(
'#type' => 'select',
'#title' => t('Nama Fungsi'),
'#options' => $divs_,
);

$form['submit'] = array('#type' => 'submit', '#value' => t('Search'));
$form['#redirect']=FALSE;

$form['spacer'] = array(
'#type' => 'item',
'#size' => 0,
'#maxlength' => 0,
'#value' => t('')
);

$form ['hasil'] = array(
'#type' => 'fieldset',
'#title' => 'Hasil Pencarian1',
'#tree' => TRUE,
);

if ($divs) {
$add_query = ' and ext_div='.$divs;
}

if ($qq && $start>=0) {
db_set_active('phonedir');
$content = phonedir_list_data("EKSTENSI TELEPON ".$caption_divs,"ext",
"ext_id as NO,ext_name as NAMA,ext_ext as EXT,ext_floor as LT,divs_name as FUNGSI, ext_jobdesc as JABATAN, ext_phone as TLP", "left join divs on (ext_div=divs_id) left join region on (ext_region=reg_id) left join prsh on (ext_company=prsh_id) where ext_name like '%".$qq."%'".$add_query,
$start,"?q=phonedir/show&qq=".$qq."&divs=".$divs,$start,1,"profile",0);
db_set_active('default');
} elseif (!$qq && $start>0) {
db_set_active('phonedir');
$content = phonedir_list_data("EKSTENSI TELEPON ".$caption_divs,"ext",
"ext_id as NO,ext_name as NAMA,ext_ext as EXT,ext_floor as LT,divs_name as FUNGSI,ext_jobdesc as JABATAN, ext_phone as TLP", "left join divs on (ext_div=divs_id) left join region on (ext_region=reg_id) left join prsh on (ext_company=prsh_id) where ext_name like '%".$qq."%'".$add_query,
$start,"?q=phonedir/show&qq=".$qq."&divs=".$divs,$start,1,"profile",0);
db_set_active('default');
} elseif (!$qq && $start=='0') {
if ($search) {
db_set_active('phonedir');
$content = phonedir_list_data("EKSTENSI TELEPON ".$caption_divs,"ext",
"ext_id as NO,ext_name as NAMA,ext_ext as EXT,ext_floor as LT,divs_name as FUNGSI,ext_jobdesc as JABATAN, ext_phone as TLP", "left join divs on (ext_div=divs_id) left join region on (ext_region=reg_id) left join prsh on (ext_company=prsh_id) where 1".$add_query,
$start,"?q=phonedir/show&qq=".$qq."&divs=".$divs,$start,1,"profile",0);
db_set_active('default');
} elseif (!$search) {
header("Location: ?q=phonedir/show&qq=$qq&divs=$divs&start=0&search=Search");
}
}

$form ['hasil']['test'] = array(
'#type' => 'item',
'#size' => 0,
'#maxlength' => 0,
'#description' => $content,
);

return $form;
}

function phonedir_load_search() {
return drupal_get_form('phonedir_search_form');
}

function phonedir_search_form_submit($form_id, $form_values) {
db_set_active('phonedir');
$qq = eregi_replace("'","`",$form_values['user']['qq']);
$divs = $form_values['user']['fungsi'];
$search = $form_values['submit'];
header("Location: ?q=phonedir/show&qq=$qq&divs=$divs&start=0&search=$search");
db_set_active('default');
}



############## Profile ###############

function phonedir_profile_form() {
$divs__ = array("0"=>'ALL');
$divs___ = phonedir_sql_array('select * from divs','divs_name','divs_id');
$divs_ = array_merge($divs__,$divs___); ## pulldown content
$search = $_GET['search'];
$divs = $_GET['divs'];
$id = $_GET['id']; # profile's id
if (!$id) $id = $_GET['id'];

db_set_active('phonedir');
$query = "select ext_id as NO,ext_name as NAMA,ext_ext as EXT,ext_floor as LT,divs_name as FUNGSI,ext_jobdesc as JABATAN, ext_phone as TLP, prsh_name as PRSH, reg_name as REGION from ext left join divs on (ext_div=divs_id) left join region on (ext_region=reg_id) left join prsh on (ext_company=prsh_id) where ext_id=".$id;
$result = mysql_query($query);
if ($result)
$row_array = mysql_fetch_array($result);
db_set_active('default');

if ($divs) {
$caption_divs = strtoupper(phonedir_printfield("divs","divs_name","divs_id",$divs));
}

$form['pro'] = array(
'#type' => 'fieldset',
'#title' => t('Cari Ekstensi Telepon'),
'#tree' => TRUE,
);
$form['pro']['qq'] = array(
'#type' => 'textfield',
'#title' => t('Nama Karyawan'),
'#default_value' => $row_array["NAMA"],
'#size' => 30,
'#maxlength' => 64,
'#description' => 'Boleh nama depan, nama tengah atau belakang.',
);
$form['pro']['fungsi'] = array(
'#type' => 'select',
'#title' => t('Nama Fungsi'),
'#options' => $divs_,
);

$form['submit'] = array('#type' => 'submit', '#value' => t('Search'));
$form['#redirect']=FALSE;

$form['spacer'] = array(
'#type' => 'item',
'#size' => 0,
'#maxlength' => 0,
'#value' => t('')
);

$form ['mypro'] = array(
'#type' => 'fieldset',
'#title' => 'Lihat Profile',
'#tree' => TRUE,
);

$content = "<h3><font color='#444444'><label for='edit-pro-qq'>";
$content .= $row_array["NAMA"] . "<br />";
$content .= $row_array["JABATAN"] . "<br />";
$content .= $row_array["FUNGSI"] . "<br />";
$content .= $row_array["PRSH"] . " " . $row_array["REGION"];
$content .= "Ext : " . $row_array["EXT"] . "<br />";
$content .= "Lantai : " . $row_array["LT"] . "<br />";
$content .= "Telepon : " . $row_array["TLP"] . "<br />";
$content .= "</label></font></h3>";

$form ['mypro']['view'] = array(
'#type' => 'item',
'#size' => 0,
'#maxlength' => 0,
'#description' => $content,
);

return $form;
}

function phonedir_load_profile() {
return drupal_get_form('phonedir_profile_form');
}

function phonedir_profile_form_submit($form_id, $form_values) {
db_set_active('phonedir');
$qq = eregi_replace("'","`",$form_values['pro']['qq']);
$divs = $form_values['pro']['fungsi'];
$search = $form_values['submit'];
header("Location: ?q=phonedir/show&qq=$qq&divs=$divs&start=0&search=$search");
db_set_active('default');
}

db_set_active('default');
?>



Search Linux Resources