Location: PHPKode > scripts > Periodic site maintenance > periodic-site-maintenance/as_nightjobs.en.htm
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head><title>as_nightjobs: Class for performing daily site's maintenance job</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
body     { font-family:verdana,arial,helvetica;font-size:12px; }
pre { font-family: verdana,arial; font-size:11px; color:#0000FF;
      background-color: #EFEFF0; border: 1px solid #D0D0F0; padding:6px;
}
td   { font-family:arial,helvetica;font-size:12px;}
tr.odd   { background-color: #F0F0F8; color:#000000; }
tr.even  { background-color: #E0E0F0; color:#000000; }
h4       { background-color: #E0E0F0; color:#000000;
           text-align: left; }
h5       { background-color: #E0E0F0; color:#000000;
           text-align: left; font-size:11px; padding-left:8px;}
-->
</style>
</head>
<body>
<!-- DOC BEGIN -->

<H3>as_nightjobs: Class for performing daily site's maintenance job</H3>

There are some actions that should be done with Your site periodically,
like deleting old files, optimizing database tables, checking full site size.

<br /><br />
If Your hosting tariff plan has a space limit (does anybody have "unlimited" hosting ? :),
it could be nice to have a "forecast" - how long Your site will grow until
it reaches the limit.

This class can help admins and developers in periodic site maintenance tasks:
<ul>
  <li>make database backups - only selected tables contents is saved into gzipped xml files);
    "big" tables can be separated from "small" tables, to enable fast restoring of a small tables
  </li>
  <li>perform backup file rotation (delete files older than N days);
  </li>
  <li>clean specified folder(s) from files by wildcard and/or modification date/time</li>
  <li>delete "obsolete" records from some database tables (for example user actions logs)
  </li>
  <li>optimize/analyze tables in MySQL DB;
  </li>
  <li>calculate space occupied by site (files and data in MySQL tables),
      and optionally estimated days before Your site exceeds disc space limit;
      <br />In case of disc limit already reached,
      respective ALARM message will be added to the final report.
  </li>
</ul>

If there are some specific tasks, You can prepare a function for calling
them and pass this function's name to the class, so these tasks will be executed too.

<br /><br />
If job initiated from any kind of scheduler (CRON on *nix systems), execution report can be
sent to the administrator's email. Otherwise it's just echoed to the client screen.

<h4>Installation on the site</h4>
<ul>
  <li>Place php modules <b>as_nighjobs.php</b> and <b>as_dbutils.php</b> from distributive into Your site's folder,</li>
<!--
  <li>Make sure Your php.ini parameter <b>short_open_tag</b>  is set to "On", because
   "short form " of starting code tag (&lt;?) is used in class.
  </li>
-->
  <li>Edit <b>job_sample.php</b> or create Your script, filling it with all Your parameters for the job.
  </li>
</ul>

<h4>Simple code example</h4>

<pre>require_once('as_dbutils.php');
require_once('as_nightjobs.php');
//don't forget to open MySQL connection !

$job = new CNightJobs();
$job-&gt;SetAdminEmail('hide@address.com'); # report will be sent to this address
$job-&gt;SiteSizeParameters('..', 'sitestatistic', 1000,array('mydb1','mydb2')); # root folder is "../", space limit - 1 GB
$job-&gt;Exec();

</pre>

<h4>Using the class</h4>

All maintenance jobs are executed from method Exec(), so ALL needed parameters must be set before calling it.
If You don't set some parameters, respective action won't be executed.
Here is a full method list with descriptions.

<br /><br />
<b>CNightJobs($apptitle='')</b> - class constructor can receive your site's title.
It will be used only in email message subject, that will be sent to administrator after all jobs executed.

<br /><br />
<b>SetTablesList($tblist, $tblist2=0)</b> - specifies lists of all database tables used by Your site, that must be backed up and/or optimized.
Second parameter $tblist2 can be used if You want backup your "BIG" and "SMALL" data tables into separated files.
This can be useful when You decide to restore some data from backup. Getting them from huge backup file maight fail
because of timeout. In that case storing "list" and other small tables into separate backup file is a good idea.
<br />Both lists will be used in making backup procedure, and "optimizing data tables" function.

<br /><br />
<b>SetBackupParameters($back_folder, $bckpdays=10,$nobackup=null, $prefix='',$prefix2='')</b> -
sets parameters for db backup operation :<br />
 <table>
  <tr class='odd'>
    <td>$back_folder</td>
    <td>
    Folder for backup files. If empty string, backup is never executed.
    </td>
  </tr>
  <tr class='even'>
    <td>$bckpdays</td>
    <td>
    How many days to keep backup files. If non-zero, all files created more than N days ago, will be deleted.
    </td>
  </tr>
  <tr class='odd'>
    <td>$nobackup</td>
    <td>
    If you want to optimize some tables, they should exist in $tblist or $tblist2, but if You don't want them to be backed up,
    just add their name(s) to this array parameter.
    </td>
  </tr>

  <tr class='even'>
    <td>$prefix</td>
    <td>
    Backup file prefix, all files will have names like <b>{prefix}YYYY-MM-DD.xml.gz</b>
    <br />By default : 'db'.
    </td>
  </tr>
  <tr class='odd'>
    <td>$prefix2</td>
    <td>
    Prefix for the second backup files
    <br />By default : 'dblist'.
    </td>
  </tr>

 </table>

<br />

<b>AddFolderToClean($folder,$mask='',$days=0)</b> - adds one folder for "cleaning" process
<table>
 <tr class='odd'>
    <td>$folder</td>
    <td>
    Folder to clean. No final "/" needed.
    </td>
 </tr>
 <tr class='even'>
    <td>$mask</td>
    <td>
    File wildcard. Empty string is equal to "*.*"
    </td>
 </tr>
 <tr class='odd'>
    <td>$days</td>
    <td>
    Delete files older than these NN days. Zero value means "kill'em all".
    </td>
 </tr>
</table>
<br />Note: subfolders are not processed. If You want to clean subfolder(s), call this method for every subfolder's name.

<br /><br />
<b>AddTableToShrink($tablename, $datefield)</b> - adds a table for "shrinking" process, that means deleting obsolete records.
Commonly it can be used for shrinking audit log tables.
<br />
<table>
 <tr class='odd'>
    <td>$tablename</td>
    <td>table name</td>
 </tr>
 <tr class='even'>
    <td>$datefield</td>
    <td>name of a date/datetime/timestamp field that contains event's recording time/date, this field will be checked</td>
 </tr>
</table>

<br /><br /><b>TableShrinkDays($days)</b> sets how many days records stays in "shrinked" tables.
If You don't call this method, 30 days will be used by default.

<br /><br />
<b>SetEmailParameters($email,$charset='')</b> sets administrator email address for sending job report.
<br />Optional $charset parameter can contain valid charset name that will be used in email headers. If Your user function
returns some localyzed text, You should pass it's character set here. Otherwise there's no need to change it,
because all "standard" report strings use only latin chars.

<br /><br />
<b>SetUserFunction($udf)</b> set Your function name, this function will be called at the end of job.
String returned by this function will be added to the job report.

<br /><br />

<b>SiteSizeParameters($rootfolder, $sitesizetable='',$maxsitesize=0, $dblist=0)</b> sets parameters for
computing whole space occupied by site - all files and data in currently connected MySQL database.
<br />
<table>
 <tr class='odd'>
    <td>$rootfolder</td>
    <td>String or array. Space occupied by all files in all subfolders will be counted from this starting point.
    You can pass an array with more than one folder, in case of impossible root folder counting (no reading rights on base folder etc.)</td>
 </tr>
 <tr class='even'>
    <td>$sitesizetable</td>
    <td>If You want day by day accumulate site statistics, pass here a table's name.<br />
    This table is auto-generated if not exists in current database. Make sure Your table name is unique and doesn't interfere with some
    other table in DB !<br />
    If statistic table used, average growth per day and for the last period (day or week - depend on how often your schedule runs a job)
    is calculated and reported, and estimated days before the site is out of limit space (if average growth is positive and space limit
    in $maxsitesize is set)
    </td>
 </tr>
 <tr class='odd'>
    <td>$maxsitesize</td>
    <td>disc space limit for your site, according current ISP tariff plan (MBytes). If non-empty integer value, some additional work will be done:
    <br />average site growth is calculated and number of days before Your site reaches the limit. If this day amount is less than 10,
    WARNING word will be added to the email message subject and the text body. If limit already exceeded, ALARM word will be added.</td>
 </tr>
 <tr class='even'>
    <td>$dblist</td>
    <td>By default Summary database space is calculated for the currently open database.<br />
    But Your site data can be scattered to many databases (they have to reside in ONE server !)
    <br />In that case You can pass an array with all database names. Total size will contain all their sizes.
    </td>
 </tr>
</table>

<br /><br />
<b>Exec()</b> - finally You call this method to start all maintenance jobs. Summary report is echoed to the screen,
and emailed ( if admin email set and script was started by CRON/scheduler).

<br /><br /><br />
There are some "internal" functions that called from Exec(), but of cource You can call them manually if You know what You want.
<br /><br />

<li>
  <b>CleanFolder($folder, $mask='',$days=0)</b> can be called to clean one folder from old (or any) files by wildcard.
</li>
<br />
<li>
<b>OptimizeTables($tlist='')</b> executes table optimization for each table from passed array $tlist.
Optimization is done by calling MySQL operators OPTIMIZE TABLE and ANALYZE TABLE.
</li>
<br />
<li>
 <b>CleanupSessions()</b> deletes session files older than 1 day from current SESSION folder. Normally web server cleans sessions
 automatically, but sometimes it can be useful. This function is never called from Exec().
</li>
<br />
<li>
<b>GetFolderSize($folder)</b> counts and returns summary disc space of the folder/directory (with all nested sub-folders) in Bytes.
</li>
<br />

<H4>Version History</H4>

<h5>1.00.001 (01/26/2009)</h5>
<ul>
  <li>First release published
  </li>
</ul>

<div style="text-align:right">Distributed under BSD License</div>

<!-- DOC END -->
<br />
<hr>
<div align=center><font size=-2>Copyright &copy; Alexander Selifonov, <a href="http://www.selifan.ru">www.selifan.ru</a>
</font></div>
</body></html>
Return current item: Periodic site maintenance