Skip to content

Commit

Permalink
WIP Replace script
Browse files Browse the repository at this point in the history
  • Loading branch information
Nathan Nguyen committed Sep 25, 2024
1 parent 2d9ff1d commit 5ca4705
Show file tree
Hide file tree
Showing 2 changed files with 166 additions and 0 deletions.
46 changes: 46 additions & 0 deletions classes/helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -371,4 +371,50 @@ public static function regular_expression_search(string $search, string $table,
}
return $results;
}

/**
* A clone of the core function replace_all_text.
*
* @since Moodle 2.6.1
* @param string $table name of the table
* @param database_column_info $column
* @param string $search
* @param string $replace
* @param int $id optional id to restrict the search
*/
public static function replace_all_text($table, database_column_info $column, $search, $replace, $id = null) {
global $DB;
if (!$DB->replace_all_text_supported()) {
return;
}

// Enclose the column name by the proper quotes if it's a reserved word.
$columnname = $DB->get_manager()->generator->getEncQuoted($column->name);

$searchsql = $DB->sql_like($columnname, '?');
$searchparam = '%'.$DB->sql_like_escape($search).'%';

// Add the id to the search.
if (!is_null($id)) {
$searchsql .= ' AND id = ?';
$searchparam = [$searchparam, $id];
}

$sql = "UPDATE {".$table."}
SET $columnname = REPLACE($columnname, ?, ?)
WHERE $searchsql";

if ($column->meta_type === 'X') {
$DB->execute($sql, [$search, $replace, $searchparam]);

} else if ($column->meta_type === 'C') {
if (core_text::strlen($search) < core_text::strlen($replace)) {
$colsize = $column->max_length;
$sql = "UPDATE {".$table."}
SET $columnname = " . $DB->sql_substr("REPLACE(" . $columnname . ", ?, ?)", 1, $colsize) . "
WHERE $searchsql";
}
$DB->execute($sql, [$search, $replace, $searchparam]);
}
}
}
120 changes: 120 additions & 0 deletions cli/replace.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// 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/>.

/**
* Replace strings using uploaded CSV file.
*
* @package tool_advancedreplace
* @copyright 2024 Catalyst IT Australia Pty Ltd
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/

use tool_advancedreplace\helper;

define('CLI_SCRIPT', true);

require(__DIR__.'/../../../../config.php');
require_once($CFG->libdir.'/clilib.php');
require_once($CFG->libdir.'/adminlib.php');
require_once($CFG->dirroot . '/lib/csvlib.class.php');
$help =
"Replace strings using uploaded CSV file..
Options:
--input=FILE Required. Input CSV file produced by find.php in detail mode.
-h, --help Print out this help.
Example:
\$ sudo -u www-data /usr/bin/php admin/tool/advancedreplace/cli/replace.php --input=/tmp/result.csv
";

list($options, $unrecognized) = cli_get_params(
[
'input' => null,
'help' => false,
],
[
'h' => 'help',
]
);
core_php_time_limit::raise();

if ($unrecognized) {
$unrecognized = implode("\n ", $unrecognized);
cli_error(get_string('cliunknowoption', 'admin', $unrecognized));
}

// Ensure that we have required parameters.
if ($options['help'] || empty($options['input'])) {
echo $help;
exit(0);
}

try {
$file = validate_param($options['input'], PARAM_RAW);
} catch (invalid_parameter_exception $e) {
cli_error(get_string('errorinvalidparam', 'tool_advancedreplace'));
}

if (!file_exists($file)) {
cli_error(get_string('errorfilenotfound', 'tool_advancedreplace'));
}

// Open the file for reading.
$fp = fopen($file, 'r');
$data = fread($fp, filesize($file));
fclose($fp);

// Load the CSV content.
$iid = csv_import_reader::get_new_iid('tool_advancedreplace');
$csvimport = new csv_import_reader($iid, 'tool_advancedreplace');
$contentcount = $csvimport->load_csv_content($data, 'utf-8', 'comma');

// Read the header and find the column indexes.
$header = $csvimport->get_columns();
if (empty($header)) {
cli_error(get_string('errorinvalidfile', 'tool_advancedreplace'));
}

$tableindex = array_search('table', $header);
$columnindex = array_search('column', $header);
$idindex = array_search('id', $header);
$matchindex = array_search('match', $header);
$replaceindex = array_search('replace', $header);

if ($tableindex === false || $columnindex === false || $idindex === false || $matchindex === false || $replaceindex === false) {
cli_error(get_string('errorinvalidfile', 'tool_advancedreplace'));
}

// Read the data and replace the strings.
$dataset = [];
$csvimport->init();
while ($record = $csvimport->next()) {
$dataset[] = $record;
$table = $record[$tableindex];
$column = $record[$columnindex];
$id = $record[$idindex];
$match = $record[$matchindex];
$replace = $record[$replaceindex];

// Replace the string.
helper::replace_all_text($table, $column, $match, $replace, $id);
}

$csvimport->cleanup();
$csvimport->close();

exit(0);

0 comments on commit 5ca4705

Please sign in to comment.