//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
/**
 * Tests database connection.
 *
 * @package local_vmoodle
 * @category local
 * @author Moheissen Fabien (fabien.moheissen@gmail.com)
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL
 */
// Loading $CFG configuration.
require '../../../config.php';
require_once $CFG->dirroot . '/local/vmoodle/bootlib.php';
// Retrieve parameters for database connection test.
$database = new stdClass();
$database->vdbtype = required_param('vdbtype', PARAM_TEXT);
$database->vdbhost = required_param('vdbhost', PARAM_TEXT);
$database->vdblogin = required_param('vdblogin', PARAM_TEXT);
$database->vdbpass = required_param('vdbpass', PARAM_TEXT);
// Works, but need to improve the style...
if (vmoodle_make_connection($database, false)) {
    echo get_string('connectionok', 'local_vmoodle');
} else {
    echo get_string('badconnection', 'local_vmoodle');
}
/**
 * load a bulk template in databse
 * @param object $vmoodle
 * @param string $bulfile a bulk file of queries to process on the database
 * @param handle $cnx
 * @param array $vars an array of vars to inject in the bulk file before processing
 */
function vmoodle_load_db_template(&$vmoodle, $bulkfile, $cnx = null, $vars = null, $filter = null)
{
    global $CFG;
    $local_cnx = 0;
    if (is_null($cnx) || $vmoodle->vdbtype == 'postgres') {
        // Postgress MUST make a new connection to ensure db is bound to handle.
        $cnx = vmoodle_make_connection($vmoodle, true);
        $local_cnx = 1;
    }
    // Get dump file.
    if (file_exists($bulkfile)) {
        $sql = file($bulkfile);
        // converts into an array of text lines
        $dumpfile = implode("", $sql);
        if ($filter) {
            foreach ($filter as $from => $to) {
                $dumpfile = mb_ereg_replace(preg_quote($from), $to, $dumpfile);
            }
        }
        // Insert any external vars.
        if (!empty($vars)) {
            foreach ($vars as $key => $value) {
                $dumpfile = str_replace("<%%{$key}%%>", $value, $dumpfile);
            }
        }
        $sql = explode("\n", $dumpfile);
        // Cleanup unuseful things.
        if ($vmoodle->vdbtype == 'mysql') {
            $sql = preg_replace("/^--.*/", "", $sql);
            $sql = preg_replace("/^\\/\\*.*/", "", $sql);
        }
        $dumpfile = implode("\n", $sql);
    } else {
        echo "vmoodle_load_db_template : Bulk file not found";
        return false;
    }
    /// split into single queries
    $dumpfile = str_replace("\r\n", "\n", $dumpfile);
    // Translates to Unix LF.
    $queries = preg_split("/;\n/", $dumpfile);
    /// feed queries in database
    $i = 0;
    $j = 0;
    if (!empty($queries)) {
        foreach ($queries as $query) {
            $query = trim($query);
            // Get rid of trailing spaces and returns
            if ($query == '') {
                continue;
                // Avoid empty queries.
            }
            $query = mb_convert_encoding($query, 'iso-8859-1', 'auto');
            if (!($res = vmoodle_execute_query($vmoodle, $query, $cnx))) {
                echo "<hr/>load error on <br/>" . $cnx . "<hr/>";
                $j++;
            } else {
                $i++;
            }
        }
    }
    echo "loaded : {$i} queries succeeded, {$j} queries failed<br/>";
    if ($local_cnx) {
        vmoodle_close_connection($vmoodle, $cnx);
    }
    return false;
}
 /**
  * Test connection validation.
  * @see lib/moodleform#validation($data, $files)
  */
 function validation($data, $files = null)
 {
     global $CFG, $DB;
     // Empty array.
     $errors = parent::validation($data, null);
     // Checks database connection again, after Javascript test.
     $database = new \stdClass();
     $database->vdbtype = $data['vdbtype'];
     $database->vdbhost = $data['vdbhost'];
     $database->vdblogin = $data['vdblogin'];
     $database->vdbpass = $data['vdbpass'];
     if (!vmoodle_make_connection($database, false)) {
         $errors['vdbhost'] = get_string('badconnection', 'local_vmoodle');
         $errors['vdblogin'] = get_string('badconnection', 'local_vmoodle');
         $errors['vdbpass'] = get_string('badconnection', 'local_vmoodle');
     }
     // Checks if database's name doesn't finish with '_'.
     if ($data['vdbname'][strlen($data['vdbname']) - 1] == '_') {
         $errors['vdbname'] = get_string('baddatabasenamecoherence', 'local_vmoodle');
     }
     // Checks if database's name doesn't finish with '_'.
     if (strstr($data['vdbname'], '-') !== false) {
         $errors['vdbname'] = get_string('badnohyphensindbname', 'local_vmoodle');
     }
     // Checks if table's prefix doesn't begin with restricted values (which can evolve).
     $restrictedvalues = array('vmoodle_');
     foreach ($restrictedvalues as $restrictedvalue) {
         if ($data['vdbprefix'] == $restrictedvalue) {
             $errors['vdbprefix'] = get_string('baddatabaseprefixvalue', 'local_vmoodle');
         }
     }
     // ATTENTION Checks if user has entered a datapath with only one backslash between each folder
     // and/or file.
     if (isset($CFG->ostype) && $CFG->ostype == 'WINDOWS' && preg_match('#\\\\{3,}#', $data['vdatapath']) > 0) {
         $errors['vdatapath'] = get_string('badmoodledatapathbackslash', 'local_vmoodle');
         return $errors;
     }
     // Test of values which have to be well-formed and can not be modified after.
     if ($this->isInAddMode()) {
         // Checks 'shortname', which must have no spaces.
         $shortname = $data['shortname'];
         if (strstr($shortname, ' ')) {
             $errors['shortname'] = get_string('badshortname', 'local_vmoodle');
         }
         // Checks 'vhostname', if not already used.
         if ($this->isEqualToAnotherVhostname($data['vhostname'])) {
             // Check if the vhostname is deleted.
             $sql = "\n                    SELECT\n                        m.deleted\n                    FROM\n                        {local_vmoodle} b,\n                        {mnet_host} m\n                    WHERE\n                        b.vhostname = ?\n                    AND\n                        b.vhostname = m.wwwroot\n                ";
             $resultsqlrequest = $DB->get_record_sql($sql, array($data['vhostname']));
             if (!empty($resultsqlrequest)) {
                 if ($resultsqlrequest->deleted == 0) {
                     $errors['vhostname'] = get_string('badhostnamealreadyused', 'local_vmoodle');
                 } else {
                     //Id the plateforme is deleted and the user want to reactivate the vhostname.
                     if ($data['vtemplate'] == 0) {
                         $sql = "\n                                SELECT\n                                    id,\n                                    vdatapath,\n                                    vdbname\n                                FROM\n                                    {local_vmoodle}\n                                WHERE\n                                    vhostname = ?\n                            ";
                         $resultsqlrequest = $DB->get_record_sql($sql, array($data['vhostname']));
                         // Checks if datapath and vdbname of vhostname are the same on the form.
                         if ($resultsqlrequest->vdatapath != stripslashes($data['vdatapath']) && $resultsqlrequest->vdbname != $data['vdbname']) {
                             $errors['vdatapath'] = get_string('errorreactivetemplate', 'local_vmoodle');
                             $errors['vdbname'] = get_string('errorreactivetemplate', 'local_vmoodle');
                         }
                     }
                 }
             }
         }
         // Checks 'vhostname' consistency, with a regular expression.
         $vhostname = $data['vhostname'];
         if (!preg_match('/^http(s)?:\\/\\//', $vhostname)) {
             $errors['vhostname'] = get_string('badvhostname', 'local_vmoodle');
         }
         // Checks 'vdatapath', if not already used.
         if ($this->isEqualToAnotherDataRoot($data['vdatapath'])) {
             if ($data['vtemplate'] === 0) {
             } else {
                 $errors['vdatapath'] = get_string('badmoodledatapathalreadyused', 'local_vmoodle');
             }
         }
         // Checks 'vdbname', if not already used.
         if ($this->isEqualToAnotherDatabaseName($data['vdbname']) && $data['vtemplate'] != 0) {
             $errors['vdbname'] = get_string('baddatabasenamealreadyused', 'local_vmoodle');
         }
     }
     return $errors;
 }
