phpDocumentor InternetAccessLog
[ class tree: InternetAccessLog ] [ index: InternetAccessLog ] [ all elements ]

Source for file MySQLRandomElements.class.php

Documentation is available at MySQLRandomElements.class.php

  1. <?php
  2. /**
  3.  *  MySQLRandomElements.class.php
  4.  *  File with the class used to generate random elements and save then in MySQL (users, URL's and IP's)
  5.  *  @author José Manuel Ciges Regueiro <jmanuel@ciges.net>, Web page {@link http://www.ciges.net}
  6.  *  @license http://www.gnu.org/copyleft/gpl.html GNU GPLv3
  7.  *  @version 20130325
  8.  *
  9.  *  @package InternetAccessLog
  10.  *  @filesource
  11.  */
  12. require_once("RandomElements.class.php");
  13. /**
  14.  *  This class is used to generate random elements (users, IP's and URL's) and save them into MySQL
  15.  *  With this elements created we can simulate non FTP and FTP log entries (in our demo the acces by FTP are stored in a separate collection)
  16.  */
  17.  class MySQLRandomElements extends RandomElements    {
  18.  
  19.     /**
  20.      * Default names for random data collections
  21.      */
  22.     const DATA_RNDUSERSC_NAME = "DATA_Random_UsersList";
  23.     const DATA_RNDIPSC_NAME = "DATA_Random_IPsList";
  24.     const DATA_RNDDOMAINSC_NAME = "DATA_Random_DomainsList";
  25.     const DATA_RNDURISC_NAME = "DATA_Random_URIsList";
  26.  
  27.     const NONFTPLOG_NAME = "NonFTP_Access_log";
  28.     const FTPLOG_NAME = "FTP_Access_log";
  29.  
  30.     /**
  31.      *  Default prefixes for monthly reports
  32.      */
  33.     const USERS_REPORT_PREFIX = "Users_Monthly_Report_";
  34.     const DOMAINS_REPORT_PREFIX = "Domains_Monthly_Report_";
  35.  
  36.     /**
  37.      * Constants for default connection values
  38.      */
  39.     const DEFAULT_USER = "mysqldb";
  40.     const DEFAULT_PASSWORD = "mysqldb";
  41.     const DEFAULT_HOST = "localhost";
  42.     const DEFAULT_DB = "InternetAccessLog";
  43.  
  44.     /**
  45.      * Connection to the database
  46.      * @access private
  47.      * @var Mongo 
  48.      */
  49.     private $db_conn;
  50.     /**
  51.      * Database name
  52.      * @access private
  53.      * @var Mongo 
  54.      */
  55.     private $db_databasename;
  56.  
  57.     /**
  58.      * Arrays to load random data in memory
  59.      * @access private
  60.      * @var array; 
  61.      */
  62.     private $rnd_users;
  63.     private $rnd_ips;
  64.     private $rnd_domains;
  65.     private $rnd_uris;
  66.  
  67.     /**
  68.      * Number of element of each created collection in MySQL (for cache purposes)
  69.      * @access private
  70.      * @var string 
  71.      */
  72.     private $rnd_users_number;
  73.     private $rnd_ips_number;
  74.     private $rnd_domains_number;
  75.     private $rnd_uris_number;
  76.  
  77.     /**
  78.      * Gets the connection to MySQL
  79.      * @returns mysqli
  80.      */
  81.     public function getDB()    {
  82.         return $this->db_conn;
  83.     }
  84.  
  85.     /**
  86.      *  Sends a query to the database and returns the results. If no rows are got null is returned
  87.      *  @param string query
  88.      *  @return mixed 
  89.      *  @access public
  90.      */
  91.     public function getResults($query)    {
  92.         if ($results $this->getDB()->query($query))    {
  93.             if ($results->num_rows 0{
  94.                 return $results;
  95.             }
  96.             else    {
  97.                 return null;
  98.             }
  99.         }
  100.         else    {
  101.             die ("Error sending the query '".$query."' to MySQL: ".$this->db_conn->error."\n");
  102.         }
  103.     }
  104.  
  105.     /**
  106.      *  Sends a query to the database and returns the first row as an associative array. If no rows are got null is returned
  107.      *  @param string query
  108.      *  @return array 
  109.      *  @access public
  110.      */
  111.     public function getRow($query)    {
  112.         $results $this->getResults($query);
  113.         return $results->fetch_assoc();
  114.     }
  115.  
  116.     /**
  117.      *  Sends a query to the database and returns the first field of the first row. If no rows are got null is returned
  118.      *  @param string query
  119.      *  @return array 
  120.      *  @access public
  121.      */
  122.     public function getOne($query)    {
  123.         $results $this->getResults($query);
  124.         $row $results->fetch_row();
  125.         return $row[0];
  126.     }
  127.  
  128.     /**
  129.      *  This function says if a table exists in MySQL
  130.      *  @param string tablename
  131.      *  @returns boolean
  132.      *  @access private
  133.      */
  134.     private function tableExists($tablename)    {
  135.         $query "show table status where Name=\"".$tablename."\"";
  136.         if ($result $this->db_conn->query($query))    {
  137.             return $result->num_rows 0;
  138.             }
  139.             else    {
  140.                     die ("Error sending the query '".$query."' to MySQL: ".$this->db_conn->error."\n");
  141.             }
  142.     }
  143.  
  144.     /**
  145.      *  This function deletes a table if it exists in MySQL. If the table does not exists returns false (and does nothing)
  146.      *  @param string tablename
  147.      *  @return boolean 
  148.      *  @access public
  149.      */
  150.     public function dropTable($tablename)    {
  151.         if ($this->tableExists($tablename))  {
  152.             if ($this->db_conn->query("drop table if exists ".$tablename)) {
  153.                 return true;
  154.                 }
  155.             else    {
  156.                 die ("Error sending the query '".$query."' to MySQL: ".$this->db_conn->error."\n");
  157.                 }
  158.             }
  159.         else    {
  160.             return false;
  161.         }
  162.     }
  163.  
  164.     /**
  165.      *  This function deletes the table used for saving NonFTP logs. If the table does not exists returns false (and does nothing)
  166.      *  @param string tablename
  167.      *  @return boolean 
  168.      *  @access public
  169.      */
  170.     public function dropTableNonFTPLogEntry()    {
  171.         $this->dropTable(self::NONFTPLOG_NAME);
  172.     }
  173.  
  174.     /**
  175.      * Sends a query to the database and stops the script if it is no succesfull
  176.      * @returns boolean
  177.      * @access private
  178.      */
  179.     private function sendQuery($query)  {
  180.         $this->db_conn->query($query||
  181.             die ("Error sending the query '".$query."' to MySQL: ".$this->db_conn->error."\n");
  182.     }
  183.  
  184.     /**
  185.      *  This function returns the number of records for the table passed as parameter.  If the table does not exists returns 0.
  186.      *  @param string tablename
  187.      *  @returns integer
  188.      *  @access private
  189.      */
  190.     private function recordNumber($tablename)    {
  191.         $query "show table status where Name=\"".$tablename."\"";
  192.         if ($result $this->db_conn->query($query))    {
  193.         if ($result->num_rows 0{
  194.             $row $result->fetch_assoc();
  195.             return (int) $row["Rows"];
  196.         }
  197.         else    {
  198.             return 0;
  199.         }
  200.             }
  201.             else    {
  202.                     die ("Error sending the query '".$query."' to MySQL: ".$this->db_conn->error."\n");
  203.             }
  204.     }
  205.  
  206.     /**
  207.     *  This function queries the database to return the users number (records in Random_UsersList)
  208.     *  @return integer 
  209.     *  @access public
  210.     */
  211.     public function getUserNumber({
  212.         $this->rnd_users_number $this->recordNumber(self::RNDUSERSC_NAME);
  213.         return $this->rnd_users_number;
  214.     }
  215.  
  216.     /**
  217.      *  This function returns the username searching by the id. If the user does not exist null is returner
  218.      *  @param integer $userid 
  219.      *  @return string $username
  220.      *  @access public
  221.      */
  222.     public function getUserFromID($userid{
  223.         if ($userid count($this->$rnd_users_number))  {
  224.             return null;
  225.         }
  226.         return $this->$rnd_users[$userid];
  227.     }
  228.  
  229.     /**
  230.     *  This function queries the database to return the domains number (records in Random_DomainsList)
  231.     *  @return integer 
  232.     *  @access public
  233.     */
  234.     public function getDomainNumber({
  235.         $this->rnd_domains_number $this->recordNumber(self::RNDDOMAINSC_NAME);
  236.         return $this->rnd_domains_number;
  237.     }
  238.  
  239.     /**
  240.      *  This function returns the domain searching by the id. If the domain does not exist null is returner
  241.      *  @param integer $id 
  242.      *  @return string $domain
  243.      *  @access public
  244.      */
  245.     public function getDomainFromID($id{
  246.         if ($id count($this->$rnd_domains_number))  {
  247.             return null;
  248.         }
  249.         return $this->$rnd_domains[$id];
  250.     }
  251.  
  252.     /**
  253.      *  This function returns the user data from the raports for a year and month specified. If there is no data returns null
  254.      *  @param string $username 
  255.      *  @param integer $year 
  256.      *  @param integer $month   Number from 1 to 12
  257.      *  @return array 
  258.      *  @access public
  259.      */
  260.     public function getUserCollectedData($username$year$month)  {
  261.         $col self::USERS_REPORT_PREFIX.$year.sprintf("%02d"$month);
  262.         $query "select * from ".$col." where user=\"".$username."\"";
  263.         if ($result $this->db_conn->query($query))   {
  264.             if ($result->num_rows 0)  {
  265.                 $row $result->fetch_array();
  266.                 return $row;
  267.             }
  268.             else    {
  269.                 return null;
  270.             }
  271.         }
  272.         else    {
  273.             die ("Error sending the query '".$query."' to MySQL");
  274.         }
  275.     }
  276.  
  277.     /**
  278.      *  This function returns the domain data from the reports for a year and month specified. If there is no data returns null
  279.      *  @param string $domainname 
  280.      *  @param integer $year 
  281.      *  @param integer $month   Number from 1 to 12
  282.      *  @return array 
  283.      *  @access public
  284.      */
  285.     public function getDomainCollectedData($domainname$year$month)  {
  286.         $col self::DOMAINS_REPORT_PREFIX.$year.sprintf("%02d"$month);
  287.         $query "select * from ".$col." where domain=\"".$username."\"";
  288.         if ($result $this->db_conn->query($query))   {
  289.             if ($result->num_rows 0)  {
  290.                 $row $result->fetch_array();
  291.                 return $row;
  292.             }
  293.             else    {
  294.                 return null;
  295.             }
  296.         }
  297.         else    {
  298.             die ("Error sending the query '".$query."' to MySQL");
  299.         }
  300.     }
  301.  
  302.     /**
  303.      *  Helper function to create Users table in database
  304.      *  @param string $tablename 
  305.      *  @param boolean $useindex    Sets if a unique index for user name must be created
  306.      *  @access private
  307.      */
  308.     private function createUsersTable($tablename self::DATA_RNDUSERSC_NAME$use_index true{
  309.         if (!$this->tableExists($tablename)) {
  310.             if ($use_index{
  311.                 $query "CREATE TABLE ".$tablename." (
  312.                 id INT NOT NULL PRIMARY KEY,
  313.                 user CHAR(7),
  314.                 unique index user_index (user)
  315.                 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
  316.             }
  317.             else {
  318.                 $query "CREATE TABLE ".$tablename." (
  319.                 id INT NOT NULL PRIMARY KEY,
  320.                 user CHAR(7)
  321.                 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
  322.             }
  323.             $this->db_conn->query($query||
  324.                 die ("Error sending the query '".$query."' to MySQL: ".$this->db_conn->error."\n");
  325.         }
  326.     }
  327.  
  328.     /**
  329.      *  This function add a user to the table passed as second argument. If not collection done then the user will be added to Random_UsersList.
  330.      *  This function is coded for load tests, not for real use. The id is autonumeric
  331.      *  Returns true if the user has been succesfull added, false if not
  332.      *  @param string $username 
  333.      *  @param string $tablename 
  334.      *  @access public
  335.      *  @return boolean 
  336.      */
  337.     public function addFakeUser($username$tablename self::DATA_RNDUSERSC_NAME)   {
  338.         // Table creation if it does not exists
  339.         if (!$this->tableExists($tablename))    {
  340.             $query "CREATE TABLE ".$tablename." (
  341.                 id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  342.                 user CHAR(7)
  343.                 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
  344.             $this->db_conn->query($query||
  345.                 die ("Error sending the query '".$query."' to MySQL: ".$this->db_conn->error."\n");
  346.         }
  347.  
  348.         $query "insert into ".$tablename." (user) values (\"".$username."\")";
  349.         if($this->db_conn->query($query))   {
  350.             return true;
  351.         }
  352.         else {
  353.             return false;
  354.         }
  355.     }
  356.  
  357.     /**
  358.      *  This function verifies if the user exists in the collection passed as second argument. If not collection done then the user will be added to Random_UsersList.
  359.      *  @param string $username 
  360.      *  @param string $tablename 
  361.      *  @return boolean 
  362.      *  @access public
  363.      */
  364.     public function existUser($username$tablename self::RNDUSERSC_NAME)    {
  365.         if ($this->tableExists($tablename)) {
  366.             $query "select id from ".$tablename." where user=\"".$username."\"";
  367.             $results $this->db_conn->query($query||
  368.                 die ("Error sending the query '".$query."' to MySQL: ".$this->mysrnd_con->error."\n");
  369.             return $results->num_rows 0;
  370.         }
  371.         else    {
  372.             return false;
  373.         }
  374.     }
  375.  
  376.     /**
  377.      *  Constructor. For creating an instance we need to pass all the parameters for the MongoDB database where the data will be stored (user, password, host & database name).
  378.      *  <ul>
  379.      *  <li>The default user and password will be mysqldb
  380.      *  <li>The default host will be localhost
  381.      *  <li>The default database name will be InternetAccessLog
  382.      *  </ul>
  383.      * @param string $user 
  384.      * @param string $password 
  385.      * @param string $host 
  386.      * @param string $database 
  387.     */
  388.     function __construct($user self::DEFAULT_USER$password self::DEFAULT_PASSWORD$host self::DEFAULT_HOST$database self::DEFAULT_DB)    {
  389.         // Open a connection to MySQL
  390.         try {
  391.             $this->db_conn new mysqli($host$user$password$database);
  392.             $this->db_databasename $database;
  393.         }
  394.         catch (Exception $e{
  395.             die("Connection MySQL impossible: (".$e->getCode().") ".$e->getMessage()."\n");
  396.         }
  397.  
  398.         // Stores the number of elements of each stored random elements collection
  399.         $this->rnd_users_number $this->recordNumber(self::DATA_RNDUSERSC_NAME);
  400.         $this->rnd_ips_number $this->recordNumber(self::DATA_RNDIPSC_NAME);
  401.         $this->rnd_domains_number $this->recordNumber(self::DATA_RNDDOMAINSC_NAME);
  402.         $this->rnd_uris_number $this->recordNumber(self::DATA_RNDURISC_NAME);
  403.         // Load the data in RAM
  404.         //$this->loadDataInRAM();
  405.     }
  406.  
  407.     /**
  408.      *  Destructor. Close the open connection to MySQL database
  409.       */
  410.     function __destruct()    {
  411.         $this->db_conn->close();
  412.     }
  413.  
  414.     /**
  415.      *  Save random users in MySQL.
  416.      *  The parameters are the number of users two create and to booleans: if we want an unique index to be created for the user name (default is TRUE) and if we want that the user name is unique (default TRUE).
  417.      *  If the user name is going to be unique the existence of the name is verified with a query before inserting a new one.
  418.      *  The id will be autonumeric (1, 2, 3 ....)
  419.      *  @param integer $number 
  420.      *  @param boolean $use_index 
  421.      *  @param boolean $dont_repeat 
  422.      */
  423.     function createUsers($number$use_index TRUE$dont_repeat TRUE)    {
  424.         $id $this->rnd_users_number 1;   // Autonumeric
  425.  
  426.         // Table creation if it does not exists
  427.         $this->createUsersTable(self::DATA_RNDUSERSC_NAME$use_index);
  428.  
  429.         $i 1;
  430.         while ($i <= $number)    {
  431.             $user $this->getRandomUser();
  432.             // We verify if the user is in the collection only if it is needed
  433.             $insert TRUE;
  434.             if ($dont_repeat{
  435.                 $query "select id from ".self::DATA_RNDUSERSC_NAME." where user=\"".$user."\"";
  436.                 if ($result $this->db_conn->query($query))   {
  437.                     $result->num_rows &&
  438.                         $insert FALSE;
  439.                 }
  440.                 else    {
  441.                     die ("Error sending the query '".$query."' to MySQL");
  442.                 }
  443.             }
  444.             if ($insert)   {
  445.                 $query "insert into ".self::DATA_RNDUSERSC_NAME." (id, user) values (".$id.", \"".$user."\")";
  446.                 $this->db_conn->query($query||
  447.                     die ("Error sending the query '".$query."' to MySQL: ".$this->mysrnd_con->error."\n");
  448.                 $id++;
  449.                 $i++;
  450.             }
  451.         }
  452.         // Update users numbers property
  453.         $this->rnd_users_number =  $this->recordNumber(self::DATA_RNDUSERSC_NAME);
  454.  
  455.     }
  456.  
  457.     /**
  458.      * Returns true if the "Random_UsersList" table has records
  459.      * @returns boolean
  460.      */
  461.     function randomUser_exists()    {
  462.     return $this->recordNumber(self::RNDUSERSC_NAME0;
  463.     }
  464.  
  465.     /**
  466.      *  Helper function to create IPs table in database
  467.      *  @param string $tablename 
  468.      *  @param boolean $useindex    Sets if a unique index for IP name must be created
  469.      *  @access private
  470.      */
  471.     private function createIPsTable($tablename self::DATA_RNDIPSC_NAME$use_index true{
  472.         // Table creation if it does not exists
  473.         if (!$this->tableExists(self::DATA_RNDIPSC_NAME)) {
  474.             if ($use_index{
  475.                 $query "CREATE TABLE ".self::DATA_RNDIPSC_NAME." (
  476.                 id INT NOT NULL PRIMARY KEY,
  477.                 ip VARCHAR(15),
  478.                 unique index ip_index (ip)
  479.                 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
  480.             }
  481.             else {
  482.                 $query "CREATE TABLE ".self::DATA_RNDIPSC_NAME." (
  483.                 id INT NOT NULL PRIMARY KEY,
  484.                 ip VARCHAR(15)
  485.                 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
  486.             }
  487.             $this->db_conn->query($query||
  488.                 die ("Error sending the query '".$query."' to MySQL: ".$this->db_conn->error."\n");
  489.         }
  490.     }
  491.  
  492.     /**
  493.      *  Save random IPs in MySQL.
  494.      *  The parameters are the number of IPs to create and two booleans: if we want an unique index to be created for the IP (default is TRUE) and if we want that the IP is unique (default TRUE)
  495.      *  If the IP is going to be unique the existence of itis verified with a query before inserting a new one.
  496.      *  The id will be autonumeric (1, 2, 3 ....)
  497.      *  @param integer $number 
  498.      *  @param boolean $use_index 
  499.      *  @param boolean $dont_repeat 
  500.      */
  501.     function createIPs($number$use_index TRUE$dont_repeat TRUE)    {
  502.         $id $this->rnd_ips_number 1;   // Autonumeric
  503.  
  504.         // Table creation if it does not exists
  505.         $this->createIPsTable(self::DATA_RNDIPSC_NAME$use_index);
  506.  
  507.         $i 1;
  508.     while ($i <= $number)    {
  509.             $ip $this->getRandomIP();
  510.             // We verify if IP is in the collection only if it is needed
  511.             $insert TRUE;
  512.             if ($dont_repeat{
  513.                 $query "select id from ".self::DATA_RNDIPSC_NAME." where ip=\"".$ip."\"";
  514.                 if ($result $this->db_conn->query($query))   {
  515.                     $result->num_rows &&
  516.                         $insert FALSE;
  517.                 }
  518.                 else    {
  519.                     die ("Error sending the query '".$query."' to MySQL");
  520.                 }
  521.             }
  522.             if ($insert)   {
  523.                 $query "insert into ".self::DATA_RNDIPSC_NAME." (id, ip) values (".$id.", \"".$ip."\")";
  524.                 $this->db_conn->query($query||
  525.                     die ("Error sending the query '".$query."' to MySQL: ".$this->mysrnd_con->error."\n");
  526.                 $id++;
  527.                 $i++;
  528.             }
  529.         }
  530.         // Update IPs number property
  531.         $this->rnd_ips_number $this->recordNumber(self::DATA_RNDIPSC_NAME);
  532.  
  533.     }
  534.  
  535.     /**
  536.      * Returns true if the "Random_IPsList" table has records
  537.      * @returns boolean
  538.      */
  539.     function randomIPs_exists()    {
  540.         return $this->recordNumber(self::RNDIPSC_NAME0;
  541.     }
  542.  
  543.     /**
  544.      *  Helper function to create Domains table in database
  545.      *  @param string $tablename 
  546.      *  @param boolean $useindex    Sets if a unique index for IP name must be created
  547.      *  @access private
  548.      */
  549.     private function createDomainsTable($tablename self::DATA_RNDDOMAINSC_NAME$use_index true{
  550.         // Table creation if it does not exists
  551.         if (!$this->tableExists(self::DATA_RNDDOMAINSC_NAME)) {
  552.             if ($use_index{
  553.                 $query "CREATE TABLE ".self::DATA_RNDDOMAINSC_NAME." (
  554.                 id INT NOT NULL PRIMARY KEY,
  555.                 domain VARCHAR(255),
  556.                 unique index domain_index (domain)
  557.                 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
  558.             }
  559.             else {
  560.                 $query "CREATE TABLE ".self::DATA_RNDDOMAINSC_NAME." (
  561.                 id INT NOT NULL PRIMARY KEY,
  562.                 domain VARCHAR(255)
  563.                 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
  564.             }
  565.             $this->db_conn->query($query||
  566.                 die ("Error sending the query '".$query."' to MySQL: ".$this->db_conn->error."\n");
  567.         }
  568.     }
  569.  
  570.     /**
  571.      *  Save random domains in MySQL.
  572.      *  The parameters are the number of domains to create and two booleans: if we want an unique index to be created for the domain (default is TRUE) and if we want that the domain is unique (default TRUE)
  573.      *  If the domain is going to be unique the existence of itis verified with a query before inserting a new one.
  574.      *  The id will be autonumeric (1, 2, 3 ....)
  575.      *  @param integer $number 
  576.      *  @param boolean $use_index 
  577.      *  @param boolean $dont_repeat 
  578.      */
  579.     function createDomains($number$use_index TRUE$dont_repeat TRUE)    {
  580.     $id $this->rnd_domains_number 1;   // Autonumeric
  581.  
  582.         // Table creation if it does not exists
  583.         $this->createIPsTable(self::DATA_RNDDOMAINSC_NAME$use_index);
  584.  
  585.         $i 1;
  586.         while ($i <= $number)    {
  587.             $domain $this->getRandomDomain();
  588.             // We verify if the domain is in the collection only if it is needed
  589.             $insert TRUE;
  590.             if ($dont_repeat{
  591.                 $query "select id from ".self::DATA_RNDDOMAINSC_NAME." where domain=\"".$domain."\"";
  592.                 if ($result $this->db_conn->query($query))   {
  593.                     $result->num_rows &&
  594.                         $insert FALSE;
  595.                 }
  596.                 else    {
  597.                     die ("Error sending the query '".$query."' to MySQL");
  598.                 }
  599.             }
  600.             if ($insert)   {
  601.                 $query "insert into ".self::DATA_RNDDOMAINSC_NAME." (id, domain) values (".$id.", \"".$domain."\")";
  602.                 $this->db_conn->query($query||
  603.                     die ("Error sending the query '".$query."' to MySQL: ".$this->mysrnd_con->error."\n");
  604.                 $id++;
  605.                 $i++;
  606.             }
  607.         }
  608.         // Update Domains number property
  609.         $this->rnd_domains_number $this->recordNumber(self::DATA_RNDDOMAINSC_NAME);
  610.     }
  611.  
  612.     /**
  613.      * Returns true if the "Random_DomainsList" table has records
  614.      * @returns boolean
  615.      */
  616.     function randomDomains_exists()    {
  617.         return $this->recordNumber(self::RNDDOMAINSC_NAME0;
  618.     }
  619.  
  620.     /**
  621.      *  Helper function to create URIs table in database
  622.      *  @param string $tablename 
  623.      *  @access private
  624.      */
  625.     private function createURIsTable($tablename self::DATA_RNDURISC_NAME{
  626.         // Table creation if it does not exists
  627.         if (!$this->tableExists(self::DATA_RNDURISC_NAME)) {
  628.             $query "CREATE TABLE ".self::DATA_RNDURISC_NAME." (
  629.                 id INT NOT NULL PRIMARY KEY,
  630.                 uri VARCHAR(100)
  631.                 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
  632.             $this->db_conn->query($query||
  633.                 die ("Error sending the query '".$query."' to MySQL: ".$this->db_conn->error."\n");
  634.         }
  635.     }
  636.     /**
  637.      *  Save random URIs in MySQL.
  638.      *  The parameter is the number of URIs to create.
  639.      *  The id will be autonumeric (1, 2, 3 ....)
  640.      *  @param integer $number 
  641.      */
  642.     function createURIs($number)     {
  643.         $id $this->rnd_uris_number 1;   // Autonumeric
  644.  
  645.         // Table creation if it does not exists
  646.         $this->createIPsTable(self::DATA_RNDURISC_NAME);
  647.  
  648.         $i 1;
  649.         while ($i <= $number)   {
  650.             $uri $this->getRandomString(mt_rand(0,100));
  651.             $query "insert into ".self::DATA_RNDURISC_NAME." (id, uri) values (".$id.", \"".$uri."\")";
  652.             $this->db_conn->query($query||
  653.                 die ("Error sending the query '".$query."' to MySQL: ".$this->mysrnd_con->error."\n");
  654.             $id++;
  655.             $i++;
  656.         }
  657.         // Update Domains number property
  658.         $this->rnd_uris_number $this->recordNumber(self::DATA_RNDURISC_NAME);
  659.     }
  660.  
  661.     /**
  662.      * Create in memory tables and loads user, ips and domains data from persitent ones
  663.      */
  664.     function loadDataInRAM()  {
  665.         // Load users
  666.         if ($this->tableExists(self::DATA_RNDUSERSC_NAME)) {
  667.             $this->rnd_users array();
  668.             if ($results $this->getResults("select * from ".self::DATA_RNDUSERSC_NAME))  {
  669.                 while ($user $results->fetch_assoc()) {
  670.                     $this->rnd_users[$user['id']] $user['user'];
  671.                 }
  672.             }
  673.         }
  674.         // Load ips
  675.         if ($this->tableExists(self::DATA_RNDIPSC_NAME)) {
  676.             $this->rnd_ips array();
  677.             if ($results $this->getResults("select * from ".self::DATA_RNDIPSC_NAME))  {
  678.                 while ($ip $results->fetch_assoc()) {
  679.                     $this->rnd_ips[$ip['id']] $ip['ip'];
  680.                 }
  681.             }
  682.         }
  683.         // Load domains
  684.         if ($this->tableExists(self::DATA_RNDDOMAINSC_NAME)) {
  685.             $this->rnd_domains array();
  686.             if ($results $this->getResults("select * from ".self::DATA_RNDDOMAINSC_NAME))  {
  687.                 while ($domain $results->fetch_assoc()) {
  688.                     $this->rnd_domains[$domain['id']] $domain['domain'];
  689.                 }
  690.             }
  691.         }
  692.         // Load URIs
  693.         if ($this->tableExists(self::DATA_RNDURISC_NAME)) {
  694.             $this->rnd_uris array();
  695.             if ($results $this->getResults("select * from ".self::DATA_RNDURISC_NAME))  {
  696.                 while ($uri $results->fetch_assoc()) {
  697.                     $this->rnd_uris[$uri['id']] $uri['uri'];
  698.                 }
  699.             }
  700.         }
  701.     }
  702.  
  703.     /**
  704.      *  Returns a random IP from the generated collection
  705.      *  @returns string
  706.      */
  707.     function searchIP()    {
  708.         $position mt_rand(1$this->rnd_ips_number);
  709.         return $this->rnd_ips[$position];
  710.     }
  711.  
  712.     /**
  713.      *  Returns a random user from the generated collection
  714.      *  @return string 
  715.      */
  716.     function searchUser()    {
  717.     $position mt_rand(1$this->rnd_users_number);
  718.         return $this->rnd_users[$position];
  719.     }
  720.  
  721.     /**
  722.      * Export user table in CSV format saving it in path passed as parameter (Users.csv under CSV directory by default)
  723.      * @param string $filename 
  724.      * @access public
  725.      */
  726.     function exportUsersToCSV($filename "CSV/Users.csv"{
  727.         if (dirname($filename== "CSV" and !file_exists("CSV"))        {
  728.             mkdir("CSV");
  729.         }
  730.  
  731.         ($fh fopen($filename"a")) || die("Not possible to open ".$filename." file");
  732.         fwrite($fh"id,user\n"|| die("Not possible to write in  ".$filename." file");
  733.         for ($i 1$i <= $this->rnd_users_number$i++)  {
  734.             fputcsv($fharray($i,$this->rnd_users[$i])) || die("Not possible to write in  ".$filename." file");
  735.         }
  736.         fclose($fh);
  737.     }
  738.  
  739.     /**
  740.      * Import users data in a CSV file to a MySQL table (if the table already exist it will be deleted)
  741.      * The MySQL user must have the global privilege FILE!
  742.      * @param string $filename 
  743.      * @access public
  744.      */
  745.     function importUsersFromCSV($filename "CSV/Users.csv")  {
  746.         if ($filename == "CSV/Users.csv")  {
  747.             $filename getcwd()."/".$filename;
  748.             }
  749.         $this->dropTable(self::DATA_RNDUSERSC_NAME);
  750.         $this->createUsersTable();
  751.         $this->sendQuery("load data infile \"".$filename."\" into table ".self::DATA_RNDUSERSC_NAME." fields terminated by ',' ignore 1 lines");
  752.     }
  753.  
  754.     /**
  755.      * Export ip's table in CSV format saving it in path passed as parameter (IPs.csv under CSV directory by default)
  756.      * @param string $filename 
  757.      * @access public
  758.      */
  759.     function exportIPsToCSV($filename "CSV/IPs.csv"{
  760.         if (dirname($filename== "CSV" and !file_exists("CSV"))        {
  761.             mkdir("CSV");
  762.         }
  763.  
  764.         ($fh fopen($filename"a")) || die("Not possible to open ".$filename." file");
  765.         fwrite($fh"id,ip\n");
  766.         for ($i 1$i <= $this->rnd_ips_number$i++)  {
  767.             fputcsv($fharray($i,$this->rnd_ips[$i])) || die("Not possible to write in  ".$filename." file");
  768.         }
  769.         fclose($fh);
  770.     }
  771.  
  772.     /**
  773.      * Import IPs data in a CSV file to a MySQL table (if the table already exist it will be deleted)
  774.      * The MySQL user must have the global privilege FILE!
  775.      * @param string $filename 
  776.      * @access public
  777.      */
  778.     function importIPsFromCSV($filename "CSV/IPs.csv")  {
  779.         if ($filename == "CSV/IPs.csv")  {
  780.             $filename getcwd()."/".$filename;
  781.             }
  782.         $this->dropTable(self::DATA_RNDIPSC_NAME);
  783.         $this->createIPsTable();
  784.         $this->sendQuery("load data infile \"".$filename."\" into table ".self::DATA_RNDIPSC_NAME." fields terminated by ',' ignore 1 lines");
  785.     }
  786.  
  787.     /**
  788.      * Export domains table in CSV format saving it in path passed as parameter (Domains.csv under CSV directory by default)
  789.      * @param string $filename 
  790.      * @access public
  791.      */
  792.     function exportDomainsToCSV($filename "CSV/Domains.csv"{
  793.         if (dirname($filename== "CSV" and !file_exists("CSV"))        {
  794.             mkdir("CSV");
  795.         }
  796.  
  797.         ($fh fopen($filename"a")) || die("Not possible to open ".$filename." file");
  798.         fwrite($fh"id,domain\n");
  799.         for ($i 1$i <= $this->rnd_domains_number$i++)  {
  800.             fputcsv($fharray($i,$this->rnd_domains[$i])) || die("Not possible to write in  ".$filename." file");
  801.         }
  802.         fclose($fh);
  803.     }
  804.  
  805.     /**
  806.      * Import Domains data in a CSV file to a MySQL table (if the table already exist it will be deleted)
  807.      * The MySQL user must have the global privilege FILE!
  808.      * @param string $filename 
  809.      * @access public
  810.      */
  811.     function importDomainsFromCSV($filename "CSV/Domains.csv")  {
  812.         if ($filename == "CSV/Domains.csv")  {
  813.             $filename getcwd()."/".$filename;
  814.             }
  815.         $this->dropTable(self::DATA_RNDDOMAINSC_NAME);
  816.         $this->createDomainsTable();
  817.         $this->sendQuery("load data infile \"".$filename."\" into table ".self::DATA_RNDDOMAINSC_NAME." fields terminated by ',' ignore 1 lines");
  818.     }
  819.  
  820.     /**
  821.      * Export URIs table in CSV format saving it in path passed as parameter (URIs.csv under CSV directory by default)
  822.      * @param string $filename 
  823.      * @access public
  824.      */
  825.     function exportURIsToCSV($filename "CSV/URIs.csv"{
  826.         if (dirname($filename== "CSV" and !file_exists("CSV"))        {
  827.             mkdir("CSV");
  828.         }
  829.  
  830.         ($fh fopen($filename"a")) || die("Not possible to open ".$filename." file");
  831.         fwrite($fh"id,uri\n");
  832.         for ($i 1$i <= $this->rnd_uris_number$i++)  {
  833.             fputcsv($fharray($i,$this->rnd_uris[$i])) || die("Not possible to write in  ".$filename." file");
  834.         }
  835.         fclose($fh);
  836.     }
  837.  
  838.     /**
  839.      * Import URIs data in a CSV file to a MySQL table (if the table already exist it will be deleted)
  840.      * The MySQL user must have the global privilege FILE!
  841.      * @param string $filename 
  842.      * @access public
  843.      */
  844.     function importURIsFromCSV($filename "CSV/URIs.csv")  {
  845.         if ($filename == "CSV/URIs.csv")  {
  846.             $filename getcwd()."/".$filename;
  847.             }
  848.         $this->dropTable(self::DATA_RNDURISC_NAME);
  849.         $this->createURIsTable();
  850.         $this->sendQuery("load data infile \"".$filename."\" into table ".self::DATA_RNDURISC_NAME." fields terminated by ',' ignore 1 lines");
  851.     }
  852.     /**
  853.      * Writes the first line (title) of a CSV file for non ftp log entry (NonFTP_Access_log.csv under CSV directory by default). If it exist it will be truncated. Returns the file handle
  854.      * @param string filename
  855.      * @returns filehandle
  856.      * @access public
  857.      */
  858.     function createRandomNonFTPLogEntryCSV($filename "CSV/NonFTP_Access_log.csv")     {
  859.         if (dirname($filename== "CSV" and !file_exists("CSV"))        {
  860.             mkdir("CSV");
  861.         }
  862.         ($fh fopen($filename"w")) || die("Not possible to open ".$filename." file");
  863.         fwrite($fh"clientip,user,datetime,method,protocol,domain,uri,return_code,size\n");
  864.         return $fh;
  865.     }
  866.  
  867.     /**
  868.      * Adds the non ftp log entry passed as parameter to a CSV file (NonFTP_Access_log.csv under CSV directory by default).
  869.      * A third optional parameter is the file handle (to not open and close the file in a for loop which calls this function)
  870.      * @param array $log_entry log entry as returned by {@link getRandomNonFTPLogEntry}
  871.      * @param string $filename 
  872.      * @param filehandle $fh 
  873.      * @access public
  874.      */
  875.     function saveRandomNonFTPLogEntryToCSV($log_entry$filename "CSV/NonFTP_Access_log.csv"$fh NULL)  {
  876.         if (dirname($filename== "CSV" and !file_exists("CSV"))        {
  877.             mkdir("CSV");
  878.         }
  879.  
  880.         if (is_null($fh))       {
  881.             // A file handle is not given
  882.             if (!file_exists($filename))    {
  883.                 $fh $this->createRandomNonFTPLogEntryCSV($filename);
  884.             }
  885.             else {
  886.                 $fh fopen($filename"a");
  887.             }
  888.         }
  889.         
  890.         $log_entry['datetime'strftime("%Y-%m-%d %H:%M:%S"$log_entry['datetime']);
  891.         fprintf($fh"%s\n"implode(","$log_entry));
  892.         if (is_null($fh))       {
  893.             fclose($fh);
  894.         }
  895.  
  896.     }
  897.  
  898.     /**
  899.      *  Returns a random HTTP method from the generated collection
  900.      *  @returns string
  901.      */
  902.     function searchHTTPMethod()    {
  903.     return $this->getRandomHTTPMethod();
  904.     }
  905.  
  906.     /**
  907.      *  Returns a random FTP method from the generated collection
  908.      *  @returns string
  909.      */
  910.     function searchFTPMethod()    {
  911.     return $this->getRandomFTPMethod();
  912.     }
  913.  
  914.     /**
  915.      *  Returns a random domain
  916.      *  @returns string
  917.      */
  918.     function searchDomain({
  919.     $position mt_rand(1$this->rnd_domains_number);
  920.         return $this->rnd_domains[$position];
  921.     }
  922.  
  923.     /**
  924.      *  Returns a random URI
  925.      *  @returns string
  926.      */
  927.     function searchURI()    {
  928.         $position mt_rand(1$this->rnd_uris_number);
  929.         return $this->rnd_uris[$position];
  930.     }
  931.  
  932.     /**
  933.      *  Returns a random size
  934.      *  @returns integer
  935.      */
  936.     function searchSize()    {
  937.     return $this->getRandomSize();
  938.     }
  939.  
  940.     /**
  941.      *  Returns a random protocol
  942.      *  @returns string
  943.      */
  944.     function searchProtocol()    {
  945.     return $this->getRandomProtocol();
  946.     }
  947.  
  948.     /**
  949.      *  Returns a random return code
  950.      *  @returns integer
  951.      */
  952.     function searchReturnCode()    {
  953.     return $this->getRandomRetourCode();
  954.     }
  955.  
  956.     /**
  957.      *  Return a random log entry for non FTP access (http and tunnel)
  958.      *  It has two optional arguments, initial and final timestamps, if we want to get a random time in log entry created
  959.      *  @param integer $initial_timestamp 
  960.      *  @param integer $final_timestamp 
  961.      *  @returns array
  962.      */
  963.     function getRandomNonFTPLogEntry()    {
  964.         if (func_num_args(== 2)    {
  965.                 $initial_timestamp func_get_arg(0);
  966.                 $final_timestamp =  func_get_arg(1);
  967.                 $ts mt_rand($initial_timestamp$final_timestamp);
  968.         }
  969.         elseif (func_num_args(!= 0)    {
  970.                 $arguments func_get_args();
  971.                 die("Incorrect arguments number in getRrandomSORLogEntry function: ".implode(" "$arguments)."\n");
  972.         }
  973.         else {
  974.                 $ts time();
  975.         }
  976.  
  977.         $document array(
  978.                 'clientip' => $this->searchIP(),
  979.                 'user' => $this->searchUser(),
  980.                 'datetime' => $ts,
  981.                 'method' => $this->searchHTTPMethod(),
  982.                 'protocol' => $this->searchProtocol(),
  983.                 'domain' => $this->searchDomain(),
  984.                 'uri' => $this->searchURI(),
  985.                 'return_code' => $this->searchReturnCode(),
  986.                 'size' => $this->searchSize()    // Size is recorded in the database as string
  987.         );
  988.  
  989.         return $document;
  990.     }
  991.  
  992.     /**
  993.      *  Update Users monthly report
  994.      *  This function is private and is meant to be used each time an access log is processed to have real time statistics (only by month)
  995.      *  @param string $user user name
  996.      *  @param timestamp $timestamp date & time of access
  997.      *  @param integer $volume size of data transferred
  998.      *  @access private
  999.      */
  1000.     private function saveUserReport($user$timestamp$volume)  {
  1001.  
  1002.         $table_name self::USERS_REPORT_PREFIX.strftime("%Y%m"$timestamp);
  1003.         // Table creation if it does not exists
  1004.         if (!$this->tableExists($table_name)) {
  1005.             $query "CREATE TABLE ".$table_name." (
  1006.                 user CHAR(7) NOT NULL,
  1007.                 nb INTEGER UNSIGNED NOT NULL,
  1008.                 volume INTEGER UNSIGNED NOT NULL,
  1009.                 unique index user_index (user)
  1010.                 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
  1011.  
  1012.             $this->db_conn->query($query||
  1013.                 die ("Error sending the query '".$query."' to MySQL: ".$this->db_conn->error."\n");
  1014.  
  1015.             // Insertion of a new user entry
  1016.             $query_insert "insert into ".$table_name." (user, nb, volume) values (\"".$user."\", 1, ".$volume.")";
  1017.             $this->db_conn->query($query_insert||
  1018.                 die ("Error sending the query '".$query_insert."' to MySQL: ".$this->db_conn->error."\n");
  1019.         }
  1020.         else {
  1021.             $query "select * from ".$table_name." where user=\"".$user."\"";
  1022.             if ($result $this->db_conn->query($query))   {
  1023.                 if ($result->num_rows 0)  {
  1024.                     // There is a user entry for this month
  1025.                     $row $result->fetch_assoc();
  1026.                     $new_nb $row['nb'1;
  1027.                     $new_volume $row['volume'$volume;
  1028.                     $query_update "update ".$table_name." set nb=".$new_nb.", volume=".$new_volume." where user=\"".$user."\"";
  1029.                     $this->db_conn->query($query_update||
  1030.                         die ("Error sending the query '".$query_update."' to MySQL: ".$this->db_conn->error."\n");
  1031.                 }
  1032.                 else  {
  1033.                     // Insertion of a new user entry
  1034.                     $query_insert "insert into ".$table_name." (user, nb, volume) values (\"".$user."\", 1, ".$volume.")";
  1035.                     $this->db_conn->query($query_insert||
  1036.                         die ("Error sending the query '".$query_insert."' to MySQL: ".$this->db_conn->error."\n");
  1037.                 }
  1038.             }
  1039.             else    {
  1040.                 die ("Error sending the query '".$query."' to MySQL");
  1041.             }
  1042.         }
  1043.     }
  1044.  
  1045.     /**
  1046.      *  Update Domains monthly report
  1047.      *  This function is private and is meant to be used each time an access log is processed to have real time statistics (only by month)
  1048.      *  @param string $domain domain name
  1049.      *  @param timestamp $timestamp date & time of access
  1050.      *  @param integer $volume size of data transferred
  1051.      *  @access private
  1052.      */
  1053.     private function saveDomainReport($domain$timestamp$volume)  {
  1054.  
  1055.         $table_name self::DOMAINS_REPORT_PREFIX.strftime("%Y%m"$timestamp);
  1056.         // Table creation if it does not exists
  1057.         if (!$this->tableExists($table_name)) {
  1058.             $query "CREATE TABLE ".$table_name." (
  1059.                 domain CHAR(255) NOT NULL,
  1060.                 nb INTEGER UNSIGNED NOT NULL,
  1061.                 volume INTEGER UNSIGNED NOT NULL,
  1062.                 unique index domain_index (domain)
  1063.                 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
  1064.  
  1065.             $this->db_conn->query($query||
  1066.                 die ("Error sending the query '".$query."' to MySQL: ".$this->db_conn->error."\n");
  1067.  
  1068.             // Insertion of a new domain entry
  1069.             $query_insert "insert into ".$table_name." (domain, nb, volume) values (\"".$domain."\", 1, ".$volume.")";
  1070.             $this->db_conn->query($query_insert||
  1071.                 die ("Error sending the query '".$query_insert."' to MySQL: ".$this->db_conn->error."\n");
  1072.         }
  1073.         else {
  1074.             $query "select * from ".$table_name." where domain=\"".$domain."\"";
  1075.             if ($result $this->db_conn->query($query))   {
  1076.                 if ($result->num_rows 0)  {
  1077.                     // There is a domain entry for this month
  1078.                     $row $result->fetch_assoc();
  1079.                     $new_nb $row['nb'1;
  1080.                     $new_volume $row['volume'$volume;
  1081.                     $query_update "update ".$table_name." set nb=".$new_nb.", volume=".$new_volume." where domain=\"".$domain."\"";
  1082.                     $this->db_conn->query($query_update||
  1083.                         die ("Error sending the query '".$query_update."' to MySQL: ".$this->db_conn->error."\n");
  1084.                 }
  1085.                 else  {
  1086.                     // Insertion of a new domain entry
  1087.                     $query_insert "insert into ".$table_name." (domain, nb, volume) values (\"".$domain."\", 1, ".$volume.")";
  1088.                     $this->db_conn->query($query_insert||
  1089.                         die ("Error sending the query '".$query_insert."' to MySQL: ".$this->db_conn->error."\n");
  1090.                 }
  1091.             }
  1092.             else    {
  1093.                 die ("Error sending the query '".$query."' to MySQL");
  1094.             }
  1095.         }
  1096.     }
  1097.     
  1098.     /**
  1099.      *  Helper function to create Domains table in database
  1100.      *  @param string $tablename 
  1101.      *  @param boolean $useindex    Sets if a unique index for IP name must be created
  1102.      *  @access private
  1103.      */
  1104.      
  1105.     /**
  1106.      *  Receives a log entry and saves the data and, optionally, monthly and daily precalculated values in database.
  1107.      *  By default the reports are created. If the second argument is FALSE they will not be generated.
  1108.      *  A id field autonumeric will be created.
  1109.      *
  1110.      *  @param array $log_entry log entry as returned by {@link getRandomNonFTPLogEntry}
  1111.      *  @param boolean $create_reports 
  1112.      */
  1113.     function saveRandomNonFTPLogEntry($log_entry$create_reports=TRUE)    {
  1114.  
  1115.         // Table creation if it does not exists
  1116.         if (!$this->tableExists(self::NONFTPLOG_NAME)) {
  1117.             $query "CREATE TABLE ".self::NONFTPLOG_NAME." (
  1118.                 `id` int(11) NOT NULL AUTO_INCREMENT,
  1119.                 `clientip` varchar(15) NOT NULL,
  1120.                 `user` char(7) NOT NULL,
  1121.                 `datetime` datetime NOT NULL,
  1122.                 `method` varchar(10) NOT NULL,
  1123.                 `protocol` varchar(10) NOT NULL,
  1124.                 `domain` varchar(255) NOT NULL,
  1125.                 `uri` varchar(100) NOT NULL,
  1126.                 `return_code` smallint(5) unsigned NOT NULL,
  1127.                 `size` int(10) unsigned NOT NULL,
  1128.                 PRIMARY KEY (`id`),
  1129.                 INDEX `domain` (`domain`),
  1130.                 INDEX `datetime` (`datetime`)
  1131.                 ) ENGINE=MyISAM DEFAULT CHARSET=utf8";
  1132.  
  1133.             $this->db_conn->query($query||
  1134.                 die ("Error sending the query '".$query."' to MySQL: ".$this->db_conn->error."\n");
  1135.         }
  1136.  
  1137.         $query "insert into ".self::NONFTPLOG_NAME." (clientip, user, datetime, method, protocol, domain, uri, return_code, size) values (".
  1138.                 "\"".$log_entry['clientip']."\", \"".$log_entry['user']."\", \"".date("Y:m:d H:i:s"$log_entry['datetime'])."\", \"".$log_entry['method']."\", ".
  1139.                 "\"".$log_entry['protocol']."\", \"".$log_entry['domain']."\", \"".$log_entry['uri']."\", ".$log_entry['return_code'].", ".$log_entry['size'].")";
  1140.         $this->db_conn->query($query||
  1141.             die ("Error sending the query '".$query."' to MySQL: ".$this->mysrnd_con->error."\n");
  1142.  
  1143.         # Monthly reports data update
  1144.         if ($create_reports)    {
  1145.             $timestamp $log_entry["datetime"];
  1146.             $this->saveUserReport($log_entry["user"]$timestamp$log_entry['size']);
  1147.             $this->saveDomainReport($log_entry["domain"]$timestamp$log_entry['size']);
  1148.             }
  1149.  
  1150.     }
  1151.  
  1152.     /**
  1153.      *  Gets a line with a log entry in CSV format and saves the data and, optionally, monthly and daily precalculated values in database.
  1154.      *  By default the reports are created. If the second argument is FALSE they will not be generated.
  1155.      *  A id field autonumeric will be created.
  1156.      *
  1157.      *  @param string $line Line in CSV format (clientip, user, datetime, method, protocol, domain, uri, return_code, size)
  1158.      *  @param boolean $create_reports 
  1159.      */
  1160.     function saveRandomNonFTPLogEntry_fromCSV($line$create_reports=TRUE{
  1161.         (list($clientip$user$datetime$method$protocol$domain$uri$return_code$sizeexplode(","$line)) || die("Not possible to read from ".$filename." file");
  1162.         $logentry array(
  1163.             'clientip' => $clientip,
  1164.             'user' => $user,
  1165.             'datetime' => $datetime,
  1166.             'method' => $method,
  1167.             'protocol' => $protocol,
  1168.             'domain' => $domain,
  1169.             'uri' => $uri,
  1170.             'return_code' => $return_code,
  1171.             'size' => $size
  1172.             );
  1173.         $this->saveRandomNonFTPLogEntry($logentry$create_reports);
  1174.     }
  1175.      
  1176.     /**
  1177.      *  Return a random log entry for FTP access. It is very similar to HTTP and tunnel access but with less fields (there is no protocol and return code)
  1178.      *  It has two optional arguments, initial and final timestamps, if we want to get a random time in log entry created
  1179.      *  @param integer $initial_timestamp 
  1180.      *  @param integer $final_timestamp 
  1181.      *  @returns array
  1182.      */
  1183.     function getRandomFTPLogEntry()    {
  1184.         if (func_num_args(== 2)    {
  1185.                 $initial_timestamp func_get_arg(0);
  1186.                 $final_timestamp =  func_get_arg(1);
  1187.                 $ts mt_rand($initial_timestamp$final_timestamp);
  1188.         }
  1189.         elseif (func_num_args(!= 0)    {
  1190.                 $arguments func_get_args();
  1191.                 die("Incorrect arguments number in getRrandomSORLogEntry function: ".implode(" "$arguments)."\n");
  1192.         }
  1193.         else {
  1194.                 $ts time();
  1195.         }
  1196.  
  1197.         $document array(
  1198.                 'clientip' => $this->searchIP(),
  1199.                 'user' => $this->searchUser(),
  1200.                 'datetime' => $ts,
  1201.                 'method' => $this->searchFTPMethod(),
  1202.                 'domain' => $this->searchDomain(),
  1203.                 'uri' => $this->searchURI(),
  1204.                 'size' => $this->searchSize()    // Size is recorded in the database as string
  1205.         );
  1206.  
  1207.         return $document;
  1208.     }
  1209.  
  1210.     /**
  1211.      *  Receives a FTP log entry and saves the data and, optionally, monthly and daily precalculated values in database.
  1212.      *  By default the reports are created. If the second argument is FALSE they will not be generated
  1213.      *  A id field autonumeric will be created.
  1214.      *
  1215.      *  @param array $log_entry log entry as returned by {@link getRandomNonFTPLogEntry}
  1216.      *  @param boolean $create_reports 
  1217.      */
  1218.     function saveRandomFTPLogEntry($log_entry$create_reports=TRUE)    {
  1219.  
  1220.         // Table creation if it does not exists
  1221.         if (!$this->tableExists(self::FTPLOG_NAME)) {
  1222.             $query "CREATE TABLE ".self::FTPLOG_NAME." (
  1223.                 id int not null auto_increment,
  1224.                 clientip VARCHAR(15) NOT NULL,
  1225.                 user CHAR(7) NOT NULL,
  1226.                 datetime DATETIME NOT NULL,
  1227.                 method VARCHAR(10) NOT NULL,
  1228.                 domain VARCHAR(255) NOT NULL,
  1229.                 uri VARCHAR(100) NOT NULL,
  1230.                 size INTEGER UNSIGNED NOT NULL
  1231.                 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
  1232.  
  1233.             $this->db_conn->query($query||
  1234.                 die ("Error sending the query '".$query."' to MySQL: ".$this->db_conn->error."\n");
  1235.         }
  1236.  
  1237.         $query "insert into ".self::FTPLOG_NAME." (clientip, user, datetime, method, domain, uri, size) values (".
  1238.                 "\"".$log_entry['clientip']."\", \"".$log_entry['user']."\", \"".date("Y-m-d H:i:s"$log_entry['datetime'])."\", \"".$log_entry['method']."\", ".
  1239.                 "\"".$log_entry['domain']."\", \"".$log_entry['uri']."\", ".$log_entry['size'].")";
  1240.         $this->db_conn->query($query||
  1241.             die ("Error sending the query '".$query."' to MySQL: ".$this->mysrnd_con->error."\n");
  1242.  
  1243.         # Monthly reports data update
  1244.         if ($create_reports)    {
  1245.             $timestamp $log_entry["datetime"];
  1246.             $this->saveUserReport($log_entry["user"]$timestamp$log_entry['size']);
  1247.             $this->saveDomainReport($log_entry["domain"]$timestamp$log_entry['size']);
  1248.             }
  1249.  
  1250.     }
  1251.  
  1252. }
  1253.  
  1254.  
  1255. ?>

Documentation generated on Fri, 12 Apr 2013 12:02:20 +0200 by phpDocumentor 1.4.4