Tải bản đầy đủ (.pdf) (5 trang)

Secure PHP Development- P123 pptx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (107.54 KB, 5 trang )

doRemind()
This function obtains four things: the user’s reminder directory ($userDir, which is
USER_REMINDER_DIR set in reminder.conf), the user reminder file name
($userFile, which is USER_REMINDER_FILE set in reminder.conf), $username, and
the user’s home directory ($homeDir).
It first determines whether the user has a reminder file in the reminder directory
inside the user’s home directory. If there is no reminder configuration
(reminders.txt) file, the function returns. That ends the user’s reminder processing.
However, because the user does have a reminders.txt file in the reminders
directory, the getRemindersForToday() function is called see if any of the
reminders are meant for the current day.
The getRemindersForToday() method parses the reminders.txt file and if
any reminder matches, it returns the associated reminder mail file. For example,
suppose a user has the following configuration in reminders.txt:
weekly:mon:my_monday_tasklist.txt
weekly:tue:my_tuesday_tasklist.txt
weekly:wed:my_wednesday_tasklist.txt
weekly:thu:my_thursday_tasklist.txt
weekly:fri:my_friday_tasklist.txt
weekly:sat:my_saturday_plans.txt
weekly:sun:my_sunday_plans.txt
Whenever the reminder is run, one of the weekly reminders will match, as the
user has a weekly reminder for each day. The matching reminder mail file will be
returned in an array called $mailings by the getRemindersForToday() function.
For each of the entries in $mailings, the doMail() method is called only if the
mail file exists. In other words, if it is Monday, the preceding configuration will
return $mailings = array(‘monday_tasklist.txt’). If ~username/reminders/
monday_tasklist.txt exists, then doMail() will send out the mail.
In the case of a missing file, log entries will be created. The log is later written to
the ~username/reminders/username.log file so that the user can review it and fix
the configuration file or create missing mail files.