/**
 * This is a boot lib that is required BEFORE we can have access
 * to $CFG defines.
 */
function vmoodle_boot_configuration()
{
    global $CFG;
    /*
     * vconfig provides an bypassed configuration using vmoodle host definition
     * from the vmoodle master instance
     *
     */
    $CFG->mainwwwroot = $CFG->wwwroot;
    if ($CFG->vmoodleroot != $CFG->wwwroot) {
        if ($CFG->vmasterdbtype == 'mysql') {
            $vmaster = new StdClass();
            $vmaster->vdbtype = $CFG->vmasterdbtype;
            $vmaster->vdbhost = $CFG->vmasterdbhost;
            $vmaster->vdblogin = $CFG->vmasterdblogin;
            $vmaster->vdbpass = $CFG->vmasterdbpass;
            if (!($side_cnx = vmoodle_make_connection($vmaster))) {
                return;
                // If vmoodle cnx not valid.
            }
            if (!mysql_select_db($CFG->vmasterdbname, $side_cnx)) {
                return;
                // If vmoodle cnx not valid.
            }
            $sql = "\n               SELECT\n               *\n               FROM\n                  {$CFG->vmasterprefix}local_vmoodle\n               WHERE\n                  vhostname = '{$CFG->vmoodleroot}'\n            ";
            $res = mysql_query($sql, $side_cnx);
            if ($res) {
                if (mysql_num_rows($res)) {
                    $vmoodle = mysql_fetch_object($res);
                    $CFG->dbtype = $vmoodle->vdbtype;
                    $CFG->dbhost = $vmoodle->vdbhost;
                    $CFG->dbname = $vmoodle->vdbname;
                    $CFG->dbuser = $vmoodle->vdblogin;
                    $CFG->dbpass = $vmoodle->vdbpass;
                    $CFG->dboptions['dbpersist'] = $vmoodle->vdbpersist;
                    $CFG->prefix = $vmoodle->vdbprefix;
                    $CFG->wwwroot = $CFG->vmoodleroot;
                    $CFG->dataroot = $vmoodle->vdatapath;
                } else {
                    die("VMoodling : No configuration for this host : {$CFG->vmoodleroot}. May be faked.");
                }
            } else {
                die("VMoodling : Could not fetch virtual moodle configuration");
            }
        } elseif ($CFG->vmasterdbtype == 'mysqli') {
            $vmaster = new StdClass();
            $vmaster->vdbtype = $CFG->vmasterdbtype;
            $vmaster->vdbhost = $CFG->vmasterdbhost;
            $vmaster->vdblogin = $CFG->vmasterdblogin;
            $vmaster->vdbpass = $CFG->vmasterdbpass;
            $vmaster->vdbname = $CFG->vmasterdbname;
            if (!($side_cnx = vmoodle_make_connection($vmaster, true))) {
                // If vmoodle cnx not valid.
                die('VMoodle master server unreachable');
            }
            $sql = "\n               SELECT\n               *\n               FROM\n                  {$CFG->vmasterprefix}local_vmoodle\n               WHERE\n                  vhostname = '{$CFG->vmoodleroot}'\n            ";
            $res = mysqli_query($side_cnx, $sql);
            if ($res) {
                if (mysqli_num_rows($res)) {
                    $vmoodle = mysqli_fetch_object($res);
                    $CFG->dbtype = $vmoodle->vdbtype;
                    $CFG->dbhost = $vmoodle->vdbhost;
                    $CFG->dbname = $vmoodle->vdbname;
                    $CFG->dbuser = $vmoodle->vdblogin;
                    $CFG->dbpass = $vmoodle->vdbpass;
                    $CFG->dboptions['dbpersist'] = $vmoodle->vdbpersist;
                    $CFG->prefix = $vmoodle->vdbprefix;
                    $CFG->wwwroot = $CFG->vmoodleroot;
                    $CFG->dataroot = $vmoodle->vdatapath;
                } else {
                    // echo mysqli_error();
                    die("VMoodling : No configuration for this host : {$CFG->vmoodleroot}. May be faked.");
                }
            } else {
                die("VMoodling : Could not fetch virtual moodle configuration");
            }
        } elseif ($CFG->vmasterdbtype == 'postgres' || $CFG->vmasterdbtype == 'postgres7') {
            $vmaster = new StdClass();
            $vmaster->vdbtype = $CFG->vmasterdbtype;
            $vmaster->vdbhost = $CFG->vmasterdbhost;
            $vmaster->vdblogin = $CFG->vmasterdblogin;
            $vmaster->vdbpass = $CFG->vmasterdbpass;
            $side_cnx = vmoodle_make_connection($vmaster);
            $sql = "\n               SELECT\n               *\n               FROM\n                  {$CFG->vmasterprefix}local_vmoodle\n               WHERE\n                  vhostname = '{$CFG->vmoodleroot}'\n            ";
            $res = pg_query($side_cnx, $sql);
            if ($res) {
                if (pg_num_rows($res)) {
                    $vmoodle = pg_fetch_object($res);
                    $CFG->dbtype = $vmoodle->vdbtype;
                    $CFG->dbhost = $vmoodle->vdbhost;
                    $CFG->dbname = $vmoodle->vdbname;
                    $CFG->dbuser = $vmoodle->vdblogin;
                    $CFG->dbpass = $vmoodle->vdbpass;
                    $CFG->dboptions['dbpersist'] = $vmoodle->vdbpersist;
                    $CFG->prefix = $vmoodle->vdbprefix;
                    $CFG->wwwroot = $CFG->vmoodleroot;
                    $CFG->dataroot = $vmoodle->vdatapath;
                } else {
                    die("VMoodling : No configuration for this host. May be faked.");
                }
                pg_close($side_cnx);
            } else {
                die("VMoodling : Could not fetch virtual moodle configuration");
            }
        } else {
            die("VMoodling : Unsupported Database for VMoodleMaster");
        }
    } elseif ($CFG->vmoodledefault) {
        // echo "VDefault selected";
        // do nothing, just bypass
    } else {
        die("real moodle instance cannot be used in this VMoodle implementation");
    }
}
        $DB->delete_records('local_vmoodle', array('id' => $id));
        /// destroy database. work silently
        @vmoodle_drop_database($vmoodle);
        /// unlink datapath
        filesystem_clear_dir($vmoodle->vdatapath, FS_FULL_DELETE, '');
        /// unbind mnet hosts
        if ($vmoodle->mnet) {
            // unregister from me (this)
            $thismoodle = vmoodle_make_this();
            $this_cnx = vmoodle_make_connection($thismoodle, true);
            if ($this_cnx) {
                vmoodle_unregister_mnet($vmoodle, $thismoodle);
                vmoodle_close_connection($vmoodle, $this_cnx);
            }
            // unregister from all remaining peers (this)
            $mnetpeers = $DB->get_records('local_vmoodle', array('mnet' => 1));
            if (!empty($mnetpeers)) {
                foreach ($mnetpeers as $peervmoodle) {
                    $this_cnx = vmoodle_make_connection($peervmoodle, true);
                    if ($peer_cnx) {
                        vmoodle_unregister_mnet($vmoodle, $peervmoodle);
                        vmoodle_close_connection($vmoodle, $peer_cnx);
                    } else {
                    }
                }
            }
        }
    } else {
        error("Bad VMoodle Id");
    }
}
示例#6
0
/**
 * This is a boot lib that is required BEFORE we can have access
 * to the Moodle framework library like DML and $CFG defines.
 */
function vmoodle_boot_configuration()
{
    global $CFG;
    /*
     * vconfig provides an bypassed configuration using vmoodle host definition
     * from the vmoodle master instance
     *
     */
    $CFG->mainwwwroot = $CFG->wwwroot;
    if ($CFG->vmoodleroot != $CFG->wwwroot) {
        if ($CFG->vmasterdbtype == 'sqlsrv') {
            $vmaster = new StdClass();
            $vmaster->vdbtype = $CFG->vmasterdbtype;
            $vmaster->vdbhost = $CFG->vmasterdbhost;
            $vmaster->vdblogin = $CFG->vmasterdblogin;
            $vmaster->vdbpass = $CFG->vmasterdbpass;
            $vmaster->vdbname = $CFG->vmasterdbname;
            $vmaster->dblibrary = $CFG->dblibrary;
            $vmaster->dboptions = $CFG->dboptions;
            try {
                $side_cnx = vmoodle_make_connection($vmaster);
                if (!$side_cnx) {
                    throw new Exception('[local/vmoodle/bootlib.php] - vmoodle_boot_configuration() : VMoodle peer connection error.');
                }
                $sql = "SELECT * FROM {$CFG->vmasterprefix}local_vmoodle WHERE vhostname = ?";
                $result = sqlsrv_query($side_cnx, $sql, array($CFG->vmoodleroot));
                $obj = sqlsrv_fetch_object($result);
                if (!$obj) {
                    throw new Exception("[local/vmoodle/bootlib.php] - vmoodle_boot_configuration() : Unable to find the current VMoodle node");
                }
                $CFG->dbtype = $obj->vdbtype;
                $CFG->dbhost = $obj->vdbhost;
                $CFG->dbname = $obj->vdbname;
                $CFG->dbuser = $obj->vdblogin;
                $CFG->dbpass = $obj->vdbpass;
                $CFG->dboptions['dbpersist'] = $obj->vdbpersist;
                $CFG->prefix = $obj->vdbprefix;
                $CFG->wwwroot = $CFG->vmoodleroot;
                $CFG->dataroot = $obj->vdatapath;
                if (!is_bool($result)) {
                    // true/false resources cannot be freed
                    sqlsrv_free_stmt($result);
                }
            } catch (Exception $e) {
                die($e->getMessage());
            } finally {
                if ($side_cnx) {
                    sqlsrv_close($side_cnx);
                    $side_cnx = null;
                }
            }
        } else {
            if ($CFG->vmasterdbtype == 'mysql') {
                $vmaster = new StdClass();
                $vmaster->vdbtype = $CFG->vmasterdbtype;
                $vmaster->vdbhost = $CFG->vmasterdbhost;
                $vmaster->vdblogin = $CFG->vmasterdblogin;
                $vmaster->vdbpass = $CFG->vmasterdbpass;
                if (!($side_cnx = vmoodle_make_connection($vmaster))) {
                    return;
                    // If vmoodle cnx not valid.
                }
                if (!mysql_select_db($CFG->vmasterdbname, $side_cnx)) {
                    return;
                    // If vmoodle cnx not valid.
                }
                $sql = "\n               SELECT\n               *\n               FROM\n                  {$CFG->vmasterprefix}local_vmoodle\n               WHERE\n                  vhostname = '{$CFG->vmoodleroot}'\n            ";
                $res = mysql_query($sql, $side_cnx);
                if ($res) {
                    if (mysql_num_rows($res)) {
                        $vmoodle = mysql_fetch_object($res);
                        $CFG->dbtype = $vmoodle->vdbtype;
                        $CFG->dbhost = $vmoodle->vdbhost;
                        $CFG->dbname = $vmoodle->vdbname;
                        $CFG->dbuser = $vmoodle->vdblogin;
                        $CFG->dbpass = $vmoodle->vdbpass;
                        $CFG->dboptions['dbpersist'] = $vmoodle->vdbpersist;
                        $CFG->prefix = $vmoodle->vdbprefix;
                        $CFG->wwwroot = $CFG->vmoodleroot;
                        $CFG->dataroot = $vmoodle->vdatapath;
                    } else {
                        die("VMoodling : No configuration for this host : {$CFG->vmoodleroot}. May be faked.");
                    }
                } else {
                    die("VMoodling : Could not fetch virtual moodle configuration");
                }
            } elseif ($CFG->vmasterdbtype == 'mysqli') {
                $vmaster = new StdClass();
                $vmaster->vdbtype = $CFG->vmasterdbtype;
                $vmaster->vdbhost = $CFG->vmasterdbhost;
                $vmaster->vdblogin = $CFG->vmasterdblogin;
                $vmaster->vdbpass = $CFG->vmasterdbpass;
                $vmaster->vdbname = $CFG->vmasterdbname;
                if (!($side_cnx = vmoodle_make_connection($vmaster, true))) {
                    // If vmoodle cnx not valid.
                    die('VMoodle master server unreachable');
                }
                $sql = "\n               SELECT\n               *\n               FROM\n                  {$CFG->vmasterprefix}local_vmoodle\n               WHERE\n                  vhostname = '{$CFG->vmoodleroot}'\n            ";
                $res = mysqli_query($side_cnx, $sql);
                if ($res) {
                    if (mysqli_num_rows($res)) {
                        $vmoodle = mysqli_fetch_object($res);
                        $CFG->dbtype = $vmoodle->vdbtype;
                        $CFG->dbhost = $vmoodle->vdbhost;
                        $CFG->dbname = $vmoodle->vdbname;
                        $CFG->dbuser = $vmoodle->vdblogin;
                        $CFG->dbpass = $vmoodle->vdbpass;
                        $CFG->dboptions['dbpersist'] = $vmoodle->vdbpersist;
                        $CFG->prefix = $vmoodle->vdbprefix;
                        $CFG->wwwroot = $CFG->vmoodleroot;
                        $CFG->dataroot = $vmoodle->vdatapath;
                    } else {
                        // echo mysqli_error();
                        die("VMoodling : No configuration for this host : {$CFG->vmoodleroot}. May be faked.");
                    }
                } else {
                    die("VMoodling : Could not fetch virtual moodle configuration");
                }
            } elseif ($CFG->vmasterdbtype == 'postgres' || $CFG->vmasterdbtype == 'postgres7') {
                $vmaster = new StdClass();
                $vmaster->vdbtype = $CFG->vmasterdbtype;
                $vmaster->vdbhost = $CFG->vmasterdbhost;
                $vmaster->vdblogin = $CFG->vmasterdblogin;
                $vmaster->vdbpass = $CFG->vmasterdbpass;
                $side_cnx = vmoodle_make_connection($vmaster);
                $sql = "\n               SELECT\n               *\n               FROM\n                  {$CFG->vmasterprefix}local_vmoodle\n               WHERE\n                  vhostname = '{$CFG->vmoodleroot}'\n            ";
                $res = pg_query($side_cnx, $sql);
                if ($res) {
                    if (pg_num_rows($res)) {
                        $vmoodle = pg_fetch_object($res);
                        $CFG->dbtype = $vmoodle->vdbtype;
                        $CFG->dbhost = $vmoodle->vdbhost;
                        $CFG->dbname = $vmoodle->vdbname;
                        $CFG->dbuser = $vmoodle->vdblogin;
                        $CFG->dbpass = $vmoodle->vdbpass;
                        $CFG->dboptions['dbpersist'] = $vmoodle->vdbpersist;
                        $CFG->prefix = $vmoodle->vdbprefix;
                        $CFG->wwwroot = $CFG->vmoodleroot;
                        $CFG->dataroot = $vmoodle->vdatapath;
                    } else {
                        die("VMoodling : No configuration for this host. May be faked.");
                    }
                    pg_close($side_cnx);
                } else {
                    die("VMoodling : Could not fetch virtual moodle configuration");
                }
            } else {
                die("VMoodling : Unsupported Database for VMoodleMaster");
            }
        }
    } elseif ($CFG->vmoodledefault) {
        // echo "VDefault selected";
        // do nothing, just bypass
    } else {
        die("real moodle instance cannot be used in this VMoodle implementation");
    }
    // Allows to split local cache from shared one to a faster local drive
    if (isset($CFG->local_vmoodle_localcachedir) && !isset($CFG->localcachedir)) {
        $splitted_path_local = explode('/', rtrim(str_replace("\\", '/', $CFG->local_vmoodle_localcachedir), '/'));
        if (count($splitted_path_local) > 0) {
            $splittedvdatapath = explode('/', rtrim(str_replace("\\", '/', $CFG->dataroot), '/'));
            $splitted_path_local[] = end($splittedvdatapath);
            $CFG->localcachedir = implode('/', $splitted_path_local) . '/localcache';
        }
    }
}