doMail()
This function sends the mail out. It receives a reminder mail filename, which exists
in the ~username/reminders directory. The function loads the file into an array
called $lines using the file() function.
Each line is parsed for mail headers, such as To:, From:, Cc:, Bcc:, Subject:, and
Content-Type:. These headers are stored in appropriate format in the $headers
array.
The other lines are considered part of the body of the message, and are stored in
the $messages array.
Chapter 16: Command-Line PHP Utilities 581
21 549669 ch16.qxd 4/4/03 9:27 AM Page 581
The default content type is set to text/plain in this function.
Then the $body string is created by concatenating the lines in the $messages
array using the implode() function. Both the $body and the $subject line are
parsed for the <%TODAY%> tag, which is replaced with the current date and time. The
$subject line is stored outside the $headers array even though it is a header too.
This is done because the PHP mail() function requires the subject as a separate
argument from the other headers. The same is true for the To: header, which is also
stored outside $headers in $to .
Finally, the $headers are imploded into $headerString, and the mail() func-
tion is called with all the necessary arguments. The mail is sent out. If the actual
mail() function encounters any errors a log entry is added to that effect.
getRemindersForToday ()
This function receives a list of lines (the contents of the reminders.txt file), and
parses through each line to determine whether the line is a reminder configuration
or should be ignored (blank or a comment line starting with the # character).
Each reminder configuration line is compared against the current date (MM, DD,
and weekday) values to determine whether any of the lines match a reminder for
today.
If a match is found, the reminder mail filename is added into the $reminders

array, which is returned by the function.
writeLog ()
This function writes a log file as ~username/reminders/username.log. The log
entries are generated by other functions in the script.
getUsers ()
This function loads the user list file (/etc/passwd) in an array, loops through each
record, and finds the username (field position 0) and home directory (field position
5) from each line separated by colons.
It stores each username and home directory in an associative array called $user
and returns it.
Installing the reminder tool as a cron job
To set up reminder.php as a cron job under Linux, do the following:
1. As root, create a symbolic link in
/etc/cron.daily as follows:
ln -s /path/to/reminder.php
582 Part IV: Using PHP for Sysadmin Tasks
21 549669 ch16.qxd 4/4/03 9:27 AM Page 582
For example, say you kept reminder.php and reminder.conf in /usr/
local/src/reminder
directory, you can run the following commands
as root to create the link:
cd /etc/cron.daily
ln -s /usr/local/src/reminder/reminder.php
2. Once the symlink is created, run: /etc/cron.daily/reminder.php
as a test. If you get an error message about reminder.conf not being
found, you need to edit the reminder.php to change require_once
(‘reminder.conf’)
to require_once(‘/path/to/reminder/
reminder.conf’)
. For our example case, this would be

require_once(‘/usr/local/src/reminder/reminder.conf’).
3. Make sure reminder.php is executable. You can run
chown root:root reminder.*
chmod 700 reminder.php
from the directory of the script to allow root to own and be able to exe-
cute the reminder scripts. If your cron daemon does not run as root, make
sure you replace root:root with the appropriate user and group names that
enable cron to execute the script.
4. Now you can set up reminders in one or more user reminder directories
(~username/remidners/reminders.txt) and create necessary mail files
in the reminders directory.
5. Let cron run the job at the regularly scheduled time and you should
receive reminders if you have set any for yourself. If you do not receive
a reminder you expect to receive, check the ~usernmame/reminders/
username.log
file. Also check /var/log/cron for possible file
execute permission issues
Building a Geo Location
Finder Tool for IP
Ever find an IP address in a log file that looked suspicious or interesting and you
wanted to know from which part of the world that IP came? A trace route might
give you clues but it is too much work to find geographic locations of an IP
address.
In this section, we will develop a simple script called geolocator.php using the
netgeo.php class, which you can download from />netgeoclass
.
Chapter 16: Command-Line PHP Utilities 583
21 549669 ch16.qxd 4/4/03 9:27 AM Page 583
This class uses The Internet Geographic Database, which maps IP addresses to
physical world locations. To learn more about this, visit />tools/utilities/netgeo

.
Listing 16-9 shows the geolocator.php script.
Listing 16-9: geolocator.php
#!/usr/bin/php -q
<?php
require_once(“netgeo.php”);
// Get a list of hosts/ip from command line
$hostList = getHostList();
// if no host/ip was given show syntax msg
if (count($hostList) < 1)
{
echo “Syntax: “ . basename($GLOBALS[‘argv’][0]) .
“ host | ip_address\n”;
exit;
}
// For each host/ip find geo location
foreach ($hostList as $host)
{
findLocation($host);
echo “ \n”;
}
exit;
function findLocation($hostname = null)
{
// Create a netgeo class object
$netgeo=new netgeo_class;
// Find location for the given host/ip
if($netgeo->GetAddressLocation($hostname,$location))
{
// Set longitude and latitude from retrieved data

$longitude=doubleval($location[“LONG”]);
$latitude=doubleval($location[“LAT”]);
584 Part IV: Using PHP for Sysadmin Tasks
21 549669 ch16.qxd 4/4/03 9:27 AM Page 584
// Show output
echo $host”: Approximate location:\n”;
if(IsSet($location[“CITY”]) ||
IsSet($location[“STATE”]) ||
IsSet($location[“COUNTRY”]))
{
if(IsSet($location[‘CITY’]))
echo “City : “ . $location[‘CITY’] . “\n”;
if(IsSet($location[‘STATE’]))
echo “State :” . $location[‘STATE’] . “\n”;
if(IsSet($location[‘COUNTRY’]))
echo “Country :”. $location[‘COUNTRY’] . “\n”;
}
echo “Longitude:” .
($longitude>=0.0 ? $longitude .
“degree East” : (-$longitude).”degree West”).”\n”;
echo “Latitude:”.
($latitude>=0.0 ? $latitude .
“degree North” : (-$latitude).”degree South”).”\n”;
}
else
{
echo “Cannot find location.\n”;
echo “Error: “.$netgeo->error.”\n”;
}
}

function getHostList()
{
$arr = array();
// Except for the first argument in the command
// line, insert all in a list as host/ip
// Note: first argument is the name of the script.
foreach($GLOBALS[‘argv’] as $key => $value)
{
if ($key) array_push($arr, $value);
}
return $arr;
}
?>
Chapter 16: Command-Line PHP Utilities 585
21 549669 ch16.qxd 4/4/03 9:27 AM Page 585

×